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