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