Fix a comment whitespace typo.
[emacs.git] / lisp / progmodes / sql.el
blobb176e52950c0c41d0f861c9fe159b534c086ac4c
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.6
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 &optional buf-name)
160 ;; "Connect ti XyzDB in a comint buffer."
162 ;; ;; Do something with `sql-user', `sql-password',
163 ;; ;; `sql-database', and `sql-server'.
164 ;; (let ((params
165 ;; (append
166 ;; (if (not (string= "" sql-user))
167 ;; (list "-U" sql-user))
168 ;; (if (not (string= "" sql-password))
169 ;; (list "-P" sql-password))
170 ;; (if (not (string= "" sql-database))
171 ;; (list "-D" sql-database))
172 ;; (if (not (string= "" sql-server))
173 ;; (list "-S" sql-server))
174 ;; options)))
175 ;; (sql-comint product params buf-name)))
177 ;; (sql-set-product-feature 'xyz
178 ;; :sqli-comint-func 'my-sql-comint-xyz)
180 ;; 6) Define a convenience function to invoke the SQL interpreter.
182 ;; (defun my-sql-xyz (&optional buffer)
183 ;; "Run ixyz by XyzDB as an inferior process."
184 ;; (interactive "P")
185 ;; (sql-product-interactive 'xyz buffer))
187 ;;; To Do:
189 ;; Improve keyword highlighting for individual products. I have tried
190 ;; to update those database that I use. Feel free to send me updates,
191 ;; or direct me to the reference manuals for your favorite database.
193 ;; When there are no keywords defined, the ANSI keywords are
194 ;; highlighted. ANSI keywords are highlighted even if the keyword is
195 ;; not used for your current product. This should help identify
196 ;; portability concerns.
198 ;; Add different highlighting levels.
200 ;; Add support for listing available tables or the columns in a table.
202 ;;; Thanks to all the people who helped me out:
204 ;; Alex Schroeder <alex@gnu.org> -- the original author
205 ;; Kai Blauberg <kai.blauberg@metla.fi>
206 ;; <ibalaban@dalet.com>
207 ;; Yair Friedman <yfriedma@JohnBryce.Co.Il>
208 ;; Gregor Zych <zych@pool.informatik.rwth-aachen.de>
209 ;; nino <nino@inform.dk>
210 ;; Berend de Boer <berend@pobox.com>
211 ;; Adam Jenkins <adam@thejenkins.org>
212 ;; Michael Mauger <michael@mauger.com> -- improved product support
213 ;; Drew Adams <drew.adams@oracle.com> -- Emacs 20 support
214 ;; Harald Maier <maierh@myself.com> -- sql-send-string
215 ;; Stefan Monnier <monnier@iro.umontreal.ca> -- font-lock corrections;
216 ;; code polish
217 ;; Paul Sleigh <bat@flurf.net> -- MySQL keyword enhancement
218 ;; Andrew Schein <andrew@andrewschein.com> -- sql-port bug
219 ;; Ian Bjorhovde <idbjorh@dataproxy.com> -- db2 escape newlines
220 ;; incorrectly enabled by default
221 ;; Roman Scherer <roman.scherer@nugg.ad> -- Connection documentation
222 ;; Mark Wilkinson <wilkinsonmr@gmail.com> -- file-local variables ignored
223 ;; Simen Heggestøyl <simenheg@gmail.com> -- Postgres database completion
228 ;;; Code:
230 (require 'cl-lib)
231 (require 'comint)
232 ;; Need the following to allow GNU Emacs 19 to compile the file.
233 (eval-when-compile
234 (require 'regexp-opt))
235 (require 'custom)
236 (require 'thingatpt)
237 (require 'view)
239 (defvar font-lock-keyword-face)
240 (defvar font-lock-set-defaults)
241 (defvar font-lock-string-face)
243 ;;; Allow customization
245 (defgroup SQL nil
246 "Running a SQL interpreter from within Emacs buffers."
247 :version "20.4"
248 :group 'languages
249 :group 'processes)
251 ;; These five variables will be used as defaults, if set.
253 (defcustom sql-user ""
254 "Default username."
255 :type 'string
256 :group 'SQL
257 :safe 'stringp)
259 (defcustom sql-password ""
260 "Default password.
261 If you customize this, the value will be stored in your init
262 file. Since that is a plaintext file, this could be dangerous."
263 :type 'string
264 :group 'SQL
265 :risky t)
267 (defcustom sql-database ""
268 "Default database."
269 :type 'string
270 :group 'SQL
271 :safe 'stringp)
273 (defcustom sql-server ""
274 "Default server or host."
275 :type 'string
276 :group 'SQL
277 :safe 'stringp)
279 (defcustom sql-port 0
280 "Default port for connecting to a MySQL or Postgres server."
281 :version "24.1"
282 :type 'number
283 :group 'SQL
284 :safe 'numberp)
286 (defcustom sql-default-directory nil
287 "Default directory for SQL processes."
288 :version "25.1"
289 :type '(choice (const nil) string)
290 :group 'SQL
291 :safe 'stringp)
293 ;; Login parameter type
295 (define-widget 'sql-login-params 'lazy
296 "Widget definition of the login parameters list"
297 :tag "Login Parameters"
298 :type '(set :tag "Login Parameters"
299 (choice :tag "user"
300 :value user
301 (const user)
302 (list :tag "Specify a default"
303 (const user)
304 (list :tag "Default"
305 :inline t (const :default) string)))
306 (const password)
307 (choice :tag "server"
308 :value server
309 (const server)
310 (list :tag "Specify a default"
311 (const server)
312 (list :tag "Default"
313 :inline t (const :default) string))
314 (list :tag "file"
315 (const :format "" server)
316 (const :format "" :file)
317 regexp)
318 (list :tag "completion"
319 (const :format "" server)
320 (const :format "" :completion)
321 (const :format "" :must-match)
322 (restricted-sexp
323 :match-alternatives (listp stringp))))
324 (choice :tag "database"
325 :value database
326 (const database)
327 (list :tag "Specify a default"
328 (const database)
329 (list :tag "Default"
330 :inline t (const :default) string))
331 (list :tag "file"
332 (const :format "" database)
333 (const :format "" :file)
334 regexp)
335 (list :tag "completion"
336 (const :format "" database)
337 (const :format "" :completion)
338 (const :format "" :must-match)
339 (restricted-sexp
340 :match-alternatives (listp stringp))))
341 (const port)))
343 ;; SQL Product support
345 (defvar sql-interactive-product nil
346 "Product under `sql-interactive-mode'.")
348 (defvar sql-connection nil
349 "Connection name if interactive session started by `sql-connect'.")
351 (defvar sql-product-alist
352 '((ansi
353 :name "ANSI"
354 :font-lock sql-mode-ansi-font-lock-keywords
355 :statement sql-ansi-statement-starters)
357 (db2
358 :name "DB2"
359 :font-lock sql-mode-db2-font-lock-keywords
360 :sqli-program sql-db2-program
361 :sqli-options sql-db2-options
362 :sqli-login sql-db2-login-params
363 :sqli-comint-func sql-comint-db2
364 :prompt-regexp "^db2 => "
365 :prompt-length 7
366 :prompt-cont-regexp "^db2 (cont\\.) => "
367 :input-filter sql-escape-newlines-filter)
369 (informix
370 :name "Informix"
371 :font-lock sql-mode-informix-font-lock-keywords
372 :sqli-program sql-informix-program
373 :sqli-options sql-informix-options
374 :sqli-login sql-informix-login-params
375 :sqli-comint-func sql-comint-informix
376 :prompt-regexp "^> "
377 :prompt-length 2
378 :syntax-alist ((?{ . "<") (?} . ">")))
380 (ingres
381 :name "Ingres"
382 :font-lock sql-mode-ingres-font-lock-keywords
383 :sqli-program sql-ingres-program
384 :sqli-options sql-ingres-options
385 :sqli-login sql-ingres-login-params
386 :sqli-comint-func sql-comint-ingres
387 :prompt-regexp "^\\* "
388 :prompt-length 2
389 :prompt-cont-regexp "^\\* ")
391 (interbase
392 :name "Interbase"
393 :font-lock sql-mode-interbase-font-lock-keywords
394 :sqli-program sql-interbase-program
395 :sqli-options sql-interbase-options
396 :sqli-login sql-interbase-login-params
397 :sqli-comint-func sql-comint-interbase
398 :prompt-regexp "^SQL> "
399 :prompt-length 5)
401 (linter
402 :name "Linter"
403 :font-lock sql-mode-linter-font-lock-keywords
404 :sqli-program sql-linter-program
405 :sqli-options sql-linter-options
406 :sqli-login sql-linter-login-params
407 :sqli-comint-func sql-comint-linter
408 :prompt-regexp "^SQL>"
409 :prompt-length 4)
412 :name "Microsoft"
413 :font-lock sql-mode-ms-font-lock-keywords
414 :sqli-program sql-ms-program
415 :sqli-options sql-ms-options
416 :sqli-login sql-ms-login-params
417 :sqli-comint-func sql-comint-ms
418 :prompt-regexp "^[0-9]*>"
419 :prompt-length 5
420 :syntax-alist ((?@ . "_"))
421 :terminator ("^go" . "go"))
423 (mysql
424 :name "MySQL"
425 :free-software t
426 :font-lock sql-mode-mysql-font-lock-keywords
427 :sqli-program sql-mysql-program
428 :sqli-options sql-mysql-options
429 :sqli-login sql-mysql-login-params
430 :sqli-comint-func sql-comint-mysql
431 :list-all "SHOW TABLES;"
432 :list-table "DESCRIBE %s;"
433 :prompt-regexp "^mysql> "
434 :prompt-length 6
435 :prompt-cont-regexp "^ -> "
436 :syntax-alist ((?# . "< b"))
437 :input-filter sql-remove-tabs-filter)
439 (oracle
440 :name "Oracle"
441 :font-lock sql-mode-oracle-font-lock-keywords
442 :sqli-program sql-oracle-program
443 :sqli-options sql-oracle-options
444 :sqli-login sql-oracle-login-params
445 :sqli-comint-func sql-comint-oracle
446 :list-all sql-oracle-list-all
447 :list-table sql-oracle-list-table
448 :completion-object sql-oracle-completion-object
449 :prompt-regexp "^SQL> "
450 :prompt-length 5
451 :prompt-cont-regexp "^\\(?:[ ][ ][1-9]\\|[ ][1-9][0-9]\\|[1-9][0-9]\\{2\\}\\)[ ]\\{2\\}"
452 :statement sql-oracle-statement-starters
453 :syntax-alist ((?$ . "_") (?# . "_"))
454 :terminator ("\\(^/\\|;\\)$" . "/")
455 :input-filter sql-placeholders-filter)
457 (postgres
458 :name "Postgres"
459 :free-software t
460 :font-lock sql-mode-postgres-font-lock-keywords
461 :sqli-program sql-postgres-program
462 :sqli-options sql-postgres-options
463 :sqli-login sql-postgres-login-params
464 :sqli-comint-func sql-comint-postgres
465 :list-all ("\\d+" . "\\dS+")
466 :list-table ("\\d+ %s" . "\\dS+ %s")
467 :completion-object sql-postgres-completion-object
468 :prompt-regexp "^[[:alnum:]_]*=[#>] "
469 :prompt-length 5
470 :prompt-cont-regexp "^[[:alnum:]_]*[-(][#>] "
471 :input-filter sql-remove-tabs-filter
472 :terminator ("\\(^\\s-*\\\\g$\\|;\\)" . "\\g"))
474 (solid
475 :name "Solid"
476 :font-lock sql-mode-solid-font-lock-keywords
477 :sqli-program sql-solid-program
478 :sqli-options sql-solid-options
479 :sqli-login sql-solid-login-params
480 :sqli-comint-func sql-comint-solid
481 :prompt-regexp "^"
482 :prompt-length 0)
484 (sqlite
485 :name "SQLite"
486 :free-software t
487 :font-lock sql-mode-sqlite-font-lock-keywords
488 :sqli-program sql-sqlite-program
489 :sqli-options sql-sqlite-options
490 :sqli-login sql-sqlite-login-params
491 :sqli-comint-func sql-comint-sqlite
492 :list-all ".tables"
493 :list-table ".schema %s"
494 :completion-object sql-sqlite-completion-object
495 :prompt-regexp "^sqlite> "
496 :prompt-length 8
497 :prompt-cont-regexp "^ \\.\\.\\.> "
498 :terminator ";")
500 (sybase
501 :name "Sybase"
502 :font-lock sql-mode-sybase-font-lock-keywords
503 :sqli-program sql-sybase-program
504 :sqli-options sql-sybase-options
505 :sqli-login sql-sybase-login-params
506 :sqli-comint-func sql-comint-sybase
507 :prompt-regexp "^SQL> "
508 :prompt-length 5
509 :syntax-alist ((?@ . "_"))
510 :terminator ("^go" . "go"))
512 (vertica
513 :name "Vertica"
514 :sqli-program sql-vertica-program
515 :sqli-options sql-vertica-options
516 :sqli-login sql-vertica-login-params
517 :sqli-comint-func sql-comint-vertica
518 :list-all ("\\d" . "\\dS")
519 :list-table "\\d %s"
520 :prompt-regexp "^[[:alnum:]_]*=[#>] "
521 :prompt-length 5
522 :prompt-cont-regexp "^[[:alnum:]_]*[-(][#>] ")
524 "An alist of product specific configuration settings.
526 Without an entry in this list a product will not be properly
527 highlighted and will not support `sql-interactive-mode'.
529 Each element in the list is in the following format:
531 (PRODUCT FEATURE VALUE ...)
533 where PRODUCT is the appropriate value of `sql-product'. The
534 product name is then followed by FEATURE-VALUE pairs. If a
535 FEATURE is not specified, its VALUE is treated as nil. FEATURE
536 may be any one of the following:
538 :name string containing the displayable name of
539 the product.
541 :free-software is the product Free (as in Freedom) software?
543 :font-lock name of the variable containing the product
544 specific font lock highlighting patterns.
546 :sqli-program name of the variable containing the product
547 specific interactive program name.
549 :sqli-options name of the variable containing the list
550 of product specific options.
552 :sqli-login name of the variable containing the list of
553 login parameters (i.e., user, password,
554 database and server) needed to connect to
555 the database.
557 :sqli-comint-func function of two arguments, PRODUCT
558 and OPTIONS, that will open a comint buffer
559 and connect to the database. PRODUCT is the
560 first argument to be passed to `sql-comint',
561 and OPTIONS should be included in its second
562 argument. The function should use the values
563 of `sql-user', `sql-password', `sql-database',
564 `sql-server' and `sql-port' to . Do product
565 specific configuration of comint in this
566 function. See `sql-comint-oracle' for an
567 example of such a function.
569 :list-all Command string or function which produces
570 a listing of all objects in the database.
571 If it's a cons cell, then the car
572 produces the standard list of objects and
573 the cdr produces an enhanced list of
574 objects. What \"enhanced\" means is
575 dependent on the SQL product and may not
576 exist. In general though, the
577 \"enhanced\" list should include visible
578 objects from other schemas.
580 :list-table Command string or function which produces
581 a detailed listing of a specific database
582 table. If its a cons cell, then the car
583 produces the standard list and the cdr
584 produces an enhanced list.
586 :completion-object A function that returns a list of
587 objects. Called with a single
588 parameter--if nil then list objects
589 accessible in the current schema, if
590 not-nil it is the name of a schema whose
591 objects should be listed.
593 :completion-column A function that returns a list of
594 columns. Called with a single
595 parameter--if nil then list objects
596 accessible in the current schema, if
597 not-nil it is the name of a schema whose
598 objects should be listed.
600 :prompt-regexp regular expression string that matches
601 the prompt issued by the product
602 interpreter.
604 :prompt-length length of the prompt on the line.
606 :prompt-cont-regexp regular expression string that matches
607 the continuation prompt issued by the
608 product interpreter.
610 :input-filter function which can filter strings sent to
611 the command interpreter. It is also used
612 by the `sql-send-string',
613 `sql-send-region', `sql-send-paragraph'
614 and `sql-send-buffer' functions. The
615 function is passed the string sent to the
616 command interpreter and must return the
617 filtered string. May also be a list of
618 such functions.
620 :statement name of a variable containing a regexp that
621 matches the beginning of SQL statements.
623 :terminator the terminator to be sent after a
624 `sql-send-string', `sql-send-region',
625 `sql-send-paragraph' and
626 `sql-send-buffer' command. May be the
627 literal string or a cons of a regexp to
628 match an existing terminator in the
629 string and the terminator to be used if
630 its absent. By default \";\".
632 :syntax-alist alist of syntax table entries to enable
633 special character treatment by font-lock
634 and imenu.
636 Other features can be stored but they will be ignored. However,
637 you can develop new functionality which is product independent by
638 using `sql-get-product-feature' to lookup the product specific
639 settings.")
641 (defvar sql-indirect-features
642 '(:font-lock :sqli-program :sqli-options :sqli-login :statement))
644 (defcustom sql-connection-alist nil
645 "An alist of connection parameters for interacting with a SQL product.
646 Each element of the alist is as follows:
648 (CONNECTION \(SQL-VARIABLE VALUE) ...)
650 Where CONNECTION is a case-insensitive string identifying the
651 connection, SQL-VARIABLE is the symbol name of a SQL mode
652 variable, and VALUE is the value to be assigned to the variable.
653 The most common SQL-VARIABLE settings associated with a
654 connection are: `sql-product', `sql-user', `sql-password',
655 `sql-port', `sql-server', and `sql-database'.
657 If a SQL-VARIABLE is part of the connection, it will not be
658 prompted for during login. The command `sql-connect' starts a
659 predefined SQLi session using the parameters from this list.
660 Connections defined here appear in the submenu SQL->Start... for
661 making new SQLi sessions."
662 :type `(alist :key-type (string :tag "Connection")
663 :value-type
664 (set
665 (group (const :tag "Product" sql-product)
666 (choice
667 ,@(mapcar
668 (lambda (prod-info)
669 `(const :tag
670 ,(or (plist-get (cdr prod-info) :name)
671 (capitalize
672 (symbol-name (car prod-info))))
673 (quote ,(car prod-info))))
674 sql-product-alist)))
675 (group (const :tag "Username" sql-user) string)
676 (group (const :tag "Password" sql-password) string)
677 (group (const :tag "Server" sql-server) string)
678 (group (const :tag "Database" sql-database) string)
679 (group (const :tag "Port" sql-port) integer)
680 (repeat :inline t
681 (list :tab "Other"
682 (symbol :tag " Variable Symbol")
683 (sexp :tag "Value Expression")))))
684 :version "24.1"
685 :group 'SQL)
687 (defcustom sql-product 'ansi
688 "Select the SQL database product used.
689 This allows highlighting buffers properly when you open them."
690 :type `(choice
691 ,@(mapcar (lambda (prod-info)
692 `(const :tag
693 ,(or (plist-get (cdr prod-info) :name)
694 (capitalize (symbol-name (car prod-info))))
695 ,(car prod-info)))
696 sql-product-alist))
697 :group 'SQL
698 :safe 'symbolp)
699 (defvaralias 'sql-dialect 'sql-product)
701 ;; misc customization of sql.el behavior
703 (defcustom sql-electric-stuff nil
704 "Treat some input as electric.
705 If set to the symbol `semicolon', then hitting `;' will send current
706 input in the SQLi buffer to the process.
707 If set to the symbol `go', then hitting `go' on a line by itself will
708 send current input in the SQLi buffer to the process.
709 If set to nil, then you must use \\[comint-send-input] in order to send
710 current input in the SQLi buffer to the process."
711 :type '(choice (const :tag "Nothing" nil)
712 (const :tag "The semicolon `;'" semicolon)
713 (const :tag "The string `go' by itself" go))
714 :version "20.8"
715 :group 'SQL)
717 (defcustom sql-send-terminator nil
718 "When non-nil, add a terminator to text sent to the SQL interpreter.
720 When text is sent to the SQL interpreter (via `sql-send-string',
721 `sql-send-region', `sql-send-paragraph' or `sql-send-buffer'), a
722 command terminator can be automatically sent as well. The
723 terminator is not sent, if the string sent already ends with the
724 terminator.
726 If this value is t, then the default command terminator for the
727 SQL interpreter is sent. If this value is a string, then the
728 string is sent.
730 If the value is a cons cell of the form (PAT . TERM), then PAT is
731 a regexp used to match the terminator in the string and TERM is
732 the terminator to be sent. This form is useful if the SQL
733 interpreter has more than one way of submitting a SQL command.
734 The PAT regexp can match any of them, and TERM is the way we do
735 it automatically."
737 :type '(choice (const :tag "No Terminator" nil)
738 (const :tag "Default Terminator" t)
739 (string :tag "Terminator String")
740 (cons :tag "Terminator Pattern and String"
741 (string :tag "Terminator Pattern")
742 (string :tag "Terminator String")))
743 :version "22.2"
744 :group 'SQL)
746 (defvar sql-contains-names nil
747 "When non-nil, the current buffer contains database names.
749 Globally should be set to nil; it will be non-nil in `sql-mode',
750 `sql-interactive-mode' and list all buffers.")
752 (defvar sql-login-delay 7.5 ;; Secs
753 "Maximum number of seconds you are willing to wait for a login connection.")
755 (defcustom sql-pop-to-buffer-after-send-region nil
756 "When non-nil, pop to the buffer SQL statements are sent to.
758 After a call to `sql-sent-string', `sql-send-region',
759 `sql-send-paragraph' or `sql-send-buffer', the window is split
760 and the SQLi buffer is shown. If this variable is not nil, that
761 buffer's window will be selected by calling `pop-to-buffer'. If
762 this variable is nil, that buffer is shown using
763 `display-buffer'."
764 :type 'boolean
765 :group 'SQL)
767 ;; imenu support for sql-mode.
769 (defvar sql-imenu-generic-expression
770 ;; Items are in reverse order because they are rendered in reverse.
771 '(("Rules/Defaults" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*\\(?:rule\\|default\\)\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\s-+\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
772 ("Sequences" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*sequence\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
773 ("Triggers" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*trigger\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
774 ("Functions" "^\\s-*\\(?:create\\s-+\\(?:\\w+\\s-+\\)*\\)?function\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
775 ("Procedures" "^\\s-*\\(?:create\\s-+\\(?:\\w+\\s-+\\)*\\)?proc\\(?:edure\\)?\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
776 ("Packages" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*package\\s-+\\(?:body\\s-+\\)?\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
777 ("Types" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*type\\s-+\\(?:body\\s-+\\)?\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
778 ("Indexes" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*index\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
779 ("Tables/Views" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*\\(?:table\\|view\\)\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1))
780 "Define interesting points in the SQL buffer for `imenu'.
782 This is used to set `imenu-generic-expression' when SQL mode is
783 entered. Subsequent changes to `sql-imenu-generic-expression' will
784 not affect existing SQL buffers because imenu-generic-expression is
785 a local variable.")
787 ;; history file
789 (defcustom sql-input-ring-file-name nil
790 "If non-nil, name of the file to read/write input history.
792 You have to set this variable if you want the history of your commands
793 saved from one Emacs session to the next. If this variable is set,
794 exiting the SQL interpreter in an SQLi buffer will write the input
795 history to the specified file. Starting a new process in a SQLi buffer
796 will read the input history from the specified file.
798 This is used to initialize `comint-input-ring-file-name'.
800 Note that the size of the input history is determined by the variable
801 `comint-input-ring-size'."
802 :type '(choice (const :tag "none" nil)
803 (file))
804 :group 'SQL)
806 (defcustom sql-input-ring-separator "\n--\n"
807 "Separator between commands in the history file.
809 If set to \"\\n\", each line in the history file will be interpreted as
810 one command. Multi-line commands are split into several commands when
811 the input ring is initialized from a history file.
813 This variable used to initialize `comint-input-ring-separator'.
814 `comint-input-ring-separator' is part of Emacs 21; if your Emacs
815 does not have it, setting `sql-input-ring-separator' will have no
816 effect. In that case multiline commands will be split into several
817 commands when the input history is read, as if you had set
818 `sql-input-ring-separator' to \"\\n\"."
819 :type 'string
820 :group 'SQL)
822 ;; The usual hooks
824 (defcustom sql-interactive-mode-hook '()
825 "Hook for customizing `sql-interactive-mode'."
826 :type 'hook
827 :group 'SQL)
829 (defcustom sql-mode-hook '()
830 "Hook for customizing `sql-mode'."
831 :type 'hook
832 :group 'SQL)
834 (defcustom sql-set-sqli-hook '()
835 "Hook for reacting to changes of `sql-buffer'.
837 This is called by `sql-set-sqli-buffer' when the value of `sql-buffer'
838 is changed."
839 :type 'hook
840 :group 'SQL)
842 (defcustom sql-login-hook '()
843 "Hook for interacting with a buffer in `sql-interactive-mode'.
845 This hook is invoked in a buffer once it is ready to accept input
846 for the first time."
847 :version "24.1"
848 :type 'hook
849 :group 'SQL)
851 ;; Customization for ANSI
853 (defcustom sql-ansi-statement-starters
854 (regexp-opt '("create" "alter" "drop"
855 "select" "insert" "update" "delete" "merge"
856 "grant" "revoke"))
857 "Regexp of keywords that start SQL commands.
859 All products share this list; products should define a regexp to
860 identify additional keywords in a variable defined by
861 the :statement feature."
862 :version "24.1"
863 :type 'string
864 :group 'SQL)
866 ;; Customization for Oracle
868 (defcustom sql-oracle-program "sqlplus"
869 "Command to start sqlplus by Oracle.
871 Starts `sql-interactive-mode' after doing some setup.
873 On Windows, \"sqlplus\" usually starts the sqlplus \"GUI\". In order
874 to start the sqlplus console, use \"plus33\" or something similar.
875 You will find the file in your Orant\\bin directory."
876 :type 'file
877 :group 'SQL)
879 (defcustom sql-oracle-options '("-L")
880 "List of additional options for `sql-oracle-program'."
881 :type '(repeat string)
882 :version "24.4"
883 :group 'SQL)
885 (defcustom sql-oracle-login-params '(user password database)
886 "List of login parameters needed to connect to Oracle."
887 :type 'sql-login-params
888 :version "24.1"
889 :group 'SQL)
891 (defcustom sql-oracle-statement-starters
892 (regexp-opt '("declare" "begin" "with"))
893 "Additional statement starting keywords in Oracle."
894 :version "24.1"
895 :type 'string
896 :group 'SQL)
898 (defcustom sql-oracle-scan-on t
899 "Non-nil if placeholders should be replaced in Oracle SQLi.
901 When non-nil, Emacs will scan text sent to sqlplus and prompt
902 for replacement text for & placeholders as sqlplus does. This
903 is needed on Windows where SQL*Plus output is buffered and the
904 prompts are not shown until after the text is entered.
906 You need to issue the following command in SQL*Plus to be safe:
908 SET DEFINE OFF
910 In older versions of SQL*Plus, this was the SET SCAN OFF command."
911 :version "24.1"
912 :type 'boolean
913 :group 'SQL)
915 (defcustom sql-db2-escape-newlines nil
916 "Non-nil if newlines should be escaped by a backslash in DB2 SQLi.
918 When non-nil, Emacs will automatically insert a space and
919 backslash prior to every newline in multi-line SQL statements as
920 they are submitted to an interactive DB2 session."
921 :version "24.3"
922 :type 'boolean
923 :group 'SQL)
925 ;; Customization for SQLite
927 (defcustom sql-sqlite-program (or (executable-find "sqlite3")
928 (executable-find "sqlite")
929 "sqlite")
930 "Command to start SQLite.
932 Starts `sql-interactive-mode' after doing some setup."
933 :type 'file
934 :group 'SQL)
936 (defcustom sql-sqlite-options nil
937 "List of additional options for `sql-sqlite-program'."
938 :type '(repeat string)
939 :version "20.8"
940 :group 'SQL)
942 (defcustom sql-sqlite-login-params '((database :file nil
943 :must-match confirm))
944 "List of login parameters needed to connect to SQLite."
945 :type 'sql-login-params
946 :version "26.1"
947 :group 'SQL)
949 ;; Customization for MySQL
951 (defcustom sql-mysql-program "mysql"
952 "Command to start mysql by TcX.
954 Starts `sql-interactive-mode' after doing some setup."
955 :type 'file
956 :group 'SQL)
958 (defcustom sql-mysql-options nil
959 "List of additional options for `sql-mysql-program'.
960 The following list of options is reported to make things work
961 on Windows: \"-C\" \"-t\" \"-f\" \"-n\"."
962 :type '(repeat string)
963 :version "20.8"
964 :group 'SQL)
966 (defcustom sql-mysql-login-params '(user password database server)
967 "List of login parameters needed to connect to MySQL."
968 :type 'sql-login-params
969 :version "24.1"
970 :group 'SQL)
972 ;; Customization for Solid
974 (defcustom sql-solid-program "solsql"
975 "Command to start SOLID SQL Editor.
977 Starts `sql-interactive-mode' after doing some setup."
978 :type 'file
979 :group 'SQL)
981 (defcustom sql-solid-login-params '(user password server)
982 "List of login parameters needed to connect to Solid."
983 :type 'sql-login-params
984 :version "24.1"
985 :group 'SQL)
987 ;; Customization for Sybase
989 (defcustom sql-sybase-program "isql"
990 "Command to start isql by Sybase.
992 Starts `sql-interactive-mode' after doing some setup."
993 :type 'file
994 :group 'SQL)
996 (defcustom sql-sybase-options nil
997 "List of additional options for `sql-sybase-program'.
998 Some versions of isql might require the -n option in order to work."
999 :type '(repeat string)
1000 :version "20.8"
1001 :group 'SQL)
1003 (defcustom sql-sybase-login-params '(server user password database)
1004 "List of login parameters needed to connect to Sybase."
1005 :type 'sql-login-params
1006 :version "24.1"
1007 :group 'SQL)
1009 ;; Customization for Informix
1011 (defcustom sql-informix-program "dbaccess"
1012 "Command to start dbaccess by Informix.
1014 Starts `sql-interactive-mode' after doing some setup."
1015 :type 'file
1016 :group 'SQL)
1018 (defcustom sql-informix-login-params '(database)
1019 "List of login parameters needed to connect to Informix."
1020 :type 'sql-login-params
1021 :version "24.1"
1022 :group 'SQL)
1024 ;; Customization for Ingres
1026 (defcustom sql-ingres-program "sql"
1027 "Command to start sql by Ingres.
1029 Starts `sql-interactive-mode' after doing some setup."
1030 :type 'file
1031 :group 'SQL)
1033 (defcustom sql-ingres-login-params '(database)
1034 "List of login parameters needed to connect to Ingres."
1035 :type 'sql-login-params
1036 :version "24.1"
1037 :group 'SQL)
1039 ;; Customization for Microsoft
1041 (defcustom sql-ms-program "osql"
1042 "Command to start osql by Microsoft.
1044 Starts `sql-interactive-mode' after doing some setup."
1045 :type 'file
1046 :group 'SQL)
1048 (defcustom sql-ms-options '("-w" "300" "-n")
1049 ;; -w is the linesize
1050 "List of additional options for `sql-ms-program'."
1051 :type '(repeat string)
1052 :version "22.1"
1053 :group 'SQL)
1055 (defcustom sql-ms-login-params '(user password server database)
1056 "List of login parameters needed to connect to Microsoft."
1057 :type 'sql-login-params
1058 :version "24.1"
1059 :group 'SQL)
1061 ;; Customization for Postgres
1063 (defcustom sql-postgres-program "psql"
1064 "Command to start psql by Postgres.
1066 Starts `sql-interactive-mode' after doing some setup."
1067 :type 'file
1068 :group 'SQL)
1070 (defcustom sql-postgres-options '("-P" "pager=off")
1071 "List of additional options for `sql-postgres-program'.
1072 The default setting includes the -P option which breaks older versions
1073 of the psql client (such as version 6.5.3). The -P option is equivalent
1074 to the --pset option. If you want the psql to prompt you for a user
1075 name, add the string \"-u\" to the list of options. If you want to
1076 provide a user name on the command line (newer versions such as 7.1),
1077 add your name with a \"-U\" prefix (such as \"-Umark\") to the list."
1078 :type '(repeat string)
1079 :version "20.8"
1080 :group 'SQL)
1082 (defcustom sql-postgres-login-params
1083 `((user :default ,(user-login-name))
1084 (database :default ,(user-login-name)
1085 :completion ,(completion-table-dynamic
1086 (lambda (_) (sql-postgres-list-databases)))
1087 :must-match confirm)
1088 server)
1089 "List of login parameters needed to connect to Postgres."
1090 :type 'sql-login-params
1091 :version "24.1"
1092 :group 'SQL)
1094 (defun sql-postgres-list-databases ()
1095 "Return a list of available PostgreSQL databases."
1096 (when (executable-find sql-postgres-program)
1097 (let ((res '()))
1098 (dolist (row (process-lines sql-postgres-program "-ltX"))
1099 (when (string-match "^ \\([[:alnum:]-_]+\\) +|.*" row)
1100 (push (match-string 1 row) res)))
1101 (nreverse res))))
1103 ;; Customization for Interbase
1105 (defcustom sql-interbase-program "isql"
1106 "Command to start isql by Interbase.
1108 Starts `sql-interactive-mode' after doing some setup."
1109 :type 'file
1110 :group 'SQL)
1112 (defcustom sql-interbase-options nil
1113 "List of additional options for `sql-interbase-program'."
1114 :type '(repeat string)
1115 :version "20.8"
1116 :group 'SQL)
1118 (defcustom sql-interbase-login-params '(user password database)
1119 "List of login parameters needed to connect to Interbase."
1120 :type 'sql-login-params
1121 :version "24.1"
1122 :group 'SQL)
1124 ;; Customization for DB2
1126 (defcustom sql-db2-program "db2"
1127 "Command to start db2 by IBM.
1129 Starts `sql-interactive-mode' after doing some setup."
1130 :type 'file
1131 :group 'SQL)
1133 (defcustom sql-db2-options nil
1134 "List of additional options for `sql-db2-program'."
1135 :type '(repeat string)
1136 :version "20.8"
1137 :group 'SQL)
1139 (defcustom sql-db2-login-params nil
1140 "List of login parameters needed to connect to DB2."
1141 :type 'sql-login-params
1142 :version "24.1"
1143 :group 'SQL)
1145 ;; Customization for Linter
1147 (defcustom sql-linter-program "inl"
1148 "Command to start inl by RELEX.
1150 Starts `sql-interactive-mode' after doing some setup."
1151 :type 'file
1152 :group 'SQL)
1154 (defcustom sql-linter-options nil
1155 "List of additional options for `sql-linter-program'."
1156 :type '(repeat string)
1157 :version "21.3"
1158 :group 'SQL)
1160 (defcustom sql-linter-login-params '(user password database server)
1161 "Login parameters to needed to connect to Linter."
1162 :type 'sql-login-params
1163 :version "24.1"
1164 :group 'SQL)
1168 ;;; Variables which do not need customization
1170 (defvar sql-user-history nil
1171 "History of usernames used.")
1173 (defvar sql-database-history nil
1174 "History of databases used.")
1176 (defvar sql-server-history nil
1177 "History of servers used.")
1179 ;; Passwords are not kept in a history.
1181 (defvar sql-product-history nil
1182 "History of products used.")
1184 (defvar sql-connection-history nil
1185 "History of connections used.")
1187 (defvar sql-buffer nil
1188 "Current SQLi buffer.
1190 The global value of `sql-buffer' is the name of the latest SQLi buffer
1191 created. Any SQL buffer created will make a local copy of this value.
1192 See `sql-interactive-mode' for more on multiple sessions. If you want
1193 to change the SQLi buffer a SQL mode sends its SQL strings to, change
1194 the local value of `sql-buffer' using \\[sql-set-sqli-buffer].")
1196 (defvar sql-prompt-regexp nil
1197 "Prompt used to initialize `comint-prompt-regexp'.
1199 You can change `sql-prompt-regexp' on `sql-interactive-mode-hook'.")
1201 (defvar sql-prompt-length 0
1202 "Prompt used to set `left-margin' in `sql-interactive-mode'.
1204 You can change `sql-prompt-length' on `sql-interactive-mode-hook'.")
1206 (defvar sql-prompt-cont-regexp nil
1207 "Prompt pattern of statement continuation prompts.")
1209 (defvar sql-alternate-buffer-name nil
1210 "Buffer-local string used to possibly rename the SQLi buffer.
1212 Used by `sql-rename-buffer'.")
1214 (defun sql-buffer-live-p (buffer &optional product connection)
1215 "Return non-nil if the process associated with buffer is live.
1217 BUFFER can be a buffer object or a buffer name. The buffer must
1218 be a live buffer, have a running process attached to it, be in
1219 `sql-interactive-mode', and, if PRODUCT or CONNECTION are
1220 specified, it's `sql-product' or `sql-connection' must match."
1222 (when buffer
1223 (setq buffer (get-buffer buffer))
1224 (and buffer
1225 (buffer-live-p buffer)
1226 (comint-check-proc buffer)
1227 (with-current-buffer buffer
1228 (and (derived-mode-p 'sql-interactive-mode)
1229 (or (not product)
1230 (eq product sql-product))
1231 (or (not connection)
1232 (eq connection sql-connection)))))))
1234 ;; Keymap for sql-interactive-mode.
1236 (defvar sql-interactive-mode-map
1237 (let ((map (make-sparse-keymap)))
1238 (if (fboundp 'set-keymap-parent)
1239 (set-keymap-parent map comint-mode-map); Emacs
1240 (if (fboundp 'set-keymap-parents)
1241 (set-keymap-parents map (list comint-mode-map)))); XEmacs
1242 (if (fboundp 'set-keymap-name)
1243 (set-keymap-name map 'sql-interactive-mode-map)); XEmacs
1244 (define-key map (kbd "C-j") 'sql-accumulate-and-indent)
1245 (define-key map (kbd "C-c C-w") 'sql-copy-column)
1246 (define-key map (kbd "O") 'sql-magic-go)
1247 (define-key map (kbd "o") 'sql-magic-go)
1248 (define-key map (kbd ";") 'sql-magic-semicolon)
1249 (define-key map (kbd "C-c C-l a") 'sql-list-all)
1250 (define-key map (kbd "C-c C-l t") 'sql-list-table)
1251 map)
1252 "Mode map used for `sql-interactive-mode'.
1253 Based on `comint-mode-map'.")
1255 ;; Keymap for sql-mode.
1257 (defvar sql-mode-map
1258 (let ((map (make-sparse-keymap)))
1259 (define-key map (kbd "C-c C-c") 'sql-send-paragraph)
1260 (define-key map (kbd "C-c C-r") 'sql-send-region)
1261 (define-key map (kbd "C-c C-s") 'sql-send-string)
1262 (define-key map (kbd "C-c C-b") 'sql-send-buffer)
1263 (define-key map (kbd "C-c C-n") 'sql-send-line-and-next)
1264 (define-key map (kbd "C-c C-i") 'sql-product-interactive)
1265 (define-key map (kbd "C-c C-z") 'sql-show-sqli-buffer)
1266 (define-key map (kbd "C-c C-l a") 'sql-list-all)
1267 (define-key map (kbd "C-c C-l t") 'sql-list-table)
1268 (define-key map [remap beginning-of-defun] 'sql-beginning-of-statement)
1269 (define-key map [remap end-of-defun] 'sql-end-of-statement)
1270 map)
1271 "Mode map used for `sql-mode'.")
1273 ;; easy menu for sql-mode.
1275 (easy-menu-define
1276 sql-mode-menu sql-mode-map
1277 "Menu for `sql-mode'."
1278 `("SQL"
1279 ["Send Paragraph" sql-send-paragraph (sql-buffer-live-p sql-buffer)]
1280 ["Send Region" sql-send-region (and mark-active
1281 (sql-buffer-live-p sql-buffer))]
1282 ["Send Buffer" sql-send-buffer (sql-buffer-live-p sql-buffer)]
1283 ["Send String" sql-send-string (sql-buffer-live-p sql-buffer)]
1284 "--"
1285 ["List all objects" sql-list-all (and (sql-buffer-live-p sql-buffer)
1286 (sql-get-product-feature sql-product :list-all))]
1287 ["List table details" sql-list-table (and (sql-buffer-live-p sql-buffer)
1288 (sql-get-product-feature sql-product :list-table))]
1289 "--"
1290 ["Start SQLi session" sql-product-interactive
1291 :visible (not sql-connection-alist)
1292 :enable (sql-get-product-feature sql-product :sqli-comint-func)]
1293 ("Start..."
1294 :visible sql-connection-alist
1295 :filter sql-connection-menu-filter
1296 "--"
1297 ["New SQLi Session" sql-product-interactive (sql-get-product-feature sql-product :sqli-comint-func)])
1298 ["--"
1299 :visible sql-connection-alist]
1300 ["Show SQLi buffer" sql-show-sqli-buffer t]
1301 ["Set SQLi buffer" sql-set-sqli-buffer t]
1302 ["Pop to SQLi buffer after send"
1303 sql-toggle-pop-to-buffer-after-send-region
1304 :style toggle
1305 :selected sql-pop-to-buffer-after-send-region]
1306 ["--" nil nil]
1307 ("Product"
1308 ,@(mapcar (lambda (prod-info)
1309 (let* ((prod (pop prod-info))
1310 (name (or (plist-get prod-info :name)
1311 (capitalize (symbol-name prod))))
1312 (cmd (intern (format "sql-highlight-%s-keywords" prod))))
1313 (fset cmd `(lambda () ,(format "Highlight %s SQL keywords." name)
1314 (interactive)
1315 (sql-set-product ',prod)))
1316 (vector name cmd
1317 :style 'radio
1318 :selected `(eq sql-product ',prod))))
1319 sql-product-alist))))
1321 ;; easy menu for sql-interactive-mode.
1323 (easy-menu-define
1324 sql-interactive-mode-menu sql-interactive-mode-map
1325 "Menu for `sql-interactive-mode'."
1326 '("SQL"
1327 ["Rename Buffer" sql-rename-buffer t]
1328 ["Save Connection" sql-save-connection (not sql-connection)]
1329 "--"
1330 ["List all objects" sql-list-all (sql-get-product-feature sql-product :list-all)]
1331 ["List table details" sql-list-table (sql-get-product-feature sql-product :list-table)]))
1333 ;; Abbreviations -- if you want more of them, define them in your init
1334 ;; file. Abbrevs have to be enabled in your init file, too.
1336 (define-abbrev-table 'sql-mode-abbrev-table
1337 '(("ins" "insert" nil nil t)
1338 ("upd" "update" nil nil t)
1339 ("del" "delete" nil nil t)
1340 ("sel" "select" nil nil t)
1341 ("proc" "procedure" nil nil t)
1342 ("func" "function" nil nil t)
1343 ("cr" "create" nil nil t))
1344 "Abbrev table used in `sql-mode' and `sql-interactive-mode'.")
1346 ;; Syntax Table
1348 (defvar sql-mode-syntax-table
1349 (let ((table (make-syntax-table)))
1350 ;; C-style comments /**/ (see elisp manual "Syntax Flags"))
1351 (modify-syntax-entry ?/ ". 14" table)
1352 (modify-syntax-entry ?* ". 23" table)
1353 ;; double-dash starts comments
1354 (modify-syntax-entry ?- ". 12b" table)
1355 ;; newline and formfeed end comments
1356 (modify-syntax-entry ?\n "> b" table)
1357 (modify-syntax-entry ?\f "> b" table)
1358 ;; single quotes (') delimit strings
1359 (modify-syntax-entry ?' "\"" table)
1360 ;; double quotes (") don't delimit strings
1361 (modify-syntax-entry ?\" "." table)
1362 ;; Make these all punctuation
1363 (mapc (lambda (c) (modify-syntax-entry c "." table))
1364 (string-to-list "!#$%&+,.:;<=>?@\\|"))
1365 table)
1366 "Syntax table used in `sql-mode' and `sql-interactive-mode'.")
1368 ;; Font lock support
1370 (defvar sql-mode-font-lock-object-name
1371 (eval-when-compile
1372 (list (concat "^\\s-*\\(?:create\\|drop\\|alter\\)\\s-+" ;; lead off with CREATE, DROP or ALTER
1373 "\\(?:\\w+\\s-+\\)*" ;; optional intervening keywords
1374 "\\(?:table\\|view\\|\\(?:package\\|type\\)\\(?:\\s-+body\\)?\\|proc\\(?:edure\\)?"
1375 "\\|function\\|trigger\\|sequence\\|rule\\|default\\)\\s-+"
1376 "\\(?:if\\s-+not\\s-+exists\\s-+\\)?" ;; IF NOT EXISTS
1377 "\\(\\w+\\(?:\\s-*[.]\\s-*\\w+\\)*\\)")
1378 1 'font-lock-function-name-face))
1380 "Pattern to match the names of top-level objects.
1382 The pattern matches the name in a CREATE, DROP or ALTER
1383 statement. The format of variable should be a valid
1384 `font-lock-keywords' entry.")
1386 ;; While there are international and American standards for SQL, they
1387 ;; are not followed closely, and most vendors offer significant
1388 ;; capabilities beyond those defined in the standard specifications.
1390 ;; SQL mode provides support for highlighting based on the product. In
1391 ;; addition to highlighting the product keywords, any ANSI keywords not
1392 ;; used by the product are also highlighted. This will help identify
1393 ;; keywords that could be restricted in future versions of the product
1394 ;; or might be a problem if ported to another product.
1396 ;; To reduce the complexity and size of the regular expressions
1397 ;; generated to match keywords, ANSI keywords are filtered out of
1398 ;; product keywords if they are equivalent. To do this, we define a
1399 ;; function `sql-font-lock-keywords-builder' that removes any keywords
1400 ;; that are matched by the ANSI patterns and results in the same face
1401 ;; being applied. For this to work properly, we must play some games
1402 ;; with the execution and compile time behavior. This code is a
1403 ;; little tricky but works properly.
1405 ;; When defining the keywords for individual products you should
1406 ;; include all of the keywords that you want matched. The filtering
1407 ;; against the ANSI keywords will be automatic if you use the
1408 ;; `sql-font-lock-keywords-builder' function and follow the
1409 ;; implementation pattern used for the other products in this file.
1411 (eval-when-compile
1412 (defvar sql-mode-ansi-font-lock-keywords)
1413 (setq sql-mode-ansi-font-lock-keywords nil))
1415 (eval-and-compile
1416 (defun sql-font-lock-keywords-builder (face boundaries &rest keywords)
1417 "Generation of regexp matching any one of KEYWORDS."
1419 (let ((bdy (or boundaries '("\\b" . "\\b")))
1420 kwd)
1422 ;; Remove keywords that are defined in ANSI
1423 (setq kwd keywords)
1424 ;; (dolist (k keywords)
1425 ;; (catch 'next
1426 ;; (dolist (a sql-mode-ansi-font-lock-keywords)
1427 ;; (when (and (eq face (cdr a))
1428 ;; (eq (string-match (car a) k 0) 0)
1429 ;; (eq (match-end 0) (length k)))
1430 ;; (setq kwd (delq k kwd))
1431 ;; (throw 'next nil)))))
1433 ;; Create a properly formed font-lock-keywords item
1434 (cons (concat (car bdy)
1435 (regexp-opt kwd t)
1436 (cdr bdy))
1437 face)))
1439 (defun sql-regexp-abbrev (keyword)
1440 (let ((brk (string-match "[~]" keyword))
1441 (len (length keyword))
1442 (sep "\\(?:")
1443 re i)
1444 (if (not brk)
1445 keyword
1446 (setq re (substring keyword 0 brk)
1447 i (+ 2 brk)
1448 brk (1+ brk))
1449 (while (<= i len)
1450 (setq re (concat re sep (substring keyword brk i))
1451 sep "\\|"
1452 i (1+ i)))
1453 (concat re "\\)?"))))
1455 (defun sql-regexp-abbrev-list (&rest keyw-list)
1456 (let ((re nil)
1457 (sep "\\<\\(?:"))
1458 (while keyw-list
1459 (setq re (concat re sep (sql-regexp-abbrev (car keyw-list)))
1460 sep "\\|"
1461 keyw-list (cdr keyw-list)))
1462 (concat re "\\)\\>"))))
1464 (eval-when-compile
1465 (setq sql-mode-ansi-font-lock-keywords
1466 (list
1467 ;; ANSI Non Reserved keywords
1468 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1469 "ada" "asensitive" "assignment" "asymmetric" "atomic" "between"
1470 "bitvar" "called" "catalog_name" "chain" "character_set_catalog"
1471 "character_set_name" "character_set_schema" "checked" "class_origin"
1472 "cobol" "collation_catalog" "collation_name" "collation_schema"
1473 "column_name" "command_function" "command_function_code" "committed"
1474 "condition_number" "connection_name" "constraint_catalog"
1475 "constraint_name" "constraint_schema" "contains" "cursor_name"
1476 "datetime_interval_code" "datetime_interval_precision" "defined"
1477 "definer" "dispatch" "dynamic_function" "dynamic_function_code"
1478 "existing" "exists" "final" "fortran" "generated" "granted"
1479 "hierarchy" "hold" "implementation" "infix" "insensitive" "instance"
1480 "instantiable" "invoker" "key_member" "key_type" "length" "m"
1481 "message_length" "message_octet_length" "message_text" "method" "more"
1482 "mumps" "name" "nullable" "number" "options" "overlaps" "overriding"
1483 "parameter_mode" "parameter_name" "parameter_ordinal_position"
1484 "parameter_specific_catalog" "parameter_specific_name"
1485 "parameter_specific_schema" "pascal" "pli" "position" "repeatable"
1486 "returned_length" "returned_octet_length" "returned_sqlstate"
1487 "routine_catalog" "routine_name" "routine_schema" "row_count" "scale"
1488 "schema_name" "security" "self" "sensitive" "serializable"
1489 "server_name" "similar" "simple" "source" "specific_name" "style"
1490 "subclass_origin" "sublist" "symmetric" "system" "table_name"
1491 "transaction_active" "transactions_committed"
1492 "transactions_rolled_back" "transform" "transforms" "trigger_catalog"
1493 "trigger_name" "trigger_schema" "type" "uncommitted" "unnamed"
1494 "user_defined_type_catalog" "user_defined_type_name"
1495 "user_defined_type_schema"
1498 ;; ANSI Reserved keywords
1499 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1500 "absolute" "action" "add" "admin" "after" "aggregate" "alias" "all"
1501 "allocate" "alter" "and" "any" "are" "as" "asc" "assertion" "at"
1502 "authorization" "before" "begin" "both" "breadth" "by" "call"
1503 "cascade" "cascaded" "case" "catalog" "check" "class" "close"
1504 "collate" "collation" "column" "commit" "completion" "connect"
1505 "connection" "constraint" "constraints" "constructor" "continue"
1506 "corresponding" "create" "cross" "cube" "current" "cursor" "cycle"
1507 "data" "day" "deallocate" "declare" "default" "deferrable" "deferred"
1508 "delete" "depth" "deref" "desc" "describe" "descriptor" "destroy"
1509 "destructor" "deterministic" "diagnostics" "dictionary" "disconnect"
1510 "distinct" "domain" "drop" "dynamic" "each" "else" "end" "equals"
1511 "escape" "every" "except" "exception" "exec" "execute" "external"
1512 "false" "fetch" "first" "for" "foreign" "found" "free" "from" "full"
1513 "function" "general" "get" "global" "go" "goto" "grant" "group"
1514 "grouping" "having" "host" "hour" "identity" "ignore" "immediate" "in"
1515 "indicator" "initialize" "initially" "inner" "inout" "input" "insert"
1516 "intersect" "into" "is" "isolation" "iterate" "join" "key" "language"
1517 "last" "lateral" "leading" "left" "less" "level" "like" "limit"
1518 "local" "locator" "map" "match" "minute" "modifies" "modify" "module"
1519 "month" "names" "natural" "new" "next" "no" "none" "not" "null" "of"
1520 "off" "old" "on" "only" "open" "operation" "option" "or" "order"
1521 "ordinality" "out" "outer" "output" "pad" "parameter" "parameters"
1522 "partial" "path" "postfix" "prefix" "preorder" "prepare" "preserve"
1523 "primary" "prior" "privileges" "procedure" "public" "read" "reads"
1524 "recursive" "references" "referencing" "relative" "restrict" "result"
1525 "return" "returns" "revoke" "right" "role" "rollback" "rollup"
1526 "routine" "rows" "savepoint" "schema" "scroll" "search" "second"
1527 "section" "select" "sequence" "session" "set" "sets" "size" "some"
1528 "space" "specific" "specifictype" "sql" "sqlexception" "sqlstate"
1529 "sqlwarning" "start" "state" "statement" "static" "structure" "table"
1530 "temporary" "terminate" "than" "then" "timezone_hour"
1531 "timezone_minute" "to" "trailing" "transaction" "translation"
1532 "trigger" "true" "under" "union" "unique" "unknown" "unnest" "update"
1533 "usage" "using" "value" "values" "variable" "view" "when" "whenever"
1534 "where" "with" "without" "work" "write" "year"
1537 ;; ANSI Functions
1538 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1539 "abs" "avg" "bit_length" "cardinality" "cast" "char_length"
1540 "character_length" "coalesce" "convert" "count" "current_date"
1541 "current_path" "current_role" "current_time" "current_timestamp"
1542 "current_user" "extract" "localtime" "localtimestamp" "lower" "max"
1543 "min" "mod" "nullif" "octet_length" "overlay" "placing" "session_user"
1544 "substring" "sum" "system_user" "translate" "treat" "trim" "upper"
1545 "user"
1548 ;; ANSI Data Types
1549 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1550 "array" "binary" "bit" "blob" "boolean" "char" "character" "clob"
1551 "date" "dec" "decimal" "double" "float" "int" "integer" "interval"
1552 "large" "national" "nchar" "nclob" "numeric" "object" "precision"
1553 "real" "ref" "row" "scope" "smallint" "time" "timestamp" "varchar"
1554 "varying" "zone"
1555 ))))
1557 (defvar sql-mode-ansi-font-lock-keywords
1558 (eval-when-compile sql-mode-ansi-font-lock-keywords)
1559 "ANSI SQL keywords used by font-lock.
1561 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1562 regular expressions are created during compilation by calling the
1563 function `regexp-opt'. Therefore, take a look at the source before
1564 you define your own `sql-mode-ansi-font-lock-keywords'. You may want
1565 to add functions and PL/SQL keywords.")
1567 (defun sql--oracle-show-reserved-words ()
1568 ;; This function is for use by the maintainer of SQL.EL only.
1569 (if (or (and (not (derived-mode-p 'sql-mode))
1570 (not (derived-mode-p 'sql-interactive-mode)))
1571 (not sql-buffer)
1572 (not (eq sql-product 'oracle)))
1573 (user-error "Not an Oracle buffer")
1575 (let ((b "*RESERVED WORDS*"))
1576 (sql-execute sql-buffer b
1577 (concat "SELECT "
1578 " keyword "
1579 ", reserved AS \"Res\" "
1580 ", res_type AS \"Type\" "
1581 ", res_attr AS \"Attr\" "
1582 ", res_semi AS \"Semi\" "
1583 ", duplicate AS \"Dup\" "
1584 "FROM V$RESERVED_WORDS "
1585 "WHERE length > 1 "
1586 "AND SUBSTR(keyword, 1, 1) BETWEEN 'A' AND 'Z' "
1587 "ORDER BY 2 DESC, 3 DESC, 4 DESC, 5 DESC, 6 DESC, 1;")
1588 nil nil)
1589 (with-current-buffer b
1590 (set (make-local-variable 'sql-product) 'oracle)
1591 (sql-product-font-lock t nil)
1592 (font-lock-mode +1)))))
1594 (defvar sql-mode-oracle-font-lock-keywords
1595 (eval-when-compile
1596 (list
1597 ;; Oracle SQL*Plus Commands
1598 ;; Only recognized in they start in column 1 and the
1599 ;; abbreviation is followed by a space or the end of line.
1600 (list (concat "^" (sql-regexp-abbrev "rem~ark") "\\(?:\\s-.*\\)?$")
1601 0 'font-lock-comment-face t)
1603 (list
1604 (concat
1605 "^\\(?:"
1606 (sql-regexp-abbrev-list
1607 "[@]\\{1,2\\}" "acc~ept" "a~ppend" "archive" "attribute"
1608 "bre~ak" "bti~tle" "c~hange" "cl~ear" "col~umn" "conn~ect"
1609 "copy" "def~ine" "del" "desc~ribe" "disc~onnect" "ed~it"
1610 "exec~ute" "exit" "get" "help" "ho~st" "[$]" "i~nput" "l~ist"
1611 "passw~ord" "pau~se" "pri~nt" "pro~mpt" "quit" "recover"
1612 "repf~ooter" "reph~eader" "r~un" "sav~e" "sho~w" "shutdown"
1613 "spo~ol" "sta~rt" "startup" "store" "tim~ing" "tti~tle"
1614 "undef~ine" "var~iable" "whenever")
1615 "\\|"
1616 (concat "\\(?:"
1617 (sql-regexp-abbrev "comp~ute")
1618 "\\s-+"
1619 (sql-regexp-abbrev-list
1620 "avg" "cou~nt" "min~imum" "max~imum" "num~ber" "sum"
1621 "std" "var~iance")
1622 "\\)")
1623 "\\|"
1624 (concat "\\(?:set\\s-+"
1625 (sql-regexp-abbrev-list
1626 "appi~nfo" "array~size" "auto~commit" "autop~rint"
1627 "autorecovery" "autot~race" "blo~ckterminator"
1628 "cmds~ep" "colsep" "com~patibility" "con~cat"
1629 "copyc~ommit" "copytypecheck" "def~ine" "describe"
1630 "echo" "editf~ile" "emb~edded" "esc~ape" "feed~back"
1631 "flagger" "flu~sh" "hea~ding" "heads~ep" "instance"
1632 "lin~esize" "lobof~fset" "long" "longc~hunksize"
1633 "mark~up" "newp~age" "null" "numf~ormat" "num~width"
1634 "pages~ize" "pau~se" "recsep" "recsepchar"
1635 "scan" "serverout~put" "shift~inout" "show~mode"
1636 "sqlbl~anklines" "sqlc~ase" "sqlco~ntinue"
1637 "sqln~umber" "sqlpluscompat~ibility" "sqlpre~fix"
1638 "sqlp~rompt" "sqlt~erminator" "suf~fix" "tab"
1639 "term~out" "ti~me" "timi~ng" "trim~out" "trims~pool"
1640 "und~erline" "ver~ify" "wra~p")
1641 "\\)")
1643 "\\)\\(?:\\s-.*\\)?\\(?:[-]\n.*\\)*$")
1644 0 'font-lock-doc-face t)
1645 '("&?&\\(?:\\sw\\|\\s_\\)+[.]?" 0 font-lock-preprocessor-face t)
1647 ;; Oracle PL/SQL Attributes (Declare these first to match %TYPE correctly)
1648 (sql-font-lock-keywords-builder 'font-lock-builtin-face '("%" . "\\b")
1649 "bulk_exceptions" "bulk_rowcount" "found" "isopen" "notfound"
1650 "rowcount" "rowtype" "type"
1652 ;; Oracle Functions
1653 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1654 "abs" "acos" "add_months" "appendchildxml" "ascii" "asciistr" "asin"
1655 "atan" "atan2" "avg" "bfilename" "bin_to_num" "bitand" "cardinality"
1656 "cast" "ceil" "chartorowid" "chr" "cluster_id" "cluster_probability"
1657 "cluster_set" "coalesce" "collect" "compose" "concat" "convert" "corr"
1658 "connect_by_root" "connect_by_iscycle" "connect_by_isleaf"
1659 "corr_k" "corr_s" "cos" "cosh" "count" "covar_pop" "covar_samp"
1660 "cube_table" "cume_dist" "current_date" "current_timestamp" "cv"
1661 "dataobj_to_partition" "dbtimezone" "decode" "decompose" "deletexml"
1662 "dense_rank" "depth" "deref" "dump" "empty_blob" "empty_clob"
1663 "existsnode" "exp" "extract" "extractvalue" "feature_id" "feature_set"
1664 "feature_value" "first" "first_value" "floor" "from_tz" "greatest"
1665 "grouping" "grouping_id" "group_id" "hextoraw" "initcap"
1666 "insertchildxml" "insertchildxmlafter" "insertchildxmlbefore"
1667 "insertxmlafter" "insertxmlbefore" "instr" "instr2" "instr4" "instrb"
1668 "instrc" "iteration_number" "lag" "last" "last_day" "last_value"
1669 "lead" "least" "length" "length2" "length4" "lengthb" "lengthc"
1670 "listagg" "ln" "lnnvl" "localtimestamp" "log" "lower" "lpad" "ltrim"
1671 "make_ref" "max" "median" "min" "mod" "months_between" "nanvl" "nchr"
1672 "new_time" "next_day" "nlssort" "nls_charset_decl_len"
1673 "nls_charset_id" "nls_charset_name" "nls_initcap" "nls_lower"
1674 "nls_upper" "nth_value" "ntile" "nullif" "numtodsinterval"
1675 "numtoyminterval" "nvl" "nvl2" "ora_dst_affected" "ora_dst_convert"
1676 "ora_dst_error" "ora_hash" "path" "percentile_cont" "percentile_disc"
1677 "percent_rank" "power" "powermultiset" "powermultiset_by_cardinality"
1678 "prediction" "prediction_bounds" "prediction_cost"
1679 "prediction_details" "prediction_probability" "prediction_set"
1680 "presentnnv" "presentv" "previous" "rank" "ratio_to_report" "rawtohex"
1681 "rawtonhex" "ref" "reftohex" "regexp_count" "regexp_instr" "regexp_like"
1682 "regexp_replace" "regexp_substr" "regr_avgx" "regr_avgy" "regr_count"
1683 "regr_intercept" "regr_r2" "regr_slope" "regr_sxx" "regr_sxy"
1684 "regr_syy" "remainder" "replace" "round" "rowidtochar" "rowidtonchar"
1685 "row_number" "rpad" "rtrim" "scn_to_timestamp" "sessiontimezone" "set"
1686 "sign" "sin" "sinh" "soundex" "sqrt" "stats_binomial_test"
1687 "stats_crosstab" "stats_f_test" "stats_ks_test" "stats_mode"
1688 "stats_mw_test" "stats_one_way_anova" "stats_t_test_indep"
1689 "stats_t_test_indepu" "stats_t_test_one" "stats_t_test_paired"
1690 "stats_wsr_test" "stddev" "stddev_pop" "stddev_samp" "substr"
1691 "substr2" "substr4" "substrb" "substrc" "sum" "sysdate" "systimestamp"
1692 "sys_connect_by_path" "sys_context" "sys_dburigen" "sys_extract_utc"
1693 "sys_guid" "sys_typeid" "sys_xmlagg" "sys_xmlgen" "tan" "tanh"
1694 "timestamp_to_scn" "to_binary_double" "to_binary_float" "to_blob"
1695 "to_char" "to_clob" "to_date" "to_dsinterval" "to_lob" "to_multi_byte"
1696 "to_nchar" "to_nclob" "to_number" "to_single_byte" "to_timestamp"
1697 "to_timestamp_tz" "to_yminterval" "translate" "treat" "trim" "trunc"
1698 "tz_offset" "uid" "unistr" "updatexml" "upper" "user" "userenv"
1699 "value" "variance" "var_pop" "var_samp" "vsize" "width_bucket"
1700 "xmlagg" "xmlcast" "xmlcdata" "xmlcolattval" "xmlcomment" "xmlconcat"
1701 "xmldiff" "xmlelement" "xmlexists" "xmlforest" "xmlisvalid" "xmlparse"
1702 "xmlpatch" "xmlpi" "xmlquery" "xmlroot" "xmlsequence" "xmlserialize"
1703 "xmltable" "xmltransform"
1706 ;; See the table V$RESERVED_WORDS
1707 ;; Oracle Keywords
1708 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1709 "abort" "access" "accessed" "account" "activate" "add" "admin"
1710 "advise" "after" "agent" "aggregate" "all" "allocate" "allow" "alter"
1711 "always" "analyze" "ancillary" "and" "any" "apply" "archive"
1712 "archivelog" "array" "as" "asc" "associate" "at" "attribute"
1713 "attributes" "audit" "authenticated" "authid" "authorization" "auto"
1714 "autoallocate" "automatic" "availability" "backup" "before" "begin"
1715 "behalf" "between" "binding" "bitmap" "block" "blocksize" "body"
1716 "both" "buffer_pool" "build" "by" "cache" "call" "cancel"
1717 "cascade" "case" "category" "certificate" "chained" "change" "check"
1718 "checkpoint" "child" "chunk" "class" "clear" "clone" "close" "cluster"
1719 "column" "column_value" "columns" "comment" "commit" "committed"
1720 "compatibility" "compile" "complete" "composite_limit" "compress"
1721 "compute" "connect" "connect_time" "consider" "consistent"
1722 "constraint" "constraints" "constructor" "contents" "context"
1723 "continue" "controlfile" "corruption" "cost" "cpu_per_call"
1724 "cpu_per_session" "create" "cross" "cube" "current" "currval" "cycle"
1725 "dangling" "data" "database" "datafile" "datafiles" "day" "ddl"
1726 "deallocate" "debug" "default" "deferrable" "deferred" "definer"
1727 "delay" "delete" "demand" "desc" "determines" "deterministic"
1728 "dictionary" "dimension" "directory" "disable" "disassociate"
1729 "disconnect" "distinct" "distinguished" "distributed" "dml" "drop"
1730 "each" "element" "else" "enable" "end" "equals_path" "escape"
1731 "estimate" "except" "exceptions" "exchange" "excluding" "exists"
1732 "expire" "explain" "extent" "external" "externally"
1733 "failed_login_attempts" "fast" "file" "final" "finish" "flush" "for"
1734 "force" "foreign" "freelist" "freelists" "freepools" "fresh" "from"
1735 "full" "function" "functions" "generated" "global" "global_name"
1736 "globally" "grant" "group" "grouping" "groups" "guard" "hash"
1737 "hashkeys" "having" "heap" "hierarchy" "id" "identified" "identifier"
1738 "idle_time" "immediate" "in" "including" "increment" "index" "indexed"
1739 "indexes" "indextype" "indextypes" "indicator" "initial" "initialized"
1740 "initially" "initrans" "inner" "insert" "instance" "instantiable"
1741 "instead" "intersect" "into" "invalidate" "is" "isolation" "java"
1742 "join" "keep" "key" "kill" "language" "left" "less" "level"
1743 "levels" "library" "like" "like2" "like4" "likec" "limit" "link"
1744 "list" "lob" "local" "location" "locator" "lock" "log" "logfile"
1745 "logging" "logical" "logical_reads_per_call"
1746 "logical_reads_per_session" "managed" "management" "manual" "map"
1747 "mapping" "master" "matched" "materialized" "maxdatafiles"
1748 "maxextents" "maximize" "maxinstances" "maxlogfiles" "maxloghistory"
1749 "maxlogmembers" "maxsize" "maxtrans" "maxvalue" "member" "memory"
1750 "merge" "migrate" "minextents" "minimize" "minimum" "minus" "minvalue"
1751 "mode" "modify" "monitoring" "month" "mount" "move" "movement" "name"
1752 "named" "natural" "nested" "never" "new" "next" "nextval" "no"
1753 "noarchivelog" "noaudit" "nocache" "nocompress" "nocopy" "nocycle"
1754 "nodelay" "noforce" "nologging" "nomapping" "nomaxvalue" "nominimize"
1755 "nominvalue" "nomonitoring" "none" "noorder" "noparallel" "norely"
1756 "noresetlogs" "noreverse" "normal" "norowdependencies" "nosort"
1757 "noswitch" "not" "nothing" "notimeout" "novalidate" "nowait" "null"
1758 "nulls" "object" "of" "off" "offline" "oidindex" "old" "on" "online"
1759 "only" "open" "operator" "optimal" "option" "or" "order"
1760 "organization" "out" "outer" "outline" "over" "overflow" "overriding"
1761 "package" "packages" "parallel" "parallel_enable" "parameters"
1762 "parent" "partition" "partitions" "password" "password_grace_time"
1763 "password_life_time" "password_lock_time" "password_reuse_max"
1764 "password_reuse_time" "password_verify_function" "pctfree"
1765 "pctincrease" "pctthreshold" "pctused" "pctversion" "percent"
1766 "performance" "permanent" "pfile" "physical" "pipelined" "pivot" "plan"
1767 "post_transaction" "pragma" "prebuilt" "preserve" "primary" "private"
1768 "private_sga" "privileges" "procedure" "profile" "protection" "public"
1769 "purge" "query" "quiesce" "quota" "range" "read" "reads" "rebuild"
1770 "records_per_block" "recover" "recovery" "recycle" "reduced" "ref"
1771 "references" "referencing" "refresh" "register" "reject" "relational"
1772 "rely" "rename" "reset" "resetlogs" "resize" "resolve" "resolver"
1773 "resource" "restrict" "restrict_references" "restricted" "result"
1774 "resumable" "resume" "retention" "return" "returning" "reuse"
1775 "reverse" "revoke" "rewrite" "right" "rnds" "rnps" "role" "roles"
1776 "rollback" "rollup" "row" "rowdependencies" "rownum" "rows" "sample"
1777 "savepoint" "scan" "schema" "scn" "scope" "segment" "select"
1778 "selectivity" "self" "sequence" "serializable" "session"
1779 "sessions_per_user" "set" "sets" "settings" "shared" "shared_pool"
1780 "shrink" "shutdown" "siblings" "sid" "single" "size" "skip" "some"
1781 "sort" "source" "space" "specification" "spfile" "split" "standby"
1782 "start" "statement_id" "static" "statistics" "stop" "storage" "store"
1783 "structure" "subpartition" "subpartitions" "substitutable"
1784 "successful" "supplemental" "suspend" "switch" "switchover" "synonym"
1785 "sys" "system" "table" "tables" "tablespace" "tempfile" "template"
1786 "temporary" "test" "than" "then" "thread" "through" "time_zone"
1787 "timeout" "to" "trace" "transaction" "trigger" "triggers" "truncate"
1788 "trust" "type" "types" "unarchived" "under" "under_path" "undo"
1789 "uniform" "union" "unique" "unlimited" "unlock" "unpivot" "unquiesce"
1790 "unrecoverable" "until" "unusable" "unused" "update" "upgrade" "usage"
1791 "use" "using" "validate" "validation" "value" "values" "variable"
1792 "varray" "version" "view" "wait" "when" "whenever" "where" "with"
1793 "without" "wnds" "wnps" "work" "write" "xmldata" "xmlschema" "xmltype"
1796 ;; Oracle Data Types
1797 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1798 "bfile" "binary_double" "binary_float" "blob" "byte" "char" "charbyte"
1799 "clob" "date" "day" "float" "interval" "local" "long" "longraw"
1800 "minute" "month" "nchar" "nclob" "number" "nvarchar2" "raw" "rowid" "second"
1801 "time" "timestamp" "urowid" "varchar2" "with" "year" "zone"
1804 ;; Oracle PL/SQL Functions
1805 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1806 "delete" "trim" "extend" "exists" "first" "last" "count" "limit"
1807 "prior" "next" "sqlcode" "sqlerrm"
1810 ;; Oracle PL/SQL Reserved words
1811 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1812 "all" "alter" "and" "any" "as" "asc" "at" "begin" "between" "by"
1813 "case" "check" "clusters" "cluster" "colauth" "columns" "compress"
1814 "connect" "crash" "create" "cursor" "declare" "default" "desc"
1815 "distinct" "drop" "else" "end" "exception" "exclusive" "fetch" "for"
1816 "from" "function" "goto" "grant" "group" "having" "identified" "if"
1817 "in" "index" "indexes" "insert" "intersect" "into" "is" "like" "lock"
1818 "minus" "mode" "nocompress" "not" "nowait" "null" "of" "on" "option"
1819 "or" "order" "overlaps" "procedure" "public" "resource" "revoke"
1820 "select" "share" "size" "sql" "start" "subtype" "tabauth" "table"
1821 "then" "to" "type" "union" "unique" "update" "values" "view" "views"
1822 "when" "where" "with"
1824 "true" "false"
1825 "raise_application_error"
1828 ;; Oracle PL/SQL Keywords
1829 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1830 "a" "add" "agent" "aggregate" "array" "attribute" "authid" "avg"
1831 "bfile_base" "binary" "blob_base" "block" "body" "both" "bound" "bulk"
1832 "byte" "c" "call" "calling" "cascade" "char" "char_base" "character"
1833 "charset" "charsetform" "charsetid" "clob_base" "close" "collect"
1834 "comment" "commit" "committed" "compiled" "constant" "constructor"
1835 "context" "continue" "convert" "count" "current" "customdatum"
1836 "dangling" "data" "date" "date_base" "day" "define" "delete"
1837 "deterministic" "double" "duration" "element" "elsif" "empty" "escape"
1838 "except" "exceptions" "execute" "exists" "exit" "external" "final"
1839 "fixed" "float" "forall" "force" "general" "hash" "heap" "hidden"
1840 "hour" "immediate" "including" "indicator" "indices" "infinite"
1841 "instantiable" "int" "interface" "interval" "invalidate" "isolation"
1842 "java" "language" "large" "leading" "length" "level" "library" "like2"
1843 "like4" "likec" "limit" "limited" "local" "long" "loop" "map" "max"
1844 "maxlen" "member" "merge" "min" "minute" "mod" "modify" "month"
1845 "multiset" "name" "nan" "national" "native" "nchar" "new" "nocopy"
1846 "number_base" "object" "ocicoll" "ocidate" "ocidatetime" "ociduration"
1847 "ociinterval" "ociloblocator" "ocinumber" "ociraw" "ociref"
1848 "ocirefcursor" "ocirowid" "ocistring" "ocitype" "old" "only" "opaque"
1849 "open" "operator" "oracle" "oradata" "organization" "orlany" "orlvary"
1850 "others" "out" "overriding" "package" "parallel_enable" "parameter"
1851 "parameters" "parent" "partition" "pascal" "pipe" "pipelined" "pragma"
1852 "precision" "prior" "private" "raise" "range" "raw" "read" "record"
1853 "ref" "reference" "relies_on" "rem" "remainder" "rename" "result"
1854 "result_cache" "return" "returning" "reverse" "rollback" "row"
1855 "sample" "save" "savepoint" "sb1" "sb2" "sb4" "second" "segment"
1856 "self" "separate" "sequence" "serializable" "set" "short" "size_t"
1857 "some" "sparse" "sqlcode" "sqldata" "sqlname" "sqlstate" "standard"
1858 "static" "stddev" "stored" "string" "struct" "style" "submultiset"
1859 "subpartition" "substitutable" "sum" "synonym" "tdo" "the" "time"
1860 "timestamp" "timezone_abbr" "timezone_hour" "timezone_minute"
1861 "timezone_region" "trailing" "transaction" "transactional" "trusted"
1862 "ub1" "ub2" "ub4" "under" "unsigned" "untrusted" "use" "using"
1863 "valist" "value" "variable" "variance" "varray" "varying" "void"
1864 "while" "work" "wrapped" "write" "year" "zone"
1865 ;; Pragma
1866 "autonomous_transaction" "exception_init" "inline"
1867 "restrict_references" "serially_reusable"
1870 ;; Oracle PL/SQL Data Types
1871 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1872 "\"BINARY LARGE OBJECT\"" "\"CHAR LARGE OBJECT\"" "\"CHAR VARYING\""
1873 "\"CHARACTER LARGE OBJECT\"" "\"CHARACTER VARYING\""
1874 "\"DOUBLE PRECISION\"" "\"INTERVAL DAY TO SECOND\""
1875 "\"INTERVAL YEAR TO MONTH\"" "\"LONG RAW\"" "\"NATIONAL CHAR\""
1876 "\"NATIONAL CHARACTER LARGE OBJECT\"" "\"NATIONAL CHARACTER\""
1877 "\"NCHAR LARGE OBJECT\"" "\"NCHAR\"" "\"NCLOB\"" "\"NVARCHAR2\""
1878 "\"TIME WITH TIME ZONE\"" "\"TIMESTAMP WITH LOCAL TIME ZONE\""
1879 "\"TIMESTAMP WITH TIME ZONE\""
1880 "bfile" "bfile_base" "binary_double" "binary_float" "binary_integer"
1881 "blob" "blob_base" "boolean" "char" "character" "char_base" "clob"
1882 "clob_base" "cursor" "date" "day" "dec" "decimal"
1883 "dsinterval_unconstrained" "float" "int" "integer" "interval" "local"
1884 "long" "mlslabel" "month" "natural" "naturaln" "nchar_cs" "number"
1885 "number_base" "numeric" "pls_integer" "positive" "positiven" "raw"
1886 "real" "ref" "rowid" "second" "signtype" "simple_double"
1887 "simple_float" "simple_integer" "smallint" "string" "time" "timestamp"
1888 "timestamp_ltz_unconstrained" "timestamp_tz_unconstrained"
1889 "timestamp_unconstrained" "time_tz_unconstrained" "time_unconstrained"
1890 "to" "urowid" "varchar" "varchar2" "with" "year"
1891 "yminterval_unconstrained" "zone"
1894 ;; Oracle PL/SQL Exceptions
1895 (sql-font-lock-keywords-builder 'font-lock-warning-face nil
1896 "access_into_null" "case_not_found" "collection_is_null"
1897 "cursor_already_open" "dup_val_on_index" "invalid_cursor"
1898 "invalid_number" "login_denied" "no_data_found" "no_data_needed"
1899 "not_logged_on" "program_error" "rowtype_mismatch" "self_is_null"
1900 "storage_error" "subscript_beyond_count" "subscript_outside_limit"
1901 "sys_invalid_rowid" "timeout_on_resource" "too_many_rows"
1902 "value_error" "zero_divide"
1905 "Oracle SQL keywords used by font-lock.
1907 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1908 regular expressions are created during compilation by calling the
1909 function `regexp-opt'. Therefore, take a look at the source before
1910 you define your own `sql-mode-oracle-font-lock-keywords'. You may want
1911 to add functions and PL/SQL keywords.")
1913 (defvar sql-mode-postgres-font-lock-keywords
1914 (eval-when-compile
1915 (list
1916 ;; Postgres psql commands
1917 '("^\\s-*\\\\.*$" . font-lock-doc-face)
1919 ;; Postgres unreserved words but may have meaning
1920 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil "a"
1921 "abs" "absent" "according" "ada" "alias" "allocate" "are" "array_agg"
1922 "asensitive" "atomic" "attribute" "attributes" "avg" "base64"
1923 "bernoulli" "bit_length" "bitvar" "blob" "blocked" "bom" "breadth" "c"
1924 "call" "cardinality" "catalog_name" "ceil" "ceiling" "char_length"
1925 "character_length" "character_set_catalog" "character_set_name"
1926 "character_set_schema" "characters" "checked" "class_origin" "clob"
1927 "cobol" "collation" "collation_catalog" "collation_name"
1928 "collation_schema" "collect" "column_name" "columns"
1929 "command_function" "command_function_code" "completion" "condition"
1930 "condition_number" "connect" "connection_name" "constraint_catalog"
1931 "constraint_name" "constraint_schema" "constructor" "contains"
1932 "control" "convert" "corr" "corresponding" "count" "covar_pop"
1933 "covar_samp" "cube" "cume_dist" "current_default_transform_group"
1934 "current_path" "current_transform_group_for_type" "cursor_name"
1935 "datalink" "datetime_interval_code" "datetime_interval_precision" "db"
1936 "defined" "degree" "dense_rank" "depth" "deref" "derived" "describe"
1937 "descriptor" "destroy" "destructor" "deterministic" "diagnostics"
1938 "disconnect" "dispatch" "dlnewcopy" "dlpreviouscopy" "dlurlcomplete"
1939 "dlurlcompleteonly" "dlurlcompletewrite" "dlurlpath" "dlurlpathonly"
1940 "dlurlpathwrite" "dlurlscheme" "dlurlserver" "dlvalue" "dynamic"
1941 "dynamic_function" "dynamic_function_code" "element" "empty"
1942 "end-exec" "equals" "every" "exception" "exec" "existing" "exp" "file"
1943 "filter" "final" "first_value" "flag" "floor" "fortran" "found" "free"
1944 "fs" "fusion" "g" "general" "generated" "get" "go" "goto" "grouping"
1945 "hex" "hierarchy" "host" "id" "ignore" "implementation" "import"
1946 "indent" "indicator" "infix" "initialize" "instance" "instantiable"
1947 "integrity" "intersection" "iterate" "k" "key_member" "key_type" "lag"
1948 "last_value" "lateral" "lead" "length" "less" "library" "like_regex"
1949 "link" "ln" "locator" "lower" "m" "map" "matched" "max"
1950 "max_cardinality" "member" "merge" "message_length"
1951 "message_octet_length" "message_text" "method" "min" "mod" "modifies"
1952 "modify" "module" "more" "multiset" "mumps" "namespace" "nclob"
1953 "nesting" "new" "nfc" "nfd" "nfkc" "nfkd" "nil" "normalize"
1954 "normalized" "nth_value" "ntile" "nullable" "number"
1955 "occurrences_regex" "octet_length" "octets" "old" "open" "operation"
1956 "ordering" "ordinality" "others" "output" "overriding" "p" "pad"
1957 "parameter" "parameter_mode" "parameter_name"
1958 "parameter_ordinal_position" "parameter_specific_catalog"
1959 "parameter_specific_name" "parameter_specific_schema" "parameters"
1960 "pascal" "passing" "passthrough" "percent_rank" "percentile_cont"
1961 "percentile_disc" "permission" "pli" "position_regex" "postfix"
1962 "power" "prefix" "preorder" "public" "rank" "reads" "recovery" "ref"
1963 "referencing" "regr_avgx" "regr_avgy" "regr_count" "regr_intercept"
1964 "regr_r2" "regr_slope" "regr_sxx" "regr_sxy" "regr_syy" "requiring"
1965 "respect" "restore" "result" "return" "returned_cardinality"
1966 "returned_length" "returned_octet_length" "returned_sqlstate" "rollup"
1967 "routine" "routine_catalog" "routine_name" "routine_schema"
1968 "row_count" "row_number" "scale" "schema_name" "scope" "scope_catalog"
1969 "scope_name" "scope_schema" "section" "selective" "self" "sensitive"
1970 "server_name" "sets" "size" "source" "space" "specific"
1971 "specific_name" "specifictype" "sql" "sqlcode" "sqlerror"
1972 "sqlexception" "sqlstate" "sqlwarning" "sqrt" "state" "static"
1973 "stddev_pop" "stddev_samp" "structure" "style" "subclass_origin"
1974 "sublist" "submultiset" "substring_regex" "sum" "system_user" "t"
1975 "table_name" "tablesample" "terminate" "than" "ties" "timezone_hour"
1976 "timezone_minute" "token" "top_level_count" "transaction_active"
1977 "transactions_committed" "transactions_rolled_back" "transform"
1978 "transforms" "translate" "translate_regex" "translation"
1979 "trigger_catalog" "trigger_name" "trigger_schema" "trim_array"
1980 "uescape" "under" "unlink" "unnamed" "unnest" "untyped" "upper" "uri"
1981 "usage" "user_defined_type_catalog" "user_defined_type_code"
1982 "user_defined_type_name" "user_defined_type_schema" "var_pop"
1983 "var_samp" "varbinary" "variable" "whenever" "width_bucket" "within"
1984 "xmlagg" "xmlbinary" "xmlcast" "xmlcomment" "xmldeclaration"
1985 "xmldocument" "xmlexists" "xmliterate" "xmlnamespaces" "xmlquery"
1986 "xmlschema" "xmltable" "xmltext" "xmlvalidate"
1989 ;; Postgres non-reserved words
1990 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1991 "abort" "absolute" "access" "action" "add" "admin" "after" "aggregate"
1992 "also" "alter" "always" "assertion" "assignment" "at" "attribute" "backward"
1993 "before" "begin" "between" "by" "cache" "called" "cascade" "cascaded"
1994 "catalog" "chain" "characteristics" "checkpoint" "class" "close"
1995 "cluster" "coalesce" "comment" "comments" "commit" "committed"
1996 "configuration" "connection" "constraints" "content" "continue"
1997 "conversion" "copy" "cost" "createdb" "createrole" "createuser" "csv"
1998 "current" "cursor" "cycle" "data" "database" "day" "deallocate" "dec"
1999 "declare" "defaults" "deferred" "definer" "delete" "delimiter"
2000 "delimiters" "dictionary" "disable" "discard" "document" "domain"
2001 "drop" "each" "enable" "encoding" "encrypted" "enum" "escape"
2002 "exclude" "excluding" "exclusive" "execute" "exists" "explain"
2003 "extension" "external" "extract" "family" "first" "float" "following" "force"
2004 "forward" "function" "functions" "global" "granted" "greatest"
2005 "handler" "header" "hold" "hour" "identity" "if" "immediate"
2006 "immutable" "implicit" "including" "increment" "index" "indexes"
2007 "inherit" "inherits" "inline" "inout" "input" "insensitive" "insert"
2008 "instead" "invoker" "isolation" "key" "label" "language" "large" "last"
2009 "lc_collate" "lc_ctype" "leakproof" "least" "level" "listen" "load" "local"
2010 "location" "lock" "login" "mapping" "match" "maxvalue" "minute"
2011 "minvalue" "mode" "month" "move" "names" "national" "nchar"
2012 "next" "no" "nocreatedb" "nocreaterole" "nocreateuser" "noinherit"
2013 "nologin" "none" "noreplication" "nosuperuser" "nothing" "notify" "nowait" "nullif"
2014 "nulls" "object" "of" "off" "oids" "operator" "option" "options" "out"
2015 "overlay" "owned" "owner" "parser" "partial" "partition" "passing" "password"
2016 "plans" "position" "preceding" "precision" "prepare" "prepared" "preserve" "prior"
2017 "privileges" "procedural" "procedure" "quote" "range" "read"
2018 "reassign" "recheck" "recursive" "ref" "reindex" "relative" "release"
2019 "rename" "repeatable" "replace" "replica" "replication" "reset" "restart" "restrict"
2020 "returns" "revoke" "role" "rollback" "row" "rows" "rule" "savepoint"
2021 "schema" "scroll" "search" "second" "security" "sequence"
2022 "serializable" "server" "session" "set" "setof" "share" "show"
2023 "simple" "snapshot" "stable" "standalone" "start" "statement" "statistics"
2024 "stdin" "stdout" "storage" "strict" "strip" "substring" "superuser"
2025 "sysid" "system" "tables" "tablespace" "temp" "template" "temporary"
2026 "transaction" "treat" "trim" "truncate" "trusted" "type" "types"
2027 "unbounded" "uncommitted" "unencrypted" "unlisten" "unlogged" "until"
2028 "update" "vacuum" "valid" "validate" "validator" "value" "values" "varying" "version"
2029 "view" "volatile" "whitespace" "without" "work" "wrapper" "write"
2030 "xmlattributes" "xmlconcat" "xmlelement" "xmlexists" "xmlforest" "xmlparse"
2031 "xmlpi" "xmlroot" "xmlserialize" "year" "yes" "zone"
2034 ;; Postgres Reserved
2035 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2036 "all" "analyse" "analyze" "and" "array" "asc" "as" "asymmetric"
2037 "authorization" "binary" "both" "case" "cast" "check" "collate"
2038 "column" "concurrently" "constraint" "create" "cross"
2039 "current_catalog" "current_date" "current_role" "current_schema"
2040 "current_time" "current_timestamp" "current_user" "default"
2041 "deferrable" "desc" "distinct" "do" "else" "end" "except" "false"
2042 "fetch" "foreign" "for" "freeze" "from" "full" "grant" "group"
2043 "having" "ilike" "initially" "inner" "in" "intersect" "into" "isnull"
2044 "is" "join" "leading" "left" "like" "limit" "localtime"
2045 "localtimestamp" "natural" "notnull" "not" "null" "offset"
2046 "only" "on" "order" "or" "outer" "overlaps" "over" "placing" "primary"
2047 "references" "returning" "right" "select" "session_user" "similar"
2048 "some" "symmetric" "table" "then" "to" "trailing" "true" "union"
2049 "unique" "user" "using" "variadic" "verbose" "when" "where" "window"
2050 "with"
2053 ;; Postgres PL/pgSQL
2054 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2055 "assign" "if" "case" "loop" "while" "for" "foreach" "exit" "elsif" "return"
2056 "raise" "execsql" "dynexecute" "perform" "getdiag" "open" "fetch" "move" "close"
2059 ;; Postgres Data Types
2060 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2061 "bigint" "bigserial" "bit" "bool" "boolean" "box" "bytea" "char"
2062 "character" "cidr" "circle" "date" "decimal" "double" "float4"
2063 "float8" "inet" "int" "int2" "int4" "int8" "integer" "interval" "line"
2064 "lseg" "macaddr" "money" "name" "numeric" "path" "point" "polygon"
2065 "precision" "real" "serial" "serial4" "serial8" "sequences" "smallint" "text"
2066 "time" "timestamp" "timestamptz" "timetz" "tsquery" "tsvector"
2067 "txid_snapshot" "unknown" "uuid" "varbit" "varchar" "varying" "without"
2068 "xml" "zone"
2071 "Postgres SQL keywords used by font-lock.
2073 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2074 regular expressions are created during compilation by calling the
2075 function `regexp-opt'. Therefore, take a look at the source before
2076 you define your own `sql-mode-postgres-font-lock-keywords'.")
2078 (defvar sql-mode-linter-font-lock-keywords
2079 (eval-when-compile
2080 (list
2081 ;; Linter Keywords
2082 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2083 "autocommit" "autoinc" "autorowid" "cancel" "cascade" "channel"
2084 "committed" "count" "countblob" "cross" "current" "data" "database"
2085 "datafile" "datafiles" "datesplit" "dba" "dbname" "default" "deferred"
2086 "denied" "description" "device" "difference" "directory" "error"
2087 "escape" "euc" "exclusive" "external" "extfile" "false" "file"
2088 "filename" "filesize" "filetime" "filter" "findblob" "first" "foreign"
2089 "full" "fuzzy" "global" "granted" "ignore" "immediate" "increment"
2090 "indexes" "indexfile" "indexfiles" "indextime" "initial" "integrity"
2091 "internal" "key" "last_autoinc" "last_rowid" "limit" "linter"
2092 "linter_file_device" "linter_file_size" "linter_name_length" "ln"
2093 "local" "login" "maxisn" "maxrow" "maxrowid" "maxvalue" "message"
2094 "minvalue" "module" "names" "national" "natural" "new" "new_table"
2095 "no" "node" "noneuc" "nulliferror" "numbers" "off" "old" "old_table"
2096 "only" "operation" "optimistic" "option" "page" "partially" "password"
2097 "phrase" "plan" "precision" "primary" "priority" "privileges"
2098 "proc_info_size" "proc_par_name_len" "protocol" "quant" "range" "raw"
2099 "read" "record" "records" "references" "remote" "rename" "replication"
2100 "restart" "rewrite" "root" "row" "rule" "savepoint" "security"
2101 "sensitive" "sequence" "serializable" "server" "since" "size" "some"
2102 "startup" "statement" "station" "success" "sys_guid" "tables" "test"
2103 "timeout" "trace" "transaction" "translation" "trigger"
2104 "trigger_info_size" "true" "trunc" "uncommitted" "unicode" "unknown"
2105 "unlimited" "unlisted" "user" "utf8" "value" "varying" "volumes"
2106 "wait" "windows_code" "workspace" "write" "xml"
2109 ;; Linter Reserved
2110 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2111 "access" "action" "add" "address" "after" "all" "alter" "always" "and"
2112 "any" "append" "as" "asc" "ascic" "async" "at_begin" "at_end" "audit"
2113 "aud_obj_name_len" "backup" "base" "before" "between" "blobfile"
2114 "blobfiles" "blobpct" "brief" "browse" "by" "case" "cast" "check"
2115 "clear" "close" "column" "comment" "commit" "connect" "contains"
2116 "correct" "create" "delete" "desc" "disable" "disconnect" "distinct"
2117 "drop" "each" "ef" "else" "enable" "end" "event" "except" "exclude"
2118 "execute" "exists" "extract" "fetch" "finish" "for" "from" "get"
2119 "grant" "group" "having" "identified" "in" "index" "inner" "insert"
2120 "instead" "intersect" "into" "is" "isolation" "join" "left" "level"
2121 "like" "lock" "mode" "modify" "not" "nowait" "null" "of" "on" "open"
2122 "or" "order" "outer" "owner" "press" "prior" "procedure" "public"
2123 "purge" "rebuild" "resource" "restrict" "revoke" "right" "role"
2124 "rollback" "rownum" "select" "session" "set" "share" "shutdown"
2125 "start" "stop" "sync" "synchronize" "synonym" "sysdate" "table" "then"
2126 "to" "union" "unique" "unlock" "until" "update" "using" "values"
2127 "view" "when" "where" "with" "without"
2130 ;; Linter Functions
2131 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2132 "abs" "acos" "asin" "atan" "atan2" "avg" "ceil" "cos" "cosh" "divtime"
2133 "exp" "floor" "getbits" "getblob" "getbyte" "getlong" "getraw"
2134 "getstr" "gettext" "getword" "hextoraw" "lenblob" "length" "log"
2135 "lower" "lpad" "ltrim" "max" "min" "mod" "monthname" "nvl"
2136 "octet_length" "power" "rand" "rawtohex" "repeat_string"
2137 "right_substr" "round" "rpad" "rtrim" "sign" "sin" "sinh" "soundex"
2138 "sqrt" "sum" "tan" "tanh" "timeint_to_days" "to_char" "to_date"
2139 "to_gmtime" "to_localtime" "to_number" "trim" "upper" "decode"
2140 "substr" "substring" "chr" "dayname" "days" "greatest" "hex" "initcap"
2141 "instr" "least" "multime" "replace" "width"
2144 ;; Linter Data Types
2145 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2146 "bigint" "bitmap" "blob" "boolean" "char" "character" "date"
2147 "datetime" "dec" "decimal" "double" "float" "int" "integer" "nchar"
2148 "number" "numeric" "real" "smallint" "varbyte" "varchar" "byte"
2149 "cursor" "long"
2152 "Linter SQL keywords used by font-lock.
2154 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2155 regular expressions are created during compilation by calling the
2156 function `regexp-opt'.")
2158 (defvar sql-mode-ms-font-lock-keywords
2159 (eval-when-compile
2160 (list
2161 ;; MS isql/osql Commands
2162 (cons
2163 (concat
2164 "^\\(?:\\(?:set\\s-+\\(?:"
2165 (regexp-opt '(
2166 "datefirst" "dateformat" "deadlock_priority" "lock_timeout"
2167 "concat_null_yields_null" "cursor_close_on_commit"
2168 "disable_def_cnst_chk" "fips_flagger" "identity_insert" "language"
2169 "offsets" "quoted_identifier" "arithabort" "arithignore" "fmtonly"
2170 "nocount" "noexec" "numeric_roundabort" "parseonly"
2171 "query_governor_cost_limit" "rowcount" "textsize" "ansi_defaults"
2172 "ansi_null_dflt_off" "ansi_null_dflt_on" "ansi_nulls" "ansi_padding"
2173 "ansi_warnings" "forceplan" "showplan_all" "showplan_text"
2174 "statistics" "implicit_transactions" "remote_proc_transactions"
2175 "transaction" "xact_abort"
2176 ) t)
2177 "\\)\\)\\|go\\s-*\\|use\\s-+\\|setuser\\s-+\\|dbcc\\s-+\\).*$")
2178 'font-lock-doc-face)
2180 ;; MS Reserved
2181 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2182 "absolute" "add" "all" "alter" "and" "any" "as" "asc" "authorization"
2183 "avg" "backup" "begin" "between" "break" "browse" "bulk" "by"
2184 "cascade" "case" "check" "checkpoint" "close" "clustered" "coalesce"
2185 "column" "commit" "committed" "compute" "confirm" "constraint"
2186 "contains" "containstable" "continue" "controlrow" "convert" "count"
2187 "create" "cross" "current" "current_date" "current_time"
2188 "current_timestamp" "current_user" "database" "deallocate" "declare"
2189 "default" "delete" "deny" "desc" "disk" "distinct" "distributed"
2190 "double" "drop" "dummy" "dump" "else" "end" "errlvl" "errorexit"
2191 "escape" "except" "exec" "execute" "exists" "exit" "fetch" "file"
2192 "fillfactor" "first" "floppy" "for" "foreign" "freetext"
2193 "freetexttable" "from" "full" "goto" "grant" "group" "having"
2194 "holdlock" "identity" "identity_insert" "identitycol" "if" "in"
2195 "index" "inner" "insert" "intersect" "into" "is" "isolation" "join"
2196 "key" "kill" "last" "left" "level" "like" "lineno" "load" "max" "min"
2197 "mirrorexit" "national" "next" "nocheck" "nolock" "nonclustered" "not"
2198 "null" "nullif" "of" "off" "offsets" "on" "once" "only" "open"
2199 "opendatasource" "openquery" "openrowset" "option" "or" "order"
2200 "outer" "output" "over" "paglock" "percent" "perm" "permanent" "pipe"
2201 "plan" "precision" "prepare" "primary" "print" "prior" "privileges"
2202 "proc" "procedure" "processexit" "public" "raiserror" "read"
2203 "readcommitted" "readpast" "readtext" "readuncommitted" "reconfigure"
2204 "references" "relative" "repeatable" "repeatableread" "replication"
2205 "restore" "restrict" "return" "revoke" "right" "rollback" "rowcount"
2206 "rowguidcol" "rowlock" "rule" "save" "schema" "select" "serializable"
2207 "session_user" "set" "shutdown" "some" "statistics" "sum"
2208 "system_user" "table" "tablock" "tablockx" "tape" "temp" "temporary"
2209 "textsize" "then" "to" "top" "tran" "transaction" "trigger" "truncate"
2210 "tsequal" "uncommitted" "union" "unique" "update" "updatetext"
2211 "updlock" "use" "user" "values" "view" "waitfor" "when" "where"
2212 "while" "with" "work" "writetext" "collate" "function" "openxml"
2213 "returns"
2216 ;; MS Functions
2217 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2218 "@@connections" "@@cpu_busy" "@@cursor_rows" "@@datefirst" "@@dbts"
2219 "@@error" "@@fetch_status" "@@identity" "@@idle" "@@io_busy"
2220 "@@langid" "@@language" "@@lock_timeout" "@@max_connections"
2221 "@@max_precision" "@@nestlevel" "@@options" "@@pack_received"
2222 "@@pack_sent" "@@packet_errors" "@@procid" "@@remserver" "@@rowcount"
2223 "@@servername" "@@servicename" "@@spid" "@@textsize" "@@timeticks"
2224 "@@total_errors" "@@total_read" "@@total_write" "@@trancount"
2225 "@@version" "abs" "acos" "and" "app_name" "ascii" "asin" "atan" "atn2"
2226 "avg" "case" "cast" "ceiling" "char" "charindex" "coalesce"
2227 "col_length" "col_name" "columnproperty" "containstable" "convert"
2228 "cos" "cot" "count" "current_timestamp" "current_user" "cursor_status"
2229 "databaseproperty" "datalength" "dateadd" "datediff" "datename"
2230 "datepart" "day" "db_id" "db_name" "degrees" "difference" "exp"
2231 "file_id" "file_name" "filegroup_id" "filegroup_name"
2232 "filegroupproperty" "fileproperty" "floor" "formatmessage"
2233 "freetexttable" "fulltextcatalogproperty" "fulltextserviceproperty"
2234 "getansinull" "getdate" "grouping" "host_id" "host_name" "ident_incr"
2235 "ident_seed" "identity" "index_col" "indexproperty" "is_member"
2236 "is_srvrolemember" "isdate" "isnull" "isnumeric" "left" "len" "log"
2237 "log10" "lower" "ltrim" "max" "min" "month" "nchar" "newid" "nullif"
2238 "object_id" "object_name" "objectproperty" "openquery" "openrowset"
2239 "parsename" "patindex" "patindex" "permissions" "pi" "power"
2240 "quotename" "radians" "rand" "replace" "replicate" "reverse" "right"
2241 "round" "rtrim" "session_user" "sign" "sin" "soundex" "space" "sqrt"
2242 "square" "stats_date" "stdev" "stdevp" "str" "stuff" "substring" "sum"
2243 "suser_id" "suser_name" "suser_sid" "suser_sname" "system_user" "tan"
2244 "textptr" "textvalid" "typeproperty" "unicode" "upper" "user"
2245 "user_id" "user_name" "var" "varp" "year"
2248 ;; MS Variables
2249 '("\\b@[a-zA-Z0-9_]*\\b" . font-lock-variable-name-face)
2251 ;; MS Types
2252 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2253 "binary" "bit" "char" "character" "cursor" "datetime" "dec" "decimal"
2254 "double" "float" "image" "int" "integer" "money" "national" "nchar"
2255 "ntext" "numeric" "numeric" "nvarchar" "precision" "real"
2256 "smalldatetime" "smallint" "smallmoney" "text" "timestamp" "tinyint"
2257 "uniqueidentifier" "varbinary" "varchar" "varying"
2260 "Microsoft SQLServer SQL keywords used by font-lock.
2262 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2263 regular expressions are created during compilation by calling the
2264 function `regexp-opt'. Therefore, take a look at the source before
2265 you define your own `sql-mode-ms-font-lock-keywords'.")
2267 (defvar sql-mode-sybase-font-lock-keywords nil
2268 "Sybase SQL keywords used by font-lock.
2270 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2271 regular expressions are created during compilation by calling the
2272 function `regexp-opt'. Therefore, take a look at the source before
2273 you define your own `sql-mode-sybase-font-lock-keywords'.")
2275 (defvar sql-mode-informix-font-lock-keywords nil
2276 "Informix SQL keywords used by font-lock.
2278 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2279 regular expressions are created during compilation by calling the
2280 function `regexp-opt'. Therefore, take a look at the source before
2281 you define your own `sql-mode-informix-font-lock-keywords'.")
2283 (defvar sql-mode-interbase-font-lock-keywords nil
2284 "Interbase SQL keywords used by font-lock.
2286 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2287 regular expressions are created during compilation by calling the
2288 function `regexp-opt'. Therefore, take a look at the source before
2289 you define your own `sql-mode-interbase-font-lock-keywords'.")
2291 (defvar sql-mode-ingres-font-lock-keywords nil
2292 "Ingres SQL keywords used by font-lock.
2294 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2295 regular expressions are created during compilation by calling the
2296 function `regexp-opt'. Therefore, take a look at the source before
2297 you define your own `sql-mode-interbase-font-lock-keywords'.")
2299 (defvar sql-mode-solid-font-lock-keywords nil
2300 "Solid SQL keywords used by font-lock.
2302 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2303 regular expressions are created during compilation by calling the
2304 function `regexp-opt'. Therefore, take a look at the source before
2305 you define your own `sql-mode-solid-font-lock-keywords'.")
2307 (defvar sql-mode-mysql-font-lock-keywords
2308 (eval-when-compile
2309 (list
2310 ;; MySQL Functions
2311 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2312 "ascii" "avg" "bdmpolyfromtext" "bdmpolyfromwkb" "bdpolyfromtext"
2313 "bdpolyfromwkb" "benchmark" "bin" "bit_and" "bit_length" "bit_or"
2314 "bit_xor" "both" "cast" "char_length" "character_length" "coalesce"
2315 "concat" "concat_ws" "connection_id" "conv" "convert" "count"
2316 "curdate" "current_date" "current_time" "current_timestamp" "curtime"
2317 "elt" "encrypt" "export_set" "field" "find_in_set" "found_rows" "from"
2318 "geomcollfromtext" "geomcollfromwkb" "geometrycollectionfromtext"
2319 "geometrycollectionfromwkb" "geometryfromtext" "geometryfromwkb"
2320 "geomfromtext" "geomfromwkb" "get_lock" "group_concat" "hex" "ifnull"
2321 "instr" "interval" "isnull" "last_insert_id" "lcase" "leading"
2322 "length" "linefromtext" "linefromwkb" "linestringfromtext"
2323 "linestringfromwkb" "load_file" "locate" "lower" "lpad" "ltrim"
2324 "make_set" "master_pos_wait" "max" "mid" "min" "mlinefromtext"
2325 "mlinefromwkb" "mpointfromtext" "mpointfromwkb" "mpolyfromtext"
2326 "mpolyfromwkb" "multilinestringfromtext" "multilinestringfromwkb"
2327 "multipointfromtext" "multipointfromwkb" "multipolygonfromtext"
2328 "multipolygonfromwkb" "now" "nullif" "oct" "octet_length" "ord"
2329 "pointfromtext" "pointfromwkb" "polyfromtext" "polyfromwkb"
2330 "polygonfromtext" "polygonfromwkb" "position" "quote" "rand"
2331 "release_lock" "repeat" "replace" "reverse" "rpad" "rtrim" "soundex"
2332 "space" "std" "stddev" "substring" "substring_index" "sum" "sysdate"
2333 "trailing" "trim" "ucase" "unix_timestamp" "upper" "user" "variance"
2336 ;; MySQL Keywords
2337 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2338 "action" "add" "after" "against" "all" "alter" "and" "as" "asc"
2339 "auto_increment" "avg_row_length" "bdb" "between" "by" "cascade"
2340 "case" "change" "character" "check" "checksum" "close" "collate"
2341 "collation" "column" "columns" "comment" "committed" "concurrent"
2342 "constraint" "create" "cross" "data" "database" "default"
2343 "delay_key_write" "delayed" "delete" "desc" "directory" "disable"
2344 "distinct" "distinctrow" "do" "drop" "dumpfile" "duplicate" "else" "elseif"
2345 "enable" "enclosed" "end" "escaped" "exists" "fields" "first" "for"
2346 "force" "foreign" "from" "full" "fulltext" "global" "group" "handler"
2347 "having" "heap" "high_priority" "if" "ignore" "in" "index" "infile"
2348 "inner" "insert" "insert_method" "into" "is" "isam" "isolation" "join"
2349 "key" "keys" "last" "left" "level" "like" "limit" "lines" "load"
2350 "local" "lock" "low_priority" "match" "max_rows" "merge" "min_rows"
2351 "mode" "modify" "mrg_myisam" "myisam" "natural" "next" "no" "not"
2352 "null" "offset" "oj" "on" "open" "optionally" "or" "order" "outer"
2353 "outfile" "pack_keys" "partial" "password" "prev" "primary"
2354 "procedure" "quick" "raid0" "raid_type" "read" "references" "rename"
2355 "repeatable" "restrict" "right" "rollback" "rollup" "row_format"
2356 "savepoint" "select" "separator" "serializable" "session" "set"
2357 "share" "show" "sql_big_result" "sql_buffer_result" "sql_cache"
2358 "sql_calc_found_rows" "sql_no_cache" "sql_small_result" "starting"
2359 "straight_join" "striped" "table" "tables" "temporary" "terminated"
2360 "then" "to" "transaction" "truncate" "type" "uncommitted" "union"
2361 "unique" "unlock" "update" "use" "using" "values" "when" "where"
2362 "with" "write" "xor"
2365 ;; MySQL Data Types
2366 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2367 "bigint" "binary" "bit" "blob" "bool" "boolean" "char" "curve" "date"
2368 "datetime" "dec" "decimal" "double" "enum" "fixed" "float" "geometry"
2369 "geometrycollection" "int" "integer" "line" "linearring" "linestring"
2370 "longblob" "longtext" "mediumblob" "mediumint" "mediumtext"
2371 "multicurve" "multilinestring" "multipoint" "multipolygon"
2372 "multisurface" "national" "numeric" "point" "polygon" "precision"
2373 "real" "smallint" "surface" "text" "time" "timestamp" "tinyblob"
2374 "tinyint" "tinytext" "unsigned" "varchar" "year" "year2" "year4"
2375 "zerofill"
2378 "MySQL SQL keywords used by font-lock.
2380 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2381 regular expressions are created during compilation by calling the
2382 function `regexp-opt'. Therefore, take a look at the source before
2383 you define your own `sql-mode-mysql-font-lock-keywords'.")
2385 (defvar sql-mode-sqlite-font-lock-keywords
2386 (eval-when-compile
2387 (list
2388 ;; SQLite commands
2389 '("^[.].*$" . font-lock-doc-face)
2391 ;; SQLite Keyword
2392 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2393 "abort" "action" "add" "after" "all" "alter" "analyze" "and" "as"
2394 "asc" "attach" "autoincrement" "before" "begin" "between" "by"
2395 "cascade" "case" "cast" "check" "collate" "column" "commit" "conflict"
2396 "constraint" "create" "cross" "database" "default" "deferrable"
2397 "deferred" "delete" "desc" "detach" "distinct" "drop" "each" "else"
2398 "end" "escape" "except" "exclusive" "exists" "explain" "fail" "for"
2399 "foreign" "from" "full" "glob" "group" "having" "if" "ignore"
2400 "immediate" "in" "index" "indexed" "initially" "inner" "insert"
2401 "instead" "intersect" "into" "is" "isnull" "join" "key" "left" "like"
2402 "limit" "match" "natural" "no" "not" "notnull" "null" "of" "offset"
2403 "on" "or" "order" "outer" "plan" "pragma" "primary" "query" "raise"
2404 "references" "regexp" "reindex" "release" "rename" "replace"
2405 "restrict" "right" "rollback" "row" "savepoint" "select" "set" "table"
2406 "temp" "temporary" "then" "to" "transaction" "trigger" "union"
2407 "unique" "update" "using" "vacuum" "values" "view" "virtual" "when"
2408 "where"
2410 ;; SQLite Data types
2411 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2412 "int" "integer" "tinyint" "smallint" "mediumint" "bigint" "unsigned"
2413 "big" "int2" "int8" "character" "varchar" "varying" "nchar" "native"
2414 "nvarchar" "text" "clob" "blob" "real" "double" "precision" "float"
2415 "numeric" "number" "decimal" "boolean" "date" "datetime"
2417 ;; SQLite Functions
2418 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2419 ;; Core functions
2420 "abs" "changes" "coalesce" "glob" "ifnull" "hex" "last_insert_rowid"
2421 "length" "like" "load_extension" "lower" "ltrim" "max" "min" "nullif"
2422 "quote" "random" "randomblob" "replace" "round" "rtrim" "soundex"
2423 "sqlite_compileoption_get" "sqlite_compileoption_used"
2424 "sqlite_source_id" "sqlite_version" "substr" "total_changes" "trim"
2425 "typeof" "upper" "zeroblob"
2426 ;; Date/time functions
2427 "time" "julianday" "strftime"
2428 "current_date" "current_time" "current_timestamp"
2429 ;; Aggregate functions
2430 "avg" "count" "group_concat" "max" "min" "sum" "total"
2433 "SQLite SQL keywords used by font-lock.
2435 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2436 regular expressions are created during compilation by calling the
2437 function `regexp-opt'. Therefore, take a look at the source before
2438 you define your own `sql-mode-sqlite-font-lock-keywords'.")
2440 (defvar sql-mode-db2-font-lock-keywords nil
2441 "DB2 SQL keywords used by font-lock.
2443 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2444 regular expressions are created during compilation by calling the
2445 function `regexp-opt'. Therefore, take a look at the source before
2446 you define your own `sql-mode-db2-font-lock-keywords'.")
2448 (defvar sql-mode-font-lock-keywords nil
2449 "SQL keywords used by font-lock.
2451 Setting this variable directly no longer has any affect. Use
2452 `sql-product' and `sql-add-product-keywords' to control the
2453 highlighting rules in SQL mode.")
2457 ;;; SQL Product support functions
2459 (defun sql-read-product (prompt &optional initial)
2460 "Read a valid SQL product."
2461 (let ((init (or (and initial (symbol-name initial)) "ansi")))
2462 (intern (completing-read
2463 prompt
2464 (mapcar (lambda (info) (symbol-name (car info)))
2465 sql-product-alist)
2466 nil 'require-match
2467 init 'sql-product-history init))))
2469 (defun sql-add-product (product display &rest plist)
2470 "Add support for a database product in `sql-mode'.
2472 Add PRODUCT to `sql-product-alist' which enables `sql-mode' to
2473 properly support syntax highlighting and interactive interaction.
2474 DISPLAY is the name of the SQL product that will appear in the
2475 menu bar and in messages. PLIST initializes the product
2476 configuration."
2478 ;; Don't do anything if the product is already supported
2479 (if (assoc product sql-product-alist)
2480 (user-error "Product `%s' is already defined" product)
2482 ;; Add product to the alist
2483 (add-to-list 'sql-product-alist `(,product :name ,display . ,plist))
2484 ;; Add a menu item to the SQL->Product menu
2485 (easy-menu-add-item sql-mode-menu '("Product")
2486 ;; Each product is represented by a radio
2487 ;; button with it's display name.
2488 `[,display
2489 (sql-set-product ',product)
2490 :style radio
2491 :selected (eq sql-product ',product)]
2492 ;; Maintain the product list in
2493 ;; (case-insensitive) alphabetic order of the
2494 ;; display names. Loop thru each keymap item
2495 ;; looking for an item whose display name is
2496 ;; after this product's name.
2497 (let ((next-item)
2498 (down-display (downcase display)))
2499 (map-keymap (lambda (k b)
2500 (when (and (not next-item)
2501 (string-lessp down-display
2502 (downcase (cadr b))))
2503 (setq next-item k)))
2504 (easy-menu-get-map sql-mode-menu '("Product")))
2505 next-item))
2506 product))
2508 (defun sql-del-product (product)
2509 "Remove support for PRODUCT in `sql-mode'."
2511 ;; Remove the menu item based on the display name
2512 (easy-menu-remove-item sql-mode-menu '("Product") (sql-get-product-feature product :name))
2513 ;; Remove the product alist item
2514 (setq sql-product-alist (assq-delete-all product sql-product-alist))
2515 nil)
2517 (defun sql-set-product-feature (product feature newvalue)
2518 "Set FEATURE of database PRODUCT to NEWVALUE.
2520 The PRODUCT must be a symbol which identifies the database
2521 product. The product must have already exist on the product
2522 list. See `sql-add-product' to add new products. The FEATURE
2523 argument must be a plist keyword accepted by
2524 `sql-product-alist'."
2526 (let* ((p (assoc product sql-product-alist))
2527 (v (plist-get (cdr p) feature)))
2528 (if p
2529 (if (and
2530 (member feature sql-indirect-features)
2531 (symbolp v))
2532 (set v newvalue)
2533 (setcdr p (plist-put (cdr p) feature newvalue)))
2534 (error "`%s' is not a known product; use `sql-add-product' to add it first." product))))
2536 (defun sql-get-product-feature (product feature &optional fallback not-indirect)
2537 "Lookup FEATURE associated with a SQL PRODUCT.
2539 If the FEATURE is nil for PRODUCT, and FALLBACK is specified,
2540 then the FEATURE associated with the FALLBACK product is
2541 returned.
2543 If the FEATURE is in the list `sql-indirect-features', and the
2544 NOT-INDIRECT parameter is not set, then the value of the symbol
2545 stored in the connect alist is returned.
2547 See `sql-product-alist' for a list of products and supported features."
2548 (let* ((p (assoc product sql-product-alist))
2549 (v (plist-get (cdr p) feature)))
2551 (if p
2552 ;; If no value and fallback, lookup feature for fallback
2553 (if (and (not v)
2554 fallback
2555 (not (eq product fallback)))
2556 (sql-get-product-feature fallback feature)
2558 (if (and
2559 (member feature sql-indirect-features)
2560 (not not-indirect)
2561 (symbolp v))
2562 (symbol-value v)
2564 (error "`%s' is not a known product; use `sql-add-product' to add it first." product)
2565 nil)))
2567 (defun sql-product-font-lock (keywords-only imenu)
2568 "Configure font-lock and imenu with product-specific settings.
2570 The KEYWORDS-ONLY flag is passed to font-lock to specify whether
2571 only keywords should be highlighted and syntactic highlighting
2572 skipped. The IMENU flag indicates whether `imenu-mode' should
2573 also be configured."
2575 (let
2576 ;; Get the product-specific syntax-alist.
2577 ((syntax-alist (sql-product-font-lock-syntax-alist)))
2579 ;; Get the product-specific keywords.
2580 (set (make-local-variable 'sql-mode-font-lock-keywords)
2581 (append
2582 (unless (eq sql-product 'ansi)
2583 (sql-get-product-feature sql-product :font-lock))
2584 ;; Always highlight ANSI keywords
2585 (sql-get-product-feature 'ansi :font-lock)
2586 ;; Fontify object names in CREATE, DROP and ALTER DDL
2587 ;; statements
2588 (list sql-mode-font-lock-object-name)))
2590 ;; Setup font-lock. Force re-parsing of `font-lock-defaults'.
2591 (kill-local-variable 'font-lock-set-defaults)
2592 (set (make-local-variable 'font-lock-defaults)
2593 (list 'sql-mode-font-lock-keywords
2594 keywords-only t syntax-alist))
2596 ;; Force font lock to reinitialize if it is already on
2597 ;; Otherwise, we can wait until it can be started.
2598 (when (and (fboundp 'font-lock-mode)
2599 (boundp 'font-lock-mode)
2600 font-lock-mode)
2601 (font-lock-mode-internal nil)
2602 (font-lock-mode-internal t))
2604 (add-hook 'font-lock-mode-hook
2605 (lambda ()
2606 ;; Provide defaults for new font-lock faces.
2607 (defvar font-lock-builtin-face
2608 (if (boundp 'font-lock-preprocessor-face)
2609 font-lock-preprocessor-face
2610 font-lock-keyword-face))
2611 (defvar font-lock-doc-face font-lock-string-face))
2612 nil t)
2614 ;; Setup imenu; it needs the same syntax-alist.
2615 (when imenu
2616 (setq imenu-syntax-alist syntax-alist))))
2618 ;;;###autoload
2619 (defun sql-add-product-keywords (product keywords &optional append)
2620 "Add highlighting KEYWORDS for SQL PRODUCT.
2622 PRODUCT should be a symbol, the name of a SQL product, such as
2623 `oracle'. KEYWORDS should be a list; see the variable
2624 `font-lock-keywords'. By default they are added at the beginning
2625 of the current highlighting list. If optional argument APPEND is
2626 `set', they are used to replace the current highlighting list.
2627 If APPEND is any other non-nil value, they are added at the end
2628 of the current highlighting list.
2630 For example:
2632 (sql-add-product-keywords \\='ms
2633 \\='((\"\\\\b\\\\w+_t\\\\b\" . font-lock-type-face)))
2635 adds a fontification pattern to fontify identifiers ending in
2636 `_t' as data types."
2638 (let* ((sql-indirect-features nil)
2639 (font-lock-var (sql-get-product-feature product :font-lock))
2640 (old-val))
2642 (setq old-val (symbol-value font-lock-var))
2643 (set font-lock-var
2644 (if (eq append 'set)
2645 keywords
2646 (if append
2647 (append old-val keywords)
2648 (append keywords old-val))))))
2650 (defun sql-for-each-login (login-params body)
2651 "Iterate through login parameters and return a list of results."
2652 (delq nil
2653 (mapcar
2654 (lambda (param)
2655 (let ((token (or (car-safe param) param))
2656 (plist (cdr-safe param)))
2657 (funcall body token plist)))
2658 login-params)))
2662 ;;; Functions to switch highlighting
2664 (defun sql-product-syntax-table ()
2665 (let ((table (copy-syntax-table sql-mode-syntax-table)))
2666 (mapc (lambda (entry)
2667 (modify-syntax-entry (car entry) (cdr entry) table))
2668 (sql-get-product-feature sql-product :syntax-alist))
2669 table))
2671 (defun sql-product-font-lock-syntax-alist ()
2672 (append
2673 ;; Change all symbol character to word characters
2674 (mapcar
2675 (lambda (entry) (if (string= (substring (cdr entry) 0 1) "_")
2676 (cons (car entry)
2677 (concat "w" (substring (cdr entry) 1)))
2678 entry))
2679 (sql-get-product-feature sql-product :syntax-alist))
2680 '((?_ . "w"))))
2682 (defun sql-highlight-product ()
2683 "Turn on the font highlighting for the SQL product selected."
2684 (when (derived-mode-p 'sql-mode)
2685 ;; Enhance the syntax table for the product
2686 (set-syntax-table (sql-product-syntax-table))
2688 ;; Setup font-lock
2689 (sql-product-font-lock nil t)
2691 ;; Set the mode name to include the product.
2692 (setq mode-name (concat "SQL[" (or (sql-get-product-feature sql-product :name)
2693 (symbol-name sql-product)) "]"))))
2695 (defun sql-set-product (product)
2696 "Set `sql-product' to PRODUCT and enable appropriate highlighting."
2697 (interactive
2698 (list (sql-read-product "SQL product: ")))
2699 (if (stringp product) (setq product (intern product)))
2700 (when (not (assoc product sql-product-alist))
2701 (user-error "SQL product %s is not supported; treated as ANSI" product)
2702 (setq product 'ansi))
2704 ;; Save product setting and fontify.
2705 (setq sql-product product)
2706 (sql-highlight-product))
2709 ;;; Compatibility functions
2711 (if (not (fboundp 'comint-line-beginning-position))
2712 ;; comint-line-beginning-position is defined in Emacs 21
2713 (defun comint-line-beginning-position ()
2714 "Return the buffer position of the beginning of the line, after any prompt.
2715 The prompt is assumed to be any text at the beginning of the line
2716 matching the regular expression `comint-prompt-regexp', a buffer
2717 local variable."
2718 (save-excursion (comint-bol nil) (point))))
2720 ;;; SMIE support
2722 ;; Needs a lot more love than I can provide. --Stef
2724 ;; (require 'smie)
2726 ;; (defconst sql-smie-grammar
2727 ;; (smie-prec2->grammar
2728 ;; (smie-bnf->prec2
2729 ;; ;; Partly based on http://www.h2database.com/html/grammar.html
2730 ;; '((cmd ("SELECT" select-exp "FROM" select-table-exp)
2731 ;; )
2732 ;; (select-exp ("*") (exp) (exp "AS" column-alias))
2733 ;; (column-alias)
2734 ;; (select-table-exp (table-exp "WHERE" exp) (table-exp))
2735 ;; (table-exp)
2736 ;; (exp ("CASE" exp "WHEN" exp "THEN" exp "ELSE" exp "END")
2737 ;; ("CASE" exp "WHEN" exp "THEN" exp "END"))
2738 ;; ;; Random ad-hoc additions.
2739 ;; (foo (foo "," foo))
2740 ;; )
2741 ;; '((assoc ",")))))
2743 ;; (defun sql-smie-rules (kind token)
2744 ;; (pcase (cons kind token)
2745 ;; (`(:list-intro . ,_) t)
2746 ;; (`(:before . "(") (smie-rule-parent))))
2748 ;;; Motion Functions
2750 (defun sql-statement-regexp (prod)
2751 (let* ((ansi-stmt (sql-get-product-feature 'ansi :statement))
2752 (prod-stmt (sql-get-product-feature prod :statement)))
2753 (concat "^\\<"
2754 (if prod-stmt
2755 ansi-stmt
2756 (concat "\\(" ansi-stmt "\\|" prod-stmt "\\)"))
2757 "\\>")))
2759 (defun sql-beginning-of-statement (arg)
2760 "Move to the beginning of the current SQL statement."
2761 (interactive "p")
2763 (let ((here (point))
2764 (regexp (sql-statement-regexp sql-product))
2765 last next)
2767 ;; Go to the end of the statement before the start we desire
2768 (setq last (or (sql-end-of-statement (- arg))
2769 (point-min)))
2770 ;; And find the end after that
2771 (setq next (or (sql-end-of-statement 1)
2772 (point-max)))
2774 ;; Our start must be between them
2775 (goto-char last)
2776 ;; Find an beginning-of-stmt that's not in a comment
2777 (while (and (re-search-forward regexp next t 1)
2778 (nth 7 (syntax-ppss)))
2779 (goto-char (match-end 0)))
2780 (goto-char
2781 (if (match-data)
2782 (match-beginning 0)
2783 last))
2784 (beginning-of-line)
2785 ;; If we didn't move, try again
2786 (when (= here (point))
2787 (sql-beginning-of-statement (* 2 (cl-signum arg))))))
2789 (defun sql-end-of-statement (arg)
2790 "Move to the end of the current SQL statement."
2791 (interactive "p")
2792 (let ((term (sql-get-product-feature sql-product :terminator))
2793 (re-search (if (> 0 arg) 're-search-backward 're-search-forward))
2794 (here (point))
2795 (n 0))
2796 (when (consp term)
2797 (setq term (car term)))
2798 ;; Iterate until we've moved the desired number of stmt ends
2799 (while (not (= (cl-signum arg) 0))
2800 ;; if we're looking at the terminator, jump by 2
2801 (if (or (and (> 0 arg) (looking-back term nil))
2802 (and (< 0 arg) (looking-at term)))
2803 (setq n 2)
2804 (setq n 1))
2805 ;; If we found another end-of-stmt
2806 (if (not (apply re-search term nil t n nil))
2807 (setq arg 0)
2808 ;; count it if we're not in a comment
2809 (unless (nth 7 (syntax-ppss))
2810 (setq arg (- arg (cl-signum arg))))))
2811 (goto-char (if (match-data)
2812 (match-end 0)
2813 here))))
2815 ;;; Small functions
2817 (defun sql-magic-go (arg)
2818 "Insert \"o\" and call `comint-send-input'.
2819 `sql-electric-stuff' must be the symbol `go'."
2820 (interactive "P")
2821 (self-insert-command (prefix-numeric-value arg))
2822 (if (and (equal sql-electric-stuff 'go)
2823 (save-excursion
2824 (comint-bol nil)
2825 (looking-at "go\\b")))
2826 (comint-send-input)))
2827 (put 'sql-magic-go 'delete-selection t)
2829 (defun sql-magic-semicolon (arg)
2830 "Insert semicolon and call `comint-send-input'.
2831 `sql-electric-stuff' must be the symbol `semicolon'."
2832 (interactive "P")
2833 (self-insert-command (prefix-numeric-value arg))
2834 (if (equal sql-electric-stuff 'semicolon)
2835 (comint-send-input)))
2836 (put 'sql-magic-semicolon 'delete-selection t)
2838 (defun sql-accumulate-and-indent ()
2839 "Continue SQL statement on the next line."
2840 (interactive)
2841 (if (fboundp 'comint-accumulate)
2842 (comint-accumulate)
2843 (newline))
2844 (indent-according-to-mode))
2846 (defun sql-help-list-products (indent freep)
2847 "Generate listing of products available for use under SQLi.
2849 List products with :free-software attribute set to FREEP. Indent
2850 each line with INDENT."
2852 (let (sqli-func doc)
2853 (setq doc "")
2854 (dolist (p sql-product-alist)
2855 (setq sqli-func (intern (concat "sql-" (symbol-name (car p)))))
2857 (if (and (fboundp sqli-func)
2858 (eq (sql-get-product-feature (car p) :free-software) freep))
2859 (setq doc
2860 (concat doc
2861 indent
2862 (or (sql-get-product-feature (car p) :name)
2863 (symbol-name (car p)))
2864 ":\t"
2865 "\\["
2866 (symbol-name sqli-func)
2867 "]\n"))))
2868 doc))
2870 (defun sql-help ()
2871 "Show short help for the SQL modes."
2872 (interactive)
2873 (describe-function 'sql-help))
2874 (put 'sql-help 'function-documentation '(sql--make-help-docstring))
2876 (defvar sql--help-docstring
2877 "Show short help for the SQL modes.
2878 Use an entry function to open an interactive SQL buffer. This buffer is
2879 usually named `*SQL*'. The name of the major mode is SQLi.
2881 Use the following commands to start a specific SQL interpreter:
2883 \\\\FREE
2885 Other non-free SQL implementations are also supported:
2887 \\\\NONFREE
2889 But we urge you to choose a free implementation instead of these.
2891 You can also use \\[sql-product-interactive] to invoke the
2892 interpreter for the current `sql-product'.
2894 Once you have the SQLi buffer, you can enter SQL statements in the
2895 buffer. The output generated is appended to the buffer and a new prompt
2896 is generated. See the In/Out menu in the SQLi buffer for some functions
2897 that help you navigate through the buffer, the input history, etc.
2899 If you have a really complex SQL statement or if you are writing a
2900 procedure, you can do this in a separate buffer. Put the new buffer in
2901 `sql-mode' by calling \\[sql-mode]. The name of this buffer can be
2902 anything. The name of the major mode is SQL.
2904 In this SQL buffer (SQL mode), you can send the region or the entire
2905 buffer to the interactive SQL buffer (SQLi mode). The results are
2906 appended to the SQLi buffer without disturbing your SQL buffer.")
2908 (defun sql--make-help-docstring ()
2909 "Return a docstring for `sql-help' listing loaded SQL products."
2910 (let ((doc sql--help-docstring))
2911 ;; Insert FREE software list
2912 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]FREE\\s-*$" doc 0)
2913 (setq doc (replace-match (sql-help-list-products (match-string 1 doc) t)
2914 t t doc 0)))
2915 ;; Insert non-FREE software list
2916 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]NONFREE\\s-*$" doc 0)
2917 (setq doc (replace-match (sql-help-list-products (match-string 1 doc) nil)
2918 t t doc 0)))
2919 doc))
2921 (defun sql-default-value (var)
2922 "Fetch the value of a variable.
2924 If the current buffer is in `sql-interactive-mode', then fetch
2925 the global value, otherwise use the buffer local value."
2926 (if (derived-mode-p 'sql-interactive-mode)
2927 (default-value var)
2928 (buffer-local-value var (current-buffer))))
2930 (defun sql-get-login-ext (symbol prompt history-var plist)
2931 "Prompt user with extended login parameters.
2933 The global value of SYMBOL is the last value and the global value
2934 of the SYMBOL is set based on the user's input.
2936 If PLIST is nil, then the user is simply prompted for a string
2937 value.
2939 The property `:default' specifies the default value. If the
2940 `:number' property is non-nil then ask for a number.
2942 The `:file' property prompts for a file name that must match the
2943 regexp pattern specified in its value.
2945 The `:completion' property prompts for a string specified by its
2946 value. (The property value is used as the PREDICATE argument to
2947 `completing-read'.)"
2948 (set-default
2949 symbol
2950 (let* ((default (plist-get plist :default))
2951 (last-value (sql-default-value symbol))
2952 (prompt-def
2953 (if default
2954 (if (string-match "\\(\\):[ \t]*\\'" prompt)
2955 (replace-match (format " (default \"%s\")" default) t t prompt 1)
2956 (replace-regexp-in-string "[ \t]*\\'"
2957 (format " (default \"%s\") " default)
2958 prompt t t))
2959 prompt))
2960 (use-dialog-box nil))
2961 (cond
2962 ((plist-member plist :file)
2963 (let ((file-name
2964 (read-file-name prompt
2965 (file-name-directory last-value)
2966 default
2967 (plist-get plist :must-match)
2968 (file-name-nondirectory last-value)
2969 (when (plist-get plist :file)
2970 `(lambda (f)
2971 (if (not (file-regular-p f))
2973 (string-match
2974 (concat "\\<" ,(plist-get plist :file) "\\>")
2975 (file-name-nondirectory f))))))))
2976 (if (string= file-name "")
2978 (expand-file-name file-name))))
2980 ((plist-member plist :completion)
2981 (completing-read prompt-def
2982 (plist-get plist :completion)
2984 (plist-get plist :must-match)
2985 last-value
2986 history-var
2987 default))
2989 ((plist-get plist :number)
2990 (read-number prompt (or default last-value 0)))
2993 (read-string prompt-def last-value history-var default))))))
2995 (defun sql-get-login (&rest what)
2996 "Get username, password and database from the user.
2998 The variables `sql-user', `sql-password', `sql-server', and
2999 `sql-database' can be customized. They are used as the default values.
3000 Usernames, servers and databases are stored in `sql-user-history',
3001 `sql-server-history' and `database-history'. Passwords are not stored
3002 in a history.
3004 Parameter WHAT is a list of tokens passed as arguments in the
3005 function call. The function asks for the username if WHAT
3006 contains the symbol `user', for the password if it contains the
3007 symbol `password', for the server if it contains the symbol
3008 `server', and for the database if it contains the symbol
3009 `database'. The members of WHAT are processed in the order in
3010 which they are provided.
3012 Each token may also be a list with the token in the car and a
3013 plist of options as the cdr. The following properties are
3014 supported:
3016 :file <filename-regexp>
3017 :completion <list-of-strings-or-function>
3018 :default <default-value>
3019 :number t
3021 In order to ask the user for username, password and database, call the
3022 function like this: (sql-get-login \\='user \\='password \\='database)."
3023 (dolist (w what)
3024 (let ((plist (cdr-safe w)))
3025 (pcase (or (car-safe w) w)
3026 (`user
3027 (sql-get-login-ext 'sql-user "User: " 'sql-user-history plist))
3029 (`password
3030 (setq-default sql-password
3031 (read-passwd "Password: " nil (sql-default-value 'sql-password))))
3033 (`server
3034 (sql-get-login-ext 'sql-server "Server: " 'sql-server-history plist))
3036 (`database
3037 (sql-get-login-ext 'sql-database "Database: "
3038 'sql-database-history plist))
3040 (`port
3041 (sql-get-login-ext 'sql-port "Port: "
3042 nil (append '(:number t) plist)))))))
3044 (defun sql-find-sqli-buffer (&optional product connection)
3045 "Return the name of the current default SQLi buffer or nil.
3046 In order to qualify, the SQLi buffer must be alive, be in
3047 `sql-interactive-mode' and have a process."
3048 (let ((buf sql-buffer)
3049 (prod (or product sql-product)))
3051 ;; Current sql-buffer, if there is one.
3052 (and (sql-buffer-live-p buf prod connection)
3053 buf)
3054 ;; Global sql-buffer
3055 (and (setq buf (default-value 'sql-buffer))
3056 (sql-buffer-live-p buf prod connection)
3057 buf)
3058 ;; Look thru each buffer
3059 (car (apply #'append
3060 (mapcar (lambda (b)
3061 (and (sql-buffer-live-p b prod connection)
3062 (list (buffer-name b))))
3063 (buffer-list)))))))
3065 (defun sql-set-sqli-buffer-generally ()
3066 "Set SQLi buffer for all SQL buffers that have none.
3067 This function checks all SQL buffers for their SQLi buffer. If their
3068 SQLi buffer is nonexistent or has no process, it is set to the current
3069 default SQLi buffer. The current default SQLi buffer is determined
3070 using `sql-find-sqli-buffer'. If `sql-buffer' is set,
3071 `sql-set-sqli-hook' is run."
3072 (interactive)
3073 (save-excursion
3074 (let ((buflist (buffer-list))
3075 (default-buffer (sql-find-sqli-buffer)))
3076 (setq-default sql-buffer default-buffer)
3077 (while (not (null buflist))
3078 (let ((candidate (car buflist)))
3079 (set-buffer candidate)
3080 (if (and (derived-mode-p 'sql-mode)
3081 (not (sql-buffer-live-p sql-buffer)))
3082 (progn
3083 (setq sql-buffer default-buffer)
3084 (when default-buffer
3085 (run-hooks 'sql-set-sqli-hook)))))
3086 (setq buflist (cdr buflist))))))
3088 (defun sql-set-sqli-buffer ()
3089 "Set the SQLi buffer SQL strings are sent to.
3091 Call this function in a SQL buffer in order to set the SQLi buffer SQL
3092 strings are sent to. Calling this function sets `sql-buffer' and runs
3093 `sql-set-sqli-hook'.
3095 If you call it from a SQL buffer, this sets the local copy of
3096 `sql-buffer'.
3098 If you call it from anywhere else, it sets the global copy of
3099 `sql-buffer'."
3100 (interactive)
3101 (let ((default-buffer (sql-find-sqli-buffer)))
3102 (if (null default-buffer)
3103 (sql-product-interactive)
3104 (let ((new-buffer (read-buffer "New SQLi buffer: " default-buffer t)))
3105 (if (null (sql-buffer-live-p new-buffer))
3106 (user-error "Buffer %s is not a working SQLi buffer" new-buffer)
3107 (when new-buffer
3108 (setq sql-buffer new-buffer)
3109 (run-hooks 'sql-set-sqli-hook)))))))
3111 (defun sql-show-sqli-buffer ()
3112 "Display the current SQLi buffer.
3114 This is the buffer SQL strings are sent to.
3115 It is stored in the variable `sql-buffer'.
3117 See also `sql-help' on how to create such a buffer."
3118 (interactive)
3119 (unless (and sql-buffer (buffer-live-p (get-buffer sql-buffer))
3120 (get-buffer-process sql-buffer))
3121 (sql-set-sqli-buffer))
3122 (display-buffer sql-buffer))
3124 (defun sql-make-alternate-buffer-name ()
3125 "Return a string that can be used to rename a SQLi buffer.
3126 This is used to set `sql-alternate-buffer-name' within
3127 `sql-interactive-mode'.
3129 If the session was started with `sql-connect' then the alternate
3130 name would be the name of the connection.
3132 Otherwise, it uses the parameters identified by the :sqlilogin
3133 parameter.
3135 If all else fails, the alternate name would be the user and
3136 server/database name."
3138 (let ((name ""))
3140 ;; Build a name using the :sqli-login setting
3141 (setq name
3142 (apply #'concat
3143 (cdr
3144 (apply #'append nil
3145 (sql-for-each-login
3146 (sql-get-product-feature sql-product :sqli-login)
3147 (lambda (token plist)
3148 (pcase token
3149 (`user
3150 (unless (string= "" sql-user)
3151 (list "/" sql-user)))
3152 (`port
3153 (unless (or (not (numberp sql-port))
3154 (= 0 sql-port))
3155 (list ":" (number-to-string sql-port))))
3156 (`server
3157 (unless (string= "" sql-server)
3158 (list "."
3159 (if (plist-member plist :file)
3160 (file-name-nondirectory sql-server)
3161 sql-server))))
3162 (`database
3163 (unless (string= "" sql-database)
3164 (list "@"
3165 (if (plist-member plist :file)
3166 (file-name-nondirectory sql-database)
3167 sql-database))))
3169 ;; (`password nil)
3170 (_ nil))))))))
3172 ;; If there's a connection, use it and the name thus far
3173 (if sql-connection
3174 (format "<%s>%s" sql-connection (or name ""))
3176 ;; If there is no name, try to create something meaningful
3177 (if (string= "" (or name ""))
3178 (concat
3179 (if (string= "" sql-user)
3180 (if (string= "" (user-login-name))
3182 (concat (user-login-name) "/"))
3183 (concat sql-user "/"))
3184 (if (string= "" sql-database)
3185 (if (string= "" sql-server)
3186 (system-name)
3187 sql-server)
3188 sql-database))
3190 ;; Use the name we've got
3191 name))))
3193 (defun sql-rename-buffer (&optional new-name)
3194 "Rename a SQL interactive buffer.
3196 Prompts for the new name if command is preceded by
3197 \\[universal-argument]. If no buffer name is provided, then the
3198 `sql-alternate-buffer-name' is used.
3200 The actual buffer name set will be \"*SQL: NEW-NAME*\". If
3201 NEW-NAME is empty, then the buffer name will be \"*SQL*\"."
3202 (interactive "P")
3204 (if (not (derived-mode-p 'sql-interactive-mode))
3205 (user-error "Current buffer is not a SQL interactive buffer")
3207 (setq sql-alternate-buffer-name
3208 (cond
3209 ((stringp new-name) new-name)
3210 ((consp new-name)
3211 (read-string "Buffer name (\"*SQL: XXX*\"; enter `XXX'): "
3212 sql-alternate-buffer-name))
3213 (t sql-alternate-buffer-name)))
3215 (setq sql-alternate-buffer-name (substring-no-properties sql-alternate-buffer-name))
3216 (rename-buffer (if (string= "" sql-alternate-buffer-name)
3217 "*SQL*"
3218 (format "*SQL: %s*" sql-alternate-buffer-name))
3219 t)))
3221 (defun sql-copy-column ()
3222 "Copy current column to the end of buffer.
3223 Inserts SELECT or commas if appropriate."
3224 (interactive)
3225 (let ((column))
3226 (save-excursion
3227 (setq column (buffer-substring-no-properties
3228 (progn (forward-char 1) (backward-sexp 1) (point))
3229 (progn (forward-sexp 1) (point))))
3230 (goto-char (point-max))
3231 (let ((bol (comint-line-beginning-position)))
3232 (cond
3233 ;; if empty command line, insert SELECT
3234 ((= bol (point))
3235 (insert "SELECT "))
3236 ;; else if appending to INTO .* (, SELECT or ORDER BY, insert a comma
3237 ((save-excursion
3238 (re-search-backward "\\b\\(\\(into\\s-+\\S-+\\s-+(\\)\\|select\\|order by\\) .+"
3239 bol t))
3240 (insert ", "))
3241 ;; else insert a space
3243 (if (eq (preceding-char) ?\s)
3245 (insert " ")))))
3246 ;; in any case, insert the column
3247 (insert column)
3248 (message "%s" column))))
3250 ;; On Windows, SQL*Plus for Oracle turns on full buffering for stdout
3251 ;; if it is not attached to a character device; therefore placeholder
3252 ;; replacement by SQL*Plus is fully buffered. The workaround lets
3253 ;; Emacs query for the placeholders.
3255 (defvar sql-placeholder-history nil
3256 "History of placeholder values used.")
3258 (defun sql-placeholders-filter (string)
3259 "Replace placeholders in STRING.
3260 Placeholders are words starting with an ampersand like &this."
3262 (when sql-oracle-scan-on
3263 (while (string-match "&?&\\(\\(?:\\sw\\|\\s_\\)+\\)[.]?" string)
3264 (setq string (replace-match
3265 (read-from-minibuffer
3266 (format "Enter value for %s: " (match-string 1 string))
3267 nil nil nil 'sql-placeholder-history)
3268 t t string))))
3269 string)
3271 ;; Using DB2 interactively, newlines must be escaped with " \".
3272 ;; The space before the backslash is relevant.
3274 (defun sql-escape-newlines-filter (string)
3275 "Escape newlines in STRING.
3276 Every newline in STRING will be preceded with a space and a backslash."
3277 (if (not sql-db2-escape-newlines)
3278 string
3279 (let ((result "") (start 0) mb me)
3280 (while (string-match "\n" string start)
3281 (setq mb (match-beginning 0)
3282 me (match-end 0)
3283 result (concat result
3284 (substring string start mb)
3285 (if (and (> mb 1)
3286 (string-equal " \\" (substring string (- mb 2) mb)))
3287 "" " \\\n"))
3288 start me))
3289 (concat result (substring string start)))))
3293 ;;; Input sender for SQLi buffers
3295 (defvar sql-output-newline-count 0
3296 "Number of newlines in the input string.
3298 Allows the suppression of continuation prompts.")
3300 (defun sql-input-sender (proc string)
3301 "Send STRING to PROC after applying filters."
3303 (let* ((product (buffer-local-value 'sql-product (process-buffer proc)))
3304 (filter (sql-get-product-feature product :input-filter)))
3306 ;; Apply filter(s)
3307 (cond
3308 ((not filter)
3309 nil)
3310 ((functionp filter)
3311 (setq string (funcall filter string)))
3312 ((listp filter)
3313 (mapc (lambda (f) (setq string (funcall f string))) filter))
3314 (t nil))
3316 ;; Count how many newlines in the string
3317 (setq sql-output-newline-count
3318 (apply #'+ (mapcar (lambda (ch)
3319 (if (eq ch ?\n) 1 0)) string)))
3321 ;; Send the string
3322 (comint-simple-send proc string)))
3324 ;;; Strip out continuation prompts
3326 (defvar sql-preoutput-hold nil)
3328 (defun sql-starts-with-prompt-re ()
3329 "Anchor the prompt expression at the beginning of the output line.
3330 Remove the start of line regexp."
3331 (concat "\\`" comint-prompt-regexp))
3333 (defun sql-ends-with-prompt-re ()
3334 "Anchor the prompt expression at the end of the output line.
3335 Match a SQL prompt or a password prompt."
3336 (concat "\\(?:\\(?:" sql-prompt-regexp "\\)\\|"
3337 "\\(?:" comint-password-prompt-regexp "\\)\\)\\'"))
3339 (defun sql-interactive-remove-continuation-prompt (oline)
3340 "Strip out continuation prompts out of the OLINE.
3342 Added to the `comint-preoutput-filter-functions' hook in a SQL
3343 interactive buffer. If `sql-output-newline-count' is greater than
3344 zero, then an output line matching the continuation prompt is filtered
3345 out. If the count is zero, then a newline is inserted into the output
3346 to force the output from the query to appear on a new line.
3348 The complication to this filter is that the continuation prompts
3349 may arrive in multiple chunks. If they do, then the function
3350 saves any unfiltered output in a buffer and prepends that buffer
3351 to the next chunk to properly match the broken-up prompt.
3353 If the filter gets confused, it should reset and stop filtering
3354 to avoid deleting non-prompt output."
3356 ;; continue gathering lines of text iff
3357 ;; + we know what a prompt looks like, and
3358 ;; + there is held text, or
3359 ;; + there are continuation prompt yet to come, or
3360 ;; + not just a prompt string
3361 (when (and comint-prompt-regexp
3362 (or (> (length (or sql-preoutput-hold "")) 0)
3363 (> (or sql-output-newline-count 0) 0)
3364 (not (or (string-match sql-prompt-regexp oline)
3365 (string-match sql-prompt-cont-regexp oline)))))
3367 (save-match-data
3368 (let (prompt-found last-nl)
3370 ;; Add this text to what's left from the last pass
3371 (setq oline (concat sql-preoutput-hold oline)
3372 sql-preoutput-hold "")
3374 ;; If we are looking for multiple prompts
3375 (when (and (integerp sql-output-newline-count)
3376 (>= sql-output-newline-count 1))
3377 ;; Loop thru each starting prompt and remove it
3378 (let ((start-re (sql-starts-with-prompt-re)))
3379 (while (and (not (string= oline ""))
3380 (> sql-output-newline-count 0)
3381 (string-match start-re oline))
3382 (setq oline (replace-match "" nil nil oline)
3383 sql-output-newline-count (1- sql-output-newline-count)
3384 prompt-found t)))
3386 ;; If we've found all the expected prompts, stop looking
3387 (if (= sql-output-newline-count 0)
3388 (setq sql-output-newline-count nil
3389 oline (concat "\n" oline))
3391 ;; Still more possible prompts, leave them for the next pass
3392 (setq sql-preoutput-hold oline
3393 oline "")))
3395 ;; If no prompts were found, stop looking
3396 (unless prompt-found
3397 (setq sql-output-newline-count nil
3398 oline (concat oline sql-preoutput-hold)
3399 sql-preoutput-hold ""))
3401 ;; Break up output by physical lines if we haven't hit the final prompt
3402 (let ((end-re (sql-ends-with-prompt-re)))
3403 (unless (and (not (string= oline ""))
3404 (string-match end-re oline)
3405 (>= (match-end 0) (length oline)))
3406 ;; Find everything upto the last nl
3407 (setq last-nl 0)
3408 (while (string-match "\n" oline last-nl)
3409 (setq last-nl (match-end 0)))
3410 ;; Hold after the last nl, return upto last nl
3411 (setq sql-preoutput-hold (concat (substring oline last-nl)
3412 sql-preoutput-hold)
3413 oline (substring oline 0 last-nl)))))))
3414 oline)
3416 ;;; Sending the region to the SQLi buffer.
3418 (defun sql-send-string (str)
3419 "Send the string STR to the SQL process."
3420 (interactive "sSQL Text: ")
3422 (let ((comint-input-sender-no-newline nil)
3423 (s (replace-regexp-in-string "[[:space:]\n\r]+\\'" "" str)))
3424 (if (sql-buffer-live-p sql-buffer)
3425 (progn
3426 ;; Ignore the hoping around...
3427 (save-excursion
3428 ;; Set product context
3429 (with-current-buffer sql-buffer
3430 ;; Send the string (trim the trailing whitespace)
3431 (sql-input-sender (get-buffer-process sql-buffer) s)
3433 ;; Send a command terminator if we must
3434 (if sql-send-terminator
3435 (sql-send-magic-terminator sql-buffer s sql-send-terminator))
3437 (message "Sent string to buffer %s" sql-buffer)))
3439 ;; Display the sql buffer
3440 (if sql-pop-to-buffer-after-send-region
3441 (pop-to-buffer sql-buffer)
3442 (display-buffer sql-buffer)))
3444 ;; We don't have no stinkin' sql
3445 (user-error "No SQL process started"))))
3447 (defun sql-send-region (start end)
3448 "Send a region to the SQL process."
3449 (interactive "r")
3450 (sql-send-string (buffer-substring-no-properties start end)))
3452 (defun sql-send-paragraph ()
3453 "Send the current paragraph to the SQL process."
3454 (interactive)
3455 (let ((start (save-excursion
3456 (backward-paragraph)
3457 (point)))
3458 (end (save-excursion
3459 (forward-paragraph)
3460 (point))))
3461 (sql-send-region start end)))
3463 (defun sql-send-buffer ()
3464 "Send the buffer contents to the SQL process."
3465 (interactive)
3466 (sql-send-region (point-min) (point-max)))
3468 (defun sql-send-line-and-next ()
3469 "Send the current line to the SQL process and go to the next line."
3470 (interactive)
3471 (sql-send-region (line-beginning-position 1) (line-beginning-position 2))
3472 (beginning-of-line 2)
3473 (while (forward-comment 1))) ; skip all comments and whitespace
3475 (defun sql-send-magic-terminator (buf str terminator)
3476 "Send TERMINATOR to buffer BUF if its not present in STR."
3477 (let (comint-input-sender-no-newline pat term)
3478 ;; If flag is merely on(t), get product-specific terminator
3479 (if (eq terminator t)
3480 (setq terminator (sql-get-product-feature sql-product :terminator)))
3482 ;; If there is no terminator specified, use default ";"
3483 (unless terminator
3484 (setq terminator ";"))
3486 ;; Parse the setting into the pattern and the terminator string
3487 (cond ((stringp terminator)
3488 (setq pat (regexp-quote terminator)
3489 term terminator))
3490 ((consp terminator)
3491 (setq pat (car terminator)
3492 term (cdr terminator)))
3494 nil))
3496 ;; Check to see if the pattern is present in the str already sent
3497 (unless (and pat term
3498 (string-match (concat pat "\\'") str))
3499 (comint-simple-send (get-buffer-process buf) term)
3500 (setq sql-output-newline-count
3501 (if sql-output-newline-count
3502 (1+ sql-output-newline-count)
3503 1)))))
3505 (defun sql-remove-tabs-filter (str)
3506 "Replace tab characters with spaces."
3507 (replace-regexp-in-string "\t" " " str nil t))
3509 (defun sql-toggle-pop-to-buffer-after-send-region (&optional value)
3510 "Toggle `sql-pop-to-buffer-after-send-region'.
3512 If given the optional parameter VALUE, sets
3513 `sql-toggle-pop-to-buffer-after-send-region' to VALUE."
3514 (interactive "P")
3515 (if value
3516 (setq sql-pop-to-buffer-after-send-region value)
3517 (setq sql-pop-to-buffer-after-send-region
3518 (null sql-pop-to-buffer-after-send-region))))
3522 ;;; Redirect output functions
3524 (defvar sql-debug-redirect nil
3525 "If non-nil, display messages related to the use of redirection.")
3527 (defun sql-str-literal (s)
3528 (concat "'" (replace-regexp-in-string "[']" "''" s) "'"))
3530 (defun sql-redirect (sqlbuf command &optional outbuf save-prior)
3531 "Execute the SQL command and send output to OUTBUF.
3533 SQLBUF must be an active SQL interactive buffer. OUTBUF may be
3534 an existing buffer, or the name of a non-existing buffer. If
3535 omitted the output is sent to a temporary buffer which will be
3536 killed after the command completes. COMMAND should be a string
3537 of commands accepted by the SQLi program. COMMAND may also be a
3538 list of SQLi command strings."
3540 (let* ((visible (and outbuf
3541 (not (string= " " (substring outbuf 0 1))))))
3542 (when visible
3543 (message "Executing SQL command..."))
3544 (if (consp command)
3545 (mapc (lambda (c) (sql-redirect-one sqlbuf c outbuf save-prior))
3546 command)
3547 (sql-redirect-one sqlbuf command outbuf save-prior))
3548 (when visible
3549 (message "Executing SQL command...done"))))
3551 (defun sql-redirect-one (sqlbuf command outbuf save-prior)
3552 (when command
3553 (with-current-buffer sqlbuf
3554 (let ((buf (get-buffer-create (or outbuf " *SQL-Redirect*")))
3555 (proc (get-buffer-process (current-buffer)))
3556 (comint-prompt-regexp (sql-get-product-feature sql-product
3557 :prompt-regexp))
3558 (start nil))
3559 (with-current-buffer buf
3560 (setq-local view-no-disable-on-exit t)
3561 (read-only-mode -1)
3562 (unless save-prior
3563 (erase-buffer))
3564 (goto-char (point-max))
3565 (unless (zerop (buffer-size))
3566 (insert "\n"))
3567 (setq start (point)))
3569 (when sql-debug-redirect
3570 (message ">>SQL> %S" command))
3572 ;; Run the command
3573 (let ((inhibit-quit t)
3574 comint-preoutput-filter-functions)
3575 (with-local-quit
3576 (comint-redirect-send-command-to-process command buf proc nil t)
3577 (while (or quit-flag (null comint-redirect-completed))
3578 (accept-process-output nil 1)))
3580 (if quit-flag
3581 (comint-redirect-cleanup)
3582 ;; Clean up the output results
3583 (with-current-buffer buf
3584 ;; Remove trailing whitespace
3585 (goto-char (point-max))
3586 (when (looking-back "[ \t\f\n\r]*" start)
3587 (delete-region (match-beginning 0) (match-end 0)))
3588 ;; Remove echo if there was one
3589 (goto-char start)
3590 (when (looking-at (concat "^" (regexp-quote command) "[\\n]"))
3591 (delete-region (match-beginning 0) (match-end 0)))
3592 ;; Remove Ctrl-Ms
3593 (goto-char start)
3594 (while (re-search-forward "\r+$" nil t)
3595 (replace-match "" t t))
3596 (goto-char start))))))))
3598 (defun sql-redirect-value (sqlbuf command regexp &optional regexp-groups)
3599 "Execute the SQL command and return part of result.
3601 SQLBUF must be an active SQL interactive buffer. COMMAND should
3602 be a string of commands accepted by the SQLi program. From the
3603 output, the REGEXP is repeatedly matched and the list of
3604 REGEXP-GROUPS submatches is returned. This behaves much like
3605 \\[comint-redirect-results-list-from-process] but instead of
3606 returning a single submatch it returns a list of each submatch
3607 for each match."
3609 (let ((outbuf " *SQL-Redirect-values*")
3610 (results nil))
3611 (sql-redirect sqlbuf command outbuf nil)
3612 (with-current-buffer outbuf
3613 (while (re-search-forward regexp nil t)
3614 (push
3615 (cond
3616 ;; no groups-return all of them
3617 ((null regexp-groups)
3618 (let ((i (/ (length (match-data)) 2))
3619 (r nil))
3620 (while (> i 0)
3621 (setq i (1- i))
3622 (push (match-string i) r))
3624 ;; one group specified
3625 ((numberp regexp-groups)
3626 (match-string regexp-groups))
3627 ;; list of numbers; return the specified matches only
3628 ((consp regexp-groups)
3629 (mapcar (lambda (c)
3630 (cond
3631 ((numberp c) (match-string c))
3632 ((stringp c) (match-substitute-replacement c))
3633 (t (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s" c))))
3634 regexp-groups))
3635 ;; String is specified; return replacement string
3636 ((stringp regexp-groups)
3637 (match-substitute-replacement regexp-groups))
3639 (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s"
3640 regexp-groups)))
3641 results)))
3643 (when sql-debug-redirect
3644 (message ">>SQL> = %S" (reverse results)))
3646 (nreverse results)))
3648 (defun sql-execute (sqlbuf outbuf command enhanced arg)
3649 "Execute a command in a SQL interactive buffer and capture the output.
3651 The commands are run in SQLBUF and the output saved in OUTBUF.
3652 COMMAND must be a string, a function or a list of such elements.
3653 Functions are called with SQLBUF, OUTBUF and ARG as parameters;
3654 strings are formatted with ARG and executed.
3656 If the results are empty the OUTBUF is deleted, otherwise the
3657 buffer is popped into a view window."
3658 (mapc
3659 (lambda (c)
3660 (cond
3661 ((stringp c)
3662 (sql-redirect sqlbuf (if arg (format c arg) c) outbuf) t)
3663 ((functionp c)
3664 (apply c sqlbuf outbuf enhanced arg nil))
3665 (t (error "Unknown sql-execute item %s" c))))
3666 (if (consp command) command (cons command nil)))
3668 (setq outbuf (get-buffer outbuf))
3669 (if (zerop (buffer-size outbuf))
3670 (kill-buffer outbuf)
3671 (let ((one-win (eq (selected-window)
3672 (get-lru-window))))
3673 (with-current-buffer outbuf
3674 (set-buffer-modified-p nil)
3675 (setq-local revert-buffer-function
3676 (lambda (_ignore-auto _noconfirm)
3677 (sql-execute sqlbuf (buffer-name outbuf)
3678 command enhanced arg)))
3679 (special-mode))
3680 (pop-to-buffer outbuf)
3681 (when one-win
3682 (shrink-window-if-larger-than-buffer)))))
3684 (defun sql-execute-feature (sqlbuf outbuf feature enhanced arg)
3685 "List objects or details in a separate display buffer."
3686 (let (command
3687 (product (buffer-local-value 'sql-product (get-buffer sqlbuf))))
3688 (setq command (sql-get-product-feature product feature))
3689 (unless command
3690 (error "%s does not support %s" product feature))
3691 (when (consp command)
3692 (setq command (if enhanced
3693 (cdr command)
3694 (car command))))
3695 (sql-execute sqlbuf outbuf command enhanced arg)))
3697 (defvar sql-completion-object nil
3698 "A list of database objects used for completion.
3700 The list is maintained in SQL interactive buffers.")
3702 (defvar sql-completion-column nil
3703 "A list of column names used for completion.
3705 The list is maintained in SQL interactive buffers.")
3707 (defun sql-build-completions-1 (schema completion-list feature)
3708 "Generate a list of objects in the database for use as completions."
3709 (let ((f (sql-get-product-feature sql-product feature)))
3710 (when f
3711 (set completion-list
3712 (let (cl)
3713 (dolist (e (append (symbol-value completion-list)
3714 (apply f (current-buffer) (cons schema nil)))
3716 (unless (member e cl) (setq cl (cons e cl))))
3717 (sort cl #'string<))))))
3719 (defun sql-build-completions (schema)
3720 "Generate a list of names in the database for use as completions."
3721 (sql-build-completions-1 schema 'sql-completion-object :completion-object)
3722 (sql-build-completions-1 schema 'sql-completion-column :completion-column))
3724 (defvar sql-completion-sqlbuf nil)
3726 (defun sql--completion-table (string pred action)
3727 (when sql-completion-sqlbuf
3728 (with-current-buffer sql-completion-sqlbuf
3729 (let ((schema (and (string-match "\\`\\(\\sw\\(:?\\sw\\|\\s_\\)*\\)[.]" string)
3730 (downcase (match-string 1 string)))))
3732 ;; If we haven't loaded any object name yet, load local schema
3733 (unless sql-completion-object
3734 (sql-build-completions nil))
3736 ;; If they want another schema, load it if we haven't yet
3737 (when schema
3738 (let ((schema-dot (concat schema "."))
3739 (schema-len (1+ (length schema)))
3740 (names sql-completion-object)
3741 has-schema)
3743 (while (and (not has-schema) names)
3744 (setq has-schema (and
3745 (>= (length (car names)) schema-len)
3746 (string= schema-dot
3747 (downcase (substring (car names)
3748 0 schema-len))))
3749 names (cdr names)))
3750 (unless has-schema
3751 (sql-build-completions schema)))))
3753 ;; Try to find the completion
3754 (complete-with-action action sql-completion-object string pred))))
3756 (defun sql-read-table-name (prompt)
3757 "Read the name of a database table."
3758 (let* ((tname
3759 (and (buffer-local-value 'sql-contains-names (current-buffer))
3760 (thing-at-point-looking-at
3761 (concat "\\_<\\sw\\(:?\\sw\\|\\s_\\)*"
3762 "\\(?:[.]+\\sw\\(?:\\sw\\|\\s_\\)*\\)*\\_>"))
3763 (buffer-substring-no-properties (match-beginning 0)
3764 (match-end 0))))
3765 (sql-completion-sqlbuf (sql-find-sqli-buffer))
3766 (product (when sql-completion-sqlbuf
3767 (with-current-buffer sql-completion-sqlbuf sql-product)))
3768 (completion-ignore-case t))
3770 (if product
3771 (if (sql-get-product-feature product :completion-object)
3772 (completing-read prompt #'sql--completion-table
3773 nil nil tname)
3774 (read-from-minibuffer prompt tname))
3775 (user-error "There is no active SQLi buffer"))))
3777 (defun sql-list-all (&optional enhanced)
3778 "List all database objects.
3779 With optional prefix argument ENHANCED, displays additional
3780 details or extends the listing to include other schemas objects."
3781 (interactive "P")
3782 (let ((sqlbuf (sql-find-sqli-buffer)))
3783 (unless sqlbuf
3784 (user-error "No SQL interactive buffer found"))
3785 (sql-execute-feature sqlbuf "*List All*" :list-all enhanced nil)
3786 (with-current-buffer sqlbuf
3787 ;; Contains the name of database objects
3788 (set (make-local-variable 'sql-contains-names) t)
3789 (set (make-local-variable 'sql-buffer) sqlbuf))))
3791 (defun sql-list-table (name &optional enhanced)
3792 "List the details of a database table named NAME.
3793 Displays the columns in the relation. With optional prefix argument
3794 ENHANCED, displays additional details about each column."
3795 (interactive
3796 (list (sql-read-table-name "Table name: ")
3797 current-prefix-arg))
3798 (let ((sqlbuf (sql-find-sqli-buffer)))
3799 (unless sqlbuf
3800 (user-error "No SQL interactive buffer found"))
3801 (unless name
3802 (user-error "No table name specified"))
3803 (sql-execute-feature sqlbuf (format "*List %s*" name)
3804 :list-table enhanced name)))
3807 ;;; SQL mode -- uses SQL interactive mode
3809 ;;;###autoload
3810 (define-derived-mode sql-mode prog-mode "SQL"
3811 "Major mode to edit SQL.
3813 You can send SQL statements to the SQLi buffer using
3814 \\[sql-send-region]. Such a buffer must exist before you can do this.
3815 See `sql-help' on how to create SQLi buffers.
3817 \\{sql-mode-map}
3818 Customization: Entry to this mode runs the `sql-mode-hook'.
3820 When you put a buffer in SQL mode, the buffer stores the last SQLi
3821 buffer created as its destination in the variable `sql-buffer'. This
3822 will be the buffer \\[sql-send-region] sends the region to. If this
3823 SQLi buffer is killed, \\[sql-send-region] is no longer able to
3824 determine where the strings should be sent to. You can set the
3825 value of `sql-buffer' using \\[sql-set-sqli-buffer].
3827 For information on how to create multiple SQLi buffers, see
3828 `sql-interactive-mode'.
3830 Note that SQL doesn't have an escape character unless you specify
3831 one. If you specify backslash as escape character in SQL, you
3832 must tell Emacs. Here's how to do that in your init file:
3834 \(add-hook \\='sql-mode-hook
3835 (lambda ()
3836 (modify-syntax-entry ?\\\\ \".\" sql-mode-syntax-table)))"
3837 :group 'SQL
3838 :abbrev-table sql-mode-abbrev-table
3840 (if sql-mode-menu
3841 (easy-menu-add sql-mode-menu)); XEmacs
3843 ;; (smie-setup sql-smie-grammar #'sql-smie-rules)
3844 (set (make-local-variable 'comment-start) "--")
3845 ;; Make each buffer in sql-mode remember the "current" SQLi buffer.
3846 (make-local-variable 'sql-buffer)
3847 ;; Add imenu support for sql-mode. Note that imenu-generic-expression
3848 ;; is buffer-local, so we don't need a local-variable for it. SQL is
3849 ;; case-insensitive, that's why we have to set imenu-case-fold-search.
3850 (setq imenu-generic-expression sql-imenu-generic-expression
3851 imenu-case-fold-search t)
3852 ;; Make `sql-send-paragraph' work on paragraphs that contain indented
3853 ;; lines.
3854 (set (make-local-variable 'paragraph-separate) "[\f]*$")
3855 (set (make-local-variable 'paragraph-start) "[\n\f]")
3856 ;; Abbrevs
3857 (setq-local abbrev-all-caps 1)
3858 ;; Contains the name of database objects
3859 (set (make-local-variable 'sql-contains-names) t)
3860 ;; Set syntax and font-face highlighting
3861 ;; Catch changes to sql-product and highlight accordingly
3862 (sql-set-product (or sql-product 'ansi)) ; Fixes bug#13591
3863 (add-hook 'hack-local-variables-hook 'sql-highlight-product t t))
3867 ;;; SQL interactive mode
3869 (put 'sql-interactive-mode 'mode-class 'special)
3870 (put 'sql-interactive-mode 'custom-mode-group 'SQL)
3872 (defun sql-interactive-mode ()
3873 "Major mode to use a SQL interpreter interactively.
3875 Do not call this function by yourself. The environment must be
3876 initialized by an entry function specific for the SQL interpreter.
3877 See `sql-help' for a list of available entry functions.
3879 \\[comint-send-input] after the end of the process' output sends the
3880 text from the end of process to the end of the current line.
3881 \\[comint-send-input] before end of process output copies the current
3882 line minus the prompt to the end of the buffer and sends it.
3883 \\[comint-copy-old-input] just copies the current line.
3884 Use \\[sql-accumulate-and-indent] to enter multi-line statements.
3886 If you want to make multiple SQL buffers, rename the `*SQL*' buffer
3887 using \\[rename-buffer] or \\[rename-uniquely] and start a new process.
3888 See `sql-help' for a list of available entry functions. The last buffer
3889 created by such an entry function is the current SQLi buffer. SQL
3890 buffers will send strings to the SQLi buffer current at the time of
3891 their creation. See `sql-mode' for details.
3893 Sample session using two connections:
3895 1. Create first SQLi buffer by calling an entry function.
3896 2. Rename buffer \"*SQL*\" to \"*Connection 1*\".
3897 3. Create a SQL buffer \"test1.sql\".
3898 4. Create second SQLi buffer by calling an entry function.
3899 5. Rename buffer \"*SQL*\" to \"*Connection 2*\".
3900 6. Create a SQL buffer \"test2.sql\".
3902 Now \\[sql-send-region] in buffer \"test1.sql\" will send the region to
3903 buffer \"*Connection 1*\", \\[sql-send-region] in buffer \"test2.sql\"
3904 will send the region to buffer \"*Connection 2*\".
3906 If you accidentally suspend your process, use \\[comint-continue-subjob]
3907 to continue it. On some operating systems, this will not work because
3908 the signals are not supported.
3910 \\{sql-interactive-mode-map}
3911 Customization: Entry to this mode runs the hooks on `comint-mode-hook'
3912 and `sql-interactive-mode-hook' (in that order). Before each input, the
3913 hooks on `comint-input-filter-functions' are run. After each SQL
3914 interpreter output, the hooks on `comint-output-filter-functions' are
3915 run.
3917 Variable `sql-input-ring-file-name' controls the initialization of the
3918 input ring history.
3920 Variables `comint-output-filter-functions', a hook, and
3921 `comint-scroll-to-bottom-on-input' and
3922 `comint-scroll-to-bottom-on-output' control whether input and output
3923 cause the window to scroll to the end of the buffer.
3925 If you want to make SQL buffers limited in length, add the function
3926 `comint-truncate-buffer' to `comint-output-filter-functions'.
3928 Here is an example for your init file. It keeps the SQLi buffer a
3929 certain length.
3931 \(add-hook \\='sql-interactive-mode-hook
3932 (function (lambda ()
3933 (setq comint-output-filter-functions \\='comint-truncate-buffer))))
3935 Here is another example. It will always put point back to the statement
3936 you entered, right above the output it created.
3938 \(setq comint-output-filter-functions
3939 (function (lambda (STR) (comint-show-output))))"
3940 (delay-mode-hooks (comint-mode))
3942 ;; Get the `sql-product' for this interactive session.
3943 (set (make-local-variable 'sql-product)
3944 (or sql-interactive-product
3945 sql-product))
3947 ;; Setup the mode.
3948 (setq major-mode 'sql-interactive-mode)
3949 (setq mode-name
3950 (concat "SQLi[" (or (sql-get-product-feature sql-product :name)
3951 (symbol-name sql-product)) "]"))
3952 (use-local-map sql-interactive-mode-map)
3953 (if sql-interactive-mode-menu
3954 (easy-menu-add sql-interactive-mode-menu)) ; XEmacs
3955 (set-syntax-table sql-mode-syntax-table)
3957 ;; Note that making KEYWORDS-ONLY nil will cause havoc if you try
3958 ;; SELECT 'x' FROM DUAL with SQL*Plus, because the title of the column
3959 ;; will have just one quote. Therefore syntactic highlighting is
3960 ;; disabled for interactive buffers. No imenu support.
3961 (sql-product-font-lock t nil)
3963 ;; Enable commenting and uncommenting of the region.
3964 (set (make-local-variable 'comment-start) "--")
3965 ;; Abbreviation table init and case-insensitive. It is not activated
3966 ;; by default.
3967 (setq local-abbrev-table sql-mode-abbrev-table)
3968 (setq abbrev-all-caps 1)
3969 ;; Exiting the process will call sql-stop.
3970 (set-process-sentinel (get-buffer-process (current-buffer)) 'sql-stop)
3971 ;; Save the connection and login params
3972 (set (make-local-variable 'sql-user) sql-user)
3973 (set (make-local-variable 'sql-database) sql-database)
3974 (set (make-local-variable 'sql-server) sql-server)
3975 (set (make-local-variable 'sql-port) sql-port)
3976 (set (make-local-variable 'sql-connection) sql-connection)
3977 (setq-default sql-connection nil)
3978 ;; Contains the name of database objects
3979 (set (make-local-variable 'sql-contains-names) t)
3980 ;; Keep track of existing object names
3981 (set (make-local-variable 'sql-completion-object) nil)
3982 (set (make-local-variable 'sql-completion-column) nil)
3983 ;; Create a useful name for renaming this buffer later.
3984 (set (make-local-variable 'sql-alternate-buffer-name)
3985 (sql-make-alternate-buffer-name))
3986 ;; User stuff. Initialize before the hook.
3987 (set (make-local-variable 'sql-prompt-regexp)
3988 (sql-get-product-feature sql-product :prompt-regexp))
3989 (set (make-local-variable 'sql-prompt-length)
3990 (sql-get-product-feature sql-product :prompt-length))
3991 (set (make-local-variable 'sql-prompt-cont-regexp)
3992 (sql-get-product-feature sql-product :prompt-cont-regexp))
3993 (make-local-variable 'sql-output-newline-count)
3994 (make-local-variable 'sql-preoutput-hold)
3995 (add-hook 'comint-preoutput-filter-functions
3996 'sql-interactive-remove-continuation-prompt nil t)
3997 (make-local-variable 'sql-input-ring-separator)
3998 (make-local-variable 'sql-input-ring-file-name)
3999 ;; Run the mode hook (along with comint's hooks).
4000 (run-mode-hooks 'sql-interactive-mode-hook)
4001 ;; Set comint based on user overrides.
4002 (setq comint-prompt-regexp
4003 (if sql-prompt-cont-regexp
4004 (concat "\\(" sql-prompt-regexp
4005 "\\|" sql-prompt-cont-regexp "\\)")
4006 sql-prompt-regexp))
4007 (setq left-margin sql-prompt-length)
4008 ;; Install input sender
4009 (set (make-local-variable 'comint-input-sender) 'sql-input-sender)
4010 ;; People wanting a different history file for each
4011 ;; buffer/process/client/whatever can change separator and file-name
4012 ;; on the sql-interactive-mode-hook.
4013 (let
4014 ((comint-input-ring-separator sql-input-ring-separator)
4015 (comint-input-ring-file-name sql-input-ring-file-name))
4016 (comint-read-input-ring t)))
4018 (defun sql-stop (process event)
4019 "Called when the SQL process is stopped.
4021 Writes the input history to a history file using
4022 `comint-write-input-ring' and inserts a short message in the SQL buffer.
4024 This function is a sentinel watching the SQL interpreter process.
4025 Sentinels will always get the two parameters PROCESS and EVENT."
4026 (with-current-buffer (process-buffer process)
4027 (let
4028 ((comint-input-ring-separator sql-input-ring-separator)
4029 (comint-input-ring-file-name sql-input-ring-file-name))
4030 (comint-write-input-ring))
4032 (if (not buffer-read-only)
4033 (insert (format "\nProcess %s %s\n" process event))
4034 (message "Process %s %s" process event))))
4038 ;;; Connection handling
4040 (defun sql-read-connection (prompt &optional initial default)
4041 "Read a connection name."
4042 (let ((completion-ignore-case t))
4043 (completing-read prompt
4044 (mapcar (lambda (c) (car c))
4045 sql-connection-alist)
4046 nil t initial 'sql-connection-history default)))
4048 ;;;###autoload
4049 (defun sql-connect (connection &optional buf-name)
4050 "Connect to an interactive session using CONNECTION settings.
4052 See `sql-connection-alist' to see how to define connections and
4053 their settings.
4055 The user will not be prompted for any login parameters if a value
4056 is specified in the connection settings."
4058 ;; Prompt for the connection from those defined in the alist
4059 (interactive
4060 (if sql-connection-alist
4061 (list (sql-read-connection "Connection: ")
4062 current-prefix-arg)
4063 (user-error "No SQL Connections defined")))
4065 ;; Are there connections defined
4066 (if sql-connection-alist
4067 ;; Was one selected
4068 (when connection
4069 ;; Get connection settings
4070 (let ((connect-set (cdr (assoc-string connection sql-connection-alist t))))
4071 ;; Settings are defined
4072 (if connect-set
4073 ;; Set the desired parameters
4074 (let (param-var login-params set-vars rem-vars)
4075 ;; Set the parameters and start the interactive session
4076 (dolist (vv connect-set)
4077 (let ((var (car vv))
4078 (val (cadr vv)))
4079 (set-default var (eval val))))
4080 (setq-default sql-connection connection)
4082 ;; :sqli-login params variable
4083 (setq param-var
4084 (sql-get-product-feature sql-product :sqli-login nil t))
4086 ;; :sqli-login params value
4087 (setq login-params (symbol-value param-var))
4089 ;; Params set in the connection
4090 (setq set-vars
4091 (mapcar
4092 (lambda (v)
4093 (pcase (car v)
4094 (`sql-user 'user)
4095 (`sql-password 'password)
4096 (`sql-server 'server)
4097 (`sql-database 'database)
4098 (`sql-port 'port)
4099 (s s)))
4100 connect-set))
4102 ;; the remaining params (w/o the connection params)
4103 (setq rem-vars
4104 (sql-for-each-login login-params
4105 (lambda (var vals)
4106 (unless (member var set-vars)
4107 (if vals (cons var vals) var)))))
4109 ;; Start the SQLi session with revised list of login parameters
4110 (eval `(let ((,param-var ',rem-vars))
4111 (sql-product-interactive
4112 ',sql-product
4113 ',(or buf-name (format "<%s>" connection))))))
4115 (user-error "SQL Connection <%s> does not exist" connection)
4116 nil)))
4118 (user-error "No SQL Connections defined")
4119 nil))
4121 (defun sql-save-connection (name)
4122 "Captures the connection information of the current SQLi session.
4124 The information is appended to `sql-connection-alist' and
4125 optionally is saved to the user's init file."
4127 (interactive "sNew connection name: ")
4129 (unless (derived-mode-p 'sql-interactive-mode)
4130 (user-error "Not in a SQL interactive mode!"))
4132 ;; Capture the buffer local settings
4133 (let* ((buf (current-buffer))
4134 (connection (buffer-local-value 'sql-connection buf))
4135 (product (buffer-local-value 'sql-product buf))
4136 (user (buffer-local-value 'sql-user buf))
4137 (database (buffer-local-value 'sql-database buf))
4138 (server (buffer-local-value 'sql-server buf))
4139 (port (buffer-local-value 'sql-port buf)))
4141 (if connection
4142 (message "This session was started by a connection; it's already been saved.")
4144 (let ((login (sql-get-product-feature product :sqli-login))
4145 (alist sql-connection-alist)
4146 connect)
4148 ;; Remove the existing connection if the user says so
4149 (when (and (assoc name alist)
4150 (yes-or-no-p (format "Replace connection definition <%s>? " name)))
4151 (setq alist (assq-delete-all name alist)))
4153 ;; Add the new connection if it doesn't exist
4154 (if (assoc name alist)
4155 (user-error "Connection <%s> already exists" name)
4156 (setq connect
4157 (cons name
4158 (sql-for-each-login
4159 `(product ,@login)
4160 (lambda (token _plist)
4161 (pcase token
4162 (`product `(sql-product ',product))
4163 (`user `(sql-user ,user))
4164 (`database `(sql-database ,database))
4165 (`server `(sql-server ,server))
4166 (`port `(sql-port ,port)))))))
4168 (setq alist (append alist (list connect)))
4170 ;; confirm whether we want to save the connections
4171 (if (yes-or-no-p "Save the connections for future sessions? ")
4172 (customize-save-variable 'sql-connection-alist alist)
4173 (customize-set-variable 'sql-connection-alist alist)))))))
4175 (defun sql-connection-menu-filter (tail)
4176 "Generate menu entries for using each connection."
4177 (append
4178 (mapcar
4179 (lambda (conn)
4180 (vector
4181 (format "Connection <%s>\t%s" (car conn)
4182 (let ((sql-user "") (sql-database "")
4183 (sql-server "") (sql-port 0))
4184 (eval `(let ,(cdr conn) (sql-make-alternate-buffer-name)))))
4185 (list 'sql-connect (car conn))
4187 sql-connection-alist)
4188 tail))
4192 ;;; Entry functions for different SQL interpreters.
4193 ;;;###autoload
4194 (defun sql-product-interactive (&optional product new-name)
4195 "Run PRODUCT interpreter as an inferior process.
4197 If buffer `*SQL*' exists but no process is running, make a new process.
4198 If buffer exists and a process is running, just switch to buffer `*SQL*'.
4200 To specify the SQL product, prefix the call with
4201 \\[universal-argument]. To set the buffer name as well, prefix
4202 the call to \\[sql-product-interactive] with
4203 \\[universal-argument] \\[universal-argument].
4205 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4206 (interactive "P")
4208 ;; Handle universal arguments if specified
4209 (when (not (or executing-kbd-macro noninteractive))
4210 (when (and (consp product)
4211 (not (cdr product))
4212 (numberp (car product)))
4213 (when (>= (prefix-numeric-value product) 16)
4214 (when (not new-name)
4215 (setq new-name '(4)))
4216 (setq product '(4)))))
4218 ;; Get the value of product that we need
4219 (setq product
4220 (cond
4221 ((= (prefix-numeric-value product) 4) ; C-u, prompt for product
4222 (sql-read-product "SQL product: " sql-product))
4223 ((and product ; Product specified
4224 (symbolp product)) product)
4225 (t sql-product))) ; Default to sql-product
4227 ;; If we have a product and it has a interactive mode
4228 (if product
4229 (when (sql-get-product-feature product :sqli-comint-func)
4230 ;; If no new name specified, try to pop to an active SQL
4231 ;; interactive for the same product
4232 (let ((buf (sql-find-sqli-buffer product sql-connection)))
4233 (if (and (not new-name) buf)
4234 (pop-to-buffer buf)
4236 ;; We have a new name or sql-buffer doesn't exist or match
4237 ;; Start by remembering where we start
4238 (let ((start-buffer (current-buffer))
4239 new-sqli-buffer rpt)
4241 ;; Get credentials.
4242 (apply #'sql-get-login
4243 (sql-get-product-feature product :sqli-login))
4245 ;; Connect to database.
4246 (setq rpt (make-progress-reporter "Login"))
4248 (let ((sql-user (default-value 'sql-user))
4249 (sql-password (default-value 'sql-password))
4250 (sql-server (default-value 'sql-server))
4251 (sql-database (default-value 'sql-database))
4252 (sql-port (default-value 'sql-port))
4253 (default-directory (or sql-default-directory
4254 default-directory)))
4255 (funcall (sql-get-product-feature product :sqli-comint-func)
4256 product
4257 (sql-get-product-feature product :sqli-options)
4258 (if (and new-name (string-prefix-p "SQL" new-name t))
4259 new-name
4260 (concat "SQL: " new-name))))
4262 ;; Set SQLi mode.
4263 (let ((sql-interactive-product product))
4264 (sql-interactive-mode))
4266 ;; Set the new buffer name
4267 (setq new-sqli-buffer (current-buffer))
4268 (set (make-local-variable 'sql-buffer)
4269 (buffer-name new-sqli-buffer))
4271 ;; Set `sql-buffer' in the start buffer
4272 (with-current-buffer start-buffer
4273 (when (derived-mode-p 'sql-mode)
4274 (setq sql-buffer (buffer-name new-sqli-buffer))
4275 (run-hooks 'sql-set-sqli-hook)))
4277 ;; Make sure the connection is complete
4278 ;; (Sometimes start up can be slow)
4279 ;; and call the login hook
4280 (let ((proc (get-buffer-process new-sqli-buffer))
4281 (secs sql-login-delay)
4282 (step 0.3))
4283 (while (and (memq (process-status proc) '(open run))
4284 (or (accept-process-output proc step)
4285 (<= 0.0 (setq secs (- secs step))))
4286 (progn (goto-char (point-max))
4287 (not (re-search-backward sql-prompt-regexp 0 t))))
4288 (progress-reporter-update rpt)))
4290 (goto-char (point-max))
4291 (when (re-search-backward sql-prompt-regexp nil t)
4292 (run-hooks 'sql-login-hook))
4294 ;; All done.
4295 (progress-reporter-done rpt)
4296 (pop-to-buffer new-sqli-buffer)
4297 (goto-char (point-max))
4298 (current-buffer)))))
4299 (user-error "No default SQL product defined. Set `sql-product'.")))
4301 (defun sql-comint (product params &optional buf-name)
4302 "Set up a comint buffer to run the SQL processor.
4304 PRODUCT is the SQL product. PARAMS is a list of strings which are
4305 passed as command line arguments. BUF-NAME is the name of the new
4306 buffer. If nil, a name is chosen for it."
4308 (let ((program (sql-get-product-feature product :sqli-program)))
4309 ;; Make sure we can find the program. `executable-find' does not
4310 ;; work for remote hosts; we suppress the check there.
4311 (unless (or (file-remote-p default-directory)
4312 (executable-find program))
4313 (error "Unable to locate SQL program `%s'" program))
4315 ;; Make sure buffer name is unique.
4316 ;; if not specified, try *SQL* then *SQL-product*, then *SQL-product1*, ...
4317 ;; otherwise, use *buf-name*
4318 (if buf-name
4319 (unless (string-match-p "\\`[*].*[*]\\'" buf-name)
4320 (setq buf-name (concat "*" buf-name "*")))
4321 (setq buf-name "*SQL*")
4322 (when (sql-buffer-live-p buf-name)
4323 (setq buf-name (format "*SQL-%s*" product)))
4324 (let ((i 1))
4325 (while (sql-buffer-live-p buf-name)
4326 (setq buf-name (format "*SQL-%s%d*" product i)
4327 i (1+ i)))))
4328 (set-text-properties 0 (length buf-name) nil buf-name)
4330 ;; Start the command interpreter in the buffer
4331 ;; PROC-NAME is BUF-NAME without enclosing asterisks
4332 (let ((proc-name (replace-regexp-in-string "\\`[*]\\(.*\\)[*]\\'" "\\1" buf-name)))
4333 (set-buffer
4334 (apply #'make-comint-in-buffer
4335 proc-name buf-name program nil params)))))
4337 ;;;###autoload
4338 (defun sql-oracle (&optional buffer)
4339 "Run sqlplus by Oracle as an inferior process.
4341 If buffer `*SQL*' exists but no process is running, make a new process.
4342 If buffer exists and a process is running, just switch to buffer
4343 `*SQL*'.
4345 Interpreter used comes from variable `sql-oracle-program'. Login uses
4346 the variables `sql-user', `sql-password', and `sql-database' as
4347 defaults, if set. Additional command line parameters can be stored in
4348 the list `sql-oracle-options'.
4350 The buffer is put in SQL interactive mode, giving commands for sending
4351 input. See `sql-interactive-mode'.
4353 To set the buffer name directly, use \\[universal-argument]
4354 before \\[sql-oracle]. Once session has started,
4355 \\[sql-rename-buffer] can be called separately to rename the
4356 buffer.
4358 To specify a coding system for converting non-ASCII characters
4359 in the input and output to the process, use \\[universal-coding-system-argument]
4360 before \\[sql-oracle]. You can also specify this with \\[set-buffer-process-coding-system]
4361 in the SQL buffer, after you start the process.
4362 The default comes from `process-coding-system-alist' and
4363 `default-process-coding-system'.
4365 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4366 (interactive "P")
4367 (sql-product-interactive 'oracle buffer))
4369 (defun sql-comint-oracle (product options &optional buf-name)
4370 "Create comint buffer and connect to Oracle."
4371 ;; Produce user/password@database construct. Password without user
4372 ;; is meaningless; database without user/password is meaningless,
4373 ;; because "@param" will ask sqlplus to interpret the script
4374 ;; "param".
4375 (let (parameter nlslang coding)
4376 (if (not (string= "" sql-user))
4377 (if (not (string= "" sql-password))
4378 (setq parameter (concat sql-user "/" sql-password))
4379 (setq parameter sql-user)))
4380 (if (and parameter (not (string= "" sql-database)))
4381 (setq parameter (concat parameter "@" sql-database)))
4382 ;; options must appear before the logon parameters
4383 (if parameter
4384 (setq parameter (append options (list parameter)))
4385 (setq parameter options))
4386 (sql-comint product parameter buf-name)
4387 ;; Set process coding system to agree with the interpreter
4388 (setq nlslang (or (getenv "NLS_LANG") "")
4389 coding (dolist (cs
4390 ;; Are we missing any common NLS character sets
4391 '(("US8PC437" . cp437)
4392 ("EL8PC737" . cp737)
4393 ("WE8PC850" . cp850)
4394 ("EE8PC852" . cp852)
4395 ("TR8PC857" . cp857)
4396 ("WE8PC858" . cp858)
4397 ("IS8PC861" . cp861)
4398 ("IW8PC1507" . cp862)
4399 ("N8PC865" . cp865)
4400 ("RU8PC866" . cp866)
4401 ("US7ASCII" . us-ascii)
4402 ("UTF8" . utf-8)
4403 ("AL32UTF8" . utf-8)
4404 ("AL16UTF16" . utf-16))
4405 (or coding 'utf-8))
4406 (when (string-match (format "\\.%s\\'" (car cs)) nlslang)
4407 (setq coding (cdr cs)))))
4408 (set-buffer-process-coding-system coding coding)))
4410 (defun sql-oracle-save-settings (sqlbuf)
4411 "Save most SQL*Plus settings so they may be reset by \\[sql-redirect]."
4412 ;; Note: does not capture the following settings:
4414 ;; APPINFO
4415 ;; BTITLE
4416 ;; COMPATIBILITY
4417 ;; COPYTYPECHECK
4418 ;; MARKUP
4419 ;; RELEASE
4420 ;; REPFOOTER
4421 ;; REPHEADER
4422 ;; SQLPLUSCOMPATIBILITY
4423 ;; TTITLE
4424 ;; USER
4427 (append
4428 ;; (apply #'concat (append
4429 ;; '("SET")
4431 ;; option value...
4432 (sql-redirect-value
4433 sqlbuf
4434 (concat "SHOW ARRAYSIZE AUTOCOMMIT AUTOPRINT AUTORECOVERY AUTOTRACE"
4435 " CMDSEP COLSEP COPYCOMMIT DESCRIBE ECHO EDITFILE EMBEDDED"
4436 " ESCAPE FLAGGER FLUSH HEADING INSTANCE LINESIZE LNO LOBOFFSET"
4437 " LOGSOURCE LONG LONGCHUNKSIZE NEWPAGE NULL NUMFORMAT NUMWIDTH"
4438 " PAGESIZE PAUSE PNO RECSEP SERVEROUTPUT SHIFTINOUT SHOWMODE"
4439 " SPOOL SQLBLANKLINES SQLCASE SQLCODE SQLCONTINUE SQLNUMBER"
4440 " SQLPROMPT SUFFIX TAB TERMOUT TIMING TRIMOUT TRIMSPOOL VERIFY")
4441 "^.+$"
4442 "SET \\&")
4444 ;; option "c" (hex xx)
4445 (sql-redirect-value
4446 sqlbuf
4447 (concat "SHOW BLOCKTERMINATOR CONCAT DEFINE SQLPREFIX SQLTERMINATOR"
4448 " UNDERLINE HEADSEP RECSEPCHAR")
4449 "^\\(.+\\) (hex ..)$"
4450 "SET \\1")
4452 ;; FEEDBACK ON for 99 or more rows
4453 ;; feedback OFF
4454 (sql-redirect-value
4455 sqlbuf
4456 "SHOW FEEDBACK"
4457 "^\\(?:FEEDBACK ON for \\([[:digit:]]+\\) or more rows\\|feedback \\(OFF\\)\\)"
4458 "SET FEEDBACK \\1\\2")
4460 ;; wrap : lines will be wrapped
4461 ;; wrap : lines will be truncated
4462 (list (concat "SET WRAP "
4463 (if (string=
4464 (car (sql-redirect-value
4465 sqlbuf
4466 "SHOW WRAP"
4467 "^wrap : lines will be \\(wrapped\\|truncated\\)" 1))
4468 "wrapped")
4469 "ON" "OFF")))))
4471 (defun sql-oracle-restore-settings (sqlbuf saved-settings)
4472 "Restore the SQL*Plus settings in SAVED-SETTINGS."
4474 ;; Remove any settings that haven't changed
4475 (mapc
4476 (lambda (one-cur-setting)
4477 (setq saved-settings (delete one-cur-setting saved-settings)))
4478 (sql-oracle-save-settings sqlbuf))
4480 ;; Restore the changed settings
4481 (sql-redirect sqlbuf saved-settings))
4483 (defun sql-oracle--list-object-name (obj-name)
4484 (format "CASE WHEN REGEXP_LIKE (%s, q'/^[A-Z0-9_#$]+$/','c') THEN %s ELSE '\"'|| %s ||'\"' END "
4485 obj-name obj-name obj-name))
4487 (defun sql-oracle-list-all (sqlbuf outbuf enhanced _table-name)
4488 ;; Query from USER_OBJECTS or ALL_OBJECTS
4489 (let ((settings (sql-oracle-save-settings sqlbuf))
4490 (simple-sql
4491 (concat
4492 "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
4493 ", " (sql-oracle--list-object-name "x.object_name") " AS SQL_EL_NAME "
4494 "FROM user_objects x "
4495 "WHERE x.object_type NOT LIKE '%% BODY' "
4496 "ORDER BY 2, 1;"))
4497 (enhanced-sql
4498 (concat
4499 "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
4500 ", " (sql-oracle--list-object-name "x.owner")
4501 " ||'.'|| " (sql-oracle--list-object-name "x.object_name") " AS SQL_EL_NAME "
4502 "FROM all_objects x "
4503 "WHERE x.object_type NOT LIKE '%% BODY' "
4504 "AND x.owner <> 'SYS' "
4505 "ORDER BY 2, 1;")))
4507 (sql-redirect sqlbuf
4508 (concat "SET LINESIZE 80 PAGESIZE 50000 TRIMOUT ON"
4509 " TAB OFF TIMING OFF FEEDBACK OFF"))
4511 (sql-redirect sqlbuf
4512 (list "COLUMN SQL_EL_TYPE HEADING \"Type\" FORMAT A19"
4513 "COLUMN SQL_EL_NAME HEADING \"Name\""
4514 (format "COLUMN SQL_EL_NAME FORMAT A%d"
4515 (if enhanced 60 35))))
4517 (sql-redirect sqlbuf
4518 (if enhanced enhanced-sql simple-sql)
4519 outbuf)
4521 (sql-redirect sqlbuf
4522 '("COLUMN SQL_EL_NAME CLEAR"
4523 "COLUMN SQL_EL_TYPE CLEAR"))
4525 (sql-oracle-restore-settings sqlbuf settings)))
4527 (defun sql-oracle-list-table (sqlbuf outbuf _enhanced table-name)
4528 "Implements :list-table under Oracle."
4529 (let ((settings (sql-oracle-save-settings sqlbuf)))
4531 (sql-redirect sqlbuf
4532 (format
4533 (concat "SET LINESIZE %d PAGESIZE 50000"
4534 " DESCRIBE DEPTH 1 LINENUM OFF INDENT ON")
4535 (max 65 (min 120 (window-width)))))
4537 (sql-redirect sqlbuf (format "DESCRIBE %s" table-name)
4538 outbuf)
4540 (sql-oracle-restore-settings sqlbuf settings)))
4542 (defcustom sql-oracle-completion-types '("FUNCTION" "PACKAGE" "PROCEDURE"
4543 "SEQUENCE" "SYNONYM" "TABLE" "TRIGGER"
4544 "TYPE" "VIEW")
4545 "List of object types to include for completion under Oracle.
4547 See the distinct values in ALL_OBJECTS.OBJECT_TYPE for possible values."
4548 :version "24.1"
4549 :type '(repeat string)
4550 :group 'SQL)
4552 (defun sql-oracle-completion-object (sqlbuf schema)
4553 (sql-redirect-value
4554 sqlbuf
4555 (concat
4556 "SELECT CHR(1)||"
4557 (if schema
4558 (concat "CASE WHEN REGEXP_LIKE (owner, q'/^[A-Z0-9_#$]+$/','c') THEN owner ELSE '\"'|| owner ||'\"' END "
4559 "||'.'||"
4560 "CASE WHEN REGEXP_LIKE (object_name, q'/^[A-Z0-9_#$]+$/','c') THEN object_name ELSE '\"'|| object_name ||'\"' END "
4561 " AS o FROM all_objects "
4562 (format "WHERE owner = %s AND "
4563 (sql-str-literal (if (string-match "^[\"]\\(.+\\)[\"]$" schema)
4564 (match-string 1 schema) (upcase schema)))))
4565 (concat "CASE WHEN REGEXP_LIKE (object_name, q'/^[A-Z0-9_#$]+$/','c') THEN object_name ELSE '\"'|| object_name ||'\"' END "
4566 " AS o FROM user_objects WHERE "))
4567 "temporary = 'N' AND generated = 'N' AND secondary = 'N' AND "
4568 "object_type IN ("
4569 (mapconcat (function sql-str-literal) sql-oracle-completion-types ",")
4570 ");")
4571 "^[\001]\\(.+\\)$" 1))
4574 ;;;###autoload
4575 (defun sql-sybase (&optional buffer)
4576 "Run isql by Sybase as an inferior process.
4578 If buffer `*SQL*' exists but no process is running, make a new process.
4579 If buffer exists and a process is running, just switch to buffer
4580 `*SQL*'.
4582 Interpreter used comes from variable `sql-sybase-program'. Login uses
4583 the variables `sql-server', `sql-user', `sql-password', and
4584 `sql-database' as defaults, if set. Additional command line parameters
4585 can be stored in the list `sql-sybase-options'.
4587 The buffer is put in SQL interactive mode, giving commands for sending
4588 input. See `sql-interactive-mode'.
4590 To set the buffer name directly, use \\[universal-argument]
4591 before \\[sql-sybase]. Once session has started,
4592 \\[sql-rename-buffer] can be called separately to rename the
4593 buffer.
4595 To specify a coding system for converting non-ASCII characters
4596 in the input and output to the process, use \\[universal-coding-system-argument]
4597 before \\[sql-sybase]. You can also specify this with \\[set-buffer-process-coding-system]
4598 in the SQL buffer, after you start the process.
4599 The default comes from `process-coding-system-alist' and
4600 `default-process-coding-system'.
4602 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4603 (interactive "P")
4604 (sql-product-interactive 'sybase buffer))
4606 (defun sql-comint-sybase (product options &optional buf-name)
4607 "Create comint buffer and connect to Sybase."
4608 ;; Put all parameters to the program (if defined) in a list and call
4609 ;; make-comint.
4610 (let ((params
4611 (append
4612 (if (not (string= "" sql-user))
4613 (list "-U" sql-user))
4614 (if (not (string= "" sql-password))
4615 (list "-P" sql-password))
4616 (if (not (string= "" sql-database))
4617 (list "-D" sql-database))
4618 (if (not (string= "" sql-server))
4619 (list "-S" sql-server))
4620 options)))
4621 (sql-comint product params buf-name)))
4625 ;;;###autoload
4626 (defun sql-informix (&optional buffer)
4627 "Run dbaccess by Informix as an inferior process.
4629 If buffer `*SQL*' exists but no process is running, make a new process.
4630 If buffer exists and a process is running, just switch to buffer
4631 `*SQL*'.
4633 Interpreter used comes from variable `sql-informix-program'. Login uses
4634 the variable `sql-database' as default, if set.
4636 The buffer is put in SQL interactive mode, giving commands for sending
4637 input. See `sql-interactive-mode'.
4639 To set the buffer name directly, use \\[universal-argument]
4640 before \\[sql-informix]. Once session has started,
4641 \\[sql-rename-buffer] can be called separately to rename the
4642 buffer.
4644 To specify a coding system for converting non-ASCII characters
4645 in the input and output to the process, use \\[universal-coding-system-argument]
4646 before \\[sql-informix]. You can also specify this with \\[set-buffer-process-coding-system]
4647 in the SQL buffer, after you start the process.
4648 The default comes from `process-coding-system-alist' and
4649 `default-process-coding-system'.
4651 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4652 (interactive "P")
4653 (sql-product-interactive 'informix buffer))
4655 (defun sql-comint-informix (product options &optional buf-name)
4656 "Create comint buffer and connect to Informix."
4657 ;; username and password are ignored.
4658 (let ((db (if (string= "" sql-database)
4660 (if (string= "" sql-server)
4661 sql-database
4662 (concat sql-database "@" sql-server)))))
4663 (sql-comint product (append `(,db "-") options) buf-name)))
4667 ;;;###autoload
4668 (defun sql-sqlite (&optional buffer)
4669 "Run sqlite as an inferior process.
4671 SQLite is free software.
4673 If buffer `*SQL*' exists but no process is running, make a new process.
4674 If buffer exists and a process is running, just switch to buffer
4675 `*SQL*'.
4677 Interpreter used comes from variable `sql-sqlite-program'. Login uses
4678 the variables `sql-user', `sql-password', `sql-database', and
4679 `sql-server' as defaults, if set. Additional command line parameters
4680 can be stored in the list `sql-sqlite-options'.
4682 The buffer is put in SQL interactive mode, giving commands for sending
4683 input. See `sql-interactive-mode'.
4685 To set the buffer name directly, use \\[universal-argument]
4686 before \\[sql-sqlite]. Once session has started,
4687 \\[sql-rename-buffer] can be called separately to rename the
4688 buffer.
4690 To specify a coding system for converting non-ASCII characters
4691 in the input and output to the process, use \\[universal-coding-system-argument]
4692 before \\[sql-sqlite]. You can also specify this with \\[set-buffer-process-coding-system]
4693 in the SQL buffer, after you start the process.
4694 The default comes from `process-coding-system-alist' and
4695 `default-process-coding-system'.
4697 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4698 (interactive "P")
4699 (sql-product-interactive 'sqlite buffer))
4701 (defun sql-comint-sqlite (product options &optional buf-name)
4702 "Create comint buffer and connect to SQLite."
4703 ;; Put all parameters to the program (if defined) in a list and call
4704 ;; make-comint.
4705 (let ((params
4706 (append options
4707 (if (not (string= "" sql-database))
4708 `(,(expand-file-name sql-database))))))
4709 (sql-comint product params buf-name)))
4711 (defun sql-sqlite-completion-object (sqlbuf _schema)
4712 (sql-redirect-value sqlbuf ".tables" "\\sw\\(?:\\sw\\|\\s_\\)*" 0))
4716 ;;;###autoload
4717 (defun sql-mysql (&optional buffer)
4718 "Run mysql by TcX as an inferior process.
4720 Mysql versions 3.23 and up are free software.
4722 If buffer `*SQL*' exists but no process is running, make a new process.
4723 If buffer exists and a process is running, just switch to buffer
4724 `*SQL*'.
4726 Interpreter used comes from variable `sql-mysql-program'. Login uses
4727 the variables `sql-user', `sql-password', `sql-database', and
4728 `sql-server' as defaults, if set. Additional command line parameters
4729 can be stored in the list `sql-mysql-options'.
4731 The buffer is put in SQL interactive mode, giving commands for sending
4732 input. See `sql-interactive-mode'.
4734 To set the buffer name directly, use \\[universal-argument]
4735 before \\[sql-mysql]. Once session has started,
4736 \\[sql-rename-buffer] can be called separately to rename the
4737 buffer.
4739 To specify a coding system for converting non-ASCII characters
4740 in the input and output to the process, use \\[universal-coding-system-argument]
4741 before \\[sql-mysql]. You can also specify this with \\[set-buffer-process-coding-system]
4742 in the SQL buffer, after you start the process.
4743 The default comes from `process-coding-system-alist' and
4744 `default-process-coding-system'.
4746 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4747 (interactive "P")
4748 (sql-product-interactive 'mysql buffer))
4750 (defun sql-comint-mysql (product options &optional buf-name)
4751 "Create comint buffer and connect to MySQL."
4752 ;; Put all parameters to the program (if defined) in a list and call
4753 ;; make-comint.
4754 (let ((params
4755 (append
4756 options
4757 (if (not (string= "" sql-user))
4758 (list (concat "--user=" sql-user)))
4759 (if (not (string= "" sql-password))
4760 (list (concat "--password=" sql-password)))
4761 (if (not (= 0 sql-port))
4762 (list (concat "--port=" (number-to-string sql-port))))
4763 (if (not (string= "" sql-server))
4764 (list (concat "--host=" sql-server)))
4765 (if (not (string= "" sql-database))
4766 (list sql-database)))))
4767 (sql-comint product params buf-name)))
4771 ;;;###autoload
4772 (defun sql-solid (&optional buffer)
4773 "Run solsql by Solid as an inferior process.
4775 If buffer `*SQL*' exists but no process is running, make a new process.
4776 If buffer exists and a process is running, just switch to buffer
4777 `*SQL*'.
4779 Interpreter used comes from variable `sql-solid-program'. Login uses
4780 the variables `sql-user', `sql-password', and `sql-server' as
4781 defaults, if set.
4783 The buffer is put in SQL interactive mode, giving commands for sending
4784 input. See `sql-interactive-mode'.
4786 To set the buffer name directly, use \\[universal-argument]
4787 before \\[sql-solid]. Once session has started,
4788 \\[sql-rename-buffer] can be called separately to rename the
4789 buffer.
4791 To specify a coding system for converting non-ASCII characters
4792 in the input and output to the process, use \\[universal-coding-system-argument]
4793 before \\[sql-solid]. You can also specify this with \\[set-buffer-process-coding-system]
4794 in the SQL buffer, after you start the process.
4795 The default comes from `process-coding-system-alist' and
4796 `default-process-coding-system'.
4798 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4799 (interactive "P")
4800 (sql-product-interactive 'solid buffer))
4802 (defun sql-comint-solid (product options &optional buf-name)
4803 "Create comint buffer and connect to Solid."
4804 ;; Put all parameters to the program (if defined) in a list and call
4805 ;; make-comint.
4806 (let ((params
4807 (append
4808 (if (not (string= "" sql-server))
4809 (list sql-server))
4810 ;; It only makes sense if both username and password are there.
4811 (if (not (or (string= "" sql-user)
4812 (string= "" sql-password)))
4813 (list sql-user sql-password))
4814 options)))
4815 (sql-comint product params buf-name)))
4819 ;;;###autoload
4820 (defun sql-ingres (&optional buffer)
4821 "Run sql by Ingres as an inferior process.
4823 If buffer `*SQL*' exists but no process is running, make a new process.
4824 If buffer exists and a process is running, just switch to buffer
4825 `*SQL*'.
4827 Interpreter used comes from variable `sql-ingres-program'. Login uses
4828 the variable `sql-database' as default, if set.
4830 The buffer is put in SQL interactive mode, giving commands for sending
4831 input. See `sql-interactive-mode'.
4833 To set the buffer name directly, use \\[universal-argument]
4834 before \\[sql-ingres]. Once session has started,
4835 \\[sql-rename-buffer] can be called separately to rename the
4836 buffer.
4838 To specify a coding system for converting non-ASCII characters
4839 in the input and output to the process, use \\[universal-coding-system-argument]
4840 before \\[sql-ingres]. You can also specify this with \\[set-buffer-process-coding-system]
4841 in the SQL buffer, after you start the process.
4842 The default comes from `process-coding-system-alist' and
4843 `default-process-coding-system'.
4845 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4846 (interactive "P")
4847 (sql-product-interactive 'ingres buffer))
4849 (defun sql-comint-ingres (product options &optional buf-name)
4850 "Create comint buffer and connect to Ingres."
4851 ;; username and password are ignored.
4852 (sql-comint product
4853 (append (if (string= "" sql-database)
4855 (list sql-database))
4856 options)
4857 buf-name))
4861 ;;;###autoload
4862 (defun sql-ms (&optional buffer)
4863 "Run osql by Microsoft as an inferior process.
4865 If buffer `*SQL*' exists but no process is running, make a new process.
4866 If buffer exists and a process is running, just switch to buffer
4867 `*SQL*'.
4869 Interpreter used comes from variable `sql-ms-program'. Login uses the
4870 variables `sql-user', `sql-password', `sql-database', and `sql-server'
4871 as defaults, if set. Additional command line parameters can be stored
4872 in the list `sql-ms-options'.
4874 The buffer is put in SQL interactive mode, giving commands for sending
4875 input. See `sql-interactive-mode'.
4877 To set the buffer name directly, use \\[universal-argument]
4878 before \\[sql-ms]. Once session has started,
4879 \\[sql-rename-buffer] can be called separately to rename the
4880 buffer.
4882 To specify a coding system for converting non-ASCII characters
4883 in the input and output to the process, use \\[universal-coding-system-argument]
4884 before \\[sql-ms]. You can also specify this with \\[set-buffer-process-coding-system]
4885 in the SQL buffer, after you start the process.
4886 The default comes from `process-coding-system-alist' and
4887 `default-process-coding-system'.
4889 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4890 (interactive "P")
4891 (sql-product-interactive 'ms buffer))
4893 (defun sql-comint-ms (product options &optional buf-name)
4894 "Create comint buffer and connect to Microsoft SQL Server."
4895 ;; Put all parameters to the program (if defined) in a list and call
4896 ;; make-comint.
4897 (let ((params
4898 (append
4899 (if (not (string= "" sql-user))
4900 (list "-U" sql-user))
4901 (if (not (string= "" sql-database))
4902 (list "-d" sql-database))
4903 (if (not (string= "" sql-server))
4904 (list "-S" sql-server))
4905 options)))
4906 (setq params
4907 (if (not (string= "" sql-password))
4908 `("-P" ,sql-password ,@params)
4909 (if (string= "" sql-user)
4910 ;; If neither user nor password is provided, use system
4911 ;; credentials.
4912 `("-E" ,@params)
4913 ;; If -P is passed to ISQL as the last argument without a
4914 ;; password, it's considered null.
4915 `(,@params "-P"))))
4916 (sql-comint product params buf-name)))
4920 ;;;###autoload
4921 (defun sql-postgres (&optional buffer)
4922 "Run psql by Postgres as an inferior process.
4924 If buffer `*SQL*' exists but no process is running, make a new process.
4925 If buffer exists and a process is running, just switch to buffer
4926 `*SQL*'.
4928 Interpreter used comes from variable `sql-postgres-program'. Login uses
4929 the variables `sql-database' and `sql-server' as default, if set.
4930 Additional command line parameters can be stored in the list
4931 `sql-postgres-options'.
4933 The buffer is put in SQL interactive mode, giving commands for sending
4934 input. See `sql-interactive-mode'.
4936 To set the buffer name directly, use \\[universal-argument]
4937 before \\[sql-postgres]. Once session has started,
4938 \\[sql-rename-buffer] can be called separately to rename the
4939 buffer.
4941 To specify a coding system for converting non-ASCII characters
4942 in the input and output to the process, use \\[universal-coding-system-argument]
4943 before \\[sql-postgres]. You can also specify this with \\[set-buffer-process-coding-system]
4944 in the SQL buffer, after you start the process.
4945 The default comes from `process-coding-system-alist' and
4946 `default-process-coding-system'. If your output lines end with ^M,
4947 your might try undecided-dos as a coding system. If this doesn't help,
4948 Try to set `comint-output-filter-functions' like this:
4950 \(setq comint-output-filter-functions (append comint-output-filter-functions
4951 \\='(comint-strip-ctrl-m)))
4953 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4954 (interactive "P")
4955 (sql-product-interactive 'postgres buffer))
4957 (defun sql-comint-postgres (product options &optional buf-name)
4958 "Create comint buffer and connect to Postgres."
4959 ;; username and password are ignored. Mark Stosberg suggests to add
4960 ;; the database at the end. Jason Beegan suggests using --pset and
4961 ;; pager=off instead of \\o|cat. The later was the solution by
4962 ;; Gregor Zych. Jason's suggestion is the default value for
4963 ;; sql-postgres-options.
4964 (let ((params
4965 (append
4966 (if (not (= 0 sql-port))
4967 (list "-p" (number-to-string sql-port)))
4968 (if (not (string= "" sql-user))
4969 (list "-U" sql-user))
4970 (if (not (string= "" sql-server))
4971 (list "-h" sql-server))
4972 options
4973 (if (not (string= "" sql-database))
4974 (list sql-database)))))
4975 (sql-comint product params buf-name)))
4977 (defun sql-postgres-completion-object (sqlbuf schema)
4978 (sql-redirect sqlbuf "\\t on")
4979 (let ((aligned
4980 (string= "aligned"
4981 (car (sql-redirect-value
4982 sqlbuf "\\a"
4983 "Output format is \\(.*\\)[.]$" 1)))))
4984 (when aligned
4985 (sql-redirect sqlbuf "\\a"))
4986 (let* ((fs (or (car (sql-redirect-value
4987 sqlbuf "\\f" "Field separator is \"\\(.\\)[.]$" 1))
4988 "|"))
4989 (re (concat "^\\([^" fs "]*\\)" fs "\\([^" fs "]*\\)"
4990 fs "[^" fs "]*" fs "[^" fs "]*$"))
4991 (cl (if (not schema)
4992 (sql-redirect-value sqlbuf "\\d" re '(1 2))
4993 (append (sql-redirect-value
4994 sqlbuf (format "\\dt %s.*" schema) re '(1 2))
4995 (sql-redirect-value
4996 sqlbuf (format "\\dv %s.*" schema) re '(1 2))
4997 (sql-redirect-value
4998 sqlbuf (format "\\ds %s.*" schema) re '(1 2))))))
5000 ;; Restore tuples and alignment to what they were.
5001 (sql-redirect sqlbuf "\\t off")
5002 (when (not aligned)
5003 (sql-redirect sqlbuf "\\a"))
5005 ;; Return the list of table names (public schema name can be omitted)
5006 (mapcar (lambda (tbl)
5007 (if (string= (car tbl) "public")
5008 (format "\"%s\"" (cadr tbl))
5009 (format "\"%s\".\"%s\"" (car tbl) (cadr tbl))))
5010 cl))))
5014 ;;;###autoload
5015 (defun sql-interbase (&optional buffer)
5016 "Run isql by Interbase as an inferior process.
5018 If buffer `*SQL*' exists but no process is running, make a new process.
5019 If buffer exists and a process is running, just switch to buffer
5020 `*SQL*'.
5022 Interpreter used comes from variable `sql-interbase-program'. Login
5023 uses the variables `sql-user', `sql-password', and `sql-database' as
5024 defaults, if set.
5026 The buffer is put in SQL interactive mode, giving commands for sending
5027 input. See `sql-interactive-mode'.
5029 To set the buffer name directly, use \\[universal-argument]
5030 before \\[sql-interbase]. Once session has started,
5031 \\[sql-rename-buffer] can be called separately to rename the
5032 buffer.
5034 To specify a coding system for converting non-ASCII characters
5035 in the input and output to the process, use \\[universal-coding-system-argument]
5036 before \\[sql-interbase]. You can also specify this with \\[set-buffer-process-coding-system]
5037 in the SQL buffer, after you start the process.
5038 The default comes from `process-coding-system-alist' and
5039 `default-process-coding-system'.
5041 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
5042 (interactive "P")
5043 (sql-product-interactive 'interbase buffer))
5045 (defun sql-comint-interbase (product options &optional buf-name)
5046 "Create comint buffer and connect to Interbase."
5047 ;; Put all parameters to the program (if defined) in a list and call
5048 ;; make-comint.
5049 (let ((params
5050 (append
5051 (if (not (string= "" sql-database))
5052 (list sql-database)) ; Add to the front!
5053 (if (not (string= "" sql-password))
5054 (list "-p" sql-password))
5055 (if (not (string= "" sql-user))
5056 (list "-u" sql-user))
5057 options)))
5058 (sql-comint product params buf-name)))
5062 ;;;###autoload
5063 (defun sql-db2 (&optional buffer)
5064 "Run db2 by IBM as an inferior process.
5066 If buffer `*SQL*' exists but no process is running, make a new process.
5067 If buffer exists and a process is running, just switch to buffer
5068 `*SQL*'.
5070 Interpreter used comes from variable `sql-db2-program'. There is not
5071 automatic login.
5073 The buffer is put in SQL interactive mode, giving commands for sending
5074 input. See `sql-interactive-mode'.
5076 If you use \\[sql-accumulate-and-indent] to send multiline commands to
5077 db2, newlines will be escaped if necessary. If you don't want that, set
5078 `comint-input-sender' back to `comint-simple-send' by writing an after
5079 advice. See the elisp manual for more information.
5081 To set the buffer name directly, use \\[universal-argument]
5082 before \\[sql-db2]. Once session has started,
5083 \\[sql-rename-buffer] can be called separately to rename the
5084 buffer.
5086 To specify a coding system for converting non-ASCII characters
5087 in the input and output to the process, use \\[universal-coding-system-argument]
5088 before \\[sql-db2]. You can also specify this with \\[set-buffer-process-coding-system]
5089 in the SQL buffer, after you start the process.
5090 The default comes from `process-coding-system-alist' and
5091 `default-process-coding-system'.
5093 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
5094 (interactive "P")
5095 (sql-product-interactive 'db2 buffer))
5097 (defun sql-comint-db2 (product options &optional buf-name)
5098 "Create comint buffer and connect to DB2."
5099 ;; Put all parameters to the program (if defined) in a list and call
5100 ;; make-comint.
5101 (sql-comint product options buf-name))
5103 ;;;###autoload
5104 (defun sql-linter (&optional buffer)
5105 "Run inl by RELEX as an inferior process.
5107 If buffer `*SQL*' exists but no process is running, make a new process.
5108 If buffer exists and a process is running, just switch to buffer
5109 `*SQL*'.
5111 Interpreter used comes from variable `sql-linter-program' - usually `inl'.
5112 Login uses the variables `sql-user', `sql-password', `sql-database' and
5113 `sql-server' as defaults, if set. Additional command line parameters
5114 can be stored in the list `sql-linter-options'. Run inl -h to get help on
5115 parameters.
5117 `sql-database' is used to set the LINTER_MBX environment variable for
5118 local connections, `sql-server' refers to the server name from the
5119 `nodetab' file for the network connection (dbc_tcp or friends must run
5120 for this to work). If `sql-password' is an empty string, inl will use
5121 an empty password.
5123 The buffer is put in SQL interactive mode, giving commands for sending
5124 input. See `sql-interactive-mode'.
5126 To set the buffer name directly, use \\[universal-argument]
5127 before \\[sql-linter]. Once session has started,
5128 \\[sql-rename-buffer] can be called separately to rename the
5129 buffer.
5131 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
5132 (interactive "P")
5133 (sql-product-interactive 'linter buffer))
5135 (defun sql-comint-linter (product options &optional buf-name)
5136 "Create comint buffer and connect to Linter."
5137 ;; Put all parameters to the program (if defined) in a list and call
5138 ;; make-comint.
5139 (let* ((login
5140 (if (not (string= "" sql-user))
5141 (concat sql-user "/" sql-password)))
5142 (params
5143 (append
5144 (if (not (string= "" sql-server))
5145 (list "-n" sql-server))
5146 (list "-u" login)
5147 options)))
5148 (cl-letf (((getenv "LINTER_MBX")
5149 (unless (string= "" sql-database) sql-database)))
5150 (sql-comint product params buf-name))))
5154 (defcustom sql-vertica-program "vsql"
5155 "Command to start the Vertica client."
5156 :version "25.1"
5157 :type 'file
5158 :group 'SQL)
5160 (defcustom sql-vertica-options '("-P" "pager=off")
5161 "List of additional options for `sql-vertica-program'.
5162 The default value disables the internal pager."
5163 :version "25.1"
5164 :type '(repeat string)
5165 :group 'SQL)
5167 (defcustom sql-vertica-login-params '(user password database server)
5168 "List of login parameters needed to connect to Vertica."
5169 :version "25.1"
5170 :type 'sql-login-params
5171 :group 'SQL)
5173 (defun sql-comint-vertica (product options &optional buf-name)
5174 "Create comint buffer and connect to Vertica."
5175 (sql-comint product
5176 (nconc
5177 (and (not (string= "" sql-server))
5178 (list "-h" sql-server))
5179 (and (not (string= "" sql-database))
5180 (list "-d" sql-database))
5181 (and (not (string= "" sql-password))
5182 (list "-w" sql-password))
5183 (and (not (string= "" sql-user))
5184 (list "-U" sql-user))
5185 options)
5186 buf-name))
5188 ;;;###autoload
5189 (defun sql-vertica (&optional buffer)
5190 "Run vsql as an inferior process."
5191 (interactive "P")
5192 (sql-product-interactive 'vertica buffer))
5195 (provide 'sql)
5197 ;;; sql.el ends here
5199 ; LocalWords: sql SQL SQLite sqlite Sybase Informix MySQL
5200 ; LocalWords: Postgres SQLServer SQLi