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