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