-
Notifications
You must be signed in to change notification settings - Fork 18
/
sql-indent.el
2593 lines (2262 loc) · 101 KB
/
sql-indent.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; sql-indent.el --- Support for indenting code in SQL files. -*- lexical-binding: t -*-
;; Copyright (C) 2015, 2017-2018, 2024 Free Software Foundation, Inc
;; Author: Alex Harsanyi <[email protected]>
;; Created: 27 Sep 2006
;; Version: 1.7
;; Keywords: languages sql
;; Homepage: https://github.com/alex-hhh/emacs-sql-indent
;; Package-Requires: ((cl-lib "0.5"))
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; `sqlind-minor-mode' is a minor mode that enables syntax-based indentation
;; for `sql-mode' buffers: the TAB key indents the current line based on the
;; SQL code on previous lines. To setup syntax-based indentation for every
;; SQL buffer, add `sqlind-minor-mode' to `sql-mode-hook'. Indentation rules
;; are flexible and can be customized to match your personal coding style.
;; For more information, see the "sql-indent.org" file.
;;
;; The package also defines align rules so that the `align' function works for
;; SQL statements, see `sqlind-align-rules'.
;;; Code:
(require 'sql)
(require 'cl-lib)
;;;; General setup
(defvar sqlind-syntax-table
(let ((table (make-syntax-table)))
;; C-style comments /**/ (see elisp manual "Syntax Flags"))
(modify-syntax-entry ?/ ". 14" table)
(modify-syntax-entry ?* ". 23" table)
;; double-dash starts comment
(modify-syntax-entry ?- ". 12b" table)
;; newline and formfeed end coments
(modify-syntax-entry ?\n "> b" table)
(modify-syntax-entry ?\f "> b" table)
;; single quotes (') quotes delimit strings
(modify-syntax-entry ?' "\"" table)
;; backslash is no escape character
(modify-syntax-entry ?\\ "." table)
;; the following are symbol constituents. Note that the dot '.' is more
;; usefull as a symbol constituent than as a punctuation char.
(modify-syntax-entry ?_ "_" table)
(modify-syntax-entry ?. "_" table)
(modify-syntax-entry ?$ "_" table)
(modify-syntax-entry ?# "_" table)
(modify-syntax-entry ?% "_" table)
table)
"Syntax table used in `sql-mode' for indenting SQL code.
This is slightly different than the syntax table used for
navigation: some punctuation characters are made symbol
constituents so that syntactic navigation works over them.")
;;;; Utilities
;; The following routines perform rudimentary syntactical analysis of SQL
;; code. The indentation engine decides how to indent based on what this code
;; returns. The main function is `sqlind-syntax-of-line'.
;;
;; To examine the syntax of the current line, you can use the
;; `sqlind-show-syntax-of-line'. This is only useful if you want to debug this
;; package or are just curious.
(defconst sqlind-comment-start-skip "\\(--+\\|/\\*+\\)\\s *"
"Regexp to match the start of a SQL comment.")
(defconst sqlind-comment-end "\\*+/"
"Regexp to match the end of a multiline SQL comment.")
(defvar sqlind-comment-prefix "\\*+\\s "
"Regexp to match the line prefix inside comments.
This is used to indent multi-line comments.")
(defsubst sqlind-in-comment-or-string (pos)
"Return non nil if POS is inside a comment or a string.
We actually return \\='string if POS is inside a string,
\\='comment if POS is inside a comment, nil otherwise."
(syntax-ppss-context (syntax-ppss pos)))
(defun sqlind-backward-syntactic-ws ()
"Move point backwards over whitespace and comments.
Leave point on the first character which is not syntactic
whitespace, or at the beginning of the buffer."
(let ((done nil))
(while (not done)
(skip-chars-backward " \t\n\r\f\v")
(unless (eq (point) (point-min))
(forward-char -1))
(let ((pps (syntax-ppss (point))))
(if (nth 4 pps) ; inside a comment?
(goto-char (nth 8 pps)) ; move to comment start than repeat
(setq done t)))))
(point))
(defun sqlind-forward-syntactic-ws ()
"Move point forward over whitespace and comments.
Leave point at the first character which is not syntactic
whitespace, or at the end of the buffer."
;; if we are inside a comment, move to the comment start and scan
;; from there.
(let ((pps (syntax-ppss (point))))
(when (nth 4 pps)
(goto-char (nth 8 pps))))
(let ((done nil))
(while (not done)
(skip-chars-forward " \t\n\r\f\v")
(cond ((looking-at sqlind-comment-start-skip) (forward-comment 1))
;; a slash ("/") by itself is a SQL*plus directive and
;; counts as whitespace
((looking-at "/\\s *$") (goto-char (match-end 0)))
(t (setq done t)))))
(point))
(defun sqlind-search-backward (start regexp limit)
"Search for REGEXP from START backward until LIMIT.
Finds a match that is not inside a comment or string, moves point
to the match and returns it. If no match is found, point is moved
to LIMIT and nil is returned."
(goto-char start)
(let ((done nil))
(while (and (not done)
(re-search-backward regexp limit 'noerror))
(when (sqlind-same-level-statement (point) start)
(setq done (point))))
done))
(defsubst sqlind-match-string (pos)
"Return the match data at POS in the current buffer.
This is similar to `match-data', but the text is fetched without
text properties and it is conveted to lower case."
(let ((start (match-beginning pos))
(end (match-end pos)))
(when (and start end)
(downcase (buffer-substring-no-properties start end)))))
(defsubst sqlind-labels-match (lb1 lb2)
"Return t when LB1 equals LB2 or LB1 is an empty string.
This is used to compare start/end block labels where the end
block label might be empty."
(or (string= lb1 lb2)
(string= lb1 "")))
(defun sqlind-same-level-statement (point start)
"Return t if POINT is at the same syntactic level as START.
This means that POINT is at the same nesting level and not inside
a string or comment."
(save-excursion
(let ((ppss-point (syntax-ppss point))
(ppss-start (syntax-ppss start)))
(and (equal (nth 3 ppss-point) (nth 3 ppss-start)) ; string
(equal (nth 4 ppss-point) (nth 4 ppss-start)) ; comment
(= (nth 0 ppss-point) (nth 0 ppss-start)))))) ; same nesting
(defun sqlind-column-definition-start (pos limit)
"Find the beginning of a column definition in a select statement.
POS is the current position of the line to be indented, assumed
to be in a \\='select-column-continuation syntax.
LIMIT is the limit of the search, the beginning of the select
statement."
(save-excursion
(goto-char pos)
(catch 'found
(while (re-search-backward "," limit 'noerror)
(when (sqlind-same-level-statement (point) limit)
(forward-char 1)
(sqlind-forward-syntactic-ws)
(throw 'found (point))))
;; nothing was found in (while ...) so try to find the first column definition.
(goto-char limit)
(forward-sexp)
(sqlind-forward-syntactic-ws)
(point))))
(defun sqlind-syntax (context)
"Return the most specific syntax of CONTEXT.
See `sqlind-syntax-of-line' for the definition of CONTEXT."
(when context
(caar context)))
(defun sqlind-syntax-symbol (context)
"Return the syntax symbol for the most specific syntax of CONTEXT.
See `sqlind-syntax-of-line' for the definition of CONTEXT."
(when context
(let ((syntax-part (caar context)))
(if (symbolp syntax-part)
syntax-part
(car syntax-part)))))
(defun sqlind-syntax-keyword (context)
"Return the syntax keyword for the most specific syntax of CONTEXT.
This is used for complex syntax symbols like \\='(in-block case
\"\"), in that case, it will return the \\='case symbol. See
`sqlind-syntax-of-line' for the definition of CONTEXT."
(when context
(let ((syntax-part (caar context)))
(if (symbolp syntax-part)
nil ; no KEYWORD
(nth 1 syntax-part)))))
(defun sqlind-anchor-point (context)
"Return the anchor point for the most specifc syntax of CONTEXT.
See `sqlind-syntax-of-line' for the definition of CONTEXT."
(when context
(cdar context)))
(defun sqlind-outer-context (context)
"Return the outer context from CONTEXT.
See `sqlind-syntax-of-line' for the definition of CONTEXT."
(when context
(cdr context)))
(defun sqlind-find-context (syntax-symbol context)
"Find SYNTAX-SYMBOL in the CONTEXT chain.
CONTEXT chain is a list of (SYNTAX-SYMBOL . ANCHOR), as returned
by `sqlind-syntax-of-line'. The function finds the fist element
which matches the specified syntax symbol and returns the list
from that point.
See `sqlind-indentation-syntax-symbols' for the possible syntax
symbols and their meaning."
(cond ((null context)
nil)
((eq syntax-symbol (sqlind-syntax-symbol context))
context)
(t
(sqlind-find-context syntax-symbol (sqlind-outer-context context)))))
(defun sqlind-looking-at-begin-transaction ()
"Return t if the point is on a \"begin transaction\" statement."
(and (looking-at "begin")
(save-excursion
(forward-word 1)
(sqlind-forward-syntactic-ws)
(looking-at "transaction\\>\\|work\\>\\|;"))))
;;;; Syntactic analysis of SQL code
;;;;; Find the beginning of the current statement
(defconst sqlind-sqlplus-directive
(concat ;; SET is handled in a special way, to avoid conflicts with the SET
;; keyworkd in updated clauses
"\\(^set\\s-+\\w+\\(\\s-+[^=].*\\)?$\\)\\|\\(^"
(regexp-opt '("column" "rem" "define" "spool" "prompt"
"clear" "compute" "whenever" "@" "@@" "start")
t)
"\\)\\b")
"Match an SQL*Plus directive at the beginning of a line.
A directive always stands on a line by itself -- we use that to
determine the statement start in SQL*Plus scripts.")
(defconst sqlind-sqlite-directive
"^[.].*?\\>"
"Match an SQLite directive at the beginning of a line.
A directive always stands on a line by itself -- we use that to
determine the statement start in SQLite scripts.")
(defconst sqlind-ms-directive
(concat
"\\(^set\\s-+\\(\\w\\|\\s_\\)+\\s-+\\(on\\|off\\)\\)\\|\\(^"
(regexp-opt '("use" "go" "declare") t)
"\\)\\b")
"Match an MS SQL Sever directive at the beginning of a line.")
(defun sqlind-beginning-of-directive ()
"Return the position of an SQL directive, or nil.
We will never move past one of these in our scan. We also assume
they are one-line only directives."
(let ((rx (cl-case (and (boundp 'sql-product) sql-product)
(ms sqlind-ms-directive)
(sqlite sqlind-sqlite-directive)
(oracle sqlind-sqlplus-directive)
(t nil))))
(when rx
(save-excursion
(when (re-search-backward rx nil 'noerror)
(forward-line 1)
(point))))))
(defvar sqlind-search-limit nil
"Limit of search when looking for syntactic elements.
This variable is dynamically bound.")
(defun sqlind-beginning-of-statement-1 (limit)
"Return the position of a block start, or nil.
But don't go before LIMIT."
(save-excursion
(catch 'done
(while (> (point) (or limit (point-min)))
(when (re-search-backward ";\\|:=\\|\\_<\\(declare\\|\\(begin\\(\\(\\s-+not\\)?\\s-+atomic\\)?\\)\\|cursor\\|for\\|while\\|loop\\|if\\|then\\|else\\|elsif\\|elseif\\)\\_>\\|)\\|\\$\\$"
limit 'noerror)
(unless (sqlind-in-comment-or-string (point))
(let ((candidate-pos (match-end 0)))
(cond ((looking-at ")")
;; Skip parenthesis expressions, we don't want to find one
;; of the keywords inside one of them and think this is a
;; statement start.
(progn (forward-char 1) (forward-sexp -1)))
((looking-at "cursor\\|for")
(unless (eq sql-product 'postgres)
(throw 'done (point))))
((looking-at "while")
(throw 'done (point)))
((looking-at "declare")
(when (eq sql-product 'postgres)
(throw 'done (point))))
((looking-at "else?if")
;; statement begins at the start of the keyword
(throw 'done (point)))
((looking-at "then\\|else")
;; then and else start statements when they are inside
;; blocks, not expressions.
(sqlind-backward-syntactic-ws)
(when (looking-at ";")
;; Statement begins after the keyword
(throw 'done candidate-pos)))
((looking-at "if")
(when (sqlind-good-if-candidate)
;; statement begins at the start of the keyword
(throw 'done (point))))
((looking-at ":=")
;; assignment statements start at the assigned variable
(sqlind-backward-syntactic-ws)
(forward-sexp -1)
(throw 'done (point)))
((looking-at "\\$\\$")
(when (eq sql-product 'postgres)
(sqlind-forward-syntactic-ws)
(throw 'done (point))))
((sqlind-looking-at-begin-transaction)
;; This is a "begin transaction" call, statement begins
;; at "begin", see #66
(throw 'done (point)))
((not (sqlind-in-comment-or-string (point)))
(throw 'done candidate-pos))))))))))
(defun sqlind-beginning-of-statement ()
"Move point to the beginning of the current statement."
(interactive)
(goto-char
(or
;; If we are inside a paranthesis expression, the start is the start of
;; that expression.
(let ((ppss (syntax-ppss (point))))
(when (> (nth 0 ppss) 0)
(nth 1 ppss)))
;; Look for an ordinary statement start
(or (sqlind-beginning-of-statement-1 sqlind-search-limit)
;; Fall back on the search limit
sqlind-search-limit)
;; ... or point-min
(point-min)))
;; a loop keyword might be part of an "end loop" statement, in that case,
;; the statement starts with the "end" keyword. we use skip-syntax-backward
;; so we won't skip over a semicolon (;)
(let ((pos (point)))
(skip-syntax-backward "w")
(if (looking-at "loop")
(progn
(forward-word -1)
(if (looking-at "\\bend\\b")
(goto-char (match-beginning 0))
(goto-char pos)))
(goto-char pos)))
;; now skip over any whitespace and comments until we find the first
;; character that is program code.
(sqlind-forward-syntactic-ws))
;;;;; Find the syntax and beginning of the current block
(defconst sqlind-end-statement-regexp
"\\_<end\\_>\\(?:[ \t\n\r\f]*\\)\\(if\\_>\\|loop\\_>\\|case\\_>\\)?\\(?:[ \t\n\r\f]*\\)\\([a-z0-9_]+\\)?"
"Match an end of statement.
Matches a string like \"end if|loop|case MAYBE-LABEL\".")
(defvar sqlind-end-stmt-stack nil
"Stack of end-of-statement positions.
This is used by the sqlind-maybe-* functions to skip over SQL
programming blocks. This variable is dynamically bound.")
(defun sqlind-maybe-end-statement ()
"Look for SQL end statements return t if found one.
If (point) is at an end statement, add it to the
`sqlind-end-stmt-stack' and return t, otherwise return nil.
See also `sqlind-beginning-of-block'"
(when (looking-at sqlind-end-statement-regexp)
(prog1 t ; make sure we return t
(let ((kind (or (sqlind-match-string 1) ""))
(label (or (sqlind-match-string 2) "")))
(push (list (point) (if (equal kind "") nil (intern kind)) label)
sqlind-end-stmt-stack)))))
(defun sqlind-maybe-then-statement ()
"Find the corresponding start block for a \"then\" statement.
When (point) is on a \"then\" statement, find the corresponding
start of the block and report its syntax. This code will skip
over nested statements to determine the actual start.
Only keywords in program code are matched, not the ones inside
expressions.
See also `sqlind-beginning-of-block'"
(when (looking-at "then")
(prog1 t ; make sure we return t
(let ((start-pos (point)))
;; a then keyword at the begining of a line is a block start
(when (null sqlind-end-stmt-stack)
(save-excursion
(back-to-indentation)
(when (eq (point) start-pos)
(throw 'finished (list 'in-block 'then "")))))
;; if it is not at the beginning of a line, the beginning of
;; the statement is the block start
(ignore-errors (forward-char -1))
(sqlind-beginning-of-statement)
;; a then keyword only starts a block when it is part of an
;; if, case/when or exception statement
(cond
((looking-at "\\(<<[a-z0-9_]+>>\\)?\\(?:[ \t\n\r\f]*\\)\\(\\(?:els\\)?if\\)\\_>")
(let ((if-label (sqlind-match-string 1))
(if-kind (intern (sqlind-match-string 2)))) ; can be if or elsif
(setq if-label (if if-label (substring if-label 2 -2) ""))
(if (null sqlind-end-stmt-stack)
(throw 'finished (list 'in-block if-kind if-label))
;; "if" blocks (but not "elsif" blocks) need to be
;; ended with "end if"
(when (eq if-kind 'if)
(cl-destructuring-bind (pos kind label)
(pop sqlind-end-stmt-stack)
(unless (and (eq kind 'if)
(sqlind-labels-match label if-label))
(throw 'finished
(list 'syntax-error
"bad closing for if block" (point) pos))))))))
((looking-at "\\(<<[a-z0-9_]+>>\\)?\\(?:[ \t\n\r\f]*\\)case\\_>")
;; find the nearest when block, but only if there are no
;; end statements in the stack
(let ((case-label (sqlind-match-string 1)))
(setq case-label
(if case-label (substring case-label 2 -2) ""))
(if (null sqlind-end-stmt-stack)
(save-excursion
(when (sqlind-search-backward start-pos "\\_<when\\_>" (point))
(throw 'finished (list 'in-block 'case case-label))))
;; else
(cl-destructuring-bind (pos kind label)
(pop sqlind-end-stmt-stack)
(unless (and (eq kind 'case)
(sqlind-labels-match label case-label))
(throw 'finished
(list 'syntax-error
"bad closing for case block" (point) pos)))))))
((looking-at "exception\\_>")
;; an exception statement is a block start only if we have
;; no end statements in the stack
(when (null sqlind-end-stmt-stack)
(throw 'finished (list 'in-block 'exception ""))))
(t ; restore position if we didn't do anything
(goto-char start-pos)
nil))))))
(defun sqlind-good-if-candidate ()
"Return non-nil if point is on an actual if statement.
We try to avoid false positives, like \"end if\" or the various
\"drop STUFF if exists\" variants."
(and (looking-at "if")
(save-excursion
(sqlind-backward-syntactic-ws)
(forward-word -1)
;; we don't want to match an "end if", and things like "drop index if
;; exists..." and "create index if not exist..."
(not (looking-at "end\\|schema\\|table\\|column\\|view\\|index\\|constraint\\|type\\|trigger\\|procedure\\|function\\|routine\\|package\\|body\\|extension")))))
(defun sqlind-maybe-if-statement ()
"If (point) is on an IF statement, report its syntax."
(when (and (sqlind-good-if-candidate) (not (eq sql-product 'ms)))
(cond ((null sqlind-end-stmt-stack)
(throw 'finished (list 'in-block 'if "")))
(t
(cl-destructuring-bind (pos kind _label)
(pop sqlind-end-stmt-stack)
(unless (eq kind 'if)
(throw 'finshed
(list 'syntax-error
"bad closing for if block" (point) pos))))))))
(defun sqlind-maybe-case-statement ()
"If (point) is on a case statement."
(when (looking-at "case")
(save-excursion
(sqlind-backward-syntactic-ws)
(forward-word -1)
(unless (looking-at "end") ; we don't want to match an "end case" here
(if (null sqlind-end-stmt-stack)
(throw 'finished (list 'in-block 'case ""))
(cl-destructuring-bind (pos kind _label)
(pop sqlind-end-stmt-stack)
(unless (or (not kind) (eq kind 'case))
(throw 'finished
(list 'syntax-error
"bad closing for case block" (point) pos)))))))))
(defun sqlind-maybe-else-statement ()
"If (point) is on an ELSE statement, report its syntax.
Only keywords in program code are matched, not the ones inside
expressions.
See also `sqlind-beginning-of-block'"
;; an else statement is only a block start if the `sqlind-end-stmt-stack' is
;; empty, otherwise, we don't do anything.
(when (and (looking-at "els\\(e\\|if\\)")
(null sqlind-end-stmt-stack))
(throw 'finished (list 'in-block (intern (sqlind-match-string 0)) ""))))
(defun sqlind-maybe-loop-statement ()
"If (point) is on a LOOP statement, report its syntax.
Only keywords in program code are matched, not the ones inside
expressions.
See also `sqlind-beginning-of-block'"
(when (looking-at "loop")
(prog1 t ; make sure we return t
(sqlind-beginning-of-statement)
;; note that we might have found a loop in an "end loop;" statement.
(or (sqlind-maybe-end-statement)
(progn
(let ((posn (point)))
(unless (looking-at "<<") ;; whe're inside an label.
(forward-word -1)
(back-to-indentation))
(let ((loop-label (if (looking-at "<<\\([a-z0-9_]+\\)>>")
(sqlind-match-string 1) "")))
(goto-char posn)
;; start of loop. this always starts a block, we only check if
;; the labels match
(if (null sqlind-end-stmt-stack)
(throw 'finished (list 'in-block 'loop loop-label))
(cl-destructuring-bind (pos kind label)
(pop sqlind-end-stmt-stack)
(unless (and (eq kind 'loop)
(sqlind-labels-match label loop-label))
(throw 'finished
(list 'syntax-error
"bad closing for loop block" (point) pos))))))))))))
(defun sqlind-maybe-begin-statement ()
"Return the syntax of a \"begin\" statement.
If (point) is on a \"begin\" statement, report its syntax. Only
keywords in program code are matched, not the ones inside
expressions.
See also `sqlind-beginning-of-block'"
(when (and (looking-at "begin") (not (sqlind-looking-at-begin-transaction)))
;; a begin statement starts a block unless it is the first begin in a
;; procedure over which we need to skip it.
(prog1 t ; make sure we return t
(let* ((saved-pos (point))
(begin-label (save-excursion
(sqlind-beginning-of-statement)
(if (looking-at "<<\\([a-z0-9_]+\\)>>\\_>")
(sqlind-match-string 1) "")))
(previous-block (save-excursion
(ignore-errors (forward-char -1))
(cons (sqlind-beginning-of-block) (point))))
(previous-block-kind (nth 0 previous-block)))
(goto-char saved-pos)
(when (null sqlind-end-stmt-stack)
(throw 'finished
(cond ((memq previous-block-kind '(toplevel declare-statement))
(list 'in-begin-block 'toplevel-block begin-label))
((and (listp previous-block-kind)
(eq (nth 0 previous-block-kind) 'defun-start))
(list 'in-begin-block 'defun (nth 1 previous-block-kind)))
((and (listp previous-block-kind)
(memq (nth 0 previous-block-kind) '(package package-body)))
(list 'in-begin-block 'package (nth 1 previous-block-kind)))
(t
(list 'in-begin-block nil begin-label)))))
(cl-destructuring-bind (pos kind label) (pop sqlind-end-stmt-stack)
(cond
(kind
(throw 'finished
(list 'syntax-error "bad closing for begin block" (point) pos)))
((not (equal begin-label ""))
;; we have a begin label. In this case it must match the end
;; label
(unless (equal begin-label label)
(throw 'finished
(list 'syntax-error "mismatched block labels" (point) pos))))
(t
;; we don't have a begin label. In this case, the begin
;; statement might not start a block if it is the begining of a
;; procedure or declare block over which we need to skip.
(cond ((memq previous-block-kind '(toplevel declare-statement))
(goto-char (cdr previous-block)))
((and (listp previous-block-kind)
(memq (nth 0 previous-block-kind)
'(defun-start package package-body)))
(unless (sqlind-labels-match
label (nth 1 previous-block-kind))
(throw 'finished
(list 'syntax-error
"bad end label for defun" (point) pos)))
(goto-char (cdr previous-block)))))))))))
(defun sqlind-maybe-declare-statement ()
"If (point) is on a DECLARE statement, report its syntax.
Only keywords in program code are matched, not the ones inside
expressions, also we don't match DECLARE directives here.
See also `sqlind-beginning-of-block'"
(when (looking-at "declare")
;; In Postgres, a DECLARE statement can be a block, or define a cursor
;; (see pr67.sql, pr92.sql for examples). It is somewhat tricky to
;; determine which is which, so we use the heuristic that a declare
;; statement immediately following a $$ is a block, otherwise it is not.
(when (or (not (eq sql-product 'postgres))
(save-excursion
(sqlind-backward-syntactic-ws)
(skip-syntax-backward "_w") ; note that the $$ is symbol constituent!
(looking-at "\\(\\$\\$\\)\\|begin\\|then\\|else\\|\\(<<[a-z0-9_]+>>\\)")))
(throw 'finished
(if (null sqlind-end-stmt-stack)
'declare-statement
(list 'syntax-error "nested declare block" (point) (point)))))))
(defun sqlind-maybe-skip-create-options ()
"Move point past any MySQL option declarations.
Statements like \"CREATE VIEW\" or \"CREATE TABLE\" can have
various options betwen the CREATE keyword and the thing being
created. If such options exist at (point) the cursor is moved
past them.
Currently we move over the following options, for different
products:
MySQL:
TEMPORARY
ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}
DEFINER = { user | CURENT_USER }
SQL SECURITY { DEFINER | INVOKER }
PostgresSQL
TEMP
TEMPORARY
GLOBAL
LOCAL
UNLOGGED
MATERIALIZED
Oracle
PRIVATE
TEMP
TEMPORARY
MATERIALIZED
We don't consider if the options are valid or not for the thing
being created. We just skip any and all of them that are
present."
(cond
((eq sql-product 'mysql)
(catch 'finished
(while t
(cond
((looking-at "temporary\\_>")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
((looking-at "\\(definer\\|algorithm\\)\\(\\s-\\|[\n]\\)*=\\(\\s-\\|[\n]\\)*\\S-+")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
((looking-at "sql\\(\\s-\\|[\n]\\)+security\\(\\s-\\|[\n]\\)+\\S-+")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
(t (throw 'finished nil))))))
((eq sql-product 'postgres)
(catch 'finished
(while t
(cond
((looking-at "temp\\(orary\\)?\\_>")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
((looking-at "\\(global\\|local\\|unlogged\\)\\_>")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
((looking-at "materialized\\_>")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
(t (throw 'finished nil))))))
((eq sql-product 'oracle)
(catch 'finished
(while t
(cond
((looking-at "temp\\(orary\\)\\_>")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
((looking-at "materialized\\_>")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
((looking-at "private\\_>")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
(t (throw 'finished nil))))))))
(defun sqlind-maybe-create-statement (&optional all-statements)
"If (point) is on a CREATE statement, report its syntax.
See also `sqlind-beginning-of-block'
Normally, only block start create statements are considered (such
as creation of procedures). In particular, create
table/view/index statements are ignored unless the ALL-STATEMENTS
argument is t"
(when (or (looking-at "create\\_>\\(?:[ \t\n\r\f]+\\)\\(or\\(?:[ \t\n\r\f]+\\)replace\\_>\\)?")
(looking-at "alter\\_>"))
(prog1 t ; make sure we return t
(save-excursion
;; let's see what are we creating
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws)
(sqlind-maybe-skip-create-options)
(let ((what (intern (downcase (buffer-substring-no-properties
(point)
(progn (forward-word) (point))))))
(name (downcase (buffer-substring-no-properties
(progn (sqlind-forward-syntactic-ws)
;; Skip over a possible "if (not)
;; exists", to get the actual name
(when (looking-at "if\\(\\s-\\|[\n]\\)+\\(not\\)?\\(\\s-\\|[\n]\\)exists")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
(point))
(progn (skip-syntax-forward "w_()") (point))))))
(when (and (eq what 'package) (equal name "body"))
(setq what 'package-body)
(setq name (downcase
(buffer-substring-no-properties
(progn (sqlind-forward-syntactic-ws) (point))
(progn (skip-syntax-forward "w_()") (point))))))
;; Keep just the name, not the argument list
(when (string-match "\\(.*?\\)(" name)
(setq name (match-string 1 name)))
(cond
((memq what '(procedure function package package-body))
;; check is name is in the form user.name, if so then suppress user part.
(when (string-match "\\(?:.*\\.\\)?\\(.*\\)" name)
(setq name (match-string 1 name)))
(if (null sqlind-end-stmt-stack)
(throw 'finished
(list (if (memq what '(procedure function)) 'defun-start what)
name))
(cl-destructuring-bind (pos kind label) (pop sqlind-end-stmt-stack)
(when (not (eq kind nil))
(throw 'finished
(list 'syntax-error
"bad closing for create block" (point) pos)))
(unless (sqlind-labels-match label name)
(throw 'finished
(list 'syntax-error
"label mismatch in create block" (point) pos))))))
((memq what '(table view index))
;; Table, view and index creations do not begin blocks and they
;; are ignored unless the ALL-STATEMENTS parameter is t
(when all-statements
(throw 'finished (list 'create-statement what name))))
(t
(unless (null sqlind-end-stmt-stack)
(throw 'finished
(list 'syntax-error "nested create statement" (point) (point))))
(throw 'finished (list 'create-statement what name)))))))))
(defun sqlind-maybe-defun-statement ()
"If (point) is on a procedure definition statement, report its syntax.
See also `sqlind-beginning-of-block'"
(catch 'exit
(when (looking-at "\\(procedure\\|function\\)\\(?:[ \t\n\r\f]+\\)\\(?:[a-z0-9_]+\\.\\)?\\([a-z0-9_]+\\)")
(prog1 t ; make sure we return t
(let ((proc-name (sqlind-match-string 2)))
;; need to find out if this is a procedure/function
;; declaration or a definition
(save-excursion
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws)
;; skip param list, if any.
(when (looking-at "(")
(ignore-errors (forward-sexp 1))
(sqlind-forward-syntactic-ws))
(when (looking-at "return\\(?:[ \t\n\r\f]+\\)\\([a-z0-9_.]+\\(?:%\\(?:row\\)?type\\)?\\)")
(goto-char (match-end 0))
(sqlind-forward-syntactic-ws))
(when (looking-at ";")
;; not a procedure after all.
(throw 'exit nil)))
(save-excursion
(sqlind-backward-syntactic-ws)
;; Find out if it is a drop procedure or function statement
(forward-word -1)
(when (looking-at "drop")
;; not a procedure after all
(throw 'exit nil))
;; Find out if it is a "comment on" statement (postgres only)
(when (and (eq sql-product 'postgres)
(looking-at "on"))
(sqlind-backward-syntactic-ws)
(forward-word -1)
(when (looking-at "comment")
;; not a procedure after all.
(throw 'exit nil))))
;; so it is a definition
;; if the procedure starts with "create or replace", move
;; point to the real start
(let ((real-start (point)))
(save-excursion
(forward-word -1)
(when (looking-at "replace")
(forward-word -2))
(when (and (or (looking-at "create\\([ \t\r\n\f]+or[ \t\r\n\f]+replace\\)?")
(looking-at "alter"))
(not (sqlind-in-comment-or-string (point))))
(setq real-start (point))))
(goto-char real-start))
(when (null sqlind-end-stmt-stack)
(throw 'finished (list 'defun-start proc-name)))
(cl-destructuring-bind (pos kind label) (pop sqlind-end-stmt-stack)
(unless (and (eq kind nil)
(sqlind-labels-match label proc-name))
(throw 'finished
(list 'syntax-error "bad end label for defun" (point) pos)))))))))
(defun sqlind-maybe-exception-statement ()
"If (point) is on an exception keyword, report its syntax.
See also `sqlind-beginning-of-block'"
(when (and (looking-at "exception")
(null sqlind-end-stmt-stack))
;; Exception is both a keyword and a type. We need to only stop on the
;; keyword. We detect that if the previous token is either ";" or
;; "BEGIN".
(save-excursion
(forward-char -1)
(sqlind-backward-syntactic-ws)
(when (or (looking-at ";")
(progn (forward-word -1) (looking-at "\\<_begin\\_>")))
(throw 'finished (list 'in-block 'exception))))))
(defun sqlind-maybe-$$-statement ()
"If (point) is on a PostgreSQL $$ quote, report its syntax.
PostgreSQL uses $$ to delimit SQL blocks in create statements,
this function tries to determine if the $$ block is a begin or an
end block and creates the appropiate syntactic context.
See also `sqlind-beginning-of-block'"
(when (looking-at "\\$\\$")
(prog1 t
(let* ((saved-pos (point)))
(ignore-errors (forward-char -1))
(sqlind-backward-syntactic-ws)
(cond ((looking-at ";")
;; Assume the $$ is ending a statement (previous line is a ';'
;; which ends another statement)
(push (list saved-pos '$$ "") sqlind-end-stmt-stack)
(goto-char saved-pos))
((progn (forward-word -1)
(looking-at "end"))
;; Assume the $$ is ending a statement (previous line contains
;; an "end" keyword)
(push (list saved-pos '$$ "") sqlind-end-stmt-stack)
(goto-char saved-pos))
((null sqlind-end-stmt-stack)
(sqlind-beginning-of-statement)
(let ((syntax (catch 'finished
(sqlind-maybe-create-statement)
(sqlind-maybe-defun-statement)
'toplevel)))
(if (and (listp syntax) (eq (nth 0 syntax) 'defun-start))
(throw 'finished (list 'in-begin-block 'defun (nth 1 syntax)))
(throw 'finished (list 'in-begin-block syntax nil)))))
(t
(sqlind-beginning-of-statement)
(cl-destructuring-bind (pos kind _label) (pop sqlind-end-stmt-stack)
(unless (eq kind '$$)
(throw 'finished
(list 'syntax-error "bad closing for $$ begin block" (point) pos))))))))))
(defconst sqlind-start-block-regexp
(concat "\\(\\_<"
(regexp-opt '("if" "then" "else" "elsif" "elseif" "loop"
"begin" "declare" "create" "alter" "exception"
"procedure" "function" "end" "case") t)
"\\_>\\)\\|)\\|\\$\\$")
"Regexp to match the start of a block.")
(defun sqlind-beginning-of-block (&optional end-statement-stack)
"Find the start of the current block and return its syntax.
END-STATEMENT-STACK contains a list of \"end\" syntaxes in
reverse order (a stack) and is used to skip over nested blocks."
(interactive)
;; This function works as follows: `sqlind-start-block-regexp` defines the
;; keywords where it stops to inspect the code. Each time it stops at one
;; of these keywords, it checks to see if the keyword is inside a comment or
;; string. If the keyworkd is not inside a comment or string, the
;; `sqlind-maybe-*` functions are called to check if the keyword is valid.
;; Each of these functions will do one of the following:
;;
;; * throw a syntax object with a 'finished tag, if they decide that the
;; keyword is valid
;;
;; * return t to indicate that they decided that the keyword is not valid
;; and `sqlind-beginning-of-block` should search for the next keyword
;;
;; * return nil to indicate that they don't recognize the keyword and
;; another `sqlind-maybe-*` function should be called
;;
;; Some of these `sqlind-maybe-*` functions are specific to the
;; `sql-product` and are only invoked for the speficied SQL dialect.
(catch 'finished
(let ((sqlind-end-stmt-stack end-statement-stack))
(while (re-search-backward sqlind-start-block-regexp sqlind-search-limit 'noerror)
(or (sqlind-in-comment-or-string (point))
(when (looking-at ")") (forward-char 1) (forward-sexp -1) t)
(sqlind-maybe-end-statement)
(sqlind-maybe-if-statement)
(sqlind-maybe-case-statement)
(sqlind-maybe-then-statement)
(sqlind-maybe-exception-statement)
(sqlind-maybe-else-statement)
(sqlind-maybe-loop-statement)
(sqlind-maybe-begin-statement)
(when (memq sql-product '(oracle postgres))
;; declare statements only start blocks in PL/SQL and PostgresSQL
(sqlind-maybe-declare-statement))
(when (eq sql-product 'postgres)
(sqlind-maybe-$$-statement))
(sqlind-maybe-create-statement)
(sqlind-maybe-defun-statement))))
'toplevel))
;;;;; Determine the syntax inside a case expression
(defconst sqlind-case-clauses-regexp
"\\_<\\(when\\|then\\|else\\|end\\)\\_>")
(defun sqlind-syntax-in-case (pos start)
"Return the syntax at POS which is part a \"case\" expression at START."
(save-excursion
(goto-char pos)
(cond ((looking-at "when\\|else")
;; A WHEN, or ELSE clause is indented relative to the start of the
;; case expression
(cons 'case-clause start))
((looking-at "end")
(cons (list 'block-end 'case "") start))
((looking-at "then")
;; THEN and ELSE clauses are indented relative to the start of the
;; when clause, which we must find
(while (not (and (re-search-backward "\\_<when\\_>")