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