* lisp/play/bubbles.el: Use lexical-binding
[emacs.git] / lisp / progmodes / sql.el
blobba180c2b26c8f0e1bd088fe983717330608f93a6
1 ;;; sql.el --- specialized comint.el for SQL interpreters -*- lexical-binding: t -*-
3 ;; Copyright (C) 1998-2018 Free Software Foundation, Inc.
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Maintainer: Michael Mauger <michael@mauger.com>
7 ;; Version: 3.6
8 ;; Keywords: comm languages processes
9 ;; URL: https://savannah.gnu.org/projects/emacs/
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Please send bug reports and bug fixes to the mailing list at
29 ;; bug-gnu-emacs@gnu.org.
30 ;; See also the general help list at
31 ;; https://lists.gnu.org/mailman/listinfo/help-gnu-emacs
32 ;; I monitor this list actively. If you send an e-mail
33 ;; to Alex Schroeder it usually makes it to me when Alex has a chance
34 ;; to forward them along (Thanks, Alex).
36 ;; This file provides a sql-mode and a sql-interactive-mode. The
37 ;; original goals were two simple modes providing syntactic
38 ;; highlighting. The interactive mode had to provide a command-line
39 ;; history; the other mode had to provide "send region/buffer to SQL
40 ;; interpreter" functions. "simple" in this context means easy to
41 ;; use, easy to maintain and little or no bells and whistles. This
42 ;; has changed somewhat as experience with the mode has accumulated.
44 ;; Support for different flavors of SQL and command interpreters was
45 ;; available in early versions of sql.el. This support has been
46 ;; extended and formalized in later versions. Part of the impetus for
47 ;; the improved support of SQL flavors was borne out of the current
48 ;; maintainers consulting experience. In the past twenty years, I
49 ;; have used Oracle, Sybase, Informix, MySQL, Postgres, and SQLServer.
50 ;; On some assignments, I have used two or more of these concurrently.
52 ;; If anybody feels like extending this sql mode, take a look at the
53 ;; above mentioned modes and write a sqlx-mode on top of this one. If
54 ;; this proves to be difficult, please suggest changes that will
55 ;; facilitate your plans. Facilities have been provided to add
56 ;; products and product-specific configuration.
58 ;; sql-interactive-mode is used to interact with a SQL interpreter
59 ;; process in a SQLi buffer (usually called `*SQL*'). The SQLi buffer
60 ;; is created by calling a SQL interpreter-specific entry function or
61 ;; sql-product-interactive. Do *not* call sql-interactive-mode by
62 ;; itself.
64 ;; The list of currently supported interpreters and the corresponding
65 ;; entry function used to create the SQLi buffers is shown with
66 ;; `sql-help' (M-x sql-help).
68 ;; Since sql-interactive-mode is built on top of the general
69 ;; command-interpreter-in-a-buffer mode (comint mode), it shares a
70 ;; common base functionality, and a common set of bindings, with all
71 ;; modes derived from comint mode. This makes these modes easier to
72 ;; use.
74 ;; sql-mode can be used to keep editing SQL statements. The SQL
75 ;; statements can be sent to the SQL process in the SQLi buffer.
77 ;; For documentation on the functionality provided by comint mode, and
78 ;; the hooks available for customizing it, see the file `comint.el'.
80 ;; Hint for newbies: take a look at `dabbrev-expand', `abbrev-mode', and
81 ;; `imenu-add-menubar-index'.
83 ;;; Bugs:
85 ;; sql-ms now uses osql instead of isql. Osql flushes its error
86 ;; stream more frequently than isql so that error messages are
87 ;; available. There is no prompt and some output still is buffered.
88 ;; This improves the interaction under Emacs but it still is somewhat
89 ;; awkward.
91 ;; Quoted identifiers are not supported for highlighting. Most
92 ;; databases support the use of double quoted strings in place of
93 ;; identifiers; ms (Microsoft SQLServer) also supports identifiers
94 ;; enclosed within brackets [].
96 ;;; Product Support:
98 ;; To add support for additional SQL products the following steps
99 ;; must be followed ("xyz" is the name of the product in the examples
100 ;; below):
102 ;; 1) Add the product to the list of known products.
104 ;; (sql-add-product 'xyz "XyzDB"
105 ;; '(:free-software t))
107 ;; 2) Define font lock settings. All ANSI keywords will be
108 ;; highlighted automatically, so only product specific keywords
109 ;; need to be defined here.
111 ;; (defvar my-sql-mode-xyz-font-lock-keywords
112 ;; '(("\\b\\(red\\|orange\\|yellow\\)\\b"
113 ;; . font-lock-keyword-face))
114 ;; "XyzDB SQL keywords used by font-lock.")
116 ;; (sql-set-product-feature 'xyz
117 ;; :font-lock
118 ;; 'my-sql-mode-xyz-font-lock-keywords)
120 ;; 3) Define any special syntax characters including comments and
121 ;; identifier characters.
123 ;; (sql-set-product-feature 'xyz
124 ;; :syntax-alist ((?# . "_")))
126 ;; 4) Define the interactive command interpreter for the database
127 ;; product.
129 ;; (defcustom my-sql-xyz-program "ixyz"
130 ;; "Command to start ixyz by XyzDB."
131 ;; :type 'file
132 ;; :group 'SQL)
134 ;; (sql-set-product-feature 'xyz
135 ;; :sqli-program 'my-sql-xyz-program)
136 ;; (sql-set-product-feature 'xyz
137 ;; :prompt-regexp "^xyzdb> ")
138 ;; (sql-set-product-feature 'xyz
139 ;; :prompt-length 7)
141 ;; 5) Define login parameters and command line formatting.
143 ;; (defcustom my-sql-xyz-login-params '(user password server database)
144 ;; "Login parameters to needed to connect to XyzDB."
145 ;; :type 'sql-login-params
146 ;; :group 'SQL)
148 ;; (sql-set-product-feature 'xyz
149 ;; :sqli-login 'my-sql-xyz-login-params)
151 ;; (defcustom my-sql-xyz-options '("-X" "-Y" "-Z")
152 ;; "List of additional options for `sql-xyz-program'."
153 ;; :type '(repeat string)
154 ;; :group 'SQL)
156 ;; (sql-set-product-feature 'xyz
157 ;; :sqli-options 'my-sql-xyz-options))
159 ;; (defun my-sql-comint-xyz (product options &optional buf-name)
160 ;; "Connect ti XyzDB in a comint buffer."
162 ;; ;; Do something with `sql-user', `sql-password',
163 ;; ;; `sql-database', and `sql-server'.
164 ;; (let ((params
165 ;; (append
166 ;; (if (not (string= "" sql-user))
167 ;; (list "-U" sql-user))
168 ;; (if (not (string= "" sql-password))
169 ;; (list "-P" sql-password))
170 ;; (if (not (string= "" sql-database))
171 ;; (list "-D" sql-database))
172 ;; (if (not (string= "" sql-server))
173 ;; (list "-S" sql-server))
174 ;; options)))
175 ;; (sql-comint product params buf-name)))
177 ;; (sql-set-product-feature 'xyz
178 ;; :sqli-comint-func 'my-sql-comint-xyz)
180 ;; 6) Define a convenience function to invoke the SQL interpreter.
182 ;; (defun my-sql-xyz (&optional buffer)
183 ;; "Run ixyz by XyzDB as an inferior process."
184 ;; (interactive "P")
185 ;; (sql-product-interactive 'xyz buffer))
187 ;;; To Do:
189 ;; Improve keyword highlighting for individual products. I have tried
190 ;; to update those database that I use. Feel free to send me updates,
191 ;; or direct me to the reference manuals for your favorite database.
193 ;; When there are no keywords defined, the ANSI keywords are
194 ;; highlighted. ANSI keywords are highlighted even if the keyword is
195 ;; not used for your current product. This should help identify
196 ;; portability concerns.
198 ;; Add different highlighting levels.
200 ;; Add support for listing available tables or the columns in a table.
202 ;;; Thanks to all the people who helped me out:
204 ;; Alex Schroeder <alex@gnu.org> -- the original author
205 ;; Kai Blauberg <kai.blauberg@metla.fi>
206 ;; <ibalaban@dalet.com>
207 ;; Yair Friedman <yfriedma@JohnBryce.Co.Il>
208 ;; Gregor Zych <zych@pool.informatik.rwth-aachen.de>
209 ;; nino <nino@inform.dk>
210 ;; Berend de Boer <berend@pobox.com>
211 ;; Adam Jenkins <adam@thejenkins.org>
212 ;; Michael Mauger <michael@mauger.com> -- improved product support
213 ;; Drew Adams <drew.adams@oracle.com> -- Emacs 20 support
214 ;; Harald Maier <maierh@myself.com> -- sql-send-string
215 ;; Stefan Monnier <monnier@iro.umontreal.ca> -- font-lock corrections;
216 ;; code polish
217 ;; Paul Sleigh <bat@flurf.net> -- MySQL keyword enhancement
218 ;; Andrew Schein <andrew@andrewschein.com> -- sql-port bug
219 ;; Ian Bjorhovde <idbjorh@dataproxy.com> -- db2 escape newlines
220 ;; incorrectly enabled by default
221 ;; Roman Scherer <roman.scherer@nugg.ad> -- Connection documentation
222 ;; Mark Wilkinson <wilkinsonmr@gmail.com> -- file-local variables ignored
223 ;; Simen Heggestøyl <simenheg@gmail.com> -- Postgres database completion
224 ;; Robert Cochran <robert-emacs@cochranmail.com> -- MariaDB support
229 ;;; Code:
231 (require 'cl-lib)
232 (require 'comint)
233 ;; Need the following to allow GNU Emacs 19 to compile the file.
234 (eval-when-compile
235 (require 'regexp-opt))
236 (require 'custom)
237 (require 'thingatpt)
238 (require 'view)
240 (defvar font-lock-keyword-face)
241 (defvar font-lock-set-defaults)
242 (defvar font-lock-string-face)
244 ;;; Allow customization
246 (defgroup SQL nil
247 "Running a SQL interpreter from within Emacs buffers."
248 :version "20.4"
249 :group 'languages
250 :group 'processes)
252 ;; These five variables will be used as defaults, if set.
254 (defcustom sql-user ""
255 "Default username."
256 :type 'string
257 :group 'SQL
258 :safe 'stringp)
260 (defcustom sql-password ""
261 "Default password.
262 If you customize this, the value will be stored in your init
263 file. Since that is a plaintext file, this could be dangerous."
264 :type 'string
265 :group 'SQL
266 :risky t)
268 (defcustom sql-database ""
269 "Default database."
270 :type 'string
271 :group 'SQL
272 :safe 'stringp)
274 (defcustom sql-server ""
275 "Default server or host."
276 :type 'string
277 :group 'SQL
278 :safe 'stringp)
280 (defcustom sql-port 0
281 "Default port for connecting to a MySQL or Postgres server."
282 :version "24.1"
283 :type 'number
284 :group 'SQL
285 :safe 'numberp)
287 (defcustom sql-default-directory nil
288 "Default directory for SQL processes."
289 :version "25.1"
290 :type '(choice (const nil) string)
291 :group 'SQL
292 :safe 'stringp)
294 ;; Login parameter type
296 ;; This seems too prescriptive. It probably fails to match some of
297 ;; the possible combinations. It would probably be better to just use
298 ;; plist for most of it.
299 (define-widget 'sql-login-params 'lazy
300 "Widget definition of the login parameters list"
301 :tag "Login Parameters"
302 :type '(set :tag "Login Parameters"
303 (choice :tag "user"
304 :value user
305 (const user)
306 (list :tag "Specify a default"
307 (const user)
308 (list :tag "Default"
309 :inline t (const :default) string)))
310 (const password)
311 (choice :tag "server"
312 :value server
313 (const server)
314 (list :tag "Specify a default"
315 (const server)
316 (list :tag "Default"
317 :inline t (const :default) string))
318 (list :tag "file"
319 (const :format "" server)
320 (const :format "" :file)
321 regexp)
322 (list :tag "completion"
323 (const :format "" server)
324 (const :format "" :completion)
325 (const :format "" :must-match)
326 (restricted-sexp
327 :match-alternatives (listp stringp))))
328 (choice :tag "database"
329 :value database
330 (const database)
331 (list :tag "Specify a default"
332 (const database)
333 (list :tag "Default"
334 :inline t (const :default) string))
335 (list :tag "file"
336 (const :format "" database)
337 (const :format "" :file)
338 (choice (const nil) regexp)
339 (const :format "" :must-match)
340 (symbol :tag ":must-match"))
341 (list :tag "completion"
342 (const :format "" database)
343 (const :format "" :default)
344 (string :tag ":default")
345 (const :format "" :completion)
346 (sexp :tag ":completion")
347 (const :format "" :must-match)
348 (restricted-sexp
349 :match-alternatives (listp stringp))))
350 (const port)))
352 ;; SQL Product support
354 (defvar sql-interactive-product nil
355 "Product under `sql-interactive-mode'.")
357 (defvar sql-connection nil
358 "Connection name if interactive session started by `sql-connect'.")
360 (defvar sql-product-alist
361 '((ansi
362 :name "ANSI"
363 :font-lock sql-mode-ansi-font-lock-keywords
364 :statement sql-ansi-statement-starters)
366 (db2
367 :name "DB2"
368 :font-lock sql-mode-db2-font-lock-keywords
369 :sqli-program sql-db2-program
370 :sqli-options sql-db2-options
371 :sqli-login sql-db2-login-params
372 :sqli-comint-func sql-comint-db2
373 :prompt-regexp "^db2 => "
374 :prompt-length 7
375 :prompt-cont-regexp "^db2 (cont\\.) => "
376 :input-filter sql-escape-newlines-filter)
378 (informix
379 :name "Informix"
380 :font-lock sql-mode-informix-font-lock-keywords
381 :sqli-program sql-informix-program
382 :sqli-options sql-informix-options
383 :sqli-login sql-informix-login-params
384 :sqli-comint-func sql-comint-informix
385 :prompt-regexp "^> "
386 :prompt-length 2
387 :syntax-alist ((?{ . "<") (?} . ">")))
389 (ingres
390 :name "Ingres"
391 :font-lock sql-mode-ingres-font-lock-keywords
392 :sqli-program sql-ingres-program
393 :sqli-options sql-ingres-options
394 :sqli-login sql-ingres-login-params
395 :sqli-comint-func sql-comint-ingres
396 :prompt-regexp "^\\* "
397 :prompt-length 2
398 :prompt-cont-regexp "^\\* ")
400 (interbase
401 :name "Interbase"
402 :font-lock sql-mode-interbase-font-lock-keywords
403 :sqli-program sql-interbase-program
404 :sqli-options sql-interbase-options
405 :sqli-login sql-interbase-login-params
406 :sqli-comint-func sql-comint-interbase
407 :prompt-regexp "^SQL> "
408 :prompt-length 5)
410 (linter
411 :name "Linter"
412 :font-lock sql-mode-linter-font-lock-keywords
413 :sqli-program sql-linter-program
414 :sqli-options sql-linter-options
415 :sqli-login sql-linter-login-params
416 :sqli-comint-func sql-comint-linter
417 :prompt-regexp "^SQL>"
418 :prompt-length 4)
420 (mariadb
421 :name "MariaDB"
422 :free-software t
423 :font-lock sql-mode-mariadb-font-lock-keywords
424 :sqli-program sql-mariadb-program
425 :sqli-options sql-mariadb-options
426 :sqli-login sql-mariadb-login-params
427 :sqli-comint-func sql-comint-mariadb
428 :list-all "SHOW TABLES;"
429 :list-table "DESCRIBE %s;"
430 :prompt-regexp "^MariaDB \\[.*]> "
431 :prompt-cont-regexp "^ [\"'`-]> "
432 :syntax-alist ((?# . "< b"))
433 :input-filter sql-remove-tabs-filter)
436 :name "Microsoft"
437 :font-lock sql-mode-ms-font-lock-keywords
438 :sqli-program sql-ms-program
439 :sqli-options sql-ms-options
440 :sqli-login sql-ms-login-params
441 :sqli-comint-func sql-comint-ms
442 :prompt-regexp "^[0-9]*>"
443 :prompt-length 5
444 :syntax-alist ((?@ . "_"))
445 :terminator ("^go" . "go"))
447 (mysql
448 :name "MySQL"
449 :free-software t
450 :font-lock sql-mode-mysql-font-lock-keywords
451 :sqli-program sql-mysql-program
452 :sqli-options sql-mysql-options
453 :sqli-login sql-mysql-login-params
454 :sqli-comint-func sql-comint-mysql
455 :list-all "SHOW TABLES;"
456 :list-table "DESCRIBE %s;"
457 :prompt-regexp "^mysql> "
458 :prompt-length 6
459 :prompt-cont-regexp "^ -> "
460 :syntax-alist ((?# . "< b"))
461 :input-filter sql-remove-tabs-filter)
463 (oracle
464 :name "Oracle"
465 :font-lock sql-mode-oracle-font-lock-keywords
466 :sqli-program sql-oracle-program
467 :sqli-options sql-oracle-options
468 :sqli-login sql-oracle-login-params
469 :sqli-comint-func sql-comint-oracle
470 :list-all sql-oracle-list-all
471 :list-table sql-oracle-list-table
472 :completion-object sql-oracle-completion-object
473 :prompt-regexp "^SQL> "
474 :prompt-length 5
475 :prompt-cont-regexp "^\\(?:[ ][ ][1-9]\\|[ ][1-9][0-9]\\|[1-9][0-9]\\{2\\}\\)[ ]\\{2\\}"
476 :statement sql-oracle-statement-starters
477 :syntax-alist ((?$ . "_") (?# . "_"))
478 :terminator ("\\(^/\\|;\\)$" . "/")
479 :input-filter sql-placeholders-filter)
481 (postgres
482 :name "Postgres"
483 :free-software t
484 :font-lock sql-mode-postgres-font-lock-keywords
485 :sqli-program sql-postgres-program
486 :sqli-options sql-postgres-options
487 :sqli-login sql-postgres-login-params
488 :sqli-comint-func sql-comint-postgres
489 :list-all ("\\d+" . "\\dS+")
490 :list-table ("\\d+ %s" . "\\dS+ %s")
491 :completion-object sql-postgres-completion-object
492 :prompt-regexp "^[[:alnum:]_]*=[#>] "
493 :prompt-length 5
494 :prompt-cont-regexp "^[[:alnum:]_]*[-(][#>] "
495 :input-filter sql-remove-tabs-filter
496 :terminator ("\\(^\\s-*\\\\g$\\|;\\)" . "\\g"))
498 (solid
499 :name "Solid"
500 :font-lock sql-mode-solid-font-lock-keywords
501 :sqli-program sql-solid-program
502 :sqli-options sql-solid-options
503 :sqli-login sql-solid-login-params
504 :sqli-comint-func sql-comint-solid
505 :prompt-regexp "^"
506 :prompt-length 0)
508 (sqlite
509 :name "SQLite"
510 :free-software t
511 :font-lock sql-mode-sqlite-font-lock-keywords
512 :sqli-program sql-sqlite-program
513 :sqli-options sql-sqlite-options
514 :sqli-login sql-sqlite-login-params
515 :sqli-comint-func sql-comint-sqlite
516 :list-all ".tables"
517 :list-table ".schema %s"
518 :completion-object sql-sqlite-completion-object
519 :prompt-regexp "^sqlite> "
520 :prompt-length 8
521 :prompt-cont-regexp "^ \\.\\.\\.> "
522 :terminator ";")
524 (sybase
525 :name "Sybase"
526 :font-lock sql-mode-sybase-font-lock-keywords
527 :sqli-program sql-sybase-program
528 :sqli-options sql-sybase-options
529 :sqli-login sql-sybase-login-params
530 :sqli-comint-func sql-comint-sybase
531 :prompt-regexp "^SQL> "
532 :prompt-length 5
533 :syntax-alist ((?@ . "_"))
534 :terminator ("^go" . "go"))
536 (vertica
537 :name "Vertica"
538 :sqli-program sql-vertica-program
539 :sqli-options sql-vertica-options
540 :sqli-login sql-vertica-login-params
541 :sqli-comint-func sql-comint-vertica
542 :list-all ("\\d" . "\\dS")
543 :list-table "\\d %s"
544 :prompt-regexp "^[[:alnum:]_]*=[#>] "
545 :prompt-length 5
546 :prompt-cont-regexp "^[[:alnum:]_]*[-(][#>] ")
548 "An alist of product specific configuration settings.
550 Without an entry in this list a product will not be properly
551 highlighted and will not support `sql-interactive-mode'.
553 Each element in the list is in the following format:
555 (PRODUCT FEATURE VALUE ...)
557 where PRODUCT is the appropriate value of `sql-product'. The
558 product name is then followed by FEATURE-VALUE pairs. If a
559 FEATURE is not specified, its VALUE is treated as nil. FEATURE
560 may be any one of the following:
562 :name string containing the displayable name of
563 the product.
565 :free-software is the product Free (as in Freedom) software?
567 :font-lock name of the variable containing the product
568 specific font lock highlighting patterns.
570 :sqli-program name of the variable containing the product
571 specific interactive program name.
573 :sqli-options name of the variable containing the list
574 of product specific options.
576 :sqli-login name of the variable containing the list of
577 login parameters (i.e., user, password,
578 database and server) needed to connect to
579 the database.
581 :sqli-comint-func function of two arguments, PRODUCT
582 and OPTIONS, that will open a comint buffer
583 and connect to the database. PRODUCT is the
584 first argument to be passed to `sql-comint',
585 and OPTIONS should be included in its second
586 argument. The function should use the values
587 of `sql-user', `sql-password', `sql-database',
588 `sql-server' and `sql-port' to . Do product
589 specific configuration of comint in this
590 function. See `sql-comint-oracle' for an
591 example of such a function.
593 :list-all Command string or function which produces
594 a listing of all objects in the database.
595 If it's a cons cell, then the car
596 produces the standard list of objects and
597 the cdr produces an enhanced list of
598 objects. What \"enhanced\" means is
599 dependent on the SQL product and may not
600 exist. In general though, the
601 \"enhanced\" list should include visible
602 objects from other schemas.
604 :list-table Command string or function which produces
605 a detailed listing of a specific database
606 table. If its a cons cell, then the car
607 produces the standard list and the cdr
608 produces an enhanced list.
610 :completion-object A function that returns a list of
611 objects. Called with a single
612 parameter--if nil then list objects
613 accessible in the current schema, if
614 not-nil it is the name of a schema whose
615 objects should be listed.
617 :completion-column A function that returns a list of
618 columns. Called with a single
619 parameter--if nil then list objects
620 accessible in the current schema, if
621 not-nil it is the name of a schema whose
622 objects should be listed.
624 :prompt-regexp regular expression string that matches
625 the prompt issued by the product
626 interpreter.
628 :prompt-length length of the prompt on the line.
630 :prompt-cont-regexp regular expression string that matches
631 the continuation prompt issued by the
632 product interpreter.
634 :input-filter function which can filter strings sent to
635 the command interpreter. It is also used
636 by the `sql-send-string',
637 `sql-send-region', `sql-send-paragraph'
638 and `sql-send-buffer' functions. The
639 function is passed the string sent to the
640 command interpreter and must return the
641 filtered string. May also be a list of
642 such functions.
644 :statement name of a variable containing a regexp that
645 matches the beginning of SQL statements.
647 :terminator the terminator to be sent after a
648 `sql-send-string', `sql-send-region',
649 `sql-send-paragraph' and
650 `sql-send-buffer' command. May be the
651 literal string or a cons of a regexp to
652 match an existing terminator in the
653 string and the terminator to be used if
654 its absent. By default \";\".
656 :syntax-alist alist of syntax table entries to enable
657 special character treatment by font-lock
658 and imenu.
660 Other features can be stored but they will be ignored. However,
661 you can develop new functionality which is product independent by
662 using `sql-get-product-feature' to lookup the product specific
663 settings.")
665 (defvar sql-indirect-features
666 '(:font-lock :sqli-program :sqli-options :sqli-login :statement))
668 (defcustom sql-connection-alist nil
669 "An alist of connection parameters for interacting with a SQL product.
670 Each element of the alist is as follows:
672 (CONNECTION \(SQL-VARIABLE VALUE) ...)
674 Where CONNECTION is a case-insensitive string identifying the
675 connection, SQL-VARIABLE is the symbol name of a SQL mode
676 variable, and VALUE is the value to be assigned to the variable.
677 The most common SQL-VARIABLE settings associated with a
678 connection are: `sql-product', `sql-user', `sql-password',
679 `sql-port', `sql-server', and `sql-database'.
681 If a SQL-VARIABLE is part of the connection, it will not be
682 prompted for during login. The command `sql-connect' starts a
683 predefined SQLi session using the parameters from this list.
684 Connections defined here appear in the submenu SQL->Start... for
685 making new SQLi sessions."
686 :type `(alist :key-type (string :tag "Connection")
687 :value-type
688 (set
689 (group (const :tag "Product" sql-product)
690 (choice
691 ,@(mapcar
692 (lambda (prod-info)
693 `(const :tag
694 ,(or (plist-get (cdr prod-info) :name)
695 (capitalize
696 (symbol-name (car prod-info))))
697 (quote ,(car prod-info))))
698 sql-product-alist)))
699 (group (const :tag "Username" sql-user) string)
700 (group (const :tag "Password" sql-password) string)
701 (group (const :tag "Server" sql-server) string)
702 (group (const :tag "Database" sql-database) string)
703 (group (const :tag "Port" sql-port) integer)
704 (repeat :inline t
705 (list :tab "Other"
706 (symbol :tag " Variable Symbol")
707 (sexp :tag "Value Expression")))))
708 :version "24.1"
709 :group 'SQL)
711 (defvaralias 'sql-dialect 'sql-product)
713 (defcustom sql-product 'ansi
714 "Select the SQL database product used.
715 This allows highlighting buffers properly when you open them."
716 :type `(choice
717 ,@(mapcar (lambda (prod-info)
718 `(const :tag
719 ,(or (plist-get (cdr prod-info) :name)
720 (capitalize (symbol-name (car prod-info))))
721 ,(car prod-info)))
722 sql-product-alist))
723 :group 'SQL
724 :safe 'symbolp)
726 ;; misc customization of sql.el behavior
728 (defcustom sql-electric-stuff nil
729 "Treat some input as electric.
730 If set to the symbol `semicolon', then hitting `;' will send current
731 input in the SQLi buffer to the process.
732 If set to the symbol `go', then hitting `go' on a line by itself will
733 send current input in the SQLi buffer to the process.
734 If set to nil, then you must use \\[comint-send-input] in order to send
735 current input in the SQLi buffer to the process."
736 :type '(choice (const :tag "Nothing" nil)
737 (const :tag "The semicolon `;'" semicolon)
738 (const :tag "The string `go' by itself" go))
739 :version "20.8"
740 :group 'SQL)
742 (defcustom sql-send-terminator nil
743 "When non-nil, add a terminator to text sent to the SQL interpreter.
745 When text is sent to the SQL interpreter (via `sql-send-string',
746 `sql-send-region', `sql-send-paragraph' or `sql-send-buffer'), a
747 command terminator can be automatically sent as well. The
748 terminator is not sent, if the string sent already ends with the
749 terminator.
751 If this value is t, then the default command terminator for the
752 SQL interpreter is sent. If this value is a string, then the
753 string is sent.
755 If the value is a cons cell of the form (PAT . TERM), then PAT is
756 a regexp used to match the terminator in the string and TERM is
757 the terminator to be sent. This form is useful if the SQL
758 interpreter has more than one way of submitting a SQL command.
759 The PAT regexp can match any of them, and TERM is the way we do
760 it automatically."
762 :type '(choice (const :tag "No Terminator" nil)
763 (const :tag "Default Terminator" t)
764 (string :tag "Terminator String")
765 (cons :tag "Terminator Pattern and String"
766 (string :tag "Terminator Pattern")
767 (string :tag "Terminator String")))
768 :version "22.2"
769 :group 'SQL)
771 (defvar sql-contains-names nil
772 "When non-nil, the current buffer contains database names.
774 Globally should be set to nil; it will be non-nil in `sql-mode',
775 `sql-interactive-mode' and list all buffers.")
777 (defvar sql-login-delay 7.5 ;; Secs
778 "Maximum number of seconds you are willing to wait for a login connection.")
780 (defvaralias 'sql-pop-to-buffer-after-send-region 'sql-display-sqli-buffer-function)
782 (defcustom sql-display-sqli-buffer-function 'display-buffer
783 "Function to be called to display a SQLi buffer after `sql-send-*'.
785 When set to a function, it will be called to display the buffer.
786 When set to t, the default function `pop-to-buffer' will be
787 called. If not set, no attempt will be made to display the
788 buffer."
790 :type '(choice (const :tag "Default" t)
791 (const :tag "No display" nil)
792 (function :tag "Display Buffer function"))
793 :version "27.1"
794 :group 'SQL)
796 ;; imenu support for sql-mode.
798 (defvar sql-imenu-generic-expression
799 ;; Items are in reverse order because they are rendered in reverse.
800 '(("Rules/Defaults" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*\\(?:rule\\|default\\)\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\s-+\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
801 ("Sequences" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*sequence\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
802 ("Triggers" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*trigger\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
803 ("Functions" "^\\s-*\\(?:create\\s-+\\(?:\\w+\\s-+\\)*\\)?function\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
804 ("Procedures" "^\\s-*\\(?:create\\s-+\\(?:\\w+\\s-+\\)*\\)?proc\\(?:edure\\)?\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
805 ("Packages" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*package\\s-+\\(?:body\\s-+\\)?\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
806 ("Types" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*type\\s-+\\(?:body\\s-+\\)?\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
807 ("Indexes" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*index\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
808 ("Tables/Views" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*\\(?:table\\|view\\)\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1))
809 "Define interesting points in the SQL buffer for `imenu'.
811 This is used to set `imenu-generic-expression' when SQL mode is
812 entered. Subsequent changes to `sql-imenu-generic-expression' will
813 not affect existing SQL buffers because `imenu-generic-expression' is
814 a local variable.")
816 ;; history file
818 (defcustom sql-input-ring-file-name nil
819 "If non-nil, name of the file to read/write input history.
821 You have to set this variable if you want the history of your commands
822 saved from one Emacs session to the next. If this variable is set,
823 exiting the SQL interpreter in an SQLi buffer will write the input
824 history to the specified file. Starting a new process in a SQLi buffer
825 will read the input history from the specified file.
827 This is used to initialize `comint-input-ring-file-name'.
829 Note that the size of the input history is determined by the variable
830 `comint-input-ring-size'."
831 :type '(choice (const :tag "none" nil)
832 (file))
833 :group 'SQL)
835 (defcustom sql-input-ring-separator "\n--\n"
836 "Separator between commands in the history file.
838 If set to \"\\n\", each line in the history file will be interpreted as
839 one command. Multi-line commands are split into several commands when
840 the input ring is initialized from a history file.
842 This variable used to initialize `comint-input-ring-separator'.
843 `comint-input-ring-separator' is part of Emacs 21; if your Emacs
844 does not have it, setting `sql-input-ring-separator' will have no
845 effect. In that case multiline commands will be split into several
846 commands when the input history is read, as if you had set
847 `sql-input-ring-separator' to \"\\n\"."
848 :type 'string
849 :group 'SQL)
851 ;; The usual hooks
853 (defcustom sql-interactive-mode-hook '()
854 "Hook for customizing `sql-interactive-mode'."
855 :type 'hook
856 :group 'SQL)
858 (defcustom sql-mode-hook '()
859 "Hook for customizing `sql-mode'."
860 :type 'hook
861 :group 'SQL)
863 (defcustom sql-set-sqli-hook '()
864 "Hook for reacting to changes of `sql-buffer'.
866 This is called by `sql-set-sqli-buffer' when the value of `sql-buffer'
867 is changed."
868 :type 'hook
869 :group 'SQL)
871 (defcustom sql-login-hook '()
872 "Hook for interacting with a buffer in `sql-interactive-mode'.
874 This hook is invoked in a buffer once it is ready to accept input
875 for the first time."
876 :version "24.1"
877 :type 'hook
878 :group 'SQL)
880 ;; Customization for ANSI
882 (defcustom sql-ansi-statement-starters
883 (regexp-opt '("create" "alter" "drop"
884 "select" "insert" "update" "delete" "merge"
885 "grant" "revoke"))
886 "Regexp of keywords that start SQL commands.
888 All products share this list; products should define a regexp to
889 identify additional keywords in a variable defined by
890 the :statement feature."
891 :version "24.1"
892 :type 'string
893 :group 'SQL)
895 ;; Customization for Oracle
897 (defcustom sql-oracle-program "sqlplus"
898 "Command to start sqlplus by Oracle.
900 Starts `sql-interactive-mode' after doing some setup.
902 On Windows, \"sqlplus\" usually starts the sqlplus \"GUI\". In order
903 to start the sqlplus console, use \"plus33\" or something similar.
904 You will find the file in your Orant\\bin directory."
905 :type 'file
906 :group 'SQL)
908 (defcustom sql-oracle-options '("-L")
909 "List of additional options for `sql-oracle-program'."
910 :type '(repeat string)
911 :version "24.4"
912 :group 'SQL)
914 (defcustom sql-oracle-login-params '(user password database)
915 "List of login parameters needed to connect to Oracle."
916 :type 'sql-login-params
917 :version "24.1"
918 :group 'SQL)
920 (defcustom sql-oracle-statement-starters
921 (regexp-opt '("declare" "begin" "with"))
922 "Additional statement starting keywords in Oracle."
923 :version "24.1"
924 :type 'string
925 :group 'SQL)
927 (defcustom sql-oracle-scan-on t
928 "Non-nil if placeholders should be replaced in Oracle SQLi.
930 When non-nil, Emacs will scan text sent to sqlplus and prompt
931 for replacement text for & placeholders as sqlplus does. This
932 is needed on Windows where SQL*Plus output is buffered and the
933 prompts are not shown until after the text is entered.
935 You need to issue the following command in SQL*Plus to be safe:
937 SET DEFINE OFF
939 In older versions of SQL*Plus, this was the SET SCAN OFF command."
940 :version "24.1"
941 :type 'boolean
942 :group 'SQL)
944 (defcustom sql-db2-escape-newlines nil
945 "Non-nil if newlines should be escaped by a backslash in DB2 SQLi.
947 When non-nil, Emacs will automatically insert a space and
948 backslash prior to every newline in multi-line SQL statements as
949 they are submitted to an interactive DB2 session."
950 :version "24.3"
951 :type 'boolean
952 :group 'SQL)
954 ;; Customization for SQLite
956 (defcustom sql-sqlite-program (or (executable-find "sqlite3")
957 (executable-find "sqlite")
958 "sqlite")
959 "Command to start SQLite.
961 Starts `sql-interactive-mode' after doing some setup."
962 :type 'file
963 :group 'SQL)
965 (defcustom sql-sqlite-options nil
966 "List of additional options for `sql-sqlite-program'."
967 :type '(repeat string)
968 :version "20.8"
969 :group 'SQL)
971 (defcustom sql-sqlite-login-params '((database :file nil
972 :must-match confirm))
973 "List of login parameters needed to connect to SQLite."
974 :type 'sql-login-params
975 :version "26.1"
976 :group 'SQL)
978 ;; Customization for MariaDB
980 ;; MariaDB is a drop-in replacement for MySQL, so just make the
981 ;; MariaDB variables aliases of the MySQL ones.
983 (defvaralias 'sql-mariadb-program 'sql-mysql-program)
984 (defvaralias 'sql-mariadb-options 'sql-mysql-options)
985 (defvaralias 'sql-mariadb-login-params 'sql-mysql-login-params)
987 ;; Customization for MySQL
989 (defcustom sql-mysql-program "mysql"
990 "Command to start mysql by Oracle.
992 Starts `sql-interactive-mode' after doing some setup."
993 :type 'file
994 :group 'SQL)
996 (defcustom sql-mysql-options nil
997 "List of additional options for `sql-mysql-program'.
998 The following list of options is reported to make things work
999 on Windows: \"-C\" \"-t\" \"-f\" \"-n\"."
1000 :type '(repeat string)
1001 :version "20.8"
1002 :group 'SQL)
1004 (defcustom sql-mysql-login-params '(user password database server)
1005 "List of login parameters needed to connect to MySQL."
1006 :type 'sql-login-params
1007 :version "24.1"
1008 :group 'SQL)
1010 ;; Customization for Solid
1012 (defcustom sql-solid-program "solsql"
1013 "Command to start SOLID SQL Editor.
1015 Starts `sql-interactive-mode' after doing some setup."
1016 :type 'file
1017 :group 'SQL)
1019 (defcustom sql-solid-login-params '(user password server)
1020 "List of login parameters needed to connect to Solid."
1021 :type 'sql-login-params
1022 :version "24.1"
1023 :group 'SQL)
1025 ;; Customization for Sybase
1027 (defcustom sql-sybase-program "isql"
1028 "Command to start isql by Sybase.
1030 Starts `sql-interactive-mode' after doing some setup."
1031 :type 'file
1032 :group 'SQL)
1034 (defcustom sql-sybase-options nil
1035 "List of additional options for `sql-sybase-program'.
1036 Some versions of isql might require the -n option in order to work."
1037 :type '(repeat string)
1038 :version "20.8"
1039 :group 'SQL)
1041 (defcustom sql-sybase-login-params '(server user password database)
1042 "List of login parameters needed to connect to Sybase."
1043 :type 'sql-login-params
1044 :version "24.1"
1045 :group 'SQL)
1047 ;; Customization for Informix
1049 (defcustom sql-informix-program "dbaccess"
1050 "Command to start dbaccess by Informix.
1052 Starts `sql-interactive-mode' after doing some setup."
1053 :type 'file
1054 :group 'SQL)
1056 (defcustom sql-informix-login-params '(database)
1057 "List of login parameters needed to connect to Informix."
1058 :type 'sql-login-params
1059 :version "24.1"
1060 :group 'SQL)
1062 ;; Customization for Ingres
1064 (defcustom sql-ingres-program "sql"
1065 "Command to start sql by Ingres.
1067 Starts `sql-interactive-mode' after doing some setup."
1068 :type 'file
1069 :group 'SQL)
1071 (defcustom sql-ingres-login-params '(database)
1072 "List of login parameters needed to connect to Ingres."
1073 :type 'sql-login-params
1074 :version "24.1"
1075 :group 'SQL)
1077 ;; Customization for Microsoft
1079 (defcustom sql-ms-program "osql"
1080 "Command to start osql by Microsoft.
1082 Starts `sql-interactive-mode' after doing some setup."
1083 :type 'file
1084 :group 'SQL)
1086 (defcustom sql-ms-options '("-w" "300" "-n")
1087 ;; -w is the linesize
1088 "List of additional options for `sql-ms-program'."
1089 :type '(repeat string)
1090 :version "22.1"
1091 :group 'SQL)
1093 (defcustom sql-ms-login-params '(user password server database)
1094 "List of login parameters needed to connect to Microsoft."
1095 :type 'sql-login-params
1096 :version "24.1"
1097 :group 'SQL)
1099 ;; Customization for Postgres
1101 (defcustom sql-postgres-program "psql"
1102 "Command to start psql by Postgres.
1104 Starts `sql-interactive-mode' after doing some setup."
1105 :type 'file
1106 :group 'SQL)
1108 (defcustom sql-postgres-options '("-P" "pager=off")
1109 "List of additional options for `sql-postgres-program'.
1110 The default setting includes the -P option which breaks older versions
1111 of the psql client (such as version 6.5.3). The -P option is equivalent
1112 to the --pset option. If you want the psql to prompt you for a user
1113 name, add the string \"-u\" to the list of options. If you want to
1114 provide a user name on the command line (newer versions such as 7.1),
1115 add your name with a \"-U\" prefix (such as \"-Umark\") to the list."
1116 :type '(repeat string)
1117 :version "20.8"
1118 :group 'SQL)
1120 (defcustom sql-postgres-login-params
1121 `((user :default ,(user-login-name))
1122 (database :default ,(user-login-name)
1123 :completion ,(completion-table-dynamic
1124 (lambda (_) (sql-postgres-list-databases)))
1125 :must-match confirm)
1126 server)
1127 "List of login parameters needed to connect to Postgres."
1128 :type 'sql-login-params
1129 :version "26.1"
1130 :group 'SQL)
1132 (defun sql-postgres-list-databases ()
1133 "Return a list of available PostgreSQL databases."
1134 (when (executable-find sql-postgres-program)
1135 (let ((res '()))
1136 (ignore-errors
1137 (dolist (row (process-lines sql-postgres-program
1138 "--list"
1139 "--no-psqlrc"
1140 "--tuples-only"))
1141 (when (string-match "^ \\([^ |]+\\) +|.*" row)
1142 (push (match-string 1 row) res))))
1143 (nreverse res))))
1145 ;; Customization for Interbase
1147 (defcustom sql-interbase-program "isql"
1148 "Command to start isql by Interbase.
1150 Starts `sql-interactive-mode' after doing some setup."
1151 :type 'file
1152 :group 'SQL)
1154 (defcustom sql-interbase-options nil
1155 "List of additional options for `sql-interbase-program'."
1156 :type '(repeat string)
1157 :version "20.8"
1158 :group 'SQL)
1160 (defcustom sql-interbase-login-params '(user password database)
1161 "List of login parameters needed to connect to Interbase."
1162 :type 'sql-login-params
1163 :version "24.1"
1164 :group 'SQL)
1166 ;; Customization for DB2
1168 (defcustom sql-db2-program "db2"
1169 "Command to start db2 by IBM.
1171 Starts `sql-interactive-mode' after doing some setup."
1172 :type 'file
1173 :group 'SQL)
1175 (defcustom sql-db2-options nil
1176 "List of additional options for `sql-db2-program'."
1177 :type '(repeat string)
1178 :version "20.8"
1179 :group 'SQL)
1181 (defcustom sql-db2-login-params nil
1182 "List of login parameters needed to connect to DB2."
1183 :type 'sql-login-params
1184 :version "24.1"
1185 :group 'SQL)
1187 ;; Customization for Linter
1189 (defcustom sql-linter-program "inl"
1190 "Command to start inl by RELEX.
1192 Starts `sql-interactive-mode' after doing some setup."
1193 :type 'file
1194 :group 'SQL)
1196 (defcustom sql-linter-options nil
1197 "List of additional options for `sql-linter-program'."
1198 :type '(repeat string)
1199 :version "21.3"
1200 :group 'SQL)
1202 (defcustom sql-linter-login-params '(user password database server)
1203 "Login parameters to needed to connect to Linter."
1204 :type 'sql-login-params
1205 :version "24.1"
1206 :group 'SQL)
1210 ;;; Variables which do not need customization
1212 (defvar sql-user-history nil
1213 "History of usernames used.")
1215 (defvar sql-database-history nil
1216 "History of databases used.")
1218 (defvar sql-server-history nil
1219 "History of servers used.")
1221 ;; Passwords are not kept in a history.
1223 (defvar sql-product-history nil
1224 "History of products used.")
1226 (defvar sql-connection-history nil
1227 "History of connections used.")
1229 (defvar sql-buffer nil
1230 "Current SQLi buffer.
1232 The global value of `sql-buffer' is the name of the latest SQLi buffer
1233 created. Any SQL buffer created will make a local copy of this value.
1234 See `sql-interactive-mode' for more on multiple sessions. If you want
1235 to change the SQLi buffer a SQL mode sends its SQL strings to, change
1236 the local value of `sql-buffer' using \\[sql-set-sqli-buffer].")
1238 (defvar sql-prompt-regexp nil
1239 "Prompt used to initialize `comint-prompt-regexp'.
1241 You can change `sql-prompt-regexp' on `sql-interactive-mode-hook'.")
1243 (defvar sql-prompt-length 0
1244 "Prompt used to set `left-margin' in `sql-interactive-mode'.
1246 You can change `sql-prompt-length' on `sql-interactive-mode-hook'.")
1248 (defvar sql-prompt-cont-regexp nil
1249 "Prompt pattern of statement continuation prompts.")
1251 (defvar sql-alternate-buffer-name nil
1252 "Buffer-local string used to possibly rename the SQLi buffer.
1254 Used by `sql-rename-buffer'.")
1256 (defun sql-buffer-live-p (buffer &optional product connection)
1257 "Return non-nil if the process associated with buffer is live.
1259 BUFFER can be a buffer object or a buffer name. The buffer must
1260 be a live buffer, have a running process attached to it, be in
1261 `sql-interactive-mode', and, if PRODUCT or CONNECTION are
1262 specified, it's `sql-product' or `sql-connection' must match."
1264 (when buffer
1265 (setq buffer (get-buffer buffer))
1266 (and buffer
1267 (buffer-live-p buffer)
1268 (comint-check-proc buffer)
1269 (with-current-buffer buffer
1270 (and (derived-mode-p 'sql-interactive-mode)
1271 (or (not product)
1272 (eq product sql-product))
1273 (or (not connection)
1274 (and (stringp connection)
1275 (string= connection sql-connection))))))))
1277 ;; Keymap for sql-interactive-mode.
1279 (defvar sql-interactive-mode-map
1280 (let ((map (make-sparse-keymap)))
1281 (if (fboundp 'set-keymap-parent)
1282 (set-keymap-parent map comint-mode-map); Emacs
1283 (if (fboundp 'set-keymap-parents)
1284 (set-keymap-parents map (list comint-mode-map)))); XEmacs
1285 (if (fboundp 'set-keymap-name)
1286 (set-keymap-name map 'sql-interactive-mode-map)); XEmacs
1287 (define-key map (kbd "C-j") 'sql-accumulate-and-indent)
1288 (define-key map (kbd "C-c C-w") 'sql-copy-column)
1289 (define-key map (kbd "O") 'sql-magic-go)
1290 (define-key map (kbd "o") 'sql-magic-go)
1291 (define-key map (kbd ";") 'sql-magic-semicolon)
1292 (define-key map (kbd "C-c C-l a") 'sql-list-all)
1293 (define-key map (kbd "C-c C-l t") 'sql-list-table)
1294 map)
1295 "Mode map used for `sql-interactive-mode'.
1296 Based on `comint-mode-map'.")
1298 ;; Keymap for sql-mode.
1300 (defvar sql-mode-map
1301 (let ((map (make-sparse-keymap)))
1302 (define-key map (kbd "C-c C-c") 'sql-send-paragraph)
1303 (define-key map (kbd "C-c C-r") 'sql-send-region)
1304 (define-key map (kbd "C-c C-s") 'sql-send-string)
1305 (define-key map (kbd "C-c C-b") 'sql-send-buffer)
1306 (define-key map (kbd "C-c C-n") 'sql-send-line-and-next)
1307 (define-key map (kbd "C-c C-i") 'sql-product-interactive)
1308 (define-key map (kbd "C-c C-z") 'sql-show-sqli-buffer)
1309 (define-key map (kbd "C-c C-l a") 'sql-list-all)
1310 (define-key map (kbd "C-c C-l t") 'sql-list-table)
1311 (define-key map [remap beginning-of-defun] 'sql-beginning-of-statement)
1312 (define-key map [remap end-of-defun] 'sql-end-of-statement)
1313 map)
1314 "Mode map used for `sql-mode'.")
1316 ;; easy menu for sql-mode.
1318 (easy-menu-define
1319 sql-mode-menu sql-mode-map
1320 "Menu for `sql-mode'."
1321 `("SQL"
1322 ["Send Paragraph" sql-send-paragraph (sql-buffer-live-p sql-buffer)]
1323 ["Send Region" sql-send-region (and mark-active
1324 (sql-buffer-live-p sql-buffer))]
1325 ["Send Buffer" sql-send-buffer (sql-buffer-live-p sql-buffer)]
1326 ["Send String" sql-send-string (sql-buffer-live-p sql-buffer)]
1327 "--"
1328 ["List all objects" sql-list-all (and (sql-buffer-live-p sql-buffer)
1329 (sql-get-product-feature sql-product :list-all))]
1330 ["List table details" sql-list-table (and (sql-buffer-live-p sql-buffer)
1331 (sql-get-product-feature sql-product :list-table))]
1332 "--"
1333 ["Start SQLi session" sql-product-interactive
1334 :visible (not sql-connection-alist)
1335 :enable (sql-get-product-feature sql-product :sqli-comint-func)]
1336 ("Start..."
1337 :visible sql-connection-alist
1338 :filter sql-connection-menu-filter
1339 "--"
1340 ["New SQLi Session" sql-product-interactive (sql-get-product-feature sql-product :sqli-comint-func)])
1341 ["--"
1342 :visible sql-connection-alist]
1343 ["Show SQLi buffer" sql-show-sqli-buffer t]
1344 ["Set SQLi buffer" sql-set-sqli-buffer t]
1345 ["Pop to SQLi buffer after send"
1346 sql-toggle-pop-to-buffer-after-send-region
1347 :style toggle
1348 :selected sql-pop-to-buffer-after-send-region]
1349 ["--" nil nil]
1350 ("Product"
1351 ,@(mapcar (lambda (prod-info)
1352 (let* ((prod (pop prod-info))
1353 (name (or (plist-get prod-info :name)
1354 (capitalize (symbol-name prod))))
1355 (cmd (intern (format "sql-highlight-%s-keywords" prod))))
1356 (fset cmd `(lambda () ,(format "Highlight %s SQL keywords." name)
1357 (interactive)
1358 (sql-set-product ',prod)))
1359 (vector name cmd
1360 :style 'radio
1361 :selected `(eq sql-product ',prod))))
1362 sql-product-alist))))
1364 ;; easy menu for sql-interactive-mode.
1366 (easy-menu-define
1367 sql-interactive-mode-menu sql-interactive-mode-map
1368 "Menu for `sql-interactive-mode'."
1369 '("SQL"
1370 ["Rename Buffer" sql-rename-buffer t]
1371 ["Save Connection" sql-save-connection (not sql-connection)]
1372 "--"
1373 ["List all objects" sql-list-all (sql-get-product-feature sql-product :list-all)]
1374 ["List table details" sql-list-table (sql-get-product-feature sql-product :list-table)]))
1376 ;; Abbreviations -- if you want more of them, define them in your init
1377 ;; file. Abbrevs have to be enabled in your init file, too.
1379 (define-abbrev-table 'sql-mode-abbrev-table
1380 '(("ins" "insert" nil nil t)
1381 ("upd" "update" nil nil t)
1382 ("del" "delete" nil nil t)
1383 ("sel" "select" nil nil t)
1384 ("proc" "procedure" nil nil t)
1385 ("func" "function" nil nil t)
1386 ("cr" "create" nil nil t))
1387 "Abbrev table used in `sql-mode' and `sql-interactive-mode'.")
1389 ;; Syntax Table
1391 (defvar sql-mode-syntax-table
1392 (let ((table (make-syntax-table)))
1393 ;; C-style comments /**/ (see elisp manual "Syntax Flags"))
1394 (modify-syntax-entry ?/ ". 14" table)
1395 (modify-syntax-entry ?* ". 23" table)
1396 ;; double-dash starts comments
1397 (modify-syntax-entry ?- ". 12b" table)
1398 ;; newline and formfeed end comments
1399 (modify-syntax-entry ?\n "> b" table)
1400 (modify-syntax-entry ?\f "> b" table)
1401 ;; single quotes (') delimit strings
1402 (modify-syntax-entry ?' "\"" table)
1403 ;; double quotes (") don't delimit strings
1404 (modify-syntax-entry ?\" "." table)
1405 ;; Make these all punctuation
1406 (mapc (lambda (c) (modify-syntax-entry c "." table))
1407 (string-to-list "!#$%&+,.:;<=>?@\\|"))
1408 table)
1409 "Syntax table used in `sql-mode' and `sql-interactive-mode'.")
1411 ;; Font lock support
1413 (defvar sql-mode-font-lock-object-name
1414 (eval-when-compile
1415 (list (concat "^\\s-*\\(?:create\\|drop\\|alter\\)\\s-+" ;; lead off with CREATE, DROP or ALTER
1416 "\\(?:\\w+\\s-+\\)*" ;; optional intervening keywords
1417 "\\(?:table\\|view\\|\\(?:package\\|type\\)\\(?:\\s-+body\\)?\\|proc\\(?:edure\\)?"
1418 "\\|function\\|trigger\\|sequence\\|rule\\|default\\)\\s-+"
1419 "\\(?:if\\s-+not\\s-+exists\\s-+\\)?" ;; IF NOT EXISTS
1420 "\\(\\w+\\(?:\\s-*[.]\\s-*\\w+\\)*\\)")
1421 1 'font-lock-function-name-face))
1423 "Pattern to match the names of top-level objects.
1425 The pattern matches the name in a CREATE, DROP or ALTER
1426 statement. The format of variable should be a valid
1427 `font-lock-keywords' entry.")
1429 ;; While there are international and American standards for SQL, they
1430 ;; are not followed closely, and most vendors offer significant
1431 ;; capabilities beyond those defined in the standard specifications.
1433 ;; SQL mode provides support for highlighting based on the product. In
1434 ;; addition to highlighting the product keywords, any ANSI keywords not
1435 ;; used by the product are also highlighted. This will help identify
1436 ;; keywords that could be restricted in future versions of the product
1437 ;; or might be a problem if ported to another product.
1439 ;; To reduce the complexity and size of the regular expressions
1440 ;; generated to match keywords, ANSI keywords are filtered out of
1441 ;; product keywords if they are equivalent. To do this, we define a
1442 ;; function `sql-font-lock-keywords-builder' that removes any keywords
1443 ;; that are matched by the ANSI patterns and results in the same face
1444 ;; being applied. For this to work properly, we must play some games
1445 ;; with the execution and compile time behavior. This code is a
1446 ;; little tricky but works properly.
1448 ;; When defining the keywords for individual products you should
1449 ;; include all of the keywords that you want matched. The filtering
1450 ;; against the ANSI keywords will be automatic if you use the
1451 ;; `sql-font-lock-keywords-builder' function and follow the
1452 ;; implementation pattern used for the other products in this file.
1454 (eval-when-compile
1455 (defvar sql-mode-ansi-font-lock-keywords)
1456 (setq sql-mode-ansi-font-lock-keywords nil))
1458 (eval-and-compile
1459 (defun sql-font-lock-keywords-builder (face boundaries &rest keywords)
1460 "Generation of regexp matching any one of KEYWORDS."
1462 (let ((bdy (or boundaries '("\\b" . "\\b")))
1463 kwd)
1465 ;; Remove keywords that are defined in ANSI
1466 (setq kwd keywords)
1467 ;; (dolist (k keywords)
1468 ;; (catch 'next
1469 ;; (dolist (a sql-mode-ansi-font-lock-keywords)
1470 ;; (when (and (eq face (cdr a))
1471 ;; (eq (string-match (car a) k 0) 0)
1472 ;; (eq (match-end 0) (length k)))
1473 ;; (setq kwd (delq k kwd))
1474 ;; (throw 'next nil)))))
1476 ;; Create a properly formed font-lock-keywords item
1477 (cons (concat (car bdy)
1478 (regexp-opt kwd t)
1479 (cdr bdy))
1480 face)))
1482 (defun sql-regexp-abbrev (keyword)
1483 (let ((brk (string-match "[~]" keyword))
1484 (len (length keyword))
1485 (sep "\\(?:")
1486 re i)
1487 (if (not brk)
1488 keyword
1489 (setq re (substring keyword 0 brk)
1490 i (+ 2 brk)
1491 brk (1+ brk))
1492 (while (<= i len)
1493 (setq re (concat re sep (substring keyword brk i))
1494 sep "\\|"
1495 i (1+ i)))
1496 (concat re "\\)?"))))
1498 (defun sql-regexp-abbrev-list (&rest keyw-list)
1499 (let ((re nil)
1500 (sep "\\<\\(?:"))
1501 (while keyw-list
1502 (setq re (concat re sep (sql-regexp-abbrev (car keyw-list)))
1503 sep "\\|"
1504 keyw-list (cdr keyw-list)))
1505 (concat re "\\)\\>"))))
1507 (eval-when-compile
1508 (setq sql-mode-ansi-font-lock-keywords
1509 (list
1510 ;; ANSI Non Reserved keywords
1511 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1512 "ada" "asensitive" "assignment" "asymmetric" "atomic" "between"
1513 "bitvar" "called" "catalog_name" "chain" "character_set_catalog"
1514 "character_set_name" "character_set_schema" "checked" "class_origin"
1515 "cobol" "collation_catalog" "collation_name" "collation_schema"
1516 "column_name" "command_function" "command_function_code" "committed"
1517 "condition_number" "connection_name" "constraint_catalog"
1518 "constraint_name" "constraint_schema" "contains" "cursor_name"
1519 "datetime_interval_code" "datetime_interval_precision" "defined"
1520 "definer" "dispatch" "dynamic_function" "dynamic_function_code"
1521 "existing" "exists" "final" "fortran" "generated" "granted"
1522 "hierarchy" "hold" "implementation" "infix" "insensitive" "instance"
1523 "instantiable" "invoker" "key_member" "key_type" "length" "m"
1524 "message_length" "message_octet_length" "message_text" "method" "more"
1525 "mumps" "name" "nullable" "number" "options" "overlaps" "overriding"
1526 "parameter_mode" "parameter_name" "parameter_ordinal_position"
1527 "parameter_specific_catalog" "parameter_specific_name"
1528 "parameter_specific_schema" "pascal" "pli" "position" "repeatable"
1529 "returned_length" "returned_octet_length" "returned_sqlstate"
1530 "routine_catalog" "routine_name" "routine_schema" "row_count" "scale"
1531 "schema_name" "security" "self" "sensitive" "serializable"
1532 "server_name" "similar" "simple" "source" "specific_name" "style"
1533 "subclass_origin" "sublist" "symmetric" "system" "table_name"
1534 "transaction_active" "transactions_committed"
1535 "transactions_rolled_back" "transform" "transforms" "trigger_catalog"
1536 "trigger_name" "trigger_schema" "type" "uncommitted" "unnamed"
1537 "user_defined_type_catalog" "user_defined_type_name"
1538 "user_defined_type_schema"
1541 ;; ANSI Reserved keywords
1542 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1543 "absolute" "action" "add" "admin" "after" "aggregate" "alias" "all"
1544 "allocate" "alter" "and" "any" "are" "as" "asc" "assertion" "at"
1545 "authorization" "before" "begin" "both" "breadth" "by" "call"
1546 "cascade" "cascaded" "case" "catalog" "check" "class" "close"
1547 "collate" "collation" "column" "commit" "completion" "connect"
1548 "connection" "constraint" "constraints" "constructor" "continue"
1549 "corresponding" "create" "cross" "cube" "current" "cursor" "cycle"
1550 "data" "day" "deallocate" "declare" "default" "deferrable" "deferred"
1551 "delete" "depth" "deref" "desc" "describe" "descriptor" "destroy"
1552 "destructor" "deterministic" "diagnostics" "dictionary" "disconnect"
1553 "distinct" "domain" "drop" "dynamic" "each" "else" "end" "equals"
1554 "escape" "every" "except" "exception" "exec" "execute" "external"
1555 "false" "fetch" "first" "for" "foreign" "found" "free" "from" "full"
1556 "function" "general" "get" "global" "go" "goto" "grant" "group"
1557 "grouping" "having" "host" "hour" "identity" "ignore" "immediate" "in"
1558 "indicator" "initialize" "initially" "inner" "inout" "input" "insert"
1559 "intersect" "into" "is" "isolation" "iterate" "join" "key" "language"
1560 "last" "lateral" "leading" "left" "less" "level" "like" "limit"
1561 "local" "locator" "map" "match" "minute" "modifies" "modify" "module"
1562 "month" "names" "natural" "new" "next" "no" "none" "not" "null" "of"
1563 "off" "old" "on" "only" "open" "operation" "option" "or" "order"
1564 "ordinality" "out" "outer" "output" "pad" "parameter" "parameters"
1565 "partial" "path" "postfix" "prefix" "preorder" "prepare" "preserve"
1566 "primary" "prior" "privileges" "procedure" "public" "read" "reads"
1567 "recursive" "references" "referencing" "relative" "restrict" "result"
1568 "return" "returns" "revoke" "right" "role" "rollback" "rollup"
1569 "routine" "rows" "savepoint" "schema" "scroll" "search" "second"
1570 "section" "select" "sequence" "session" "set" "sets" "size" "some"
1571 "space" "specific" "specifictype" "sql" "sqlexception" "sqlstate"
1572 "sqlwarning" "start" "state" "statement" "static" "structure" "table"
1573 "temporary" "terminate" "than" "then" "timezone_hour"
1574 "timezone_minute" "to" "trailing" "transaction" "translation"
1575 "trigger" "true" "under" "union" "unique" "unknown" "unnest" "update"
1576 "usage" "using" "value" "values" "variable" "view" "when" "whenever"
1577 "where" "with" "without" "work" "write" "year"
1580 ;; ANSI Functions
1581 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1582 "abs" "avg" "bit_length" "cardinality" "cast" "char_length"
1583 "character_length" "coalesce" "convert" "count" "current_date"
1584 "current_path" "current_role" "current_time" "current_timestamp"
1585 "current_user" "extract" "localtime" "localtimestamp" "lower" "max"
1586 "min" "mod" "nullif" "octet_length" "overlay" "placing" "session_user"
1587 "substring" "sum" "system_user" "translate" "treat" "trim" "upper"
1588 "user"
1591 ;; ANSI Data Types
1592 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1593 "array" "binary" "bit" "blob" "boolean" "char" "character" "clob"
1594 "date" "dec" "decimal" "double" "float" "int" "integer" "interval"
1595 "large" "national" "nchar" "nclob" "numeric" "object" "precision"
1596 "real" "ref" "row" "scope" "smallint" "time" "timestamp" "varchar"
1597 "varying" "zone"
1598 ))))
1600 (defvar sql-mode-ansi-font-lock-keywords
1601 (eval-when-compile sql-mode-ansi-font-lock-keywords)
1602 "ANSI SQL keywords used by font-lock.
1604 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1605 regular expressions are created during compilation by calling the
1606 function `regexp-opt'. Therefore, take a look at the source before
1607 you define your own `sql-mode-ansi-font-lock-keywords'. You may want
1608 to add functions and PL/SQL keywords.")
1610 (defun sql--oracle-show-reserved-words ()
1611 ;; This function is for use by the maintainer of SQL.EL only.
1612 (if (or (and (not (derived-mode-p 'sql-mode))
1613 (not (derived-mode-p 'sql-interactive-mode)))
1614 (not sql-buffer)
1615 (not (eq sql-product 'oracle)))
1616 (user-error "Not an Oracle buffer")
1618 (let ((b "*RESERVED WORDS*"))
1619 (sql-execute sql-buffer b
1620 (concat "SELECT "
1621 " keyword "
1622 ", reserved AS \"Res\" "
1623 ", res_type AS \"Type\" "
1624 ", res_attr AS \"Attr\" "
1625 ", res_semi AS \"Semi\" "
1626 ", duplicate AS \"Dup\" "
1627 "FROM V$RESERVED_WORDS "
1628 "WHERE length > 1 "
1629 "AND SUBSTR(keyword, 1, 1) BETWEEN 'A' AND 'Z' "
1630 "ORDER BY 2 DESC, 3 DESC, 4 DESC, 5 DESC, 6 DESC, 1;")
1631 nil nil)
1632 (with-current-buffer b
1633 (set (make-local-variable 'sql-product) 'oracle)
1634 (sql-product-font-lock t nil)
1635 (font-lock-mode +1)))))
1637 (defvar sql-mode-oracle-font-lock-keywords
1638 (eval-when-compile
1639 (list
1640 ;; Oracle SQL*Plus Commands
1641 ;; Only recognized in they start in column 1 and the
1642 ;; abbreviation is followed by a space or the end of line.
1643 (list (concat "^" (sql-regexp-abbrev "rem~ark") "\\(?:\\s-.*\\)?$")
1644 0 'font-lock-comment-face t)
1646 (list
1647 (concat
1648 "^\\(?:"
1649 (sql-regexp-abbrev-list
1650 "[@]\\{1,2\\}" "acc~ept" "a~ppend" "archive" "attribute"
1651 "bre~ak" "bti~tle" "c~hange" "cl~ear" "col~umn" "conn~ect"
1652 "copy" "def~ine" "del" "desc~ribe" "disc~onnect" "ed~it"
1653 "exec~ute" "exit" "get" "help" "ho~st" "[$]" "i~nput" "l~ist"
1654 "passw~ord" "pau~se" "pri~nt" "pro~mpt" "quit" "recover"
1655 "repf~ooter" "reph~eader" "r~un" "sav~e" "sho~w" "shutdown"
1656 "spo~ol" "sta~rt" "startup" "store" "tim~ing" "tti~tle"
1657 "undef~ine" "var~iable" "whenever")
1658 "\\|"
1659 (concat "\\(?:"
1660 (sql-regexp-abbrev "comp~ute")
1661 "\\s-+"
1662 (sql-regexp-abbrev-list
1663 "avg" "cou~nt" "min~imum" "max~imum" "num~ber" "sum"
1664 "std" "var~iance")
1665 "\\)")
1666 "\\|"
1667 (concat "\\(?:set\\s-+"
1668 (sql-regexp-abbrev-list
1669 "appi~nfo" "array~size" "auto~commit" "autop~rint"
1670 "autorecovery" "autot~race" "blo~ckterminator"
1671 "cmds~ep" "colsep" "com~patibility" "con~cat"
1672 "copyc~ommit" "copytypecheck" "def~ine" "describe"
1673 "echo" "editf~ile" "emb~edded" "esc~ape" "feed~back"
1674 "flagger" "flu~sh" "hea~ding" "heads~ep" "instance"
1675 "lin~esize" "lobof~fset" "long" "longc~hunksize"
1676 "mark~up" "newp~age" "null" "numf~ormat" "num~width"
1677 "pages~ize" "pau~se" "recsep" "recsepchar"
1678 "scan" "serverout~put" "shift~inout" "show~mode"
1679 "sqlbl~anklines" "sqlc~ase" "sqlco~ntinue"
1680 "sqln~umber" "sqlpluscompat~ibility" "sqlpre~fix"
1681 "sqlp~rompt" "sqlt~erminator" "suf~fix" "tab"
1682 "term~out" "ti~me" "timi~ng" "trim~out" "trims~pool"
1683 "und~erline" "ver~ify" "wra~p")
1684 "\\)")
1686 "\\)\\(?:\\s-.*\\)?\\(?:[-]\n.*\\)*$")
1687 0 'font-lock-doc-face t)
1688 '("&?&\\(?:\\sw\\|\\s_\\)+[.]?" 0 font-lock-preprocessor-face t)
1690 ;; Oracle PL/SQL Attributes (Declare these first to match %TYPE correctly)
1691 (sql-font-lock-keywords-builder 'font-lock-builtin-face '("%" . "\\b")
1692 "bulk_exceptions" "bulk_rowcount" "found" "isopen" "notfound"
1693 "rowcount" "rowtype" "type"
1695 ;; Oracle Functions
1696 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1697 "abs" "acos" "add_months" "appendchildxml" "ascii" "asciistr" "asin"
1698 "atan" "atan2" "avg" "bfilename" "bin_to_num" "bitand" "cardinality"
1699 "cast" "ceil" "chartorowid" "chr" "cluster_id" "cluster_probability"
1700 "cluster_set" "coalesce" "collect" "compose" "concat" "convert" "corr"
1701 "connect_by_root" "connect_by_iscycle" "connect_by_isleaf"
1702 "corr_k" "corr_s" "cos" "cosh" "count" "covar_pop" "covar_samp"
1703 "cube_table" "cume_dist" "current_date" "current_timestamp" "cv"
1704 "dataobj_to_partition" "dbtimezone" "decode" "decompose" "deletexml"
1705 "dense_rank" "depth" "deref" "dump" "empty_blob" "empty_clob"
1706 "existsnode" "exp" "extract" "extractvalue" "feature_id" "feature_set"
1707 "feature_value" "first" "first_value" "floor" "from_tz" "greatest"
1708 "grouping" "grouping_id" "group_id" "hextoraw" "initcap"
1709 "insertchildxml" "insertchildxmlafter" "insertchildxmlbefore"
1710 "insertxmlafter" "insertxmlbefore" "instr" "instr2" "instr4" "instrb"
1711 "instrc" "iteration_number" "lag" "last" "last_day" "last_value"
1712 "lead" "least" "length" "length2" "length4" "lengthb" "lengthc"
1713 "listagg" "ln" "lnnvl" "localtimestamp" "log" "lower" "lpad" "ltrim"
1714 "make_ref" "max" "median" "min" "mod" "months_between" "nanvl" "nchr"
1715 "new_time" "next_day" "nlssort" "nls_charset_decl_len"
1716 "nls_charset_id" "nls_charset_name" "nls_initcap" "nls_lower"
1717 "nls_upper" "nth_value" "ntile" "nullif" "numtodsinterval"
1718 "numtoyminterval" "nvl" "nvl2" "ora_dst_affected" "ora_dst_convert"
1719 "ora_dst_error" "ora_hash" "path" "percentile_cont" "percentile_disc"
1720 "percent_rank" "power" "powermultiset" "powermultiset_by_cardinality"
1721 "prediction" "prediction_bounds" "prediction_cost"
1722 "prediction_details" "prediction_probability" "prediction_set"
1723 "presentnnv" "presentv" "previous" "rank" "ratio_to_report" "rawtohex"
1724 "rawtonhex" "ref" "reftohex" "regexp_count" "regexp_instr" "regexp_like"
1725 "regexp_replace" "regexp_substr" "regr_avgx" "regr_avgy" "regr_count"
1726 "regr_intercept" "regr_r2" "regr_slope" "regr_sxx" "regr_sxy"
1727 "regr_syy" "remainder" "replace" "round" "rowidtochar" "rowidtonchar"
1728 "row_number" "rpad" "rtrim" "scn_to_timestamp" "sessiontimezone" "set"
1729 "sign" "sin" "sinh" "soundex" "sqrt" "stats_binomial_test"
1730 "stats_crosstab" "stats_f_test" "stats_ks_test" "stats_mode"
1731 "stats_mw_test" "stats_one_way_anova" "stats_t_test_indep"
1732 "stats_t_test_indepu" "stats_t_test_one" "stats_t_test_paired"
1733 "stats_wsr_test" "stddev" "stddev_pop" "stddev_samp" "substr"
1734 "substr2" "substr4" "substrb" "substrc" "sum" "sysdate" "systimestamp"
1735 "sys_connect_by_path" "sys_context" "sys_dburigen" "sys_extract_utc"
1736 "sys_guid" "sys_typeid" "sys_xmlagg" "sys_xmlgen" "tan" "tanh"
1737 "timestamp_to_scn" "to_binary_double" "to_binary_float" "to_blob"
1738 "to_char" "to_clob" "to_date" "to_dsinterval" "to_lob" "to_multi_byte"
1739 "to_nchar" "to_nclob" "to_number" "to_single_byte" "to_timestamp"
1740 "to_timestamp_tz" "to_yminterval" "translate" "treat" "trim" "trunc"
1741 "tz_offset" "uid" "unistr" "updatexml" "upper" "user" "userenv"
1742 "value" "variance" "var_pop" "var_samp" "vsize" "width_bucket"
1743 "xmlagg" "xmlcast" "xmlcdata" "xmlcolattval" "xmlcomment" "xmlconcat"
1744 "xmldiff" "xmlelement" "xmlexists" "xmlforest" "xmlisvalid" "xmlparse"
1745 "xmlpatch" "xmlpi" "xmlquery" "xmlroot" "xmlsequence" "xmlserialize"
1746 "xmltable" "xmltransform"
1749 ;; See the table V$RESERVED_WORDS
1750 ;; Oracle Keywords
1751 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1752 "abort" "access" "accessed" "account" "activate" "add" "admin"
1753 "advise" "after" "agent" "aggregate" "all" "allocate" "allow" "alter"
1754 "always" "analyze" "ancillary" "and" "any" "apply" "archive"
1755 "archivelog" "array" "as" "asc" "associate" "at" "attribute"
1756 "attributes" "audit" "authenticated" "authid" "authorization" "auto"
1757 "autoallocate" "automatic" "availability" "backup" "before" "begin"
1758 "behalf" "between" "binding" "bitmap" "block" "blocksize" "body"
1759 "both" "buffer_pool" "build" "by" "cache" "call" "cancel"
1760 "cascade" "case" "category" "certificate" "chained" "change" "check"
1761 "checkpoint" "child" "chunk" "class" "clear" "clone" "close" "cluster"
1762 "column" "column_value" "columns" "comment" "commit" "committed"
1763 "compatibility" "compile" "complete" "composite_limit" "compress"
1764 "compute" "connect" "connect_time" "consider" "consistent"
1765 "constraint" "constraints" "constructor" "contents" "context"
1766 "continue" "controlfile" "corruption" "cost" "cpu_per_call"
1767 "cpu_per_session" "create" "cross" "cube" "current" "currval" "cycle"
1768 "dangling" "data" "database" "datafile" "datafiles" "day" "ddl"
1769 "deallocate" "debug" "default" "deferrable" "deferred" "definer"
1770 "delay" "delete" "demand" "desc" "determines" "deterministic"
1771 "dictionary" "dimension" "directory" "disable" "disassociate"
1772 "disconnect" "distinct" "distinguished" "distributed" "dml" "drop"
1773 "each" "element" "else" "enable" "end" "equals_path" "escape"
1774 "estimate" "except" "exceptions" "exchange" "excluding" "exists"
1775 "expire" "explain" "extent" "external" "externally"
1776 "failed_login_attempts" "fast" "file" "final" "finish" "flush" "for"
1777 "force" "foreign" "freelist" "freelists" "freepools" "fresh" "from"
1778 "full" "function" "functions" "generated" "global" "global_name"
1779 "globally" "grant" "group" "grouping" "groups" "guard" "hash"
1780 "hashkeys" "having" "heap" "hierarchy" "id" "identified" "identifier"
1781 "idle_time" "immediate" "in" "including" "increment" "index" "indexed"
1782 "indexes" "indextype" "indextypes" "indicator" "initial" "initialized"
1783 "initially" "initrans" "inner" "insert" "instance" "instantiable"
1784 "instead" "intersect" "into" "invalidate" "is" "isolation" "java"
1785 "join" "keep" "key" "kill" "language" "left" "less" "level"
1786 "levels" "library" "like" "like2" "like4" "likec" "limit" "link"
1787 "list" "lob" "local" "location" "locator" "lock" "log" "logfile"
1788 "logging" "logical" "logical_reads_per_call"
1789 "logical_reads_per_session" "managed" "management" "manual" "map"
1790 "mapping" "master" "matched" "materialized" "maxdatafiles"
1791 "maxextents" "maximize" "maxinstances" "maxlogfiles" "maxloghistory"
1792 "maxlogmembers" "maxsize" "maxtrans" "maxvalue" "member" "memory"
1793 "merge" "migrate" "minextents" "minimize" "minimum" "minus" "minvalue"
1794 "mode" "modify" "monitoring" "month" "mount" "move" "movement" "name"
1795 "named" "natural" "nested" "never" "new" "next" "nextval" "no"
1796 "noarchivelog" "noaudit" "nocache" "nocompress" "nocopy" "nocycle"
1797 "nodelay" "noforce" "nologging" "nomapping" "nomaxvalue" "nominimize"
1798 "nominvalue" "nomonitoring" "none" "noorder" "noparallel" "norely"
1799 "noresetlogs" "noreverse" "normal" "norowdependencies" "nosort"
1800 "noswitch" "not" "nothing" "notimeout" "novalidate" "nowait" "null"
1801 "nulls" "object" "of" "off" "offline" "oidindex" "old" "on" "online"
1802 "only" "open" "operator" "optimal" "option" "or" "order"
1803 "organization" "out" "outer" "outline" "over" "overflow" "overriding"
1804 "package" "packages" "parallel" "parallel_enable" "parameters"
1805 "parent" "partition" "partitions" "password" "password_grace_time"
1806 "password_life_time" "password_lock_time" "password_reuse_max"
1807 "password_reuse_time" "password_verify_function" "pctfree"
1808 "pctincrease" "pctthreshold" "pctused" "pctversion" "percent"
1809 "performance" "permanent" "pfile" "physical" "pipelined" "pivot" "plan"
1810 "post_transaction" "pragma" "prebuilt" "preserve" "primary" "private"
1811 "private_sga" "privileges" "procedure" "profile" "protection" "public"
1812 "purge" "query" "quiesce" "quota" "range" "read" "reads" "rebuild"
1813 "records_per_block" "recover" "recovery" "recycle" "reduced" "ref"
1814 "references" "referencing" "refresh" "register" "reject" "relational"
1815 "rely" "rename" "reset" "resetlogs" "resize" "resolve" "resolver"
1816 "resource" "restrict" "restrict_references" "restricted" "result"
1817 "resumable" "resume" "retention" "return" "returning" "reuse"
1818 "reverse" "revoke" "rewrite" "right" "rnds" "rnps" "role" "roles"
1819 "rollback" "rollup" "row" "rowdependencies" "rownum" "rows" "sample"
1820 "savepoint" "scan" "schema" "scn" "scope" "segment" "select"
1821 "selectivity" "self" "sequence" "serializable" "session"
1822 "sessions_per_user" "set" "sets" "settings" "shared" "shared_pool"
1823 "shrink" "shutdown" "siblings" "sid" "single" "size" "skip" "some"
1824 "sort" "source" "space" "specification" "spfile" "split" "standby"
1825 "start" "statement_id" "static" "statistics" "stop" "storage" "store"
1826 "structure" "subpartition" "subpartitions" "substitutable"
1827 "successful" "supplemental" "suspend" "switch" "switchover" "synonym"
1828 "sys" "system" "table" "tables" "tablespace" "tempfile" "template"
1829 "temporary" "test" "than" "then" "thread" "through" "time_zone"
1830 "timeout" "to" "trace" "transaction" "trigger" "triggers" "truncate"
1831 "trust" "type" "types" "unarchived" "under" "under_path" "undo"
1832 "uniform" "union" "unique" "unlimited" "unlock" "unpivot" "unquiesce"
1833 "unrecoverable" "until" "unusable" "unused" "update" "upgrade" "usage"
1834 "use" "using" "validate" "validation" "value" "values" "variable"
1835 "varray" "version" "view" "wait" "when" "whenever" "where" "with"
1836 "without" "wnds" "wnps" "work" "write" "xmldata" "xmlschema" "xmltype"
1839 ;; Oracle Data Types
1840 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1841 "bfile" "binary_double" "binary_float" "blob" "byte" "char" "charbyte"
1842 "clob" "date" "day" "float" "interval" "local" "long" "longraw"
1843 "minute" "month" "nchar" "nclob" "number" "nvarchar2" "raw" "rowid" "second"
1844 "time" "timestamp" "urowid" "varchar2" "with" "year" "zone"
1847 ;; Oracle PL/SQL Functions
1848 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1849 "delete" "trim" "extend" "exists" "first" "last" "count" "limit"
1850 "prior" "next" "sqlcode" "sqlerrm"
1853 ;; Oracle PL/SQL Reserved words
1854 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1855 "all" "alter" "and" "any" "as" "asc" "at" "begin" "between" "by"
1856 "case" "check" "clusters" "cluster" "colauth" "columns" "compress"
1857 "connect" "crash" "create" "cursor" "declare" "default" "desc"
1858 "distinct" "drop" "else" "end" "exception" "exclusive" "fetch" "for"
1859 "from" "function" "goto" "grant" "group" "having" "identified" "if"
1860 "in" "index" "indexes" "insert" "intersect" "into" "is" "like" "lock"
1861 "minus" "mode" "nocompress" "not" "nowait" "null" "of" "on" "option"
1862 "or" "order" "overlaps" "procedure" "public" "resource" "revoke"
1863 "select" "share" "size" "sql" "start" "subtype" "tabauth" "table"
1864 "then" "to" "type" "union" "unique" "update" "values" "view" "views"
1865 "when" "where" "with"
1867 "true" "false"
1868 "raise_application_error"
1871 ;; Oracle PL/SQL Keywords
1872 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1873 "a" "add" "agent" "aggregate" "array" "attribute" "authid" "avg"
1874 "bfile_base" "binary" "blob_base" "block" "body" "both" "bound" "bulk"
1875 "byte" "c" "call" "calling" "cascade" "char" "char_base" "character"
1876 "charset" "charsetform" "charsetid" "clob_base" "close" "collect"
1877 "comment" "commit" "committed" "compiled" "constant" "constructor"
1878 "context" "continue" "convert" "count" "current" "customdatum"
1879 "dangling" "data" "date" "date_base" "day" "define" "delete"
1880 "deterministic" "double" "duration" "element" "elsif" "empty" "escape"
1881 "except" "exceptions" "execute" "exists" "exit" "external" "final"
1882 "fixed" "float" "forall" "force" "general" "hash" "heap" "hidden"
1883 "hour" "immediate" "including" "indicator" "indices" "infinite"
1884 "instantiable" "int" "interface" "interval" "invalidate" "isolation"
1885 "java" "language" "large" "leading" "length" "level" "library" "like2"
1886 "like4" "likec" "limit" "limited" "local" "long" "loop" "map" "max"
1887 "maxlen" "member" "merge" "min" "minute" "mod" "modify" "month"
1888 "multiset" "name" "nan" "national" "native" "nchar" "new" "nocopy"
1889 "number_base" "object" "ocicoll" "ocidate" "ocidatetime" "ociduration"
1890 "ociinterval" "ociloblocator" "ocinumber" "ociraw" "ociref"
1891 "ocirefcursor" "ocirowid" "ocistring" "ocitype" "old" "only" "opaque"
1892 "open" "operator" "oracle" "oradata" "organization" "orlany" "orlvary"
1893 "others" "out" "overriding" "package" "parallel_enable" "parameter"
1894 "parameters" "parent" "partition" "pascal" "pipe" "pipelined" "pragma"
1895 "precision" "prior" "private" "raise" "range" "raw" "read" "record"
1896 "ref" "reference" "relies_on" "rem" "remainder" "rename" "result"
1897 "result_cache" "return" "returning" "reverse" "rollback" "row"
1898 "sample" "save" "savepoint" "sb1" "sb2" "sb4" "second" "segment"
1899 "self" "separate" "sequence" "serializable" "set" "short" "size_t"
1900 "some" "sparse" "sqlcode" "sqldata" "sqlname" "sqlstate" "standard"
1901 "static" "stddev" "stored" "string" "struct" "style" "submultiset"
1902 "subpartition" "substitutable" "sum" "synonym" "tdo" "the" "time"
1903 "timestamp" "timezone_abbr" "timezone_hour" "timezone_minute"
1904 "timezone_region" "trailing" "transaction" "transactional" "trusted"
1905 "ub1" "ub2" "ub4" "under" "unsigned" "untrusted" "use" "using"
1906 "valist" "value" "variable" "variance" "varray" "varying" "void"
1907 "while" "work" "wrapped" "write" "year" "zone"
1908 ;; Pragma
1909 "autonomous_transaction" "exception_init" "inline"
1910 "restrict_references" "serially_reusable"
1913 ;; Oracle PL/SQL Data Types
1914 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1915 "\"BINARY LARGE OBJECT\"" "\"CHAR LARGE OBJECT\"" "\"CHAR VARYING\""
1916 "\"CHARACTER LARGE OBJECT\"" "\"CHARACTER VARYING\""
1917 "\"DOUBLE PRECISION\"" "\"INTERVAL DAY TO SECOND\""
1918 "\"INTERVAL YEAR TO MONTH\"" "\"LONG RAW\"" "\"NATIONAL CHAR\""
1919 "\"NATIONAL CHARACTER LARGE OBJECT\"" "\"NATIONAL CHARACTER\""
1920 "\"NCHAR LARGE OBJECT\"" "\"NCHAR\"" "\"NCLOB\"" "\"NVARCHAR2\""
1921 "\"TIME WITH TIME ZONE\"" "\"TIMESTAMP WITH LOCAL TIME ZONE\""
1922 "\"TIMESTAMP WITH TIME ZONE\""
1923 "bfile" "bfile_base" "binary_double" "binary_float" "binary_integer"
1924 "blob" "blob_base" "boolean" "char" "character" "char_base" "clob"
1925 "clob_base" "cursor" "date" "day" "dec" "decimal"
1926 "dsinterval_unconstrained" "float" "int" "integer" "interval" "local"
1927 "long" "mlslabel" "month" "natural" "naturaln" "nchar_cs" "number"
1928 "number_base" "numeric" "pls_integer" "positive" "positiven" "raw"
1929 "real" "ref" "rowid" "second" "signtype" "simple_double"
1930 "simple_float" "simple_integer" "smallint" "string" "time" "timestamp"
1931 "timestamp_ltz_unconstrained" "timestamp_tz_unconstrained"
1932 "timestamp_unconstrained" "time_tz_unconstrained" "time_unconstrained"
1933 "to" "urowid" "varchar" "varchar2" "with" "year"
1934 "yminterval_unconstrained" "zone"
1937 ;; Oracle PL/SQL Exceptions
1938 (sql-font-lock-keywords-builder 'font-lock-warning-face nil
1939 "access_into_null" "case_not_found" "collection_is_null"
1940 "cursor_already_open" "dup_val_on_index" "invalid_cursor"
1941 "invalid_number" "login_denied" "no_data_found" "no_data_needed"
1942 "not_logged_on" "program_error" "rowtype_mismatch" "self_is_null"
1943 "storage_error" "subscript_beyond_count" "subscript_outside_limit"
1944 "sys_invalid_rowid" "timeout_on_resource" "too_many_rows"
1945 "value_error" "zero_divide"
1948 "Oracle SQL keywords used by font-lock.
1950 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1951 regular expressions are created during compilation by calling the
1952 function `regexp-opt'. Therefore, take a look at the source before
1953 you define your own `sql-mode-oracle-font-lock-keywords'. You may want
1954 to add functions and PL/SQL keywords.")
1956 (defvar sql-mode-postgres-font-lock-keywords
1957 (eval-when-compile
1958 (list
1959 ;; Postgres psql commands
1960 '("^\\s-*\\\\.*$" . font-lock-doc-face)
1962 ;; Postgres unreserved words but may have meaning
1963 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil "a"
1964 "abs" "absent" "according" "ada" "alias" "allocate" "are" "array_agg"
1965 "asensitive" "atomic" "attribute" "attributes" "avg" "base64"
1966 "bernoulli" "bit_length" "bitvar" "blob" "blocked" "bom" "breadth" "c"
1967 "call" "cardinality" "catalog_name" "ceil" "ceiling" "char_length"
1968 "character_length" "character_set_catalog" "character_set_name"
1969 "character_set_schema" "characters" "checked" "class_origin" "clob"
1970 "cobol" "collation" "collation_catalog" "collation_name"
1971 "collation_schema" "collect" "column_name" "columns"
1972 "command_function" "command_function_code" "completion" "condition"
1973 "condition_number" "connect" "connection_name" "constraint_catalog"
1974 "constraint_name" "constraint_schema" "constructor" "contains"
1975 "control" "convert" "corr" "corresponding" "count" "covar_pop"
1976 "covar_samp" "cube" "cume_dist" "current_default_transform_group"
1977 "current_path" "current_transform_group_for_type" "cursor_name"
1978 "datalink" "datetime_interval_code" "datetime_interval_precision" "db"
1979 "defined" "degree" "dense_rank" "depth" "deref" "derived" "describe"
1980 "descriptor" "destroy" "destructor" "deterministic" "diagnostics"
1981 "disconnect" "dispatch" "dlnewcopy" "dlpreviouscopy" "dlurlcomplete"
1982 "dlurlcompleteonly" "dlurlcompletewrite" "dlurlpath" "dlurlpathonly"
1983 "dlurlpathwrite" "dlurlscheme" "dlurlserver" "dlvalue" "dynamic"
1984 "dynamic_function" "dynamic_function_code" "element" "empty"
1985 "end-exec" "equals" "every" "exception" "exec" "existing" "exp" "file"
1986 "filter" "final" "first_value" "flag" "floor" "fortran" "found" "free"
1987 "fs" "fusion" "g" "general" "generated" "get" "go" "goto" "grouping"
1988 "hex" "hierarchy" "host" "id" "ignore" "implementation" "import"
1989 "indent" "indicator" "infix" "initialize" "instance" "instantiable"
1990 "integrity" "intersection" "iterate" "k" "key_member" "key_type" "lag"
1991 "last_value" "lateral" "lead" "length" "less" "library" "like_regex"
1992 "link" "ln" "locator" "lower" "m" "map" "matched" "max"
1993 "max_cardinality" "member" "merge" "message_length"
1994 "message_octet_length" "message_text" "method" "min" "mod" "modifies"
1995 "modify" "module" "more" "multiset" "mumps" "namespace" "nclob"
1996 "nesting" "new" "nfc" "nfd" "nfkc" "nfkd" "nil" "normalize"
1997 "normalized" "nth_value" "ntile" "nullable" "number"
1998 "occurrences_regex" "octet_length" "octets" "old" "open" "operation"
1999 "ordering" "ordinality" "others" "output" "overriding" "p" "pad"
2000 "parameter" "parameter_mode" "parameter_name"
2001 "parameter_ordinal_position" "parameter_specific_catalog"
2002 "parameter_specific_name" "parameter_specific_schema" "parameters"
2003 "pascal" "passing" "passthrough" "percent_rank" "percentile_cont"
2004 "percentile_disc" "permission" "pli" "position_regex" "postfix"
2005 "power" "prefix" "preorder" "public" "rank" "reads" "recovery" "ref"
2006 "referencing" "regr_avgx" "regr_avgy" "regr_count" "regr_intercept"
2007 "regr_r2" "regr_slope" "regr_sxx" "regr_sxy" "regr_syy" "requiring"
2008 "respect" "restore" "result" "return" "returned_cardinality"
2009 "returned_length" "returned_octet_length" "returned_sqlstate" "rollup"
2010 "routine" "routine_catalog" "routine_name" "routine_schema"
2011 "row_count" "row_number" "scale" "schema_name" "scope" "scope_catalog"
2012 "scope_name" "scope_schema" "section" "selective" "self" "sensitive"
2013 "server_name" "sets" "size" "source" "space" "specific"
2014 "specific_name" "specifictype" "sql" "sqlcode" "sqlerror"
2015 "sqlexception" "sqlstate" "sqlwarning" "sqrt" "state" "static"
2016 "stddev_pop" "stddev_samp" "structure" "style" "subclass_origin"
2017 "sublist" "submultiset" "substring_regex" "sum" "system_user" "t"
2018 "table_name" "tablesample" "terminate" "than" "ties" "timezone_hour"
2019 "timezone_minute" "token" "top_level_count" "transaction_active"
2020 "transactions_committed" "transactions_rolled_back" "transform"
2021 "transforms" "translate" "translate_regex" "translation"
2022 "trigger_catalog" "trigger_name" "trigger_schema" "trim_array"
2023 "uescape" "under" "unlink" "unnamed" "unnest" "untyped" "upper" "uri"
2024 "usage" "user_defined_type_catalog" "user_defined_type_code"
2025 "user_defined_type_name" "user_defined_type_schema" "var_pop"
2026 "var_samp" "varbinary" "variable" "whenever" "width_bucket" "within"
2027 "xmlagg" "xmlbinary" "xmlcast" "xmlcomment" "xmldeclaration"
2028 "xmldocument" "xmlexists" "xmliterate" "xmlnamespaces" "xmlquery"
2029 "xmlschema" "xmltable" "xmltext" "xmlvalidate"
2032 ;; Postgres non-reserved words
2033 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2034 "abort" "absolute" "access" "action" "add" "admin" "after" "aggregate"
2035 "also" "alter" "always" "assertion" "assignment" "at" "attribute" "backward"
2036 "before" "begin" "between" "by" "cache" "called" "cascade" "cascaded"
2037 "catalog" "chain" "characteristics" "checkpoint" "class" "close"
2038 "cluster" "coalesce" "comment" "comments" "commit" "committed"
2039 "configuration" "connection" "constraints" "content" "continue"
2040 "conversion" "copy" "cost" "createdb" "createrole" "createuser" "csv"
2041 "current" "cursor" "cycle" "data" "database" "day" "deallocate" "dec"
2042 "declare" "defaults" "deferred" "definer" "delete" "delimiter"
2043 "delimiters" "dictionary" "disable" "discard" "document" "domain"
2044 "drop" "each" "enable" "encoding" "encrypted" "enum" "escape"
2045 "exclude" "excluding" "exclusive" "execute" "exists" "explain"
2046 "extension" "external" "extract" "family" "first" "float" "following" "force"
2047 "forward" "function" "functions" "global" "granted" "greatest"
2048 "handler" "header" "hold" "hour" "identity" "if" "immediate"
2049 "immutable" "implicit" "including" "increment" "index" "indexes"
2050 "inherit" "inherits" "inline" "inout" "input" "insensitive" "insert"
2051 "instead" "invoker" "isolation" "key" "label" "language" "large" "last"
2052 "lc_collate" "lc_ctype" "leakproof" "least" "level" "listen" "load" "local"
2053 "location" "lock" "login" "mapping" "match" "maxvalue" "minute"
2054 "minvalue" "mode" "month" "move" "names" "national" "nchar"
2055 "next" "no" "nocreatedb" "nocreaterole" "nocreateuser" "noinherit"
2056 "nologin" "none" "noreplication" "nosuperuser" "nothing" "notify" "nowait" "nullif"
2057 "nulls" "object" "of" "off" "oids" "operator" "option" "options" "out"
2058 "overlay" "owned" "owner" "parser" "partial" "partition" "passing" "password"
2059 "plans" "position" "preceding" "precision" "prepare" "prepared" "preserve" "prior"
2060 "privileges" "procedural" "procedure" "quote" "range" "read"
2061 "reassign" "recheck" "recursive" "ref" "reindex" "relative" "release"
2062 "rename" "repeatable" "replace" "replica" "replication" "reset" "restart" "restrict"
2063 "returns" "revoke" "role" "rollback" "row" "rows" "rule" "savepoint"
2064 "schema" "scroll" "search" "second" "security" "sequence"
2065 "serializable" "server" "session" "set" "setof" "share" "show"
2066 "simple" "snapshot" "stable" "standalone" "start" "statement" "statistics"
2067 "stdin" "stdout" "storage" "strict" "strip" "substring" "superuser"
2068 "sysid" "system" "tables" "tablespace" "temp" "template" "temporary"
2069 "transaction" "treat" "trim" "truncate" "trusted" "type" "types"
2070 "unbounded" "uncommitted" "unencrypted" "unlisten" "unlogged" "until"
2071 "update" "vacuum" "valid" "validate" "validator" "value" "values" "varying" "version"
2072 "view" "volatile" "whitespace" "without" "work" "wrapper" "write"
2073 "xmlattributes" "xmlconcat" "xmlelement" "xmlexists" "xmlforest" "xmlparse"
2074 "xmlpi" "xmlroot" "xmlserialize" "year" "yes" "zone"
2077 ;; Postgres Reserved
2078 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2079 "all" "analyse" "analyze" "and" "array" "asc" "as" "asymmetric"
2080 "authorization" "binary" "both" "case" "cast" "check" "collate"
2081 "column" "concurrently" "constraint" "create" "cross"
2082 "current_catalog" "current_date" "current_role" "current_schema"
2083 "current_time" "current_timestamp" "current_user" "default"
2084 "deferrable" "desc" "distinct" "do" "else" "end" "except" "false"
2085 "fetch" "foreign" "for" "freeze" "from" "full" "grant" "group"
2086 "having" "ilike" "initially" "inner" "in" "intersect" "into" "isnull"
2087 "is" "join" "leading" "left" "like" "limit" "localtime"
2088 "localtimestamp" "natural" "notnull" "not" "null" "offset"
2089 "only" "on" "order" "or" "outer" "overlaps" "over" "placing" "primary"
2090 "references" "returning" "right" "select" "session_user" "similar"
2091 "some" "symmetric" "table" "then" "to" "trailing" "true" "union"
2092 "unique" "user" "using" "variadic" "verbose" "when" "where" "window"
2093 "with"
2096 ;; Postgres PL/pgSQL
2097 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2098 "assign" "if" "case" "loop" "while" "for" "foreach" "exit" "elsif" "return"
2099 "raise" "execsql" "dynexecute" "perform" "getdiag" "open" "fetch" "move" "close"
2102 ;; Postgres Data Types
2103 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2104 "bigint" "bigserial" "bit" "bool" "boolean" "box" "bytea" "char"
2105 "character" "cidr" "circle" "date" "decimal" "double" "float4"
2106 "float8" "inet" "int" "int2" "int4" "int8" "integer" "interval" "line"
2107 "lseg" "macaddr" "money" "name" "numeric" "path" "point" "polygon"
2108 "precision" "real" "serial" "serial4" "serial8" "sequences" "smallint" "text"
2109 "time" "timestamp" "timestamptz" "timetz" "tsquery" "tsvector"
2110 "txid_snapshot" "unknown" "uuid" "varbit" "varchar" "varying" "without"
2111 "xml" "zone"
2114 "Postgres SQL keywords used by font-lock.
2116 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2117 regular expressions are created during compilation by calling the
2118 function `regexp-opt'. Therefore, take a look at the source before
2119 you define your own `sql-mode-postgres-font-lock-keywords'.")
2121 (defvar sql-mode-linter-font-lock-keywords
2122 (eval-when-compile
2123 (list
2124 ;; Linter Keywords
2125 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2126 "autocommit" "autoinc" "autorowid" "cancel" "cascade" "channel"
2127 "committed" "count" "countblob" "cross" "current" "data" "database"
2128 "datafile" "datafiles" "datesplit" "dba" "dbname" "default" "deferred"
2129 "denied" "description" "device" "difference" "directory" "error"
2130 "escape" "euc" "exclusive" "external" "extfile" "false" "file"
2131 "filename" "filesize" "filetime" "filter" "findblob" "first" "foreign"
2132 "full" "fuzzy" "global" "granted" "ignore" "immediate" "increment"
2133 "indexes" "indexfile" "indexfiles" "indextime" "initial" "integrity"
2134 "internal" "key" "last_autoinc" "last_rowid" "limit" "linter"
2135 "linter_file_device" "linter_file_size" "linter_name_length" "ln"
2136 "local" "login" "maxisn" "maxrow" "maxrowid" "maxvalue" "message"
2137 "minvalue" "module" "names" "national" "natural" "new" "new_table"
2138 "no" "node" "noneuc" "nulliferror" "numbers" "off" "old" "old_table"
2139 "only" "operation" "optimistic" "option" "page" "partially" "password"
2140 "phrase" "plan" "precision" "primary" "priority" "privileges"
2141 "proc_info_size" "proc_par_name_len" "protocol" "quant" "range" "raw"
2142 "read" "record" "records" "references" "remote" "rename" "replication"
2143 "restart" "rewrite" "root" "row" "rule" "savepoint" "security"
2144 "sensitive" "sequence" "serializable" "server" "since" "size" "some"
2145 "startup" "statement" "station" "success" "sys_guid" "tables" "test"
2146 "timeout" "trace" "transaction" "translation" "trigger"
2147 "trigger_info_size" "true" "trunc" "uncommitted" "unicode" "unknown"
2148 "unlimited" "unlisted" "user" "utf8" "value" "varying" "volumes"
2149 "wait" "windows_code" "workspace" "write" "xml"
2152 ;; Linter Reserved
2153 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2154 "access" "action" "add" "address" "after" "all" "alter" "always" "and"
2155 "any" "append" "as" "asc" "ascic" "async" "at_begin" "at_end" "audit"
2156 "aud_obj_name_len" "backup" "base" "before" "between" "blobfile"
2157 "blobfiles" "blobpct" "brief" "browse" "by" "case" "cast" "check"
2158 "clear" "close" "column" "comment" "commit" "connect" "contains"
2159 "correct" "create" "delete" "desc" "disable" "disconnect" "distinct"
2160 "drop" "each" "ef" "else" "enable" "end" "event" "except" "exclude"
2161 "execute" "exists" "extract" "fetch" "finish" "for" "from" "get"
2162 "grant" "group" "having" "identified" "in" "index" "inner" "insert"
2163 "instead" "intersect" "into" "is" "isolation" "join" "left" "level"
2164 "like" "lock" "mode" "modify" "not" "nowait" "null" "of" "on" "open"
2165 "or" "order" "outer" "owner" "press" "prior" "procedure" "public"
2166 "purge" "rebuild" "resource" "restrict" "revoke" "right" "role"
2167 "rollback" "rownum" "select" "session" "set" "share" "shutdown"
2168 "start" "stop" "sync" "synchronize" "synonym" "sysdate" "table" "then"
2169 "to" "union" "unique" "unlock" "until" "update" "using" "values"
2170 "view" "when" "where" "with" "without"
2173 ;; Linter Functions
2174 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2175 "abs" "acos" "asin" "atan" "atan2" "avg" "ceil" "cos" "cosh" "divtime"
2176 "exp" "floor" "getbits" "getblob" "getbyte" "getlong" "getraw"
2177 "getstr" "gettext" "getword" "hextoraw" "lenblob" "length" "log"
2178 "lower" "lpad" "ltrim" "max" "min" "mod" "monthname" "nvl"
2179 "octet_length" "power" "rand" "rawtohex" "repeat_string"
2180 "right_substr" "round" "rpad" "rtrim" "sign" "sin" "sinh" "soundex"
2181 "sqrt" "sum" "tan" "tanh" "timeint_to_days" "to_char" "to_date"
2182 "to_gmtime" "to_localtime" "to_number" "trim" "upper" "decode"
2183 "substr" "substring" "chr" "dayname" "days" "greatest" "hex" "initcap"
2184 "instr" "least" "multime" "replace" "width"
2187 ;; Linter Data Types
2188 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2189 "bigint" "bitmap" "blob" "boolean" "char" "character" "date"
2190 "datetime" "dec" "decimal" "double" "float" "int" "integer" "nchar"
2191 "number" "numeric" "real" "smallint" "varbyte" "varchar" "byte"
2192 "cursor" "long"
2195 "Linter SQL keywords used by font-lock.
2197 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2198 regular expressions are created during compilation by calling the
2199 function `regexp-opt'.")
2201 (defvar sql-mode-ms-font-lock-keywords
2202 (eval-when-compile
2203 (list
2204 ;; MS isql/osql Commands
2205 (cons
2206 (concat
2207 "^\\(?:\\(?:set\\s-+\\(?:"
2208 (regexp-opt '(
2209 "datefirst" "dateformat" "deadlock_priority" "lock_timeout"
2210 "concat_null_yields_null" "cursor_close_on_commit"
2211 "disable_def_cnst_chk" "fips_flagger" "identity_insert" "language"
2212 "offsets" "quoted_identifier" "arithabort" "arithignore" "fmtonly"
2213 "nocount" "noexec" "numeric_roundabort" "parseonly"
2214 "query_governor_cost_limit" "rowcount" "textsize" "ansi_defaults"
2215 "ansi_null_dflt_off" "ansi_null_dflt_on" "ansi_nulls" "ansi_padding"
2216 "ansi_warnings" "forceplan" "showplan_all" "showplan_text"
2217 "statistics" "implicit_transactions" "remote_proc_transactions"
2218 "transaction" "xact_abort"
2219 ) t)
2220 "\\)\\)\\|go\\s-*\\|use\\s-+\\|setuser\\s-+\\|dbcc\\s-+\\).*$")
2221 'font-lock-doc-face)
2223 ;; MS Reserved
2224 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2225 "absolute" "add" "all" "alter" "and" "any" "as" "asc" "authorization"
2226 "avg" "backup" "begin" "between" "break" "browse" "bulk" "by"
2227 "cascade" "case" "check" "checkpoint" "close" "clustered" "coalesce"
2228 "column" "commit" "committed" "compute" "confirm" "constraint"
2229 "contains" "containstable" "continue" "controlrow" "convert" "count"
2230 "create" "cross" "current" "current_date" "current_time"
2231 "current_timestamp" "current_user" "database" "deallocate" "declare"
2232 "default" "delete" "deny" "desc" "disk" "distinct" "distributed"
2233 "double" "drop" "dummy" "dump" "else" "end" "errlvl" "errorexit"
2234 "escape" "except" "exec" "execute" "exists" "exit" "fetch" "file"
2235 "fillfactor" "first" "floppy" "for" "foreign" "freetext"
2236 "freetexttable" "from" "full" "goto" "grant" "group" "having"
2237 "holdlock" "identity" "identity_insert" "identitycol" "if" "in"
2238 "index" "inner" "insert" "intersect" "into" "is" "isolation" "join"
2239 "key" "kill" "last" "left" "level" "like" "lineno" "load" "max" "min"
2240 "mirrorexit" "national" "next" "nocheck" "nolock" "nonclustered" "not"
2241 "null" "nullif" "of" "off" "offsets" "on" "once" "only" "open"
2242 "opendatasource" "openquery" "openrowset" "option" "or" "order"
2243 "outer" "output" "over" "paglock" "percent" "perm" "permanent" "pipe"
2244 "plan" "precision" "prepare" "primary" "print" "prior" "privileges"
2245 "proc" "procedure" "processexit" "public" "raiserror" "read"
2246 "readcommitted" "readpast" "readtext" "readuncommitted" "reconfigure"
2247 "references" "relative" "repeatable" "repeatableread" "replication"
2248 "restore" "restrict" "return" "revoke" "right" "rollback" "rowcount"
2249 "rowguidcol" "rowlock" "rule" "save" "schema" "select" "serializable"
2250 "session_user" "set" "shutdown" "some" "statistics" "sum"
2251 "system_user" "table" "tablock" "tablockx" "tape" "temp" "temporary"
2252 "textsize" "then" "to" "top" "tran" "transaction" "trigger" "truncate"
2253 "tsequal" "uncommitted" "union" "unique" "update" "updatetext"
2254 "updlock" "use" "user" "values" "view" "waitfor" "when" "where"
2255 "while" "with" "work" "writetext" "collate" "function" "openxml"
2256 "returns"
2259 ;; MS Functions
2260 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2261 "@@connections" "@@cpu_busy" "@@cursor_rows" "@@datefirst" "@@dbts"
2262 "@@error" "@@fetch_status" "@@identity" "@@idle" "@@io_busy"
2263 "@@langid" "@@language" "@@lock_timeout" "@@max_connections"
2264 "@@max_precision" "@@nestlevel" "@@options" "@@pack_received"
2265 "@@pack_sent" "@@packet_errors" "@@procid" "@@remserver" "@@rowcount"
2266 "@@servername" "@@servicename" "@@spid" "@@textsize" "@@timeticks"
2267 "@@total_errors" "@@total_read" "@@total_write" "@@trancount"
2268 "@@version" "abs" "acos" "and" "app_name" "ascii" "asin" "atan" "atn2"
2269 "avg" "case" "cast" "ceiling" "char" "charindex" "coalesce"
2270 "col_length" "col_name" "columnproperty" "containstable" "convert"
2271 "cos" "cot" "count" "current_timestamp" "current_user" "cursor_status"
2272 "databaseproperty" "datalength" "dateadd" "datediff" "datename"
2273 "datepart" "day" "db_id" "db_name" "degrees" "difference" "exp"
2274 "file_id" "file_name" "filegroup_id" "filegroup_name"
2275 "filegroupproperty" "fileproperty" "floor" "formatmessage"
2276 "freetexttable" "fulltextcatalogproperty" "fulltextserviceproperty"
2277 "getansinull" "getdate" "grouping" "host_id" "host_name" "ident_incr"
2278 "ident_seed" "identity" "index_col" "indexproperty" "is_member"
2279 "is_srvrolemember" "isdate" "isnull" "isnumeric" "left" "len" "log"
2280 "log10" "lower" "ltrim" "max" "min" "month" "nchar" "newid" "nullif"
2281 "object_id" "object_name" "objectproperty" "openquery" "openrowset"
2282 "parsename" "patindex" "patindex" "permissions" "pi" "power"
2283 "quotename" "radians" "rand" "replace" "replicate" "reverse" "right"
2284 "round" "rtrim" "session_user" "sign" "sin" "soundex" "space" "sqrt"
2285 "square" "stats_date" "stdev" "stdevp" "str" "stuff" "substring" "sum"
2286 "suser_id" "suser_name" "suser_sid" "suser_sname" "system_user" "tan"
2287 "textptr" "textvalid" "typeproperty" "unicode" "upper" "user"
2288 "user_id" "user_name" "var" "varp" "year"
2291 ;; MS Variables
2292 '("\\b@[a-zA-Z0-9_]*\\b" . font-lock-variable-name-face)
2294 ;; MS Types
2295 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2296 "binary" "bit" "char" "character" "cursor" "datetime" "dec" "decimal"
2297 "double" "float" "image" "int" "integer" "money" "national" "nchar"
2298 "ntext" "numeric" "numeric" "nvarchar" "precision" "real"
2299 "smalldatetime" "smallint" "smallmoney" "text" "timestamp" "tinyint"
2300 "uniqueidentifier" "varbinary" "varchar" "varying"
2303 "Microsoft SQLServer SQL keywords used by font-lock.
2305 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2306 regular expressions are created during compilation by calling the
2307 function `regexp-opt'. Therefore, take a look at the source before
2308 you define your own `sql-mode-ms-font-lock-keywords'.")
2310 (defvar sql-mode-sybase-font-lock-keywords nil
2311 "Sybase SQL keywords used by font-lock.
2313 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2314 regular expressions are created during compilation by calling the
2315 function `regexp-opt'. Therefore, take a look at the source before
2316 you define your own `sql-mode-sybase-font-lock-keywords'.")
2318 (defvar sql-mode-informix-font-lock-keywords nil
2319 "Informix SQL keywords used by font-lock.
2321 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2322 regular expressions are created during compilation by calling the
2323 function `regexp-opt'. Therefore, take a look at the source before
2324 you define your own `sql-mode-informix-font-lock-keywords'.")
2326 (defvar sql-mode-interbase-font-lock-keywords nil
2327 "Interbase SQL keywords used by font-lock.
2329 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2330 regular expressions are created during compilation by calling the
2331 function `regexp-opt'. Therefore, take a look at the source before
2332 you define your own `sql-mode-interbase-font-lock-keywords'.")
2334 (defvar sql-mode-ingres-font-lock-keywords nil
2335 "Ingres SQL keywords used by font-lock.
2337 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2338 regular expressions are created during compilation by calling the
2339 function `regexp-opt'. Therefore, take a look at the source before
2340 you define your own `sql-mode-interbase-font-lock-keywords'.")
2342 (defvar sql-mode-solid-font-lock-keywords nil
2343 "Solid SQL keywords used by font-lock.
2345 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2346 regular expressions are created during compilation by calling the
2347 function `regexp-opt'. Therefore, take a look at the source before
2348 you define your own `sql-mode-solid-font-lock-keywords'.")
2350 (defvaralias 'sql-mode-mariadb-font-lock-keywords 'sql-mode-mysql-font-lock-keywords
2351 "MariaDB is SQL compatible with MySQL.")
2353 (defvar sql-mode-mysql-font-lock-keywords
2354 (eval-when-compile
2355 (list
2356 ;; MySQL Functions
2357 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2358 "acos" "adddate" "addtime" "aes_decrypt" "aes_encrypt" "area"
2359 "asbinary" "ascii" "asin" "astext" "aswkb" "aswkt" "atan" "atan2"
2360 "avg" "bdmpolyfromtext" "bdmpolyfromwkb" "bdpolyfromtext"
2361 "bdpolyfromwkb" "benchmark" "bin" "binlog_gtid_pos" "bit_and"
2362 "bit_count" "bit_length" "bit_or" "bit_xor" "both" "boundary" "buffer"
2363 "cast" "ceil" "ceiling" "centroid" "character_length" "char_length"
2364 "charset" "coalesce" "coercibility" "column_add" "column_check"
2365 "column_create" "column_delete" "column_exists" "column_get"
2366 "column_json" "column_list" "compress" "concat" "concat_ws"
2367 "connection_id" "conv" "convert" "convert_tz" "convexhull" "cos" "cot"
2368 "count" "crc32" "crosses" "cume_dist" "cume_dist" "curdate"
2369 "current_date" "current_time" "current_timestamp" "curtime" "date_add"
2370 "datediff" "date_format" "date_sub" "dayname" "dayofmonth" "dayofweek"
2371 "dayofyear" "decode" "decode_histogram" "degrees" "dense_rank"
2372 "dense_rank" "des_decrypt" "des_encrypt" "dimension" "disjoint" "div"
2373 "elt" "encode" "encrypt" "endpoint" "envelope" "exp" "export_set"
2374 "exteriorring" "extractvalue" "field" "find_in_set" "floor" "format"
2375 "found_rows" "from" "from_base64" "from_days" "from_unixtime"
2376 "geomcollfromtext" "geomcollfromwkb" "geometrycollectionfromtext"
2377 "geometrycollectionfromwkb" "geometryfromtext" "geometryfromwkb"
2378 "geometryn" "geometrytype" "geomfromtext" "geomfromwkb" "get_format"
2379 "get_lock" "glength" "greatest" "group_concat" "hex" "ifnull"
2380 "inet6_aton" "inet6_ntoa" "inet_aton" "inet_ntoa" "instr"
2381 "interiorringn" "intersects" "interval" "isclosed" "isempty"
2382 "is_free_lock" "is_ipv4" "is_ipv4_compat" "is_ipv4_mapped" "is_ipv6"
2383 "isnull" "isring" "issimple" "is_used_lock" "json_array"
2384 "json_array_append" "json_array_insert" "json_compact" "json_contains"
2385 "json_contains_path" "json_depth" "json_detailed" "json_exists"
2386 "json_extract" "json_insert" "json_keys" "json_length" "json_loose"
2387 "json_merge" "json_object" "json_query" "json_quote" "json_remove"
2388 "json_replace" "json_search" "json_set" "json_type" "json_unquote"
2389 "json_valid" "json_value" "lag" "last_day" "last_insert_id" "lastval"
2390 "last_value" "last_value" "lcase" "lead" "leading" "least" "length"
2391 "linefromtext" "linefromwkb" "linestringfromtext" "linestringfromwkb"
2392 "ln" "load_file" "locate" "log" "log10" "log2" "lower" "lpad" "ltrim"
2393 "makedate" "make_set" "maketime" "master_gtid_wait" "master_pos_wait"
2394 "max" "mbrcontains" "mbrdisjoint" "mbrequal" "mbrintersects"
2395 "mbroverlaps" "mbrtouches" "mbrwithin" "md5" "median"
2396 "mid" "min" "mlinefromtext" "mlinefromwkb" "monthname"
2397 "mpointfromtext" "mpointfromwkb" "mpolyfromtext" "mpolyfromwkb"
2398 "multilinestringfromtext" "multilinestringfromwkb"
2399 "multipointfromtext" "multipointfromwkb" "multipolygonfromtext"
2400 "multipolygonfromwkb" "name_const" "nextval" "now" "nth_value" "ntile"
2401 "ntile" "nullif" "numgeometries" "numinteriorrings" "numpoints" "oct"
2402 "octet_length" "old_password" "ord" "percentile_cont"
2403 "percentile_disc" "percent_rank" "percent_rank" "period_add"
2404 "period_diff" "pi" "pointfromtext" "pointfromwkb" "pointn"
2405 "pointonsurface" "polyfromtext" "polyfromwkb" "polygonfromtext"
2406 "polygonfromwkb" "position" "pow" "power" "quote" "radians"
2407 "rand" "rank" "rank" "regexp" "regexp_instr" "regexp_replace"
2408 "regexp_substr" "release_lock" "repeat" "replace" "reverse" "rlike"
2409 "row_number" "row_number" "rpad" "rtrim" "sec_to_time" "setval" "sha"
2410 "sha1" "sha2" "sign" "sin" "sleep" "soundex" "space"
2411 "spider_bg_direct_sql" "spider_copy_tables" "spider_direct_sql"
2412 "spider_flush_table_mon_cache" "sqrt" "srid" "st_area" "startpoint"
2413 "st_asbinary" "st_astext" "st_aswkb" "st_aswkt" "st_boundary"
2414 "st_buffer" "st_centroid" "st_contains" "st_convexhull" "st_crosses"
2415 "std" "stddev" "stddev_pop" "stddev_samp" "st_difference"
2416 "st_dimension" "st_disjoint" "st_distance" "st_endpoint" "st_envelope"
2417 "st_equals" "st_exteriorring" "st_geomcollfromtext"
2418 "st_geomcollfromwkb" "st_geometrycollectionfromtext"
2419 "st_geometrycollectionfromwkb" "st_geometryfromtext"
2420 "st_geometryfromwkb" "st_geometryn" "st_geometrytype"
2421 "st_geomfromtext" "st_geomfromwkb" "st_interiorringn"
2422 "st_intersection" "st_intersects" "st_isclosed" "st_isempty"
2423 "st_isring" "st_issimple" "st_length" "st_linefromtext"
2424 "st_linefromwkb" "st_linestringfromtext" "st_linestringfromwkb"
2425 "st_numgeometries" "st_numinteriorrings" "st_numpoints" "st_overlaps"
2426 "st_pointfromtext" "st_pointfromwkb" "st_pointn" "st_pointonsurface"
2427 "st_polyfromtext" "st_polyfromwkb" "st_polygonfromtext"
2428 "st_polygonfromwkb" "strcmp" "st_relate" "str_to_date" "st_srid"
2429 "st_startpoint" "st_symdifference" "st_touches" "st_union" "st_within"
2430 "st_x" "st_y" "subdate" "substr" "substring" "substring_index"
2431 "subtime" "sum" "sysdate" "tan" "timediff" "time_format"
2432 "timestampadd" "timestampdiff" "time_to_sec" "to_base64" "to_days"
2433 "to_seconds" "touches" "trailing" "trim" "ucase" "uncompress"
2434 "uncompressed_length" "unhex" "unix_timestamp" "updatexml" "upper"
2435 "user" "utc_date" "utc_time" "utc_timestamp" "uuid" "uuid_short"
2436 "variance" "var_pop" "var_samp" "version" "weekday"
2437 "weekofyear" "weight_string" "within"
2440 ;; MySQL Keywords
2441 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2442 "accessible" "action" "add" "after" "against" "all" "alter" "analyze"
2443 "and" "as" "asc" "auto_increment" "avg_row_length" "bdb" "between"
2444 "body" "by" "cascade" "case" "change" "character" "check" "checksum"
2445 "close" "collate" "collation" "column" "columns" "comment" "committed"
2446 "concurrent" "condition" "constraint" "create" "cross" "data"
2447 "database" "databases" "default" "delayed" "delay_key_write" "delete"
2448 "desc" "directory" "disable" "distinct" "distinctrow" "do" "drop"
2449 "dual" "dumpfile" "duplicate" "else" "elseif" "elsif" "enable"
2450 "enclosed" "end" "escaped" "exists" "exit" "explain" "fields" "first"
2451 "for" "force" "foreign" "from" "full" "fulltext" "global" "group"
2452 "handler" "having" "heap" "high_priority" "history" "if" "ignore"
2453 "ignore_server_ids" "in" "index" "infile" "inner" "insert"
2454 "insert_method" "into" "is" "isam" "isolation" "join" "key" "keys"
2455 "kill" "last" "leave" "left" "level" "like" "limit" "linear" "lines"
2456 "load" "local" "lock" "long" "loop" "low_priority"
2457 "master_heartbeat_period" "master_ssl_verify_server_cert" "match"
2458 "max_rows" "maxvalue" "merge" "min_rows" "mode" "modify" "mrg_myisam"
2459 "myisam" "natural" "next" "no" "not" "no_write_to_binlog" "null"
2460 "offset" "oj" "on" "open" "optimize" "optionally" "or" "order" "outer"
2461 "outfile" "over" "package" "pack_keys" "partial" "partition"
2462 "password" "period" "prev" "primary" "procedure" "purge" "quick"
2463 "raid0" "raid_type" "raise" "range" "read" "read_write" "references"
2464 "release" "rename" "repeatable" "require" "resignal" "restrict"
2465 "returning" "right" "rollback" "rollup" "row_format" "rowtype"
2466 "savepoint" "schemas" "select" "separator" "serializable" "session"
2467 "set" "share" "show" "signal" "slow" "spatial" "sql_big_result"
2468 "sql_buffer_result" "sql_cache" "sql_calc_found_rows" "sql_no_cache"
2469 "sql_small_result" "ssl" "starting" "straight_join" "striped"
2470 "system_time" "table" "tables" "temporary" "terminated" "then" "to"
2471 "transaction" "truncate" "type" "uncommitted" "undo" "union" "unique"
2472 "unlock" "update" "use" "using" "values" "versioning" "when" "where"
2473 "while" "window" "with" "write" "xor"
2476 ;; MySQL Data Types
2477 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2478 "bigint" "binary" "bit" "blob" "bool" "boolean" "byte" "char" "curve"
2479 "date" "datetime" "day" "day_hour" "day_microsecond" "day_minute"
2480 "day_second" "dec" "decimal" "double" "enum" "fixed" "float" "float4"
2481 "float8" "geometry" "geometrycollection" "hour" "hour_microsecond"
2482 "hour_minute" "hour_second" "int" "int1" "int2" "int3" "int4" "int8"
2483 "integer" "json" "line" "linearring" "linestring" "longblob"
2484 "longtext" "mediumblob" "mediumint" "mediumtext" "microsecond"
2485 "middleint" "minute" "minute_microsecond" "minute_second" "month"
2486 "multicurve" "multilinestring" "multipoint" "multipolygon"
2487 "multisurface" "national" "numeric" "point" "polygon" "precision"
2488 "quarter" "real" "second" "second_microsecond" "signed" "smallint"
2489 "surface" "text" "time" "timestamp" "tinyblob" "tinyint" "tinytext"
2490 "unsigned" "varbinary" "varchar" "varcharacter" "week" "year" "year2"
2491 "year4" "year_month" "zerofill"
2494 "MySQL SQL keywords used by font-lock.
2496 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2497 regular expressions are created during compilation by calling the
2498 function `regexp-opt'. Therefore, take a look at the source before
2499 you define your own `sql-mode-mysql-font-lock-keywords'.")
2501 (defvar sql-mode-sqlite-font-lock-keywords
2502 (eval-when-compile
2503 (list
2504 ;; SQLite commands
2505 '("^[.].*$" . font-lock-doc-face)
2507 ;; SQLite Keyword
2508 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2509 "abort" "action" "add" "after" "all" "alter" "analyze" "and" "as"
2510 "asc" "attach" "autoincrement" "before" "begin" "between" "by"
2511 "cascade" "case" "cast" "check" "collate" "column" "commit" "conflict"
2512 "constraint" "create" "cross" "database" "default" "deferrable"
2513 "deferred" "delete" "desc" "detach" "distinct" "drop" "each" "else"
2514 "end" "escape" "except" "exclusive" "exists" "explain" "fail" "for"
2515 "foreign" "from" "full" "glob" "group" "having" "if" "ignore"
2516 "immediate" "in" "index" "indexed" "initially" "inner" "insert"
2517 "instead" "intersect" "into" "is" "isnull" "join" "key" "left" "like"
2518 "limit" "match" "natural" "no" "not" "notnull" "null" "of" "offset"
2519 "on" "or" "order" "outer" "plan" "pragma" "primary" "query" "raise"
2520 "references" "regexp" "reindex" "release" "rename" "replace"
2521 "restrict" "right" "rollback" "row" "savepoint" "select" "set" "table"
2522 "temp" "temporary" "then" "to" "transaction" "trigger" "union"
2523 "unique" "update" "using" "vacuum" "values" "view" "virtual" "when"
2524 "where"
2526 ;; SQLite Data types
2527 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2528 "int" "integer" "tinyint" "smallint" "mediumint" "bigint" "unsigned"
2529 "big" "int2" "int8" "character" "varchar" "varying" "nchar" "native"
2530 "nvarchar" "text" "clob" "blob" "real" "double" "precision" "float"
2531 "numeric" "number" "decimal" "boolean" "date" "datetime"
2533 ;; SQLite Functions
2534 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2535 ;; Core functions
2536 "abs" "changes" "coalesce" "glob" "ifnull" "hex" "last_insert_rowid"
2537 "length" "like" "load_extension" "lower" "ltrim" "max" "min" "nullif"
2538 "quote" "random" "randomblob" "replace" "round" "rtrim" "soundex"
2539 "sqlite_compileoption_get" "sqlite_compileoption_used"
2540 "sqlite_source_id" "sqlite_version" "substr" "total_changes" "trim"
2541 "typeof" "upper" "zeroblob"
2542 ;; Date/time functions
2543 "time" "julianday" "strftime"
2544 "current_date" "current_time" "current_timestamp"
2545 ;; Aggregate functions
2546 "avg" "count" "group_concat" "max" "min" "sum" "total"
2549 "SQLite SQL keywords used by font-lock.
2551 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2552 regular expressions are created during compilation by calling the
2553 function `regexp-opt'. Therefore, take a look at the source before
2554 you define your own `sql-mode-sqlite-font-lock-keywords'.")
2556 (defvar sql-mode-db2-font-lock-keywords nil
2557 "DB2 SQL keywords used by font-lock.
2559 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2560 regular expressions are created during compilation by calling the
2561 function `regexp-opt'. Therefore, take a look at the source before
2562 you define your own `sql-mode-db2-font-lock-keywords'.")
2564 (defvar sql-mode-font-lock-keywords nil
2565 "SQL keywords used by font-lock.
2567 Setting this variable directly no longer has any affect. Use
2568 `sql-product' and `sql-add-product-keywords' to control the
2569 highlighting rules in SQL mode.")
2573 ;;; SQL Product support functions
2575 (defun sql-read-product (prompt &optional initial)
2576 "Read a valid SQL product."
2577 (let ((init (or (and initial (symbol-name initial)) "ansi")))
2578 (intern (completing-read
2579 prompt
2580 (mapcar (lambda (info) (symbol-name (car info)))
2581 sql-product-alist)
2582 nil 'require-match
2583 init 'sql-product-history init))))
2585 (defun sql-add-product (product display &rest plist)
2586 "Add support for a database product in `sql-mode'.
2588 Add PRODUCT to `sql-product-alist' which enables `sql-mode' to
2589 properly support syntax highlighting and interactive interaction.
2590 DISPLAY is the name of the SQL product that will appear in the
2591 menu bar and in messages. PLIST initializes the product
2592 configuration."
2594 ;; Don't do anything if the product is already supported
2595 (if (assoc product sql-product-alist)
2596 (user-error "Product `%s' is already defined" product)
2598 ;; Add product to the alist
2599 (add-to-list 'sql-product-alist `(,product :name ,display . ,plist))
2600 ;; Add a menu item to the SQL->Product menu
2601 (easy-menu-add-item sql-mode-menu '("Product")
2602 ;; Each product is represented by a radio
2603 ;; button with it's display name.
2604 `[,display
2605 (sql-set-product ',product)
2606 :style radio
2607 :selected (eq sql-product ',product)]
2608 ;; Maintain the product list in
2609 ;; (case-insensitive) alphabetic order of the
2610 ;; display names. Loop thru each keymap item
2611 ;; looking for an item whose display name is
2612 ;; after this product's name.
2613 (let ((next-item)
2614 (down-display (downcase display)))
2615 (map-keymap (lambda (k b)
2616 (when (and (not next-item)
2617 (string-lessp down-display
2618 (downcase (cadr b))))
2619 (setq next-item k)))
2620 (easy-menu-get-map sql-mode-menu '("Product")))
2621 next-item))
2622 product))
2624 (defun sql-del-product (product)
2625 "Remove support for PRODUCT in `sql-mode'."
2627 ;; Remove the menu item based on the display name
2628 (easy-menu-remove-item sql-mode-menu '("Product") (sql-get-product-feature product :name))
2629 ;; Remove the product alist item
2630 (setq sql-product-alist (assq-delete-all product sql-product-alist))
2631 nil)
2633 (defun sql-set-product-feature (product feature newvalue)
2634 "Set FEATURE of database PRODUCT to NEWVALUE.
2636 The PRODUCT must be a symbol which identifies the database
2637 product. The product must have already exist on the product
2638 list. See `sql-add-product' to add new products. The FEATURE
2639 argument must be a plist keyword accepted by
2640 `sql-product-alist'."
2642 (let* ((p (assoc product sql-product-alist))
2643 (v (plist-get (cdr p) feature)))
2644 (if p
2645 (if (and
2646 (member feature sql-indirect-features)
2647 (symbolp v))
2648 (set v newvalue)
2649 (setcdr p (plist-put (cdr p) feature newvalue)))
2650 (error "`%s' is not a known product; use `sql-add-product' to add it first." product))))
2652 (defun sql-get-product-feature (product feature &optional fallback not-indirect)
2653 "Lookup FEATURE associated with a SQL PRODUCT.
2655 If the FEATURE is nil for PRODUCT, and FALLBACK is specified,
2656 then the FEATURE associated with the FALLBACK product is
2657 returned.
2659 If the FEATURE is in the list `sql-indirect-features', and the
2660 NOT-INDIRECT parameter is not set, then the value of the symbol
2661 stored in the connect alist is returned.
2663 See `sql-product-alist' for a list of products and supported features."
2664 (let* ((p (assoc product sql-product-alist))
2665 (v (plist-get (cdr p) feature)))
2667 (if p
2668 ;; If no value and fallback, lookup feature for fallback
2669 (if (and (not v)
2670 fallback
2671 (not (eq product fallback)))
2672 (sql-get-product-feature fallback feature)
2674 (if (and
2675 (member feature sql-indirect-features)
2676 (not not-indirect)
2677 (symbolp v))
2678 (symbol-value v)
2680 (error "`%s' is not a known product; use `sql-add-product' to add it first." product)
2681 nil)))
2683 (defun sql-product-font-lock (keywords-only imenu)
2684 "Configure font-lock and imenu with product-specific settings.
2686 The KEYWORDS-ONLY flag is passed to font-lock to specify whether
2687 only keywords should be highlighted and syntactic highlighting
2688 skipped. The IMENU flag indicates whether `imenu-mode' should
2689 also be configured."
2691 (let
2692 ;; Get the product-specific syntax-alist.
2693 ((syntax-alist (sql-product-font-lock-syntax-alist)))
2695 ;; Get the product-specific keywords.
2696 (set (make-local-variable 'sql-mode-font-lock-keywords)
2697 (append
2698 (unless (eq sql-product 'ansi)
2699 (sql-get-product-feature sql-product :font-lock))
2700 ;; Always highlight ANSI keywords
2701 (sql-get-product-feature 'ansi :font-lock)
2702 ;; Fontify object names in CREATE, DROP and ALTER DDL
2703 ;; statements
2704 (list sql-mode-font-lock-object-name)))
2706 ;; Setup font-lock. Force re-parsing of `font-lock-defaults'.
2707 (kill-local-variable 'font-lock-set-defaults)
2708 (set (make-local-variable 'font-lock-defaults)
2709 (list 'sql-mode-font-lock-keywords
2710 keywords-only t syntax-alist))
2712 ;; Force font lock to reinitialize if it is already on
2713 ;; Otherwise, we can wait until it can be started.
2714 (when (and (fboundp 'font-lock-mode)
2715 (boundp 'font-lock-mode)
2716 font-lock-mode)
2717 (font-lock-mode-internal nil)
2718 (font-lock-mode-internal t))
2720 (add-hook 'font-lock-mode-hook
2721 (lambda ()
2722 ;; Provide defaults for new font-lock faces.
2723 (defvar font-lock-builtin-face
2724 (if (boundp 'font-lock-preprocessor-face)
2725 font-lock-preprocessor-face
2726 font-lock-keyword-face))
2727 (defvar font-lock-doc-face font-lock-string-face))
2728 nil t)
2730 ;; Setup imenu; it needs the same syntax-alist.
2731 (when imenu
2732 (setq imenu-syntax-alist syntax-alist))))
2734 ;;;###autoload
2735 (defun sql-add-product-keywords (product keywords &optional append)
2736 "Add highlighting KEYWORDS for SQL PRODUCT.
2738 PRODUCT should be a symbol, the name of a SQL product, such as
2739 `oracle'. KEYWORDS should be a list; see the variable
2740 `font-lock-keywords'. By default they are added at the beginning
2741 of the current highlighting list. If optional argument APPEND is
2742 `set', they are used to replace the current highlighting list.
2743 If APPEND is any other non-nil value, they are added at the end
2744 of the current highlighting list.
2746 For example:
2748 (sql-add-product-keywords \\='ms
2749 \\='((\"\\\\b\\\\w+_t\\\\b\" . font-lock-type-face)))
2751 adds a fontification pattern to fontify identifiers ending in
2752 `_t' as data types."
2754 (let* ((sql-indirect-features nil)
2755 (font-lock-var (sql-get-product-feature product :font-lock))
2756 (old-val))
2758 (setq old-val (symbol-value font-lock-var))
2759 (set font-lock-var
2760 (if (eq append 'set)
2761 keywords
2762 (if append
2763 (append old-val keywords)
2764 (append keywords old-val))))))
2766 (defun sql-for-each-login (login-params body)
2767 "Iterate through login parameters and return a list of results."
2768 (delq nil
2769 (mapcar
2770 (lambda (param)
2771 (let ((token (or (car-safe param) param))
2772 (plist (cdr-safe param)))
2773 (funcall body token plist)))
2774 login-params)))
2778 ;;; Functions to switch highlighting
2780 (defun sql-product-syntax-table ()
2781 (let ((table (copy-syntax-table sql-mode-syntax-table)))
2782 (mapc (lambda (entry)
2783 (modify-syntax-entry (car entry) (cdr entry) table))
2784 (sql-get-product-feature sql-product :syntax-alist))
2785 table))
2787 (defun sql-product-font-lock-syntax-alist ()
2788 (append
2789 ;; Change all symbol character to word characters
2790 (mapcar
2791 (lambda (entry) (if (string= (substring (cdr entry) 0 1) "_")
2792 (cons (car entry)
2793 (concat "w" (substring (cdr entry) 1)))
2794 entry))
2795 (sql-get-product-feature sql-product :syntax-alist))
2796 '((?_ . "w"))))
2798 (defun sql-highlight-product ()
2799 "Turn on the font highlighting for the SQL product selected."
2800 (when (derived-mode-p 'sql-mode)
2801 ;; Enhance the syntax table for the product
2802 (set-syntax-table (sql-product-syntax-table))
2804 ;; Setup font-lock
2805 (sql-product-font-lock nil t)
2807 ;; Set the mode name to include the product.
2808 (setq mode-name (concat "SQL[" (or (sql-get-product-feature sql-product :name)
2809 (symbol-name sql-product)) "]"))))
2811 (defun sql-set-product (product)
2812 "Set `sql-product' to PRODUCT and enable appropriate highlighting."
2813 (interactive
2814 (list (sql-read-product "SQL product: ")))
2815 (if (stringp product) (setq product (intern product)))
2816 (when (not (assoc product sql-product-alist))
2817 (user-error "SQL product %s is not supported; treated as ANSI" product)
2818 (setq product 'ansi))
2820 ;; Save product setting and fontify.
2821 (setq sql-product product)
2822 (sql-highlight-product))
2823 (defalias 'sql-set-dialect 'sql-set-product)
2825 (defun sql-buffer-hidden-p (buf)
2826 "Is the buffer hidden?"
2827 (string-prefix-p " "
2828 (cond
2829 ((stringp buf)
2830 (when (get-buffer buf)
2831 buf))
2832 ((bufferp buf)
2833 (buffer-name buf))
2834 (t nil))))
2836 (defun sql-display-buffer (buf)
2837 "Display a SQLi buffer based on `sql-display-sqli-buffer-function'.
2839 If BUF is hidden or `sql-display-sqli-buffer-function' is nil,
2840 then the buffer will not be displayed. Otherwise the BUF is
2841 displayed."
2842 (unless (sql-buffer-hidden-p buf)
2843 (cond
2844 ((eq sql-display-sqli-buffer-function t)
2845 (pop-to-buffer buf))
2846 ((not sql-display-sqli-buffer-function)
2847 nil)
2848 ((functionp sql-display-sqli-buffer-function)
2849 (funcall sql-display-sqli-buffer-function buf))
2851 (message "Invalid setting of `sql-display-sqli-buffer-function'")
2852 (pop-to-buffer buf)))))
2854 (defun sql-make-progress-reporter (buf message &optional min-value max-value current-value min-change min-time)
2855 "Make a progress reporter if BUF is not hidden."
2856 (unless (or (sql-buffer-hidden-p buf)
2857 (not sql-display-sqli-buffer-function))
2858 (make-progress-reporter message min-value max-value current-value min-change min-time)))
2860 (defun sql-progress-reporter-update (reporter &optional value)
2861 "Report progress of an operation in the echo area."
2862 (when reporter
2863 (progress-reporter-update reporter value)))
2865 (defun sql-progress-reporter-done (reporter)
2866 "Print reporter’s message followed by word \"done\" in echo area."
2867 (when reporter
2868 (progress-reporter-done reporter)))
2870 ;;; SMIE support
2872 ;; Needs a lot more love than I can provide. --Stef
2874 ;; (require 'smie)
2876 ;; (defconst sql-smie-grammar
2877 ;; (smie-prec2->grammar
2878 ;; (smie-bnf->prec2
2879 ;; ;; Partly based on http://www.h2database.com/html/grammar.html
2880 ;; '((cmd ("SELECT" select-exp "FROM" select-table-exp)
2881 ;; )
2882 ;; (select-exp ("*") (exp) (exp "AS" column-alias))
2883 ;; (column-alias)
2884 ;; (select-table-exp (table-exp "WHERE" exp) (table-exp))
2885 ;; (table-exp)
2886 ;; (exp ("CASE" exp "WHEN" exp "THEN" exp "ELSE" exp "END")
2887 ;; ("CASE" exp "WHEN" exp "THEN" exp "END"))
2888 ;; ;; Random ad-hoc additions.
2889 ;; (foo (foo "," foo))
2890 ;; )
2891 ;; '((assoc ",")))))
2893 ;; (defun sql-smie-rules (kind token)
2894 ;; (pcase (cons kind token)
2895 ;; (`(:list-intro . ,_) t)
2896 ;; (`(:before . "(") (smie-rule-parent))))
2898 ;;; Motion Functions
2900 (defun sql-statement-regexp (prod)
2901 (let* ((ansi-stmt (sql-get-product-feature 'ansi :statement))
2902 (prod-stmt (sql-get-product-feature prod :statement)))
2903 (concat "^\\<"
2904 (if prod-stmt
2905 (concat "\\(" ansi-stmt "\\|" prod-stmt "\\)")
2906 ansi-stmt)
2907 "\\>")))
2909 (defun sql-beginning-of-statement (arg)
2910 "Move to the beginning of the current SQL statement."
2911 (interactive "p")
2913 (let ((here (point))
2914 (regexp (sql-statement-regexp sql-product))
2915 last next)
2917 ;; Go to the end of the statement before the start we desire
2918 (setq last (or (sql-end-of-statement (- arg))
2919 (point-min)))
2920 ;; And find the end after that
2921 (setq next (or (sql-end-of-statement 1)
2922 (point-max)))
2924 ;; Our start must be between them
2925 (goto-char last)
2926 ;; Find a beginning-of-stmt that's not in a comment
2927 (while (and (re-search-forward regexp next t 1)
2928 (nth 7 (syntax-ppss)))
2929 (goto-char (match-end 0)))
2930 (goto-char
2931 (if (match-data)
2932 (match-beginning 0)
2933 last))
2934 (beginning-of-line)
2935 ;; If we didn't move, try again
2936 (when (= here (point))
2937 (sql-beginning-of-statement (* 2 (cl-signum arg))))))
2939 (defun sql-end-of-statement (arg)
2940 "Move to the end of the current SQL statement."
2941 (interactive "p")
2942 (let ((term (sql-get-product-feature sql-product :terminator))
2943 (re-search (if (> 0 arg) 're-search-backward 're-search-forward))
2944 (here (point))
2945 (n 0))
2946 (when (consp term)
2947 (setq term (car term)))
2948 ;; Iterate until we've moved the desired number of stmt ends
2949 (while (not (= (cl-signum arg) 0))
2950 ;; if we're looking at the terminator, jump by 2
2951 (if (or (and (> 0 arg) (looking-back term nil))
2952 (and (< 0 arg) (looking-at term)))
2953 (setq n 2)
2954 (setq n 1))
2955 ;; If we found another end-of-stmt
2956 (if (not (apply re-search term nil t n nil))
2957 (setq arg 0)
2958 ;; count it if we're not in a comment
2959 (unless (nth 7 (syntax-ppss))
2960 (setq arg (- arg (cl-signum arg))))))
2961 (goto-char (if (match-data)
2962 (match-end 0)
2963 here))))
2965 ;;; Small functions
2967 (defun sql-magic-go (arg)
2968 "Insert \"o\" and call `comint-send-input'.
2969 `sql-electric-stuff' must be the symbol `go'."
2970 (interactive "P")
2971 (self-insert-command (prefix-numeric-value arg))
2972 (if (and (equal sql-electric-stuff 'go)
2973 (save-excursion
2974 (comint-bol nil)
2975 (looking-at "go\\b")))
2976 (comint-send-input)))
2977 (put 'sql-magic-go 'delete-selection t)
2979 (defun sql-magic-semicolon (arg)
2980 "Insert semicolon and call `comint-send-input'.
2981 `sql-electric-stuff' must be the symbol `semicolon'."
2982 (interactive "P")
2983 (self-insert-command (prefix-numeric-value arg))
2984 (if (equal sql-electric-stuff 'semicolon)
2985 (comint-send-input)))
2986 (put 'sql-magic-semicolon 'delete-selection t)
2988 (defun sql-accumulate-and-indent ()
2989 "Continue SQL statement on the next line."
2990 (interactive)
2991 (if (fboundp 'comint-accumulate)
2992 (comint-accumulate)
2993 (newline))
2994 (indent-according-to-mode))
2996 (defun sql-help-list-products (indent freep)
2997 "Generate listing of products available for use under SQLi.
2999 List products with :free-software attribute set to FREEP. Indent
3000 each line with INDENT."
3002 (let (sqli-func doc)
3003 (setq doc "")
3004 (dolist (p sql-product-alist)
3005 (setq sqli-func (intern (concat "sql-" (symbol-name (car p)))))
3007 (if (and (fboundp sqli-func)
3008 (eq (sql-get-product-feature (car p) :free-software) freep))
3009 (setq doc
3010 (concat doc
3011 indent
3012 (or (sql-get-product-feature (car p) :name)
3013 (symbol-name (car p)))
3014 ":\t"
3015 "\\["
3016 (symbol-name sqli-func)
3017 "]\n"))))
3018 doc))
3020 (defun sql-help ()
3021 "Show short help for the SQL modes."
3022 (interactive)
3023 (describe-function 'sql-help))
3024 (put 'sql-help 'function-documentation '(sql--make-help-docstring))
3026 (defvar sql--help-docstring
3027 "Show short help for the SQL modes.
3028 Use an entry function to open an interactive SQL buffer. This buffer is
3029 usually named `*SQL*'. The name of the major mode is SQLi.
3031 Use the following commands to start a specific SQL interpreter:
3033 \\\\FREE
3035 Other non-free SQL implementations are also supported:
3037 \\\\NONFREE
3039 But we urge you to choose a free implementation instead of these.
3041 You can also use \\[sql-product-interactive] to invoke the
3042 interpreter for the current `sql-product'.
3044 Once you have the SQLi buffer, you can enter SQL statements in the
3045 buffer. The output generated is appended to the buffer and a new prompt
3046 is generated. See the In/Out menu in the SQLi buffer for some functions
3047 that help you navigate through the buffer, the input history, etc.
3049 If you have a really complex SQL statement or if you are writing a
3050 procedure, you can do this in a separate buffer. Put the new buffer in
3051 `sql-mode' by calling \\[sql-mode]. The name of this buffer can be
3052 anything. The name of the major mode is SQL.
3054 In this SQL buffer (SQL mode), you can send the region or the entire
3055 buffer to the interactive SQL buffer (SQLi mode). The results are
3056 appended to the SQLi buffer without disturbing your SQL buffer.")
3058 (defun sql--make-help-docstring ()
3059 "Return a docstring for `sql-help' listing loaded SQL products."
3060 (let ((doc sql--help-docstring))
3061 ;; Insert FREE software list
3062 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]FREE\\s-*$" doc 0)
3063 (setq doc (replace-match (sql-help-list-products (match-string 1 doc) t)
3064 t t doc 0)))
3065 ;; Insert non-FREE software list
3066 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]NONFREE\\s-*$" doc 0)
3067 (setq doc (replace-match (sql-help-list-products (match-string 1 doc) nil)
3068 t t doc 0)))
3069 doc))
3071 (defun sql-default-value (var)
3072 "Fetch the value of a variable.
3074 If the current buffer is in `sql-interactive-mode', then fetch
3075 the global value, otherwise use the buffer local value."
3076 (if (derived-mode-p 'sql-interactive-mode)
3077 (default-value var)
3078 (buffer-local-value var (current-buffer))))
3080 (defun sql-get-login-ext (symbol prompt history-var plist)
3081 "Prompt user with extended login parameters.
3083 The global value of SYMBOL is the last value and the global value
3084 of the SYMBOL is set based on the user's input.
3086 If PLIST is nil, then the user is simply prompted for a string
3087 value.
3089 The property `:default' specifies the default value. If the
3090 `:number' property is non-nil then ask for a number.
3092 The `:file' property prompts for a file name that must match the
3093 regexp pattern specified in its value.
3095 The `:completion' property prompts for a string specified by its
3096 value. (The property value is used as the PREDICATE argument to
3097 `completing-read'.)
3099 For both `:file' and `:completion', there can also be a
3100 `:must-match' property that controls REQUIRE-MATCH parameter to
3101 `completing-read'."
3103 (set-default
3104 symbol
3105 (let* ((default (plist-get plist :default))
3106 (last-value (sql-default-value symbol))
3107 (prompt-def
3108 (if default
3109 (if (string-match "\\(\\):[ \t]*\\'" prompt)
3110 (replace-match (format " (default \"%s\")" default) t t prompt 1)
3111 (replace-regexp-in-string "[ \t]*\\'"
3112 (format " (default \"%s\") " default)
3113 prompt t t))
3114 prompt))
3115 (use-dialog-box nil))
3116 (cond
3117 ((plist-member plist :file)
3118 (let ((file-name
3119 (read-file-name prompt
3120 (file-name-directory last-value)
3121 default
3122 (if (plist-member plist :must-match)
3123 (plist-get plist :must-match)
3125 (file-name-nondirectory last-value)
3126 (when (plist-get plist :file)
3127 `(lambda (f)
3128 (if (not (file-regular-p f))
3130 (string-match
3131 (concat "\\<" ,(plist-get plist :file) "\\>")
3132 (file-name-nondirectory f))))))))
3133 (if (string= file-name "")
3135 (expand-file-name file-name))))
3137 ((plist-member plist :completion)
3138 (completing-read prompt-def
3139 (plist-get plist :completion)
3141 (if (plist-member plist :must-match)
3142 (plist-get plist :must-match)
3144 last-value
3145 history-var
3146 default))
3148 ((plist-get plist :number)
3149 (read-number prompt (or default last-value 0)))
3152 (read-string prompt-def last-value history-var default))))))
3154 (defun sql-get-login (&rest what)
3155 "Get username, password and database from the user.
3157 The variables `sql-user', `sql-password', `sql-server', and
3158 `sql-database' can be customized. They are used as the default values.
3159 Usernames, servers and databases are stored in `sql-user-history',
3160 `sql-server-history' and `database-history'. Passwords are not stored
3161 in a history.
3163 Parameter WHAT is a list of tokens passed as arguments in the
3164 function call. The function asks for the username if WHAT
3165 contains the symbol `user', for the password if it contains the
3166 symbol `password', for the server if it contains the symbol
3167 `server', and for the database if it contains the symbol
3168 `database'. The members of WHAT are processed in the order in
3169 which they are provided.
3171 Each token may also be a list with the token in the car and a
3172 plist of options as the cdr. The following properties are
3173 supported:
3175 :file <filename-regexp>
3176 :completion <list-of-strings-or-function>
3177 :default <default-value>
3178 :number t
3180 In order to ask the user for username, password and database, call the
3181 function like this: (sql-get-login \\='user \\='password \\='database)."
3182 (dolist (w what)
3183 (let ((plist (cdr-safe w)))
3184 (pcase (or (car-safe w) w)
3185 (`user
3186 (sql-get-login-ext 'sql-user "User: " 'sql-user-history plist))
3188 (`password
3189 (setq-default sql-password
3190 (read-passwd "Password: " nil (sql-default-value 'sql-password))))
3192 (`server
3193 (sql-get-login-ext 'sql-server "Server: " 'sql-server-history plist))
3195 (`database
3196 (sql-get-login-ext 'sql-database "Database: "
3197 'sql-database-history plist))
3199 (`port
3200 (sql-get-login-ext 'sql-port "Port: "
3201 nil (append '(:number t) plist)))))))
3203 (defun sql-find-sqli-buffer (&optional product connection)
3204 "Return the name of the current default SQLi buffer or nil.
3205 In order to qualify, the SQLi buffer must be alive, be in
3206 `sql-interactive-mode' and have a process."
3207 (let ((buf sql-buffer)
3208 (prod (or product sql-product)))
3210 ;; Current sql-buffer, if there is one.
3211 (and (sql-buffer-live-p buf prod connection)
3212 buf)
3213 ;; Global sql-buffer
3214 (and (setq buf (default-value 'sql-buffer))
3215 (sql-buffer-live-p buf prod connection)
3216 buf)
3217 ;; Look thru each buffer
3218 (car (apply #'append
3219 (mapcar (lambda (b)
3220 (and (sql-buffer-live-p b prod connection)
3221 (list (buffer-name b))))
3222 (buffer-list)))))))
3224 (defun sql-set-sqli-buffer-generally ()
3225 "Set SQLi buffer for all SQL buffers that have none.
3226 This function checks all SQL buffers for their SQLi buffer. If their
3227 SQLi buffer is nonexistent or has no process, it is set to the current
3228 default SQLi buffer. The current default SQLi buffer is determined
3229 using `sql-find-sqli-buffer'. If `sql-buffer' is set,
3230 `sql-set-sqli-hook' is run."
3231 (interactive)
3232 (save-excursion
3233 (let ((buflist (buffer-list))
3234 (default-buffer (sql-find-sqli-buffer)))
3235 (setq-default sql-buffer default-buffer)
3236 (while (not (null buflist))
3237 (let ((candidate (car buflist)))
3238 (set-buffer candidate)
3239 (if (and (derived-mode-p 'sql-mode)
3240 (not (sql-buffer-live-p sql-buffer)))
3241 (progn
3242 (setq sql-buffer default-buffer)
3243 (when default-buffer
3244 (run-hooks 'sql-set-sqli-hook)))))
3245 (setq buflist (cdr buflist))))))
3247 (defun sql-set-sqli-buffer ()
3248 "Set the SQLi buffer SQL strings are sent to.
3250 Call this function in a SQL buffer in order to set the SQLi buffer SQL
3251 strings are sent to. Calling this function sets `sql-buffer' and runs
3252 `sql-set-sqli-hook'.
3254 If you call it from a SQL buffer, this sets the local copy of
3255 `sql-buffer'.
3257 If you call it from anywhere else, it sets the global copy of
3258 `sql-buffer'."
3259 (interactive)
3260 (let ((default-buffer (sql-find-sqli-buffer)))
3261 (if (null default-buffer)
3262 (sql-product-interactive)
3263 (let ((new-buffer (read-buffer "New SQLi buffer: " default-buffer t)))
3264 (if (null (sql-buffer-live-p new-buffer))
3265 (user-error "Buffer %s is not a working SQLi buffer" new-buffer)
3266 (when new-buffer
3267 (setq sql-buffer new-buffer)
3268 (run-hooks 'sql-set-sqli-hook)))))))
3270 (defun sql-show-sqli-buffer ()
3271 "Display the current SQLi buffer.
3273 This is the buffer SQL strings are sent to.
3274 It is stored in the variable `sql-buffer'.
3276 See also `sql-help' on how to create such a buffer."
3277 (interactive)
3278 (unless (and sql-buffer (buffer-live-p (get-buffer sql-buffer))
3279 (get-buffer-process sql-buffer))
3280 (sql-set-sqli-buffer))
3281 (display-buffer sql-buffer))
3283 (defun sql-make-alternate-buffer-name (&optional product)
3284 "Return a string that can be used to rename a SQLi buffer.
3285 This is used to set `sql-alternate-buffer-name' within
3286 `sql-interactive-mode'.
3288 If the session was started with `sql-connect' then the alternate
3289 name would be the name of the connection.
3291 Otherwise, it uses the parameters identified by the :sqlilogin
3292 parameter.
3294 If all else fails, the alternate name would be the user and
3295 server/database name."
3297 (let ((name ""))
3299 ;; Build a name using the :sqli-login setting
3300 (setq name
3301 (apply #'concat
3302 (cdr
3303 (apply #'append nil
3304 (sql-for-each-login
3305 (sql-get-product-feature (or product sql-product) :sqli-login)
3306 (lambda (token plist)
3307 (pcase token
3308 (`user
3309 (unless (string= "" sql-user)
3310 (list "/" sql-user)))
3311 (`port
3312 (unless (or (not (numberp sql-port))
3313 (= 0 sql-port))
3314 (list ":" (number-to-string sql-port))))
3315 (`server
3316 (unless (string= "" sql-server)
3317 (list "."
3318 (if (plist-member plist :file)
3319 (file-name-nondirectory sql-server)
3320 sql-server))))
3321 (`database
3322 (unless (string= "" sql-database)
3323 (list "@"
3324 (if (plist-member plist :file)
3325 (file-name-nondirectory sql-database)
3326 sql-database))))
3328 ;; (`password nil)
3329 (_ nil))))))))
3331 ;; If there's a connection, use it and the name thus far
3332 (if sql-connection
3333 (format "<%s>%s" sql-connection (or name ""))
3335 ;; If there is no name, try to create something meaningful
3336 (if (string= "" (or name ""))
3337 (concat
3338 (if (string= "" sql-user)
3339 (if (string= "" (user-login-name))
3341 (concat (user-login-name) "/"))
3342 (concat sql-user "/"))
3343 (if (string= "" sql-database)
3344 (if (string= "" sql-server)
3345 (system-name)
3346 sql-server)
3347 sql-database))
3349 ;; Use the name we've got
3350 name))))
3352 (defun sql-generate-unique-sqli-buffer-name (product base)
3353 "Generate a new, unique buffer name for a SQLi buffer.
3355 Append a sequence number until a unique name is found."
3356 (let ((base-name (when (stringp base)
3357 (substring-no-properties
3358 (or base
3359 (sql-get-product-feature product :name)
3360 (symbol-name product)))))
3361 buf-fmt-1st buf-fmt-rest)
3363 ;; Calculate buffer format
3364 (if base-name
3365 (setq buf-fmt-1st (format "*SQL: %s*" base-name)
3366 buf-fmt-rest (format "*SQL: %s-%%d*" base-name))
3367 (setq buf-fmt-1st "*SQL*"
3368 buf-fmt-rest "*SQL-%d*"))
3370 ;; See if we can find an unused buffer
3371 (let ((buf-name buf-fmt-1st)
3372 (i 1))
3373 (while (sql-buffer-live-p buf-name)
3374 ;; Check a sequence number on the BASE
3375 (setq buf-name (format buf-fmt-rest i)
3376 i (1+ i)))
3378 buf-name)))
3380 (defun sql-rename-buffer (&optional new-name)
3381 "Rename a SQL interactive buffer.
3383 Prompts for the new name if command is preceded by
3384 \\[universal-argument]. If no buffer name is provided, then the
3385 `sql-alternate-buffer-name' is used.
3387 The actual buffer name set will be \"*SQL: NEW-NAME*\". If
3388 NEW-NAME is empty, then the buffer name will be \"*SQL*\"."
3389 (interactive "P")
3391 (if (not (derived-mode-p 'sql-interactive-mode))
3392 (user-error "Current buffer is not a SQL interactive buffer")
3394 (setq sql-alternate-buffer-name
3395 (substring-no-properties
3396 (cond
3397 ((stringp new-name)
3398 new-name)
3399 ((consp new-name)
3400 (read-string "Buffer name (\"*SQL: XXX*\"; enter `XXX'): "
3401 sql-alternate-buffer-name))
3403 sql-alternate-buffer-name))))
3405 (rename-buffer
3406 (sql-generate-unique-sqli-buffer-name sql-product
3407 sql-alternate-buffer-name)
3408 t)))
3410 (defun sql-copy-column ()
3411 "Copy current column to the end of buffer.
3412 Inserts SELECT or commas if appropriate."
3413 (interactive)
3414 (let ((column))
3415 (save-excursion
3416 (setq column (buffer-substring-no-properties
3417 (progn (forward-char 1) (backward-sexp 1) (point))
3418 (progn (forward-sexp 1) (point))))
3419 (goto-char (point-max))
3420 (let ((bol (comint-line-beginning-position)))
3421 (cond
3422 ;; if empty command line, insert SELECT
3423 ((= bol (point))
3424 (insert "SELECT "))
3425 ;; else if appending to INTO .* (, SELECT or ORDER BY, insert a comma
3426 ((save-excursion
3427 (re-search-backward "\\b\\(\\(into\\s-+\\S-+\\s-+(\\)\\|select\\|order by\\) .+"
3428 bol t))
3429 (insert ", "))
3430 ;; else insert a space
3432 (if (eq (preceding-char) ?\s)
3434 (insert " ")))))
3435 ;; in any case, insert the column
3436 (insert column)
3437 (message "%s" column))))
3439 ;; On Windows, SQL*Plus for Oracle turns on full buffering for stdout
3440 ;; if it is not attached to a character device; therefore placeholder
3441 ;; replacement by SQL*Plus is fully buffered. The workaround lets
3442 ;; Emacs query for the placeholders.
3444 (defvar sql-placeholder-history nil
3445 "History of placeholder values used.")
3447 (defun sql-placeholders-filter (string)
3448 "Replace placeholders in STRING.
3449 Placeholders are words starting with an ampersand like &this."
3451 (when sql-oracle-scan-on
3452 (while (string-match "&?&\\(\\(?:\\sw\\|\\s_\\)+\\)[.]?" string)
3453 (setq string (replace-match
3454 (read-from-minibuffer
3455 (format "Enter value for %s: " (match-string 1 string))
3456 nil nil nil 'sql-placeholder-history)
3457 t t string))))
3458 string)
3460 ;; Using DB2 interactively, newlines must be escaped with " \".
3461 ;; The space before the backslash is relevant.
3463 (defun sql-escape-newlines-filter (string)
3464 "Escape newlines in STRING.
3465 Every newline in STRING will be preceded with a space and a backslash."
3466 (if (not sql-db2-escape-newlines)
3467 string
3468 (let ((result "") (start 0) mb me)
3469 (while (string-match "\n" string start)
3470 (setq mb (match-beginning 0)
3471 me (match-end 0)
3472 result (concat result
3473 (substring string start mb)
3474 (if (and (> mb 1)
3475 (string-equal " \\" (substring string (- mb 2) mb)))
3476 "" " \\\n"))
3477 start me))
3478 (concat result (substring string start)))))
3482 ;;; Input sender for SQLi buffers
3484 (defvar sql-output-newline-count 0
3485 "Number of newlines in the input string.
3487 Allows the suppression of continuation prompts.")
3489 (defun sql-input-sender (proc string)
3490 "Send STRING to PROC after applying filters."
3492 (let* ((product (buffer-local-value 'sql-product (process-buffer proc)))
3493 (filter (sql-get-product-feature product :input-filter)))
3495 ;; Apply filter(s)
3496 (cond
3497 ((not filter)
3498 nil)
3499 ((functionp filter)
3500 (setq string (funcall filter string)))
3501 ((listp filter)
3502 (mapc (lambda (f) (setq string (funcall f string))) filter))
3503 (t nil))
3505 ;; Count how many newlines in the string
3506 (setq sql-output-newline-count
3507 (apply #'+ (mapcar (lambda (ch)
3508 (if (eq ch ?\n) 1 0)) string)))
3510 ;; Send the string
3511 (comint-simple-send proc string)))
3513 ;;; Strip out continuation prompts
3515 (defvar sql-preoutput-hold nil)
3517 (defun sql-starts-with-prompt-re ()
3518 "Anchor the prompt expression at the beginning of the output line.
3519 Remove the start of line regexp."
3520 (concat "\\`" comint-prompt-regexp))
3522 (defun sql-ends-with-prompt-re ()
3523 "Anchor the prompt expression at the end of the output line.
3524 Match a SQL prompt or a password prompt."
3525 (concat "\\(?:\\(?:" sql-prompt-regexp "\\)\\|"
3526 "\\(?:" comint-password-prompt-regexp "\\)\\)\\'"))
3528 (defun sql-interactive-remove-continuation-prompt (oline)
3529 "Strip out continuation prompts out of the OLINE.
3531 Added to the `comint-preoutput-filter-functions' hook in a SQL
3532 interactive buffer. If `sql-output-newline-count' is greater than
3533 zero, then an output line matching the continuation prompt is filtered
3534 out. If the count is zero, then a newline is inserted into the output
3535 to force the output from the query to appear on a new line.
3537 The complication to this filter is that the continuation prompts
3538 may arrive in multiple chunks. If they do, then the function
3539 saves any unfiltered output in a buffer and prepends that buffer
3540 to the next chunk to properly match the broken-up prompt.
3542 If the filter gets confused, it should reset and stop filtering
3543 to avoid deleting non-prompt output."
3545 ;; continue gathering lines of text iff
3546 ;; + we know what a prompt looks like, and
3547 ;; + there is held text, or
3548 ;; + there are continuation prompt yet to come, or
3549 ;; + not just a prompt string
3550 (when (and comint-prompt-regexp
3551 (or (> (length (or sql-preoutput-hold "")) 0)
3552 (> (or sql-output-newline-count 0) 0)
3553 (not (or (string-match sql-prompt-regexp oline)
3554 (string-match sql-prompt-cont-regexp oline)))))
3556 (save-match-data
3557 (let (prompt-found last-nl)
3559 ;; Add this text to what's left from the last pass
3560 (setq oline (concat sql-preoutput-hold oline)
3561 sql-preoutput-hold "")
3563 ;; If we are looking for multiple prompts
3564 (when (and (integerp sql-output-newline-count)
3565 (>= sql-output-newline-count 1))
3566 ;; Loop thru each starting prompt and remove it
3567 (let ((start-re (sql-starts-with-prompt-re)))
3568 (while (and (not (string= oline ""))
3569 (> sql-output-newline-count 0)
3570 (string-match start-re oline))
3571 (setq oline (replace-match "" nil nil oline)
3572 sql-output-newline-count (1- sql-output-newline-count)
3573 prompt-found t)))
3575 ;; If we've found all the expected prompts, stop looking
3576 (if (= sql-output-newline-count 0)
3577 (setq sql-output-newline-count nil
3578 oline (concat "\n" oline))
3580 ;; Still more possible prompts, leave them for the next pass
3581 (setq sql-preoutput-hold oline
3582 oline "")))
3584 ;; If no prompts were found, stop looking
3585 (unless prompt-found
3586 (setq sql-output-newline-count nil
3587 oline (concat oline sql-preoutput-hold)
3588 sql-preoutput-hold ""))
3590 ;; Break up output by physical lines if we haven't hit the final prompt
3591 (let ((end-re (sql-ends-with-prompt-re)))
3592 (unless (and (not (string= oline ""))
3593 (string-match end-re oline)
3594 (>= (match-end 0) (length oline)))
3595 ;; Find everything upto the last nl
3596 (setq last-nl 0)
3597 (while (string-match "\n" oline last-nl)
3598 (setq last-nl (match-end 0)))
3599 ;; Hold after the last nl, return upto last nl
3600 (setq sql-preoutput-hold (concat (substring oline last-nl)
3601 sql-preoutput-hold)
3602 oline (substring oline 0 last-nl)))))))
3603 oline)
3605 ;;; Sending the region to the SQLi buffer.
3607 (defun sql-send-string (str)
3608 "Send the string STR to the SQL process."
3609 (interactive "sSQL Text: ")
3611 (let ((comint-input-sender-no-newline nil)
3612 (s (replace-regexp-in-string "[[:space:]\n\r]+\\'" "" str)))
3613 (if (sql-buffer-live-p sql-buffer)
3614 (progn
3615 ;; Ignore the hoping around...
3616 (save-excursion
3617 ;; Set product context
3618 (with-current-buffer sql-buffer
3619 ;; Send the string (trim the trailing whitespace)
3620 (sql-input-sender (get-buffer-process sql-buffer) s)
3622 ;; Send a command terminator if we must
3623 (when sql-send-terminator
3624 (sql-send-magic-terminator sql-buffer s sql-send-terminator))
3626 (when sql-pop-to-buffer-after-send-region
3627 (message "Sent string to buffer %s" sql-buffer))))
3629 ;; Display the sql buffer
3630 (sql-display-buffer sql-buffer))
3632 ;; We don't have no stinkin' sql
3633 (user-error "No SQL process started"))))
3635 (defun sql-send-region (start end)
3636 "Send a region to the SQL process."
3637 (interactive "r")
3638 (sql-send-string (buffer-substring-no-properties start end)))
3640 (defun sql-send-paragraph ()
3641 "Send the current paragraph to the SQL process."
3642 (interactive)
3643 (let ((start (save-excursion
3644 (backward-paragraph)
3645 (point)))
3646 (end (save-excursion
3647 (forward-paragraph)
3648 (point))))
3649 (sql-send-region start end)))
3651 (defun sql-send-buffer ()
3652 "Send the buffer contents to the SQL process."
3653 (interactive)
3654 (sql-send-region (point-min) (point-max)))
3656 (defun sql-send-line-and-next ()
3657 "Send the current line to the SQL process and go to the next line."
3658 (interactive)
3659 (sql-send-region (line-beginning-position 1) (line-beginning-position 2))
3660 (beginning-of-line 2)
3661 (while (forward-comment 1))) ; skip all comments and whitespace
3663 (defun sql-send-magic-terminator (buf str terminator)
3664 "Send TERMINATOR to buffer BUF if its not present in STR."
3665 (let (comint-input-sender-no-newline pat term)
3666 ;; If flag is merely on(t), get product-specific terminator
3667 (if (eq terminator t)
3668 (setq terminator (sql-get-product-feature sql-product :terminator)))
3670 ;; If there is no terminator specified, use default ";"
3671 (unless terminator
3672 (setq terminator ";"))
3674 ;; Parse the setting into the pattern and the terminator string
3675 (cond ((stringp terminator)
3676 (setq pat (regexp-quote terminator)
3677 term terminator))
3678 ((consp terminator)
3679 (setq pat (car terminator)
3680 term (cdr terminator)))
3682 nil))
3684 ;; Check to see if the pattern is present in the str already sent
3685 (unless (and pat term
3686 (string-match (concat pat "\\'") str))
3687 (comint-simple-send (get-buffer-process buf) term)
3688 (setq sql-output-newline-count
3689 (if sql-output-newline-count
3690 (1+ sql-output-newline-count)
3691 1)))))
3693 (defun sql-remove-tabs-filter (str)
3694 "Replace tab characters with spaces."
3695 (replace-regexp-in-string "\t" " " str nil t))
3697 (defun sql-toggle-pop-to-buffer-after-send-region (&optional value)
3698 "Toggle `sql-pop-to-buffer-after-send-region'.
3700 If given the optional parameter VALUE, sets
3701 `sql-toggle-pop-to-buffer-after-send-region' to VALUE."
3702 (interactive "P")
3703 (if value
3704 (setq sql-pop-to-buffer-after-send-region value)
3705 (setq sql-pop-to-buffer-after-send-region
3706 (null sql-pop-to-buffer-after-send-region))))
3710 ;;; Redirect output functions
3712 (defvar sql-debug-redirect nil
3713 "If non-nil, display messages related to the use of redirection.")
3715 (defun sql-str-literal (s)
3716 (concat "'" (replace-regexp-in-string "[']" "''" s) "'"))
3718 (defun sql-redirect (sqlbuf command &optional outbuf save-prior)
3719 "Execute the SQL command and send output to OUTBUF.
3721 SQLBUF must be an active SQL interactive buffer. OUTBUF may be
3722 an existing buffer, or the name of a non-existing buffer. If
3723 omitted the output is sent to a temporary buffer which will be
3724 killed after the command completes. COMMAND should be a string
3725 of commands accepted by the SQLi program. COMMAND may also be a
3726 list of SQLi command strings."
3728 (let* ((visible (and outbuf
3729 (not (sql-buffer-hidden-p outbuf))))
3730 (this-save save-prior)
3731 (next-save t))
3733 (when visible
3734 (message "Executing SQL command..."))
3736 (if (consp command)
3737 (dolist (onecmd command)
3738 (sql-redirect-one sqlbuf onecmd outbuf this-save)
3739 (setq this-save next-save))
3740 (sql-redirect-one sqlbuf command outbuf save-prior))
3742 (when visible
3743 (message "Executing SQL command...done"))
3744 nil))
3746 (defun sql-redirect-one (sqlbuf command outbuf save-prior)
3747 (when command
3748 (with-current-buffer sqlbuf
3749 (let ((buf (get-buffer-create (or outbuf " *SQL-Redirect*")))
3750 (proc (get-buffer-process (current-buffer)))
3751 (comint-prompt-regexp (sql-get-product-feature sql-product
3752 :prompt-regexp))
3753 (start nil))
3754 (with-current-buffer buf
3755 (setq-local view-no-disable-on-exit t)
3756 (read-only-mode -1)
3757 (unless save-prior
3758 (erase-buffer))
3759 (goto-char (point-max))
3760 (unless (zerop (buffer-size))
3761 (insert "\n"))
3762 (setq start (point)))
3764 (when sql-debug-redirect
3765 (message ">>SQL> %S" command))
3767 ;; Run the command
3768 (let ((inhibit-quit t)
3769 comint-preoutput-filter-functions)
3770 (with-local-quit
3771 (comint-redirect-send-command-to-process command buf proc nil t)
3772 (while (or quit-flag (null comint-redirect-completed))
3773 (accept-process-output nil 1)))
3775 (if quit-flag
3776 (comint-redirect-cleanup)
3777 ;; Clean up the output results
3778 (with-current-buffer buf
3779 ;; Remove trailing whitespace
3780 (goto-char (point-max))
3781 (when (looking-back "[ \t\f\n\r]*" start)
3782 (delete-region (match-beginning 0) (match-end 0)))
3783 ;; Remove echo if there was one
3784 (goto-char start)
3785 (when (looking-at (concat "^" (regexp-quote command) "[\\n]"))
3786 (delete-region (match-beginning 0) (match-end 0)))
3787 ;; Remove Ctrl-Ms
3788 (goto-char start)
3789 (while (re-search-forward "\r+$" nil t)
3790 (replace-match "" t t))
3791 (goto-char start))))))))
3793 (defun sql-redirect-value (sqlbuf command &optional regexp regexp-groups)
3794 "Execute the SQL command and return part of result.
3796 SQLBUF must be an active SQL interactive buffer. COMMAND should
3797 be a string of commands accepted by the SQLi program. From the
3798 output, the REGEXP is repeatedly matched and the list of
3799 REGEXP-GROUPS submatches is returned. This behaves much like
3800 \\[comint-redirect-results-list-from-process] but instead of
3801 returning a single submatch it returns a list of each submatch
3802 for each match."
3804 (let ((outbuf " *SQL-Redirect-values*")
3805 (results nil))
3806 (sql-redirect sqlbuf command outbuf nil)
3807 (with-current-buffer outbuf
3808 (while (re-search-forward (or regexp "^.+$") nil t)
3809 (push
3810 (cond
3811 ;; no groups-return all of them
3812 ((null regexp-groups)
3813 (let ((i (/ (length (match-data)) 2))
3814 (r nil))
3815 (while (> i 0)
3816 (setq i (1- i))
3817 (push (match-string i) r))
3819 ;; one group specified
3820 ((numberp regexp-groups)
3821 (match-string regexp-groups))
3822 ;; list of numbers; return the specified matches only
3823 ((consp regexp-groups)
3824 (mapcar (lambda (c)
3825 (cond
3826 ((numberp c) (match-string c))
3827 ((stringp c) (match-substitute-replacement c))
3828 (t (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s" c))))
3829 regexp-groups))
3830 ;; String is specified; return replacement string
3831 ((stringp regexp-groups)
3832 (match-substitute-replacement regexp-groups))
3834 (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s"
3835 regexp-groups)))
3836 results)))
3838 (when sql-debug-redirect
3839 (message ">>SQL> = %S" (reverse results)))
3841 (nreverse results)))
3843 (defun sql-execute (sqlbuf outbuf command enhanced arg)
3844 "Execute a command in a SQL interactive buffer and capture the output.
3846 The commands are run in SQLBUF and the output saved in OUTBUF.
3847 COMMAND must be a string, a function or a list of such elements.
3848 Functions are called with SQLBUF, OUTBUF and ARG as parameters;
3849 strings are formatted with ARG and executed.
3851 If the results are empty the OUTBUF is deleted, otherwise the
3852 buffer is popped into a view window."
3853 (mapc
3854 (lambda (c)
3855 (cond
3856 ((stringp c)
3857 (sql-redirect sqlbuf (if arg (format c arg) c) outbuf) t)
3858 ((functionp c)
3859 (apply c sqlbuf outbuf enhanced arg nil))
3860 (t (error "Unknown sql-execute item %s" c))))
3861 (if (consp command) command (cons command nil)))
3863 (setq outbuf (get-buffer outbuf))
3864 (if (zerop (buffer-size outbuf))
3865 (kill-buffer outbuf)
3866 (let ((one-win (eq (selected-window)
3867 (get-lru-window))))
3868 (with-current-buffer outbuf
3869 (set-buffer-modified-p nil)
3870 (setq-local revert-buffer-function
3871 (lambda (_ignore-auto _noconfirm)
3872 (sql-execute sqlbuf (buffer-name outbuf)
3873 command enhanced arg)))
3874 (special-mode))
3875 (pop-to-buffer outbuf)
3876 (when one-win
3877 (shrink-window-if-larger-than-buffer)))))
3879 (defun sql-execute-feature (sqlbuf outbuf feature enhanced arg)
3880 "List objects or details in a separate display buffer."
3881 (let (command
3882 (product (buffer-local-value 'sql-product (get-buffer sqlbuf))))
3883 (setq command (sql-get-product-feature product feature))
3884 (unless command
3885 (error "%s does not support %s" product feature))
3886 (when (consp command)
3887 (setq command (if enhanced
3888 (cdr command)
3889 (car command))))
3890 (sql-execute sqlbuf outbuf command enhanced arg)))
3892 (defvar sql-completion-object nil
3893 "A list of database objects used for completion.
3895 The list is maintained in SQL interactive buffers.")
3897 (defvar sql-completion-column nil
3898 "A list of column names used for completion.
3900 The list is maintained in SQL interactive buffers.")
3902 (defun sql-build-completions-1 (schema completion-list feature)
3903 "Generate a list of objects in the database for use as completions."
3904 (let ((f (sql-get-product-feature sql-product feature)))
3905 (when f
3906 (set completion-list
3907 (let (cl)
3908 (dolist (e (append (symbol-value completion-list)
3909 (apply f (current-buffer) (cons schema nil)))
3911 (unless (member e cl) (setq cl (cons e cl))))
3912 (sort cl #'string<))))))
3914 (defun sql-build-completions (schema)
3915 "Generate a list of names in the database for use as completions."
3916 (sql-build-completions-1 schema 'sql-completion-object :completion-object)
3917 (sql-build-completions-1 schema 'sql-completion-column :completion-column))
3919 (defvar sql-completion-sqlbuf nil)
3921 (defun sql--completion-table (string pred action)
3922 (when sql-completion-sqlbuf
3923 (with-current-buffer sql-completion-sqlbuf
3924 (let ((schema (and (string-match "\\`\\(\\sw\\(:?\\sw\\|\\s_\\)*\\)[.]" string)
3925 (downcase (match-string 1 string)))))
3927 ;; If we haven't loaded any object name yet, load local schema
3928 (unless sql-completion-object
3929 (sql-build-completions nil))
3931 ;; If they want another schema, load it if we haven't yet
3932 (when schema
3933 (let ((schema-dot (concat schema "."))
3934 (schema-len (1+ (length schema)))
3935 (names sql-completion-object)
3936 has-schema)
3938 (while (and (not has-schema) names)
3939 (setq has-schema (and
3940 (>= (length (car names)) schema-len)
3941 (string= schema-dot
3942 (downcase (substring (car names)
3943 0 schema-len))))
3944 names (cdr names)))
3945 (unless has-schema
3946 (sql-build-completions schema)))))
3948 ;; Try to find the completion
3949 (complete-with-action action sql-completion-object string pred))))
3951 (defun sql-read-table-name (prompt)
3952 "Read the name of a database table."
3953 (let* ((tname
3954 (and (buffer-local-value 'sql-contains-names (current-buffer))
3955 (thing-at-point-looking-at
3956 (concat "\\_<\\sw\\(:?\\sw\\|\\s_\\)*"
3957 "\\(?:[.]+\\sw\\(?:\\sw\\|\\s_\\)*\\)*\\_>"))
3958 (buffer-substring-no-properties (match-beginning 0)
3959 (match-end 0))))
3960 (sql-completion-sqlbuf (sql-find-sqli-buffer))
3961 (product (when sql-completion-sqlbuf
3962 (with-current-buffer sql-completion-sqlbuf sql-product)))
3963 (completion-ignore-case t))
3965 (if product
3966 (if (sql-get-product-feature product :completion-object)
3967 (completing-read prompt #'sql--completion-table
3968 nil nil tname)
3969 (read-from-minibuffer prompt tname))
3970 (user-error "There is no active SQLi buffer"))))
3972 (defun sql-list-all (&optional enhanced)
3973 "List all database objects.
3974 With optional prefix argument ENHANCED, displays additional
3975 details or extends the listing to include other schemas objects."
3976 (interactive "P")
3977 (let ((sqlbuf (sql-find-sqli-buffer)))
3978 (unless sqlbuf
3979 (user-error "No SQL interactive buffer found"))
3980 (sql-execute-feature sqlbuf "*List All*" :list-all enhanced nil)
3981 (with-current-buffer sqlbuf
3982 ;; Contains the name of database objects
3983 (set (make-local-variable 'sql-contains-names) t)
3984 (set (make-local-variable 'sql-buffer) sqlbuf))))
3986 (defun sql-list-table (name &optional enhanced)
3987 "List the details of a database table named NAME.
3988 Displays the columns in the relation. With optional prefix argument
3989 ENHANCED, displays additional details about each column."
3990 (interactive
3991 (list (sql-read-table-name "Table name: ")
3992 current-prefix-arg))
3993 (let ((sqlbuf (sql-find-sqli-buffer)))
3994 (unless sqlbuf
3995 (user-error "No SQL interactive buffer found"))
3996 (unless name
3997 (user-error "No table name specified"))
3998 (sql-execute-feature sqlbuf (format "*List %s*" name)
3999 :list-table enhanced name)))
4002 ;;; SQL mode -- uses SQL interactive mode
4004 ;;;###autoload
4005 (define-derived-mode sql-mode prog-mode "SQL"
4006 "Major mode to edit SQL.
4008 You can send SQL statements to the SQLi buffer using
4009 \\[sql-send-region]. Such a buffer must exist before you can do this.
4010 See `sql-help' on how to create SQLi buffers.