Update docstrings and comments to use "init file" terminology.
[emacs.git] / lisp / progmodes / sql.el
blob3d5abc4df62a38396a194f5990376be8ff59f352
1 ;;; sql.el --- specialized comint.el for SQL interpreters
3 ;; Copyright (C) 1998-2012 Free Software Foundation, Inc.
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Maintainer: Michael Mauger <mmaug@yahoo.com>
7 ;; Version: 3.1
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 ;;; Requirements for Emacs 19.34:
85 ;; If you are using Emacs 19.34, you will have to get and install
86 ;; the file regexp-opt.el
87 ;; <URL:ftp://ftp.ifi.uio.no/pub/emacs/emacs-20.3/lisp/emacs-lisp/regexp-opt.el>
88 ;; and the custom package
89 ;; <URL:http://www.dina.kvl.dk/~abraham/custom/>.
91 ;;; Bugs:
93 ;; sql-ms now uses osql instead of isql. Osql flushes its error
94 ;; stream more frequently than isql so that error messages are
95 ;; available. There is no prompt and some output still is buffered.
96 ;; This improves the interaction under Emacs but it still is somewhat
97 ;; awkward.
99 ;; Quoted identifiers are not supported for highlighting. Most
100 ;; databases support the use of double quoted strings in place of
101 ;; identifiers; ms (Microsoft SQLServer) also supports identifiers
102 ;; enclosed within brackets [].
104 ;;; Product Support:
106 ;; To add support for additional SQL products the following steps
107 ;; must be followed ("xyz" is the name of the product in the examples
108 ;; below):
110 ;; 1) Add the product to the list of known products.
112 ;; (sql-add-product 'xyz "XyzDB"
113 ;; '(:free-software t))
115 ;; 2) Define font lock settings. All ANSI keywords will be
116 ;; highlighted automatically, so only product specific keywords
117 ;; need to be defined here.
119 ;; (defvar my-sql-mode-xyz-font-lock-keywords
120 ;; '(("\\b\\(red\\|orange\\|yellow\\)\\b"
121 ;; . font-lock-keyword-face))
122 ;; "XyzDB SQL keywords used by font-lock.")
124 ;; (sql-set-product-feature 'xyz
125 ;; :font-lock
126 ;; 'my-sql-mode-xyz-font-lock-keywords)
128 ;; 3) Define any special syntax characters including comments and
129 ;; identifier characters.
131 ;; (sql-set-product-feature 'xyz
132 ;; :syntax-alist ((?# . "_")))
134 ;; 4) Define the interactive command interpreter for the database
135 ;; product.
137 ;; (defcustom my-sql-xyz-program "ixyz"
138 ;; "Command to start ixyz by XyzDB."
139 ;; :type 'file
140 ;; :group 'SQL)
142 ;; (sql-set-product-feature 'xyz
143 ;; :sqli-program 'my-sql-xyz-program)
144 ;; (sql-set-product-feature 'xyz
145 ;; :prompt-regexp "^xyzdb> ")
146 ;; (sql-set-product-feature 'xyz
147 ;; :prompt-length 7)
149 ;; 5) Define login parameters and command line formatting.
151 ;; (defcustom my-sql-xyz-login-params '(user password server database)
152 ;; "Login parameters to needed to connect to XyzDB."
153 ;; :type 'sql-login-params
154 ;; :group 'SQL)
156 ;; (sql-set-product-feature 'xyz
157 ;; :sqli-login 'my-sql-xyz-login-params)
159 ;; (defcustom my-sql-xyz-options '("-X" "-Y" "-Z")
160 ;; "List of additional options for `sql-xyz-program'."
161 ;; :type '(repeat string)
162 ;; :group 'SQL)
164 ;; (sql-set-product-feature 'xyz
165 ;; :sqli-options 'my-sql-xyz-options))
167 ;; (defun my-sql-comint-xyz (product options)
168 ;; "Connect ti XyzDB in a comint buffer."
170 ;; ;; Do something with `sql-user', `sql-password',
171 ;; ;; `sql-database', and `sql-server'.
172 ;; (let ((params options))
173 ;; (if (not (string= "" sql-server))
174 ;; (setq params (append (list "-S" sql-server) params)))
175 ;; (if (not (string= "" sql-database))
176 ;; (setq params (append (list "-D" sql-database) params)))
177 ;; (if (not (string= "" sql-password))
178 ;; (setq params (append (list "-P" sql-password) params)))
179 ;; (if (not (string= "" sql-user))
180 ;; (setq params (append (list "-U" sql-user) params)))
181 ;; (sql-comint product params)))
183 ;; (sql-set-product-feature 'xyz
184 ;; :sqli-comint-func 'my-sql-comint-xyz)
186 ;; 6) Define a convenience function to invoke the SQL interpreter.
188 ;; (defun my-sql-xyz (&optional buffer)
189 ;; "Run ixyz by XyzDB as an inferior process."
190 ;; (interactive "P")
191 ;; (sql-product-interactive 'xyz buffer))
193 ;;; To Do:
195 ;; Improve keyword highlighting for individual products. I have tried
196 ;; to update those database that I use. Feel free to send me updates,
197 ;; or direct me to the reference manuals for your favorite database.
199 ;; When there are no keywords defined, the ANSI keywords are
200 ;; highlighted. ANSI keywords are highlighted even if the keyword is
201 ;; not used for your current product. This should help identify
202 ;; portability concerns.
204 ;; Add different highlighting levels.
206 ;; Add support for listing available tables or the columns in a table.
208 ;;; Thanks to all the people who helped me out:
210 ;; Alex Schroeder <alex@gnu.org> -- the original author
211 ;; Kai Blauberg <kai.blauberg@metla.fi>
212 ;; <ibalaban@dalet.com>
213 ;; Yair Friedman <yfriedma@JohnBryce.Co.Il>
214 ;; Gregor Zych <zych@pool.informatik.rwth-aachen.de>
215 ;; nino <nino@inform.dk>
216 ;; Berend de Boer <berend@pobox.com>
217 ;; Adam Jenkins <adam@thejenkins.org>
218 ;; Michael Mauger <mmaug@yahoo.com> -- improved product support
219 ;; Drew Adams <drew.adams@oracle.com> -- Emacs 20 support
220 ;; Harald Maier <maierh@myself.com> -- sql-send-string
221 ;; Stefan Monnier <monnier@iro.umontreal.ca> -- font-lock corrections;
222 ;; code polish
223 ;; Paul Sleigh <bat@flurf.net> -- MySQL keyword enhancement
224 ;; Andrew Schein <andrew@andrewschein.com> -- sql-port bug
225 ;; Ian Bjorhovde <idbjorh@dataproxy.com> -- db2 escape newlines
226 ;; incorrectly enabled by default
230 ;;; Code:
232 (require 'comint)
233 ;; Need the following to allow GNU Emacs 19 to compile the file.
234 (eval-when-compile
235 (require 'regexp-opt))
236 (require 'custom)
237 (require 'thingatpt)
238 (eval-when-compile ;; needed in Emacs 19, 20
239 (setq max-specpdl-size (max max-specpdl-size 2000)))
241 (defun sql-signum (n)
242 "Return 1, 0, or -1 to identify the sign of N."
243 (cond
244 ((not (numberp n)) nil)
245 ((< n 0) -1)
246 ((> n 0) 1)
247 (t 0)))
249 (defvar font-lock-keyword-face)
250 (defvar font-lock-set-defaults)
251 (defvar font-lock-string-face)
253 ;;; Allow customization
255 (defgroup SQL nil
256 "Running a SQL interpreter from within Emacs buffers."
257 :version "20.4"
258 :group 'languages
259 :group 'processes)
261 ;; These four variables will be used as defaults, if set.
263 (defcustom sql-user ""
264 "Default username."
265 :type 'string
266 :group 'SQL
267 :safe 'stringp)
269 (defcustom sql-password ""
270 "Default password.
271 If you customize this, the value will be stored in your init
272 file. Since that is a plaintext file, this could be dangerous."
273 :type 'string
274 :group 'SQL
275 :risky t)
277 (defcustom sql-database ""
278 "Default database."
279 :type 'string
280 :group 'SQL
281 :safe 'stringp)
283 (defcustom sql-server ""
284 "Default server or host."
285 :type 'string
286 :group 'SQL
287 :safe 'stringp)
289 (defcustom sql-port 0
290 "Default port for connecting to a MySQL or Postgres server."
291 :version "24.1"
292 :type 'number
293 :group 'SQL
294 :safe 'numberp)
296 ;; Login parameter type
298 (define-widget 'sql-login-params 'lazy
299 "Widget definition of the login parameters list"
300 ;; FIXME: does not implement :default property for the user,
301 ;; database and server options. Anybody have some guidance on how to
302 ;; do this.
303 :tag "Login Parameters"
304 :type '(repeat (choice
305 (const user)
306 (const password)
307 (choice :tag "server"
308 (const server)
309 (list :tag "file"
310 (const :format "" server)
311 (const :format "" :file)
312 regexp)
313 (list :tag "completion"
314 (const :format "" server)
315 (const :format "" :completion)
316 (restricted-sexp
317 :match-alternatives (listp stringp))))
318 (choice :tag "database"
319 (const database)
320 (list :tag "file"
321 (const :format "" database)
322 (const :format "" :file)
323 regexp)
324 (list :tag "completion"
325 (const :format "" database)
326 (const :format "" :completion)
327 (restricted-sexp
328 :match-alternatives (listp stringp))))
329 (const port))))
331 ;; SQL Product support
333 (defvar sql-interactive-product nil
334 "Product under `sql-interactive-mode'.")
336 (defvar sql-connection nil
337 "Connection name if interactive session started by `sql-connect'.")
339 (defvar sql-product-alist
340 '((ansi
341 :name "ANSI"
342 :font-lock sql-mode-ansi-font-lock-keywords
343 :statement sql-ansi-statement-starters)
345 (db2
346 :name "DB2"
347 :font-lock sql-mode-db2-font-lock-keywords
348 :sqli-program sql-db2-program
349 :sqli-options sql-db2-options
350 :sqli-login sql-db2-login-params
351 :sqli-comint-func sql-comint-db2
352 :prompt-regexp "^db2 => "
353 :prompt-length 7
354 :prompt-cont-regexp "^db2 (cont\.) => "
355 :input-filter sql-escape-newlines-filter)
357 (informix
358 :name "Informix"
359 :font-lock sql-mode-informix-font-lock-keywords
360 :sqli-program sql-informix-program
361 :sqli-options sql-informix-options
362 :sqli-login sql-informix-login-params
363 :sqli-comint-func sql-comint-informix
364 :prompt-regexp "^> "
365 :prompt-length 2
366 :syntax-alist ((?{ . "<") (?} . ">")))
368 (ingres
369 :name "Ingres"
370 :font-lock sql-mode-ingres-font-lock-keywords
371 :sqli-program sql-ingres-program
372 :sqli-options sql-ingres-options
373 :sqli-login sql-ingres-login-params
374 :sqli-comint-func sql-comint-ingres
375 :prompt-regexp "^\* "
376 :prompt-length 2
377 :prompt-cont-regexp "^\* ")
379 (interbase
380 :name "Interbase"
381 :font-lock sql-mode-interbase-font-lock-keywords
382 :sqli-program sql-interbase-program
383 :sqli-options sql-interbase-options
384 :sqli-login sql-interbase-login-params
385 :sqli-comint-func sql-comint-interbase
386 :prompt-regexp "^SQL> "
387 :prompt-length 5)
389 (linter
390 :name "Linter"
391 :font-lock sql-mode-linter-font-lock-keywords
392 :sqli-program sql-linter-program
393 :sqli-options sql-linter-options
394 :sqli-login sql-linter-login-params
395 :sqli-comint-func sql-comint-linter
396 :prompt-regexp "^SQL>"
397 :prompt-length 4)
400 :name "Microsoft"
401 :font-lock sql-mode-ms-font-lock-keywords
402 :sqli-program sql-ms-program
403 :sqli-options sql-ms-options
404 :sqli-login sql-ms-login-params
405 :sqli-comint-func sql-comint-ms
406 :prompt-regexp "^[0-9]*>"
407 :prompt-length 5
408 :syntax-alist ((?@ . "_"))
409 :terminator ("^go" . "go"))
411 (mysql
412 :name "MySQL"
413 :free-software t
414 :font-lock sql-mode-mysql-font-lock-keywords
415 :sqli-program sql-mysql-program
416 :sqli-options sql-mysql-options
417 :sqli-login sql-mysql-login-params
418 :sqli-comint-func sql-comint-mysql
419 :list-all "SHOW TABLES;"
420 :list-table "DESCRIBE %s;"
421 :prompt-regexp "^mysql> "
422 :prompt-length 6
423 :prompt-cont-regexp "^ -> "
424 :syntax-alist ((?# . "< b"))
425 :input-filter sql-remove-tabs-filter)
427 (oracle
428 :name "Oracle"
429 :font-lock sql-mode-oracle-font-lock-keywords
430 :sqli-program sql-oracle-program
431 :sqli-options sql-oracle-options
432 :sqli-login sql-oracle-login-params
433 :sqli-comint-func sql-comint-oracle
434 :list-all sql-oracle-list-all
435 :list-table sql-oracle-list-table
436 :completion-object sql-oracle-completion-object
437 :prompt-regexp "^SQL> "
438 :prompt-length 5
439 :prompt-cont-regexp "^\\s-*[[:digit:]]+ "
440 :statement sql-oracle-statement-starters
441 :syntax-alist ((?$ . "_") (?# . "_"))
442 :terminator ("\\(^/\\|;\\)$" . "/")
443 :input-filter sql-placeholders-filter)
445 (postgres
446 :name "Postgres"
447 :free-software t
448 :font-lock sql-mode-postgres-font-lock-keywords
449 :sqli-program sql-postgres-program
450 :sqli-options sql-postgres-options
451 :sqli-login sql-postgres-login-params
452 :sqli-comint-func sql-comint-postgres
453 :list-all ("\\d+" . "\\dS+")
454 :list-table ("\\d+ %s" . "\\dS+ %s")
455 :completion-object sql-postgres-completion-object
456 :prompt-regexp "^\\w*=[#>] "
457 :prompt-length 5
458 :prompt-cont-regexp "^\\w*[-(][#>] "
459 :input-filter sql-remove-tabs-filter
460 :terminator ("\\(^\\s-*\\\\g$\\|;\\)" . "\\g"))
462 (solid
463 :name "Solid"
464 :font-lock sql-mode-solid-font-lock-keywords
465 :sqli-program sql-solid-program
466 :sqli-options sql-solid-options
467 :sqli-login sql-solid-login-params
468 :sqli-comint-func sql-comint-solid
469 :prompt-regexp "^"
470 :prompt-length 0)
472 (sqlite
473 :name "SQLite"
474 :free-software t
475 :font-lock sql-mode-sqlite-font-lock-keywords
476 :sqli-program sql-sqlite-program
477 :sqli-options sql-sqlite-options
478 :sqli-login sql-sqlite-login-params
479 :sqli-comint-func sql-comint-sqlite
480 :list-all ".tables"
481 :list-table ".schema %s"
482 :completion-object sql-sqlite-completion-object
483 :prompt-regexp "^sqlite> "
484 :prompt-length 8
485 :prompt-cont-regexp "^ \.\.\.> "
486 :terminator ";")
488 (sybase
489 :name "Sybase"
490 :font-lock sql-mode-sybase-font-lock-keywords
491 :sqli-program sql-sybase-program
492 :sqli-options sql-sybase-options
493 :sqli-login sql-sybase-login-params
494 :sqli-comint-func sql-comint-sybase
495 :prompt-regexp "^SQL> "
496 :prompt-length 5
497 :syntax-alist ((?@ . "_"))
498 :terminator ("^go" . "go"))
500 "An alist of product specific configuration settings.
502 Without an entry in this list a product will not be properly
503 highlighted and will not support `sql-interactive-mode'.
505 Each element in the list is in the following format:
507 \(PRODUCT FEATURE VALUE ...)
509 where PRODUCT is the appropriate value of `sql-product'. The
510 product name is then followed by FEATURE-VALUE pairs. If a
511 FEATURE is not specified, its VALUE is treated as nil. FEATURE
512 may be any one of the following:
514 :name string containing the displayable name of
515 the product.
517 :free-software is the product Free (as in Freedom) software?
519 :font-lock name of the variable containing the product
520 specific font lock highlighting patterns.
522 :sqli-program name of the variable containing the product
523 specific interactive program name.
525 :sqli-options name of the variable containing the list
526 of product specific options.
528 :sqli-login name of the variable containing the list of
529 login parameters (i.e., user, password,
530 database and server) needed to connect to
531 the database.
533 :sqli-comint-func name of a function which accepts no
534 parameters that will use the values of
535 `sql-user', `sql-password',
536 `sql-database', `sql-server' and
537 `sql-port' to open a comint buffer and
538 connect to the database. Do product
539 specific configuration of comint in this
540 function.
542 :list-all Command string or function which produces
543 a listing of all objects in the database.
544 If it's a cons cell, then the car
545 produces the standard list of objects and
546 the cdr produces an enhanced list of
547 objects. What \"enhanced\" means is
548 dependent on the SQL product and may not
549 exist. In general though, the
550 \"enhanced\" list should include visible
551 objects from other schemas.
553 :list-table Command string or function which produces
554 a detailed listing of a specific database
555 table. If its a cons cell, then the car
556 produces the standard list and the cdr
557 produces an enhanced list.
559 :completion-object A function that returns a list of
560 objects. Called with a single
561 parameter--if nil then list objects
562 accessible in the current schema, if
563 not-nil it is the name of a schema whose
564 objects should be listed.
566 :completion-column A function that returns a list of
567 columns. Called with a single
568 parameter--if nil then list objects
569 accessible in the current schema, if
570 not-nil it is the name of a schema whose
571 objects should be listed.
573 :prompt-regexp regular expression string that matches
574 the prompt issued by the product
575 interpreter.
577 :prompt-length length of the prompt on the line.
579 :prompt-cont-regexp regular expression string that matches
580 the continuation prompt issued by the
581 product interpreter.
583 :input-filter function which can filter strings sent to
584 the command interpreter. It is also used
585 by the `sql-send-string',
586 `sql-send-region', `sql-send-paragraph'
587 and `sql-send-buffer' functions. The
588 function is passed the string sent to the
589 command interpreter and must return the
590 filtered string. May also be a list of
591 such functions.
593 :statement name of a variable containing a regexp that
594 matches the beginning of SQL statements.
596 :terminator the terminator to be sent after a
597 `sql-send-string', `sql-send-region',
598 `sql-send-paragraph' and
599 `sql-send-buffer' command. May be the
600 literal string or a cons of a regexp to
601 match an existing terminator in the
602 string and the terminator to be used if
603 its absent. By default \";\".
605 :syntax-alist alist of syntax table entries to enable
606 special character treatment by font-lock
607 and imenu.
609 Other features can be stored but they will be ignored. However,
610 you can develop new functionality which is product independent by
611 using `sql-get-product-feature' to lookup the product specific
612 settings.")
614 (defvar sql-indirect-features
615 '(:font-lock :sqli-program :sqli-options :sqli-login :statement))
617 (defcustom sql-connection-alist nil
618 "An alist of connection parameters for interacting with a SQL product.
619 Each element of the alist is as follows:
621 \(CONNECTION \(SQL-VARIABLE VALUE) ...)
623 Where CONNECTION is a symbol identifying the connection, SQL-VARIABLE
624 is the symbol name of a SQL mode variable, and VALUE is the value to
625 be assigned to the variable. The most common SQL-VARIABLE settings
626 associated with a connection are: `sql-product', `sql-user',
627 `sql-password', `sql-port', `sql-server', and `sql-database'.
629 If a SQL-VARIABLE is part of the connection, it will not be
630 prompted for during login. The command `sql-connect' starts a
631 predefined SQLi session using the parameters from this list.
632 Connections defined here appear in the submenu SQL->Start... for
633 making new SQLi sessions."
634 :type `(alist :key-type (string :tag "Connection")
635 :value-type
636 (set
637 (group (const :tag "Product" sql-product)
638 (choice
639 ,@(mapcar (lambda (prod-info)
640 `(const :tag
641 ,(or (plist-get (cdr prod-info) :name)
642 (capitalize (symbol-name (car prod-info))))
643 (quote ,(car prod-info))))
644 sql-product-alist)))
645 (group (const :tag "Username" sql-user) string)
646 (group (const :tag "Password" sql-password) string)
647 (group (const :tag "Server" sql-server) string)
648 (group (const :tag "Database" sql-database) string)
649 (group (const :tag "Port" sql-port) integer)
650 (repeat :inline t
651 (list :tab "Other"
652 (symbol :tag " Variable Symbol")
653 (sexp :tag "Value Expression")))))
654 :version "24.1"
655 :group 'SQL)
657 (defcustom sql-product 'ansi
658 "Select the SQL database product used so that buffers can be
659 highlighted properly when you open them."
660 :type `(choice
661 ,@(mapcar (lambda (prod-info)
662 `(const :tag
663 ,(or (plist-get (cdr prod-info) :name)
664 (capitalize (symbol-name (car prod-info))))
665 ,(car prod-info)))
666 sql-product-alist))
667 :group 'SQL
668 :safe 'symbolp)
669 (defvaralias 'sql-dialect 'sql-product)
671 ;; misc customization of sql.el behavior
673 (defcustom sql-electric-stuff nil
674 "Treat some input as electric.
675 If set to the symbol `semicolon', then hitting `;' will send current
676 input in the SQLi buffer to the process.
677 If set to the symbol `go', then hitting `go' on a line by itself will
678 send current input in the SQLi buffer to the process.
679 If set to nil, then you must use \\[comint-send-input] in order to send
680 current input in the SQLi buffer to the process."
681 :type '(choice (const :tag "Nothing" nil)
682 (const :tag "The semicolon `;'" semicolon)
683 (const :tag "The string `go' by itself" go))
684 :version "20.8"
685 :group 'SQL)
687 (defcustom sql-send-terminator nil
688 "When non-nil, add a terminator to text sent to the SQL interpreter.
690 When text is sent to the SQL interpreter (via `sql-send-string',
691 `sql-send-region', `sql-send-paragraph' or `sql-send-buffer'), a
692 command terminator can be automatically sent as well. The
693 terminator is not sent, if the string sent already ends with the
694 terminator.
696 If this value is t, then the default command terminator for the
697 SQL interpreter is sent. If this value is a string, then the
698 string is sent.
700 If the value is a cons cell of the form (PAT . TERM), then PAT is
701 a regexp used to match the terminator in the string and TERM is
702 the terminator to be sent. This form is useful if the SQL
703 interpreter has more than one way of submitting a SQL command.
704 The PAT regexp can match any of them, and TERM is the way we do
705 it automatically."
707 :type '(choice (const :tag "No Terminator" nil)
708 (const :tag "Default Terminator" t)
709 (string :tag "Terminator String")
710 (cons :tag "Terminator Pattern and String"
711 (string :tag "Terminator Pattern")
712 (string :tag "Terminator String")))
713 :version "22.2"
714 :group 'SQL)
716 (defvar sql-contains-names nil
717 "When non-nil, the current buffer contains database names.
719 Globally should be set to nil; it will be non-nil in `sql-mode',
720 `sql-interactive-mode' and list all buffers.")
723 (defcustom sql-pop-to-buffer-after-send-region nil
724 "When non-nil, pop to the buffer SQL statements are sent to.
726 After a call to `sql-sent-string', `sql-send-region',
727 `sql-send-paragraph' or `sql-send-buffer', the window is split
728 and the SQLi buffer is shown. If this variable is not nil, that
729 buffer's window will be selected by calling `pop-to-buffer'. If
730 this variable is nil, that buffer is shown using
731 `display-buffer'."
732 :type 'boolean
733 :group 'SQL)
735 ;; imenu support for sql-mode.
737 (defvar sql-imenu-generic-expression
738 ;; Items are in reverse order because they are rendered in reverse.
739 '(("Rules/Defaults" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*\\(rule\\|default\\)\\s-+\\(\\w+\\)" 3)
740 ("Sequences" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*sequence\\s-+\\(\\w+\\)" 2)
741 ("Triggers" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*trigger\\s-+\\(\\w+\\)" 2)
742 ("Functions" "^\\s-*\\(create\\s-+\\(\\w+\\s-+\\)*\\)?function\\s-+\\(\\w+\\)" 3)
743 ("Procedures" "^\\s-*\\(create\\s-+\\(\\w+\\s-+\\)*\\)?proc\\(edure\\)?\\s-+\\(\\w+\\)" 4)
744 ("Packages" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*package\\s-+\\(body\\s-+\\)?\\(\\w+\\)" 3)
745 ("Types" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*type\\s-+\\(body\\s-+\\)?\\(\\w+\\)" 3)
746 ("Indexes" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*index\\s-+\\(\\w+\\)" 2)
747 ("Tables/Views" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*\\(table\\|view\\)\\s-+\\(\\w+\\)" 3))
748 "Define interesting points in the SQL buffer for `imenu'.
750 This is used to set `imenu-generic-expression' when SQL mode is
751 entered. Subsequent changes to `sql-imenu-generic-expression' will
752 not affect existing SQL buffers because imenu-generic-expression is
753 a local variable.")
755 ;; history file
757 (defcustom sql-input-ring-file-name nil
758 "If non-nil, name of the file to read/write input history.
760 You have to set this variable if you want the history of your commands
761 saved from one Emacs session to the next. If this variable is set,
762 exiting the SQL interpreter in an SQLi buffer will write the input
763 history to the specified file. Starting a new process in a SQLi buffer
764 will read the input history from the specified file.
766 This is used to initialize `comint-input-ring-file-name'.
768 Note that the size of the input history is determined by the variable
769 `comint-input-ring-size'."
770 :type '(choice (const :tag "none" nil)
771 (file))
772 :group 'SQL)
774 (defcustom sql-input-ring-separator "\n--\n"
775 "Separator between commands in the history file.
777 If set to \"\\n\", each line in the history file will be interpreted as
778 one command. Multi-line commands are split into several commands when
779 the input ring is initialized from a history file.
781 This variable used to initialize `comint-input-ring-separator'.
782 `comint-input-ring-separator' is part of Emacs 21; if your Emacs
783 does not have it, setting `sql-input-ring-separator' will have no
784 effect. In that case multiline commands will be split into several
785 commands when the input history is read, as if you had set
786 `sql-input-ring-separator' to \"\\n\"."
787 :type 'string
788 :group 'SQL)
790 ;; The usual hooks
792 (defcustom sql-interactive-mode-hook '()
793 "Hook for customizing `sql-interactive-mode'."
794 :type 'hook
795 :group 'SQL)
797 (defcustom sql-mode-hook '()
798 "Hook for customizing `sql-mode'."
799 :type 'hook
800 :group 'SQL)
802 (defcustom sql-set-sqli-hook '()
803 "Hook for reacting to changes of `sql-buffer'.
805 This is called by `sql-set-sqli-buffer' when the value of `sql-buffer'
806 is changed."
807 :type 'hook
808 :group 'SQL)
810 (defcustom sql-login-hook '()
811 "Hook for interacting with a buffer in `sql-interactive-mode'.
813 This hook is invoked in a buffer once it is ready to accept input
814 for the first time."
815 :version "24.1"
816 :type 'hook
817 :group 'SQL)
819 ;; Customization for ANSI
821 (defcustom sql-ansi-statement-starters (regexp-opt '(
822 "create" "alter" "drop"
823 "select" "insert" "update" "delete" "merge"
824 "grant" "revoke"
826 "Regexp of keywords that start SQL commands
828 All products share this list; products should define a regexp to
829 identify additional keywords in a variable defined by
830 the :statement feature."
831 :version "24.1"
832 :type 'string
833 :group 'SQL)
835 ;; Customization for Oracle
837 (defcustom sql-oracle-program "sqlplus"
838 "Command to start sqlplus by Oracle.
840 Starts `sql-interactive-mode' after doing some setup.
842 On Windows, \"sqlplus\" usually starts the sqlplus \"GUI\". In order
843 to start the sqlplus console, use \"plus33\" or something similar.
844 You will find the file in your Orant\\bin directory."
845 :type 'file
846 :group 'SQL)
848 (defcustom sql-oracle-options nil
849 "List of additional options for `sql-oracle-program'."
850 :type '(repeat string)
851 :version "20.8"
852 :group 'SQL)
854 (defcustom sql-oracle-login-params '(user password database)
855 "List of login parameters needed to connect to Oracle."
856 :type 'sql-login-params
857 :version "24.1"
858 :group 'SQL)
860 (defcustom sql-oracle-statement-starters
861 (regexp-opt '("declare" "begin" "with"))
862 "Additional statement starting keywords in Oracle."
863 :version "24.1"
864 :type 'string
865 :group 'SQL)
867 (defcustom sql-oracle-scan-on t
868 "Non-nil if placeholders should be replaced in Oracle SQLi.
870 When non-nil, Emacs will scan text sent to sqlplus and prompt
871 for replacement text for & placeholders as sqlplus does. This
872 is needed on Windows where SQL*Plus output is buffered and the
873 prompts are not shown until after the text is entered.
875 You need to issue the following command in SQL*Plus to be safe:
877 SET DEFINE OFF
879 In older versions of SQL*Plus, this was the SET SCAN OFF command."
880 :version "24.1"
881 :type 'boolean
882 :group 'SQL)
884 (defcustom sql-db2-escape-newlines nil
885 "Non-nil if newlines should be escaped by a backslash in DB2 SQLi.
887 When non-nil, Emacs will automatically insert a space and
888 backslash prior to every newline in multi-line SQL statements as
889 they are submitted to an interactive DB2 session."
890 :version "24.3"
891 :type 'boolean
892 :group 'SQL)
894 ;; Customization for SQLite
896 (defcustom sql-sqlite-program (or (executable-find "sqlite3")
897 (executable-find "sqlite")
898 "sqlite")
899 "Command to start SQLite.
901 Starts `sql-interactive-mode' after doing some setup."
902 :type 'file
903 :group 'SQL)
905 (defcustom sql-sqlite-options nil
906 "List of additional options for `sql-sqlite-program'."
907 :type '(repeat string)
908 :version "20.8"
909 :group 'SQL)
911 (defcustom sql-sqlite-login-params '((database :file ".*\\.\\(db\\|sqlite[23]?\\)"))
912 "List of login parameters needed to connect to SQLite."
913 :type 'sql-login-params
914 :version "24.1"
915 :group 'SQL)
917 ;; Customization for MySQL
919 (defcustom sql-mysql-program "mysql"
920 "Command to start mysql by TcX.
922 Starts `sql-interactive-mode' after doing some setup."
923 :type 'file
924 :group 'SQL)
926 (defcustom sql-mysql-options nil
927 "List of additional options for `sql-mysql-program'.
928 The following list of options is reported to make things work
929 on Windows: \"-C\" \"-t\" \"-f\" \"-n\"."
930 :type '(repeat string)
931 :version "20.8"
932 :group 'SQL)
934 (defcustom sql-mysql-login-params '(user password database server)
935 "List of login parameters needed to connect to MySQL."
936 :type 'sql-login-params
937 :version "24.1"
938 :group 'SQL)
940 ;; Customization for Solid
942 (defcustom sql-solid-program "solsql"
943 "Command to start SOLID SQL Editor.
945 Starts `sql-interactive-mode' after doing some setup."
946 :type 'file
947 :group 'SQL)
949 (defcustom sql-solid-login-params '(user password server)
950 "List of login parameters needed to connect to Solid."
951 :type 'sql-login-params
952 :version "24.1"
953 :group 'SQL)
955 ;; Customization for Sybase
957 (defcustom sql-sybase-program "isql"
958 "Command to start isql by Sybase.
960 Starts `sql-interactive-mode' after doing some setup."
961 :type 'file
962 :group 'SQL)
964 (defcustom sql-sybase-options nil
965 "List of additional options for `sql-sybase-program'.
966 Some versions of isql might require the -n option in order to work."
967 :type '(repeat string)
968 :version "20.8"
969 :group 'SQL)
971 (defcustom sql-sybase-login-params '(server user password database)
972 "List of login parameters needed to connect to Sybase."
973 :type 'sql-login-params
974 :version "24.1"
975 :group 'SQL)
977 ;; Customization for Informix
979 (defcustom sql-informix-program "dbaccess"
980 "Command to start dbaccess by Informix.
982 Starts `sql-interactive-mode' after doing some setup."
983 :type 'file
984 :group 'SQL)
986 (defcustom sql-informix-login-params '(database)
987 "List of login parameters needed to connect to Informix."
988 :type 'sql-login-params
989 :version "24.1"
990 :group 'SQL)
992 ;; Customization for Ingres
994 (defcustom sql-ingres-program "sql"
995 "Command to start sql by Ingres.
997 Starts `sql-interactive-mode' after doing some setup."
998 :type 'file
999 :group 'SQL)
1001 (defcustom sql-ingres-login-params '(database)
1002 "List of login parameters needed to connect to Ingres."
1003 :type 'sql-login-params
1004 :version "24.1"
1005 :group 'SQL)
1007 ;; Customization for Microsoft
1009 (defcustom sql-ms-program "osql"
1010 "Command to start osql by Microsoft.
1012 Starts `sql-interactive-mode' after doing some setup."
1013 :type 'file
1014 :group 'SQL)
1016 (defcustom sql-ms-options '("-w" "300" "-n")
1017 ;; -w is the linesize
1018 "List of additional options for `sql-ms-program'."
1019 :type '(repeat string)
1020 :version "22.1"
1021 :group 'SQL)
1023 (defcustom sql-ms-login-params '(user password server database)
1024 "List of login parameters needed to connect to Microsoft."
1025 :type 'sql-login-params
1026 :version "24.1"
1027 :group 'SQL)
1029 ;; Customization for Postgres
1031 (defcustom sql-postgres-program "psql"
1032 "Command to start psql by Postgres.
1034 Starts `sql-interactive-mode' after doing some setup."
1035 :type 'file
1036 :group 'SQL)
1038 (defcustom sql-postgres-options '("-P" "pager=off")
1039 "List of additional options for `sql-postgres-program'.
1040 The default setting includes the -P option which breaks older versions
1041 of the psql client (such as version 6.5.3). The -P option is equivalent
1042 to the --pset option. If you want the psql to prompt you for a user
1043 name, add the string \"-u\" to the list of options. If you want to
1044 provide a user name on the command line (newer versions such as 7.1),
1045 add your name with a \"-U\" prefix (such as \"-Umark\") to the list."
1046 :type '(repeat string)
1047 :version "20.8"
1048 :group 'SQL)
1050 (defcustom sql-postgres-login-params `((user :default ,(user-login-name))
1051 (database :default ,(user-login-name))
1052 server)
1053 "List of login parameters needed to connect to Postgres."
1054 :type 'sql-login-params
1055 :version "24.1"
1056 :group 'SQL)
1058 ;; Customization for Interbase
1060 (defcustom sql-interbase-program "isql"
1061 "Command to start isql by Interbase.
1063 Starts `sql-interactive-mode' after doing some setup."
1064 :type 'file
1065 :group 'SQL)
1067 (defcustom sql-interbase-options nil
1068 "List of additional options for `sql-interbase-program'."
1069 :type '(repeat string)
1070 :version "20.8"
1071 :group 'SQL)
1073 (defcustom sql-interbase-login-params '(user password database)
1074 "List of login parameters needed to connect to Interbase."
1075 :type 'sql-login-params
1076 :version "24.1"
1077 :group 'SQL)
1079 ;; Customization for DB2
1081 (defcustom sql-db2-program "db2"
1082 "Command to start db2 by IBM.
1084 Starts `sql-interactive-mode' after doing some setup."
1085 :type 'file
1086 :group 'SQL)
1088 (defcustom sql-db2-options nil
1089 "List of additional options for `sql-db2-program'."
1090 :type '(repeat string)
1091 :version "20.8"
1092 :group 'SQL)
1094 (defcustom sql-db2-login-params nil
1095 "List of login parameters needed to connect to DB2."
1096 :type 'sql-login-params
1097 :version "24.1"
1098 :group 'SQL)
1100 ;; Customization for Linter
1102 (defcustom sql-linter-program "inl"
1103 "Command to start inl by RELEX.
1105 Starts `sql-interactive-mode' after doing some setup."
1106 :type 'file
1107 :group 'SQL)
1109 (defcustom sql-linter-options nil
1110 "List of additional options for `sql-linter-program'."
1111 :type '(repeat string)
1112 :version "21.3"
1113 :group 'SQL)
1115 (defcustom sql-linter-login-params '(user password database server)
1116 "Login parameters to needed to connect to Linter."
1117 :type 'sql-login-params
1118 :version "24.1"
1119 :group 'SQL)
1123 ;;; Variables which do not need customization
1125 (defvar sql-user-history nil
1126 "History of usernames used.")
1128 (defvar sql-database-history nil
1129 "History of databases used.")
1131 (defvar sql-server-history nil
1132 "History of servers used.")
1134 ;; Passwords are not kept in a history.
1136 (defvar sql-product-history nil
1137 "History of products used.")
1139 (defvar sql-connection-history nil
1140 "History of connections used.")
1142 (defvar sql-buffer nil
1143 "Current SQLi buffer.
1145 The global value of `sql-buffer' is the name of the latest SQLi buffer
1146 created. Any SQL buffer created will make a local copy of this value.
1147 See `sql-interactive-mode' for more on multiple sessions. If you want
1148 to change the SQLi buffer a SQL mode sends its SQL strings to, change
1149 the local value of `sql-buffer' using \\[sql-set-sqli-buffer].")
1151 (defvar sql-prompt-regexp nil
1152 "Prompt used to initialize `comint-prompt-regexp'.
1154 You can change `sql-prompt-regexp' on `sql-interactive-mode-hook'.")
1156 (defvar sql-prompt-length 0
1157 "Prompt used to set `left-margin' in `sql-interactive-mode'.
1159 You can change `sql-prompt-length' on `sql-interactive-mode-hook'.")
1161 (defvar sql-prompt-cont-regexp nil
1162 "Prompt pattern of statement continuation prompts.")
1164 (defvar sql-alternate-buffer-name nil
1165 "Buffer-local string used to possibly rename the SQLi buffer.
1167 Used by `sql-rename-buffer'.")
1169 (defun sql-buffer-live-p (buffer &optional product connection)
1170 "Returns non-nil if the process associated with buffer is live.
1172 BUFFER can be a buffer object or a buffer name. The buffer must
1173 be a live buffer, have an running process attached to it, be in
1174 `sql-interactive-mode', and, if PRODUCT or CONNECTION are
1175 specified, it's `sql-product' or `sql-connection' must match."
1177 (when buffer
1178 (setq buffer (get-buffer buffer))
1179 (and buffer
1180 (buffer-live-p buffer)
1181 (get-buffer-process buffer)
1182 (comint-check-proc buffer)
1183 (with-current-buffer buffer
1184 (and (derived-mode-p 'sql-interactive-mode)
1185 (or (not product)
1186 (eq product sql-product))
1187 (or (not connection)
1188 (eq connection sql-connection)))))))
1190 ;; Keymap for sql-interactive-mode.
1192 (defvar sql-interactive-mode-map
1193 (let ((map (make-sparse-keymap)))
1194 (if (fboundp 'set-keymap-parent)
1195 (set-keymap-parent map comint-mode-map); Emacs
1196 (if (fboundp 'set-keymap-parents)
1197 (set-keymap-parents map (list comint-mode-map)))); XEmacs
1198 (if (fboundp 'set-keymap-name)
1199 (set-keymap-name map 'sql-interactive-mode-map)); XEmacs
1200 (define-key map (kbd "C-j") 'sql-accumulate-and-indent)
1201 (define-key map (kbd "C-c C-w") 'sql-copy-column)
1202 (define-key map (kbd "O") 'sql-magic-go)
1203 (define-key map (kbd "o") 'sql-magic-go)
1204 (define-key map (kbd ";") 'sql-magic-semicolon)
1205 (define-key map (kbd "C-c C-l a") 'sql-list-all)
1206 (define-key map (kbd "C-c C-l t") 'sql-list-table)
1207 map)
1208 "Mode map used for `sql-interactive-mode'.
1209 Based on `comint-mode-map'.")
1211 ;; Keymap for sql-mode.
1213 (defvar sql-mode-map
1214 (let ((map (make-sparse-keymap)))
1215 (define-key map (kbd "C-c C-c") 'sql-send-paragraph)
1216 (define-key map (kbd "C-c C-r") 'sql-send-region)
1217 (define-key map (kbd "C-c C-s") 'sql-send-string)
1218 (define-key map (kbd "C-c C-b") 'sql-send-buffer)
1219 (define-key map (kbd "C-c C-i") 'sql-product-interactive)
1220 (define-key map (kbd "C-c C-l a") 'sql-list-all)
1221 (define-key map (kbd "C-c C-l t") 'sql-list-table)
1222 (define-key map [remap beginning-of-defun] 'sql-beginning-of-statement)
1223 (define-key map [remap end-of-defun] 'sql-end-of-statement)
1224 map)
1225 "Mode map used for `sql-mode'.")
1227 ;; easy menu for sql-mode.
1229 (easy-menu-define
1230 sql-mode-menu sql-mode-map
1231 "Menu for `sql-mode'."
1232 `("SQL"
1233 ["Send Paragraph" sql-send-paragraph (sql-buffer-live-p sql-buffer)]
1234 ["Send Region" sql-send-region (and mark-active
1235 (sql-buffer-live-p sql-buffer))]
1236 ["Send Buffer" sql-send-buffer (sql-buffer-live-p sql-buffer)]
1237 ["Send String" sql-send-string (sql-buffer-live-p sql-buffer)]
1238 "--"
1239 ["List all objects" sql-list-all (and (sql-buffer-live-p sql-buffer)
1240 (sql-get-product-feature sql-product :list-all))]
1241 ["List table details" sql-list-table (and (sql-buffer-live-p sql-buffer)
1242 (sql-get-product-feature sql-product :list-table))]
1243 "--"
1244 ["Start SQLi session" sql-product-interactive
1245 :visible (not sql-connection-alist)
1246 :enable (sql-get-product-feature sql-product :sqli-comint-func)]
1247 ("Start..."
1248 :visible sql-connection-alist
1249 :filter sql-connection-menu-filter
1250 "--"
1251 ["New SQLi Session" sql-product-interactive (sql-get-product-feature sql-product :sqli-comint-func)])
1252 ["--"
1253 :visible sql-connection-alist]
1254 ["Show SQLi buffer" sql-show-sqli-buffer t]
1255 ["Set SQLi buffer" sql-set-sqli-buffer t]
1256 ["Pop to SQLi buffer after send"
1257 sql-toggle-pop-to-buffer-after-send-region
1258 :style toggle
1259 :selected sql-pop-to-buffer-after-send-region]
1260 ["--" nil nil]
1261 ("Product"
1262 ,@(mapcar (lambda (prod-info)
1263 (let* ((prod (pop prod-info))
1264 (name (or (plist-get prod-info :name)
1265 (capitalize (symbol-name prod))))
1266 (cmd (intern (format "sql-highlight-%s-keywords" prod))))
1267 (fset cmd `(lambda () ,(format "Highlight %s SQL keywords." name)
1268 (interactive)
1269 (sql-set-product ',prod)))
1270 (vector name cmd
1271 :style 'radio
1272 :selected `(eq sql-product ',prod))))
1273 sql-product-alist))))
1275 ;; easy menu for sql-interactive-mode.
1277 (easy-menu-define
1278 sql-interactive-mode-menu sql-interactive-mode-map
1279 "Menu for `sql-interactive-mode'."
1280 '("SQL"
1281 ["Rename Buffer" sql-rename-buffer t]
1282 ["Save Connection" sql-save-connection (not sql-connection)]
1283 "--"
1284 ["List all objects" sql-list-all (sql-get-product-feature sql-product :list-all)]
1285 ["List table details" sql-list-table (sql-get-product-feature sql-product :list-table)]))
1287 ;; Abbreviations -- if you want more of them, define them in your init
1288 ;; file. Abbrevs have to be enabled in your init file, too.
1290 (defvar sql-mode-abbrev-table nil
1291 "Abbrev table used in `sql-mode' and `sql-interactive-mode'.")
1292 (unless sql-mode-abbrev-table
1293 (define-abbrev-table 'sql-mode-abbrev-table nil))
1295 (mapc
1296 ;; In Emacs 22+, provide SYSTEM-FLAG to define-abbrev.
1297 (lambda (abbrev)
1298 (let ((name (car abbrev))
1299 (expansion (cdr abbrev)))
1300 (condition-case nil
1301 (define-abbrev sql-mode-abbrev-table name expansion nil 0 t)
1302 (error
1303 (define-abbrev sql-mode-abbrev-table name expansion)))))
1304 '(("ins" . "insert")
1305 ("upd" . "update")
1306 ("del" . "delete")
1307 ("sel" . "select")
1308 ("proc" . "procedure")
1309 ("func" . "function")
1310 ("cr" . "create")))
1312 ;; Syntax Table
1314 (defvar sql-mode-syntax-table
1315 (let ((table (make-syntax-table)))
1316 ;; C-style comments /**/ (see elisp manual "Syntax Flags"))
1317 (modify-syntax-entry ?/ ". 14" table)
1318 (modify-syntax-entry ?* ". 23" table)
1319 ;; double-dash starts comments
1320 (modify-syntax-entry ?- ". 12b" table)
1321 ;; newline and formfeed end comments
1322 (modify-syntax-entry ?\n "> b" table)
1323 (modify-syntax-entry ?\f "> b" table)
1324 ;; single quotes (') delimit strings
1325 (modify-syntax-entry ?' "\"" table)
1326 ;; double quotes (") don't delimit strings
1327 (modify-syntax-entry ?\" "." table)
1328 ;; Make these all punctuation
1329 (mapc (lambda (c) (modify-syntax-entry c "." table))
1330 (string-to-list "!#$%&+,.:;<=>?@\\|"))
1331 table)
1332 "Syntax table used in `sql-mode' and `sql-interactive-mode'.")
1334 ;; Font lock support
1336 (defvar sql-mode-font-lock-object-name
1337 (eval-when-compile
1338 (list (concat "^\\s-*\\(?:create\\|drop\\|alter\\)\\s-+" ;; lead off with CREATE, DROP or ALTER
1339 "\\(?:\\w+\\s-+\\)*" ;; optional intervening keywords
1340 "\\(?:table\\|view\\|\\(?:package\\|type\\)\\(?:\\s-+body\\)?\\|proc\\(?:edure\\)?"
1341 "\\|function\\|trigger\\|sequence\\|rule\\|default\\)\\s-+"
1342 "\\(\\w+\\)")
1343 1 'font-lock-function-name-face))
1345 "Pattern to match the names of top-level objects.
1347 The pattern matches the name in a CREATE, DROP or ALTER
1348 statement. The format of variable should be a valid
1349 `font-lock-keywords' entry.")
1351 ;; While there are international and American standards for SQL, they
1352 ;; are not followed closely, and most vendors offer significant
1353 ;; capabilities beyond those defined in the standard specifications.
1355 ;; SQL mode provides support for highlighting based on the product. In
1356 ;; addition to highlighting the product keywords, any ANSI keywords not
1357 ;; used by the product are also highlighted. This will help identify
1358 ;; keywords that could be restricted in future versions of the product
1359 ;; or might be a problem if ported to another product.
1361 ;; To reduce the complexity and size of the regular expressions
1362 ;; generated to match keywords, ANSI keywords are filtered out of
1363 ;; product keywords if they are equivalent. To do this, we define a
1364 ;; function `sql-font-lock-keywords-builder' that removes any keywords
1365 ;; that are matched by the ANSI patterns and results in the same face
1366 ;; being applied. For this to work properly, we must play some games
1367 ;; with the execution and compile time behavior. This code is a
1368 ;; little tricky but works properly.
1370 ;; When defining the keywords for individual products you should
1371 ;; include all of the keywords that you want matched. The filtering
1372 ;; against the ANSI keywords will be automatic if you use the
1373 ;; `sql-font-lock-keywords-builder' function and follow the
1374 ;; implementation pattern used for the other products in this file.
1376 (eval-when-compile
1377 (defvar sql-mode-ansi-font-lock-keywords)
1378 (setq sql-mode-ansi-font-lock-keywords nil))
1380 (eval-and-compile
1381 (defun sql-font-lock-keywords-builder (face boundaries &rest keywords)
1382 "Generation of regexp matching any one of KEYWORDS."
1384 (let ((bdy (or boundaries '("\\b" . "\\b")))
1385 kwd)
1387 ;; Remove keywords that are defined in ANSI
1388 (setq kwd keywords)
1389 ;; (dolist (k keywords)
1390 ;; (catch 'next
1391 ;; (dolist (a sql-mode-ansi-font-lock-keywords)
1392 ;; (when (and (eq face (cdr a))
1393 ;; (eq (string-match (car a) k 0) 0)
1394 ;; (eq (match-end 0) (length k)))
1395 ;; (setq kwd (delq k kwd))
1396 ;; (throw 'next nil)))))
1398 ;; Create a properly formed font-lock-keywords item
1399 (cons (concat (car bdy)
1400 (regexp-opt kwd t)
1401 (cdr bdy))
1402 face)))
1404 (defun sql-regexp-abbrev (keyword)
1405 (let ((brk (string-match "[~]" keyword))
1406 (len (length keyword))
1407 (sep "\\(?:")
1408 re i)
1409 (if (not brk)
1410 keyword
1411 (setq re (substring keyword 0 brk)
1412 i (+ 2 brk)
1413 brk (1+ brk))
1414 (while (<= i len)
1415 (setq re (concat re sep (substring keyword brk i))
1416 sep "\\|"
1417 i (1+ i)))
1418 (concat re "\\)?"))))
1420 (defun sql-regexp-abbrev-list (&rest keyw-list)
1421 (let ((re nil)
1422 (sep "\\<\\(?:"))
1423 (while keyw-list
1424 (setq re (concat re sep (sql-regexp-abbrev (car keyw-list)))
1425 sep "\\|"
1426 keyw-list (cdr keyw-list)))
1427 (concat re "\\)\\>"))))
1429 (eval-when-compile
1430 (setq sql-mode-ansi-font-lock-keywords
1431 (list
1432 ;; ANSI Non Reserved keywords
1433 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1434 "ada" "asensitive" "assignment" "asymmetric" "atomic" "between"
1435 "bitvar" "called" "catalog_name" "chain" "character_set_catalog"
1436 "character_set_name" "character_set_schema" "checked" "class_origin"
1437 "cobol" "collation_catalog" "collation_name" "collation_schema"
1438 "column_name" "command_function" "command_function_code" "committed"
1439 "condition_number" "connection_name" "constraint_catalog"
1440 "constraint_name" "constraint_schema" "contains" "cursor_name"
1441 "datetime_interval_code" "datetime_interval_precision" "defined"
1442 "definer" "dispatch" "dynamic_function" "dynamic_function_code"
1443 "existing" "exists" "final" "fortran" "generated" "granted"
1444 "hierarchy" "hold" "implementation" "infix" "insensitive" "instance"
1445 "instantiable" "invoker" "key_member" "key_type" "length" "m"
1446 "message_length" "message_octet_length" "message_text" "method" "more"
1447 "mumps" "name" "nullable" "number" "options" "overlaps" "overriding"
1448 "parameter_mode" "parameter_name" "parameter_ordinal_position"
1449 "parameter_specific_catalog" "parameter_specific_name"
1450 "parameter_specific_schema" "pascal" "pli" "position" "repeatable"
1451 "returned_length" "returned_octet_length" "returned_sqlstate"
1452 "routine_catalog" "routine_name" "routine_schema" "row_count" "scale"
1453 "schema_name" "security" "self" "sensitive" "serializable"
1454 "server_name" "similar" "simple" "source" "specific_name" "style"
1455 "subclass_origin" "sublist" "symmetric" "system" "table_name"
1456 "transaction_active" "transactions_committed"
1457 "transactions_rolled_back" "transform" "transforms" "trigger_catalog"
1458 "trigger_name" "trigger_schema" "type" "uncommitted" "unnamed"
1459 "user_defined_type_catalog" "user_defined_type_name"
1460 "user_defined_type_schema"
1463 ;; ANSI Reserved keywords
1464 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1465 "absolute" "action" "add" "admin" "after" "aggregate" "alias" "all"
1466 "allocate" "alter" "and" "any" "are" "as" "asc" "assertion" "at"
1467 "authorization" "before" "begin" "both" "breadth" "by" "call"
1468 "cascade" "cascaded" "case" "catalog" "check" "class" "close"
1469 "collate" "collation" "column" "commit" "completion" "connect"
1470 "connection" "constraint" "constraints" "constructor" "continue"
1471 "corresponding" "create" "cross" "cube" "current" "cursor" "cycle"
1472 "data" "day" "deallocate" "declare" "default" "deferrable" "deferred"
1473 "delete" "depth" "deref" "desc" "describe" "descriptor" "destroy"
1474 "destructor" "deterministic" "diagnostics" "dictionary" "disconnect"
1475 "distinct" "domain" "drop" "dynamic" "each" "else" "end" "equals"
1476 "escape" "every" "except" "exception" "exec" "execute" "external"
1477 "false" "fetch" "first" "for" "foreign" "found" "free" "from" "full"
1478 "function" "general" "get" "global" "go" "goto" "grant" "group"
1479 "grouping" "having" "host" "hour" "identity" "ignore" "immediate" "in"
1480 "indicator" "initialize" "initially" "inner" "inout" "input" "insert"
1481 "intersect" "into" "is" "isolation" "iterate" "join" "key" "language"
1482 "last" "lateral" "leading" "left" "less" "level" "like" "limit"
1483 "local" "locator" "map" "match" "minute" "modifies" "modify" "module"
1484 "month" "names" "natural" "new" "next" "no" "none" "not" "null" "of"
1485 "off" "old" "on" "only" "open" "operation" "option" "or" "order"
1486 "ordinality" "out" "outer" "output" "pad" "parameter" "parameters"
1487 "partial" "path" "postfix" "prefix" "preorder" "prepare" "preserve"
1488 "primary" "prior" "privileges" "procedure" "public" "read" "reads"
1489 "recursive" "references" "referencing" "relative" "restrict" "result"
1490 "return" "returns" "revoke" "right" "role" "rollback" "rollup"
1491 "routine" "rows" "savepoint" "schema" "scroll" "search" "second"
1492 "section" "select" "sequence" "session" "set" "sets" "size" "some"
1493 "space" "specific" "specifictype" "sql" "sqlexception" "sqlstate"
1494 "sqlwarning" "start" "state" "statement" "static" "structure" "table"
1495 "temporary" "terminate" "than" "then" "timezone_hour"
1496 "timezone_minute" "to" "trailing" "transaction" "translation"
1497 "trigger" "true" "under" "union" "unique" "unknown" "unnest" "update"
1498 "usage" "using" "value" "values" "variable" "view" "when" "whenever"
1499 "where" "with" "without" "work" "write" "year"
1502 ;; ANSI Functions
1503 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1504 "abs" "avg" "bit_length" "cardinality" "cast" "char_length"
1505 "character_length" "coalesce" "convert" "count" "current_date"
1506 "current_path" "current_role" "current_time" "current_timestamp"
1507 "current_user" "extract" "localtime" "localtimestamp" "lower" "max"
1508 "min" "mod" "nullif" "octet_length" "overlay" "placing" "session_user"
1509 "substring" "sum" "system_user" "translate" "treat" "trim" "upper"
1510 "user"
1513 ;; ANSI Data Types
1514 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1515 "array" "binary" "bit" "blob" "boolean" "char" "character" "clob"
1516 "date" "dec" "decimal" "double" "float" "int" "integer" "interval"
1517 "large" "national" "nchar" "nclob" "numeric" "object" "precision"
1518 "real" "ref" "row" "scope" "smallint" "time" "timestamp" "varchar"
1519 "varying" "zone"
1520 ))))
1522 (defvar sql-mode-ansi-font-lock-keywords
1523 (eval-when-compile sql-mode-ansi-font-lock-keywords)
1524 "ANSI SQL keywords used by font-lock.
1526 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1527 regular expressions are created during compilation by calling the
1528 function `regexp-opt'. Therefore, take a look at the source before
1529 you define your own `sql-mode-ansi-font-lock-keywords'. You may want
1530 to add functions and PL/SQL keywords.")
1532 (defun sql-oracle-show-reserved-words ()
1533 ;; This function is for use by the maintainer of SQL.EL only.
1534 (interactive)
1535 (if (or (and (not (derived-mode-p 'sql-mode))
1536 (not (derived-mode-p 'sql-interactive-mode)))
1537 (not sql-buffer)
1538 (not (eq sql-product 'oracle)))
1539 (error "Not an Oracle buffer")
1541 (let ((b "*RESERVED WORDS*"))
1542 (sql-execute sql-buffer b
1543 (concat "SELECT "
1544 " keyword "
1545 ", reserved AS \"Res\" "
1546 ", res_type AS \"Type\" "
1547 ", res_attr AS \"Attr\" "
1548 ", res_semi AS \"Semi\" "
1549 ", duplicate AS \"Dup\" "
1550 "FROM V$RESERVED_WORDS "
1551 "WHERE length > 1 "
1552 "AND SUBSTR(keyword, 1, 1) BETWEEN 'A' AND 'Z' "
1553 "ORDER BY 2 DESC, 3 DESC, 4 DESC, 5 DESC, 6 DESC, 1;")
1554 nil nil)
1555 (with-current-buffer b
1556 (set (make-local-variable 'sql-product) 'oracle)
1557 (sql-product-font-lock t nil)
1558 (font-lock-mode +1)))))
1560 (defvar sql-mode-oracle-font-lock-keywords
1561 (eval-when-compile
1562 (list
1563 ;; Oracle SQL*Plus Commands
1564 ;; Only recognized in they start in column 1 and the
1565 ;; abbreviation is followed by a space or the end of line.
1567 "\\|"
1568 (list (concat "^" (sql-regexp-abbrev "rem~ark") "\\(?:\\s-.*\\)?$")
1569 0 'font-lock-comment-face t)
1571 (list
1572 (concat
1573 "^\\(?:"
1574 (sql-regexp-abbrev-list
1575 "[@]\\{1,2\\}" "acc~ept" "a~ppend" "archive" "attribute"
1576 "bre~ak" "bti~tle" "c~hange" "cl~ear" "col~umn" "conn~ect"
1577 "copy" "def~ine" "del" "desc~ribe" "disc~onnect" "ed~it"
1578 "exec~ute" "exit" "get" "help" "ho~st" "[$]" "i~nput" "l~ist"
1579 "passw~ord" "pau~se" "pri~nt" "pro~mpt" "quit" "recover"
1580 "repf~ooter" "reph~eader" "r~un" "sav~e" "sho~w" "shutdown"
1581 "spo~ol" "sta~rt" "startup" "store" "tim~ing" "tti~tle"
1582 "undef~ine" "var~iable" "whenever")
1583 "\\|"
1584 (concat "\\(?:"
1585 (sql-regexp-abbrev "comp~ute")
1586 "\\s-+"
1587 (sql-regexp-abbrev-list
1588 "avg" "cou~nt" "min~imum" "max~imum" "num~ber" "sum"
1589 "std" "var~iance")
1590 "\\)")
1591 "\\|"
1592 (concat "\\(?:set\\s-+"
1593 (sql-regexp-abbrev-list
1594 "appi~nfo" "array~size" "auto~commit" "autop~rint"
1595 "autorecovery" "autot~race" "blo~ckterminator"
1596 "cmds~ep" "colsep" "com~patibility" "con~cat"
1597 "copyc~ommit" "copytypecheck" "def~ine" "describe"
1598 "echo" "editf~ile" "emb~edded" "esc~ape" "feed~back"
1599 "flagger" "flu~sh" "hea~ding" "heads~ep" "instance"
1600 "lin~esize" "lobof~fset" "long" "longc~hunksize"
1601 "mark~up" "newp~age" "null" "numf~ormat" "num~width"
1602 "pages~ize" "pau~se" "recsep" "recsepchar"
1603 "scan" "serverout~put" "shift~inout" "show~mode"
1604 "sqlbl~anklines" "sqlc~ase" "sqlco~ntinue"
1605 "sqln~umber" "sqlpluscompat~ibility" "sqlpre~fix"
1606 "sqlp~rompt" "sqlt~erminator" "suf~fix" "tab"
1607 "term~out" "ti~me" "timi~ng" "trim~out" "trims~pool"
1608 "und~erline" "ver~ify" "wra~p")
1609 "\\)")
1611 "\\)\\(?:\\s-.*\\)?\\(?:[-]\n.*\\)*$")
1612 0 'font-lock-doc-face t)
1614 ;; Oracle Functions
1615 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1616 "abs" "acos" "add_months" "appendchildxml" "ascii" "asciistr" "asin"
1617 "atan" "atan2" "avg" "bfilename" "bin_to_num" "bitand" "cardinality"
1618 "cast" "ceil" "chartorowid" "chr" "cluster_id" "cluster_probability"
1619 "cluster_set" "coalesce" "collect" "compose" "concat" "convert" "corr"
1620 "connect_by_root" "connect_by_iscycle" "connect_by_isleaf"
1621 "corr_k" "corr_s" "cos" "cosh" "count" "covar_pop" "covar_samp"
1622 "cube_table" "cume_dist" "current_date" "current_timestamp" "cv"
1623 "dataobj_to_partition" "dbtimezone" "decode" "decompose" "deletexml"
1624 "dense_rank" "depth" "deref" "dump" "empty_blob" "empty_clob"
1625 "existsnode" "exp" "extract" "extractvalue" "feature_id" "feature_set"
1626 "feature_value" "first" "first_value" "floor" "from_tz" "greatest"
1627 "grouping" "grouping_id" "group_id" "hextoraw" "initcap"
1628 "insertchildxml" "insertchildxmlafter" "insertchildxmlbefore"
1629 "insertxmlafter" "insertxmlbefore" "instr" "instr2" "instr4" "instrb"
1630 "instrc" "iteration_number" "lag" "last" "last_day" "last_value"
1631 "lead" "least" "length" "length2" "length4" "lengthb" "lengthc"
1632 "listagg" "ln" "lnnvl" "localtimestamp" "log" "lower" "lpad" "ltrim"
1633 "make_ref" "max" "median" "min" "mod" "months_between" "nanvl" "nchr"
1634 "new_time" "next_day" "nlssort" "nls_charset_decl_len"
1635 "nls_charset_id" "nls_charset_name" "nls_initcap" "nls_lower"
1636 "nls_upper" "nth_value" "ntile" "nullif" "numtodsinterval"
1637 "numtoyminterval" "nvl" "nvl2" "ora_dst_affected" "ora_dst_convert"
1638 "ora_dst_error" "ora_hash" "path" "percentile_cont" "percentile_disc"
1639 "percent_rank" "power" "powermultiset" "powermultiset_by_cardinality"
1640 "prediction" "prediction_bounds" "prediction_cost"
1641 "prediction_details" "prediction_probability" "prediction_set"
1642 "presentnnv" "presentv" "previous" "rank" "ratio_to_report" "rawtohex"
1643 "rawtonhex" "ref" "reftohex" "regexp_count" "regexp_instr"
1644 "regexp_replace" "regexp_substr" "regr_avgx" "regr_avgy" "regr_count"
1645 "regr_intercept" "regr_r2" "regr_slope" "regr_sxx" "regr_sxy"
1646 "regr_syy" "remainder" "replace" "round" "rowidtochar" "rowidtonchar"
1647 "row_number" "rpad" "rtrim" "scn_to_timestamp" "sessiontimezone" "set"
1648 "sign" "sin" "sinh" "soundex" "sqrt" "stats_binomial_test"
1649 "stats_crosstab" "stats_f_test" "stats_ks_test" "stats_mode"
1650 "stats_mw_test" "stats_one_way_anova" "stats_t_test_indep"
1651 "stats_t_test_indepu" "stats_t_test_one" "stats_t_test_paired"
1652 "stats_wsr_test" "stddev" "stddev_pop" "stddev_samp" "substr"
1653 "substr2" "substr4" "substrb" "substrc" "sum" "sysdate" "systimestamp"
1654 "sys_connect_by_path" "sys_context" "sys_dburigen" "sys_extract_utc"
1655 "sys_guid" "sys_typeid" "sys_xmlagg" "sys_xmlgen" "tan" "tanh"
1656 "timestamp_to_scn" "to_binary_double" "to_binary_float" "to_blob"
1657 "to_char" "to_clob" "to_date" "to_dsinterval" "to_lob" "to_multi_byte"
1658 "to_nchar" "to_nclob" "to_number" "to_single_byte" "to_timestamp"
1659 "to_timestamp_tz" "to_yminterval" "translate" "treat" "trim" "trunc"
1660 "tz_offset" "uid" "unistr" "updatexml" "upper" "user" "userenv"
1661 "value" "variance" "var_pop" "var_samp" "vsize" "width_bucket"
1662 "xmlagg" "xmlcast" "xmlcdata" "xmlcolattval" "xmlcomment" "xmlconcat"
1663 "xmldiff" "xmlelement" "xmlexists" "xmlforest" "xmlisvalid" "xmlparse"
1664 "xmlpatch" "xmlpi" "xmlquery" "xmlroot" "xmlsequence" "xmlserialize"
1665 "xmltable" "xmltransform"
1668 ;; See the table V$RESERVED_WORDS
1669 ;; Oracle Keywords
1670 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1671 "abort" "access" "accessed" "account" "activate" "add" "admin"
1672 "advise" "after" "agent" "aggregate" "all" "allocate" "allow" "alter"
1673 "always" "analyze" "ancillary" "and" "any" "apply" "archive"
1674 "archivelog" "array" "as" "asc" "associate" "at" "attribute"
1675 "attributes" "audit" "authenticated" "authid" "authorization" "auto"
1676 "autoallocate" "automatic" "availability" "backup" "before" "begin"
1677 "behalf" "between" "binding" "bitmap" "block" "blocksize" "body"
1678 "both" "buffer_pool" "build" "by" "cache" "call" "cancel"
1679 "cascade" "case" "category" "certificate" "chained" "change" "check"
1680 "checkpoint" "child" "chunk" "class" "clear" "clone" "close" "cluster"
1681 "column" "column_value" "columns" "comment" "commit" "committed"
1682 "compatibility" "compile" "complete" "composite_limit" "compress"
1683 "compute" "connect" "connect_time" "consider" "consistent"
1684 "constraint" "constraints" "constructor" "contents" "context"
1685 "continue" "controlfile" "corruption" "cost" "cpu_per_call"
1686 "cpu_per_session" "create" "cross" "cube" "current" "currval" "cycle"
1687 "dangling" "data" "database" "datafile" "datafiles" "day" "ddl"
1688 "deallocate" "debug" "default" "deferrable" "deferred" "definer"
1689 "delay" "delete" "demand" "desc" "determines" "deterministic"
1690 "dictionary" "dimension" "directory" "disable" "disassociate"
1691 "disconnect" "distinct" "distinguished" "distributed" "dml" "drop"
1692 "each" "element" "else" "enable" "end" "equals_path" "escape"
1693 "estimate" "except" "exceptions" "exchange" "excluding" "exists"
1694 "expire" "explain" "extent" "external" "externally"
1695 "failed_login_attempts" "fast" "file" "final" "finish" "flush" "for"
1696 "force" "foreign" "freelist" "freelists" "freepools" "fresh" "from"
1697 "full" "function" "functions" "generated" "global" "global_name"
1698 "globally" "grant" "group" "grouping" "groups" "guard" "hash"
1699 "hashkeys" "having" "heap" "hierarchy" "id" "identified" "identifier"
1700 "idle_time" "immediate" "in" "including" "increment" "index" "indexed"
1701 "indexes" "indextype" "indextypes" "indicator" "initial" "initialized"
1702 "initially" "initrans" "inner" "insert" "instance" "instantiable"
1703 "instead" "intersect" "into" "invalidate" "is" "isolation" "java"
1704 "join" "keep" "key" "kill" "language" "left" "less" "level"
1705 "levels" "library" "like" "like2" "like4" "likec" "limit" "link"
1706 "list" "lob" "local" "location" "locator" "lock" "log" "logfile"
1707 "logging" "logical" "logical_reads_per_call"
1708 "logical_reads_per_session" "managed" "management" "manual" "map"
1709 "mapping" "master" "matched" "materialized" "maxdatafiles"
1710 "maxextents" "maximize" "maxinstances" "maxlogfiles" "maxloghistory"
1711 "maxlogmembers" "maxsize" "maxtrans" "maxvalue" "member" "memory"
1712 "merge" "migrate" "minextents" "minimize" "minimum" "minus" "minvalue"
1713 "mode" "modify" "monitoring" "month" "mount" "move" "movement" "name"
1714 "named" "natural" "nested" "never" "new" "next" "nextval" "no"
1715 "noarchivelog" "noaudit" "nocache" "nocompress" "nocopy" "nocycle"
1716 "nodelay" "noforce" "nologging" "nomapping" "nomaxvalue" "nominimize"
1717 "nominvalue" "nomonitoring" "none" "noorder" "noparallel" "norely"
1718 "noresetlogs" "noreverse" "normal" "norowdependencies" "nosort"
1719 "noswitch" "not" "nothing" "notimeout" "novalidate" "nowait" "null"
1720 "nulls" "object" "of" "off" "offline" "oidindex" "old" "on" "online"
1721 "only" "open" "operator" "optimal" "option" "or" "order"
1722 "organization" "out" "outer" "outline" "overflow" "overriding"
1723 "package" "packages" "parallel" "parallel_enable" "parameters"
1724 "parent" "partition" "partitions" "password" "password_grace_time"
1725 "password_life_time" "password_lock_time" "password_reuse_max"
1726 "password_reuse_time" "password_verify_function" "pctfree"
1727 "pctincrease" "pctthreshold" "pctused" "pctversion" "percent"
1728 "performance" "permanent" "pfile" "physical" "pipelined" "plan"
1729 "post_transaction" "pragma" "prebuilt" "preserve" "primary" "private"
1730 "private_sga" "privileges" "procedure" "profile" "protection" "public"
1731 "purge" "query" "quiesce" "quota" "range" "read" "reads" "rebuild"
1732 "records_per_block" "recover" "recovery" "recycle" "reduced" "ref"
1733 "references" "referencing" "refresh" "register" "reject" "relational"
1734 "rely" "rename" "reset" "resetlogs" "resize" "resolve" "resolver"
1735 "resource" "restrict" "restrict_references" "restricted" "result"
1736 "resumable" "resume" "retention" "return" "returning" "reuse"
1737 "reverse" "revoke" "rewrite" "right" "rnds" "rnps" "role" "roles"
1738 "rollback" "rollup" "row" "rowdependencies" "rownum" "rows" "sample"
1739 "savepoint" "scan" "schema" "scn" "scope" "segment" "select"
1740 "selectivity" "self" "sequence" "serializable" "session"
1741 "sessions_per_user" "set" "sets" "settings" "shared" "shared_pool"
1742 "shrink" "shutdown" "siblings" "sid" "single" "size" "skip" "some"
1743 "sort" "source" "space" "specification" "spfile" "split" "standby"
1744 "start" "statement_id" "static" "statistics" "stop" "storage" "store"
1745 "structure" "subpartition" "subpartitions" "substitutable"
1746 "successful" "supplemental" "suspend" "switch" "switchover" "synonym"
1747 "sys" "system" "table" "tables" "tablespace" "tempfile" "template"
1748 "temporary" "test" "than" "then" "thread" "through" "time_zone"
1749 "timeout" "to" "trace" "transaction" "trigger" "triggers" "truncate"
1750 "trust" "type" "types" "unarchived" "under" "under_path" "undo"
1751 "uniform" "union" "unique" "unlimited" "unlock" "unquiesce"
1752 "unrecoverable" "until" "unusable" "unused" "update" "upgrade" "usage"
1753 "use" "using" "validate" "validation" "value" "values" "variable"
1754 "varray" "version" "view" "wait" "when" "whenever" "where" "with"
1755 "without" "wnds" "wnps" "work" "write" "xmldata" "xmlschema" "xmltype"
1758 ;; Oracle Data Types
1759 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1760 "bfile" "binary_double" "binary_float" "blob" "byte" "char" "charbyte"
1761 "clob" "date" "day" "float" "interval" "local" "long" "longraw"
1762 "minute" "month" "nchar" "nclob" "number" "nvarchar2" "raw" "rowid" "second"
1763 "time" "timestamp" "urowid" "varchar2" "with" "year" "zone"
1766 ;; Oracle PL/SQL Attributes
1767 (sql-font-lock-keywords-builder 'font-lock-builtin-face '("%" . "\\b")
1768 "bulk_exceptions" "bulk_rowcount" "found" "isopen" "notfound"
1769 "rowcount" "rowtype" "type"
1772 ;; Oracle PL/SQL Functions
1773 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1774 "delete" "trim" "extend" "exists" "first" "last" "count" "limit"
1775 "prior" "next"
1778 ;; Oracle PL/SQL Reserved words
1779 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1780 "all" "alter" "and" "any" "as" "asc" "at" "begin" "between" "by"
1781 "case" "check" "clusters" "cluster" "colauth" "columns" "compress"
1782 "connect" "crash" "create" "cursor" "declare" "default" "desc"
1783 "distinct" "drop" "else" "end" "exception" "exclusive" "fetch" "for"
1784 "from" "function" "goto" "grant" "group" "having" "identified" "if"
1785 "in" "index" "indexes" "insert" "intersect" "into" "is" "like" "lock"
1786 "minus" "mode" "nocompress" "not" "nowait" "null" "of" "on" "option"
1787 "or" "order" "overlaps" "procedure" "public" "resource" "revoke"
1788 "select" "share" "size" "sql" "start" "subtype" "tabauth" "table"
1789 "then" "to" "type" "union" "unique" "update" "values" "view" "views"
1790 "when" "where" "with"
1792 "true" "false"
1793 "raise_application_error"
1796 ;; Oracle PL/SQL Keywords
1797 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1798 "a" "add" "agent" "aggregate" "array" "attribute" "authid" "avg"
1799 "bfile_base" "binary" "blob_base" "block" "body" "both" "bound" "bulk"
1800 "byte" "c" "call" "calling" "cascade" "char" "char_base" "character"
1801 "charset" "charsetform" "charsetid" "clob_base" "close" "collect"
1802 "comment" "commit" "committed" "compiled" "constant" "constructor"
1803 "context" "continue" "convert" "count" "current" "customdatum"
1804 "dangling" "data" "date" "date_base" "day" "define" "delete"
1805 "deterministic" "double" "duration" "element" "elsif" "empty" "escape"
1806 "except" "exceptions" "execute" "exists" "exit" "external" "final"
1807 "fixed" "float" "forall" "force" "general" "hash" "heap" "hidden"
1808 "hour" "immediate" "including" "indicator" "indices" "infinite"
1809 "instantiable" "int" "interface" "interval" "invalidate" "isolation"
1810 "java" "language" "large" "leading" "length" "level" "library" "like2"
1811 "like4" "likec" "limit" "limited" "local" "long" "loop" "map" "max"
1812 "maxlen" "member" "merge" "min" "minute" "mod" "modify" "month"
1813 "multiset" "name" "nan" "national" "native" "nchar" "new" "nocopy"
1814 "number_base" "object" "ocicoll" "ocidate" "ocidatetime" "ociduration"
1815 "ociinterval" "ociloblocator" "ocinumber" "ociraw" "ociref"
1816 "ocirefcursor" "ocirowid" "ocistring" "ocitype" "old" "only" "opaque"
1817 "open" "operator" "oracle" "oradata" "organization" "orlany" "orlvary"
1818 "others" "out" "overriding" "package" "parallel_enable" "parameter"
1819 "parameters" "parent" "partition" "pascal" "pipe" "pipelined" "pragma"
1820 "precision" "prior" "private" "raise" "range" "raw" "read" "record"
1821 "ref" "reference" "relies_on" "rem" "remainder" "rename" "result"
1822 "result_cache" "return" "returning" "reverse" "rollback" "row"
1823 "sample" "save" "savepoint" "sb1" "sb2" "sb4" "second" "segment"
1824 "self" "separate" "sequence" "serializable" "set" "short" "size_t"
1825 "some" "sparse" "sqlcode" "sqldata" "sqlname" "sqlstate" "standard"
1826 "static" "stddev" "stored" "string" "struct" "style" "submultiset"
1827 "subpartition" "substitutable" "sum" "synonym" "tdo" "the" "time"
1828 "timestamp" "timezone_abbr" "timezone_hour" "timezone_minute"
1829 "timezone_region" "trailing" "transaction" "transactional" "trusted"
1830 "ub1" "ub2" "ub4" "under" "unsigned" "untrusted" "use" "using"
1831 "valist" "value" "variable" "variance" "varray" "varying" "void"
1832 "while" "work" "wrapped" "write" "year" "zone"
1833 ;; Pragma
1834 "autonomous_transaction" "exception_init" "inline"
1835 "restrict_references" "serially_reusable"
1838 ;; Oracle PL/SQL Data Types
1839 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1840 "\"BINARY LARGE OBJECT\"" "\"CHAR LARGE OBJECT\"" "\"CHAR VARYING\""
1841 "\"CHARACTER LARGE OBJECT\"" "\"CHARACTER VARYING\""
1842 "\"DOUBLE PRECISION\"" "\"INTERVAL DAY TO SECOND\""
1843 "\"INTERVAL YEAR TO MONTH\"" "\"LONG RAW\"" "\"NATIONAL CHAR\""
1844 "\"NATIONAL CHARACTER LARGE OBJECT\"" "\"NATIONAL CHARACTER\""
1845 "\"NCHAR LARGE OBJECT\"" "\"NCHAR\"" "\"NCLOB\"" "\"NVARCHAR2\""
1846 "\"TIME WITH TIME ZONE\"" "\"TIMESTAMP WITH LOCAL TIME ZONE\""
1847 "\"TIMESTAMP WITH TIME ZONE\""
1848 "bfile" "bfile_base" "binary_double" "binary_float" "binary_integer"
1849 "blob" "blob_base" "boolean" "char" "character" "char_base" "clob"
1850 "clob_base" "cursor" "date" "day" "dec" "decimal"
1851 "dsinterval_unconstrained" "float" "int" "integer" "interval" "local"
1852 "long" "mlslabel" "month" "natural" "naturaln" "nchar_cs" "number"
1853 "number_base" "numeric" "pls_integer" "positive" "positiven" "raw"
1854 "real" "ref" "rowid" "second" "signtype" "simple_double"
1855 "simple_float" "simple_integer" "smallint" "string" "time" "timestamp"
1856 "timestamp_ltz_unconstrained" "timestamp_tz_unconstrained"
1857 "timestamp_unconstrained" "time_tz_unconstrained" "time_unconstrained"
1858 "to" "urowid" "varchar" "varchar2" "with" "year"
1859 "yminterval_unconstrained" "zone"
1862 ;; Oracle PL/SQL Exceptions
1863 (sql-font-lock-keywords-builder 'font-lock-warning-face nil
1864 "access_into_null" "case_not_found" "collection_is_null"
1865 "cursor_already_open" "dup_val_on_index" "invalid_cursor"
1866 "invalid_number" "login_denied" "no_data_found" "no_data_needed"
1867 "not_logged_on" "program_error" "rowtype_mismatch" "self_is_null"
1868 "storage_error" "subscript_beyond_count" "subscript_outside_limit"
1869 "sys_invalid_rowid" "timeout_on_resource" "too_many_rows"
1870 "value_error" "zero_divide"
1873 "Oracle SQL keywords used by font-lock.
1875 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1876 regular expressions are created during compilation by calling the
1877 function `regexp-opt'. Therefore, take a look at the source before
1878 you define your own `sql-mode-oracle-font-lock-keywords'. You may want
1879 to add functions and PL/SQL keywords.")
1881 (defvar sql-mode-postgres-font-lock-keywords
1882 (eval-when-compile
1883 (list
1884 ;; Postgres psql commands
1885 '("^\\s-*\\\\.*$" . font-lock-doc-face)
1887 ;; Postgres unreserved words but may have meaning
1888 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil "a"
1889 "abs" "absent" "according" "ada" "alias" "allocate" "are" "array_agg"
1890 "asensitive" "atomic" "attribute" "attributes" "avg" "base64"
1891 "bernoulli" "bit_length" "bitvar" "blob" "blocked" "bom" "breadth" "c"
1892 "call" "cardinality" "catalog_name" "ceil" "ceiling" "char_length"
1893 "character_length" "character_set_catalog" "character_set_name"
1894 "character_set_schema" "characters" "checked" "class_origin" "clob"
1895 "cobol" "collation" "collation_catalog" "collation_name"
1896 "collation_schema" "collect" "column_name" "columns"
1897 "command_function" "command_function_code" "completion" "condition"
1898 "condition_number" "connect" "connection_name" "constraint_catalog"
1899 "constraint_name" "constraint_schema" "constructor" "contains"
1900 "control" "convert" "corr" "corresponding" "count" "covar_pop"
1901 "covar_samp" "cube" "cume_dist" "current_default_transform_group"
1902 "current_path" "current_transform_group_for_type" "cursor_name"
1903 "datalink" "datetime_interval_code" "datetime_interval_precision" "db"
1904 "defined" "degree" "dense_rank" "depth" "deref" "derived" "describe"
1905 "descriptor" "destroy" "destructor" "deterministic" "diagnostics"
1906 "disconnect" "dispatch" "dlnewcopy" "dlpreviouscopy" "dlurlcomplete"
1907 "dlurlcompleteonly" "dlurlcompletewrite" "dlurlpath" "dlurlpathonly"
1908 "dlurlpathwrite" "dlurlscheme" "dlurlserver" "dlvalue" "dynamic"
1909 "dynamic_function" "dynamic_function_code" "element" "empty"
1910 "end-exec" "equals" "every" "exception" "exec" "existing" "exp" "file"
1911 "filter" "final" "first_value" "flag" "floor" "fortran" "found" "free"
1912 "fs" "fusion" "g" "general" "generated" "get" "go" "goto" "grouping"
1913 "hex" "hierarchy" "host" "id" "ignore" "implementation" "import"
1914 "indent" "indicator" "infix" "initialize" "instance" "instantiable"
1915 "integrity" "intersection" "iterate" "k" "key_member" "key_type" "lag"
1916 "last_value" "lateral" "lead" "length" "less" "library" "like_regex"
1917 "link" "ln" "locator" "lower" "m" "map" "matched" "max"
1918 "max_cardinality" "member" "merge" "message_length"
1919 "message_octet_length" "message_text" "method" "min" "mod" "modifies"
1920 "modify" "module" "more" "multiset" "mumps" "namespace" "nclob"
1921 "nesting" "new" "nfc" "nfd" "nfkc" "nfkd" "nil" "normalize"
1922 "normalized" "nth_value" "ntile" "nullable" "number"
1923 "occurrences_regex" "octet_length" "octets" "old" "open" "operation"
1924 "ordering" "ordinality" "others" "output" "overriding" "p" "pad"
1925 "parameter" "parameter_mode" "parameter_name"
1926 "parameter_ordinal_position" "parameter_specific_catalog"
1927 "parameter_specific_name" "parameter_specific_schema" "parameters"
1928 "pascal" "passing" "passthrough" "percent_rank" "percentile_cont"
1929 "percentile_disc" "permission" "pli" "position_regex" "postfix"
1930 "power" "prefix" "preorder" "public" "rank" "reads" "recovery" "ref"
1931 "referencing" "regr_avgx" "regr_avgy" "regr_count" "regr_intercept"
1932 "regr_r2" "regr_slope" "regr_sxx" "regr_sxy" "regr_syy" "requiring"
1933 "respect" "restore" "result" "return" "returned_cardinality"
1934 "returned_length" "returned_octet_length" "returned_sqlstate" "rollup"
1935 "routine" "routine_catalog" "routine_name" "routine_schema"
1936 "row_count" "row_number" "scale" "schema_name" "scope" "scope_catalog"
1937 "scope_name" "scope_schema" "section" "selective" "self" "sensitive"
1938 "server_name" "sets" "size" "source" "space" "specific"
1939 "specific_name" "specifictype" "sql" "sqlcode" "sqlerror"
1940 "sqlexception" "sqlstate" "sqlwarning" "sqrt" "state" "static"
1941 "stddev_pop" "stddev_samp" "structure" "style" "subclass_origin"
1942 "sublist" "submultiset" "substring_regex" "sum" "system_user" "t"
1943 "table_name" "tablesample" "terminate" "than" "ties" "timezone_hour"
1944 "timezone_minute" "token" "top_level_count" "transaction_active"
1945 "transactions_committed" "transactions_rolled_back" "transform"
1946 "transforms" "translate" "translate_regex" "translation"
1947 "trigger_catalog" "trigger_name" "trigger_schema" "trim_array"
1948 "uescape" "under" "unlink" "unnamed" "unnest" "untyped" "upper" "uri"
1949 "usage" "user_defined_type_catalog" "user_defined_type_code"
1950 "user_defined_type_name" "user_defined_type_schema" "var_pop"
1951 "var_samp" "varbinary" "variable" "whenever" "width_bucket" "within"
1952 "xmlagg" "xmlbinary" "xmlcast" "xmlcomment" "xmldeclaration"
1953 "xmldocument" "xmlexists" "xmliterate" "xmlnamespaces" "xmlquery"
1954 "xmlschema" "xmltable" "xmltext" "xmlvalidate"
1957 ;; Postgres non-reserved words
1958 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1959 "abort" "absolute" "access" "action" "add" "admin" "after" "aggregate"
1960 "also" "alter" "always" "assertion" "assignment" "at" "backward"
1961 "before" "begin" "between" "by" "cache" "called" "cascade" "cascaded"
1962 "catalog" "chain" "characteristics" "checkpoint" "class" "close"
1963 "cluster" "coalesce" "comment" "comments" "commit" "committed"
1964 "configuration" "connection" "constraints" "content" "continue"
1965 "conversion" "copy" "cost" "createdb" "createrole" "createuser" "csv"
1966 "current" "cursor" "cycle" "data" "database" "day" "deallocate" "dec"
1967 "declare" "defaults" "deferred" "definer" "delete" "delimiter"
1968 "delimiters" "dictionary" "disable" "discard" "document" "domain"
1969 "drop" "each" "enable" "encoding" "encrypted" "enum" "escape"
1970 "exclude" "excluding" "exclusive" "execute" "exists" "explain"
1971 "external" "extract" "family" "first" "float" "following" "force"
1972 "forward" "function" "functions" "global" "granted" "greatest"
1973 "handler" "header" "hold" "hour" "identity" "if" "immediate"
1974 "immutable" "implicit" "including" "increment" "index" "indexes"
1975 "inherit" "inherits" "inline" "inout" "input" "insensitive" "insert"
1976 "instead" "invoker" "isolation" "key" "language" "large" "last"
1977 "lc_collate" "lc_ctype" "least" "level" "listen" "load" "local"
1978 "location" "lock" "login" "mapping" "match" "maxvalue" "minute"
1979 "minvalue" "mode" "month" "move" "name" "names" "national" "nchar"
1980 "next" "no" "nocreatedb" "nocreaterole" "nocreateuser" "noinherit"
1981 "nologin" "none" "nosuperuser" "nothing" "notify" "nowait" "nullif"
1982 "nulls" "object" "of" "oids" "operator" "option" "options" "out"
1983 "overlay" "owned" "owner" "parser" "partial" "partition" "password"
1984 "plans" "position" "preceding" "prepare" "prepared" "preserve" "prior"
1985 "privileges" "procedural" "procedure" "quote" "range" "read"
1986 "reassign" "recheck" "recursive" "reindex" "relative" "release"
1987 "rename" "repeatable" "replace" "replica" "reset" "restart" "restrict"
1988 "returns" "revoke" "role" "rollback" "row" "rows" "rule" "savepoint"
1989 "schema" "scroll" "search" "second" "security" "sequence" "sequences"
1990 "serializable" "server" "session" "set" "setof" "share" "show"
1991 "simple" "stable" "standalone" "start" "statement" "statistics"
1992 "stdin" "stdout" "storage" "strict" "strip" "substring" "superuser"
1993 "sysid" "system" "tables" "tablespace" "temp" "template" "temporary"
1994 "transaction" "treat" "trigger" "trim" "truncate" "trusted" "type"
1995 "unbounded" "uncommitted" "unencrypted" "unknown" "unlisten" "until"
1996 "update" "vacuum" "valid" "validator" "value" "values" "version"
1997 "view" "volatile" "whitespace" "work" "wrapper" "write"
1998 "xmlattributes" "xmlconcat" "xmlelement" "xmlforest" "xmlparse"
1999 "xmlpi" "xmlroot" "xmlserialize" "year" "yes"
2002 ;; Postgres Reserved
2003 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2004 "all" "analyse" "analyze" "and" "any" "array" "asc" "as" "asymmetric"
2005 "authorization" "binary" "both" "case" "cast" "check" "collate"
2006 "column" "concurrently" "constraint" "create" "cross"
2007 "current_catalog" "current_date" "current_role" "current_schema"
2008 "current_time" "current_timestamp" "current_user" "default"
2009 "deferrable" "desc" "distinct" "do" "else" "end" "except" "false"
2010 "fetch" "foreign" "for" "freeze" "from" "full" "grant" "group"
2011 "having" "ilike" "initially" "inner" "in" "intersect" "into" "isnull"
2012 "is" "join" "leading" "left" "like" "limit" "localtime"
2013 "localtimestamp" "natural" "notnull" "not" "null" "off" "offset"
2014 "only" "on" "order" "or" "outer" "overlaps" "over" "placing" "primary"
2015 "references" "returning" "right" "select" "session_user" "similar"
2016 "some" "symmetric" "table" "then" "to" "trailing" "true" "union"
2017 "unique" "user" "using" "variadic" "verbose" "when" "where" "window"
2018 "with"
2021 ;; Postgres Data Types
2022 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2023 "bigint" "bigserial" "bit" "bool" "boolean" "box" "bytea" "char"
2024 "character" "cidr" "circle" "date" "decimal" "double" "float4"
2025 "float8" "inet" "int" "int2" "int4" "int8" "integer" "interval" "line"
2026 "lseg" "macaddr" "money" "numeric" "path" "point" "polygon"
2027 "precision" "real" "serial" "serial4" "serial8" "smallint" "text"
2028 "time" "timestamp" "timestamptz" "timetz" "tsquery" "tsvector"
2029 "txid_snapshot" "uuid" "varbit" "varchar" "varying" "without"
2030 "xml" "zone"
2033 "Postgres SQL keywords used by font-lock.
2035 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2036 regular expressions are created during compilation by calling the
2037 function `regexp-opt'. Therefore, take a look at the source before
2038 you define your own `sql-mode-postgres-font-lock-keywords'.")
2040 (defvar sql-mode-linter-font-lock-keywords
2041 (eval-when-compile
2042 (list
2043 ;; Linter Keywords
2044 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2045 "autocommit" "autoinc" "autorowid" "cancel" "cascade" "channel"
2046 "committed" "count" "countblob" "cross" "current" "data" "database"
2047 "datafile" "datafiles" "datesplit" "dba" "dbname" "default" "deferred"
2048 "denied" "description" "device" "difference" "directory" "error"
2049 "escape" "euc" "exclusive" "external" "extfile" "false" "file"
2050 "filename" "filesize" "filetime" "filter" "findblob" "first" "foreign"
2051 "full" "fuzzy" "global" "granted" "ignore" "immediate" "increment"
2052 "indexes" "indexfile" "indexfiles" "indextime" "initial" "integrity"
2053 "internal" "key" "last_autoinc" "last_rowid" "limit" "linter"
2054 "linter_file_device" "linter_file_size" "linter_name_length" "ln"
2055 "local" "login" "maxisn" "maxrow" "maxrowid" "maxvalue" "message"
2056 "minvalue" "module" "names" "national" "natural" "new" "new_table"
2057 "no" "node" "noneuc" "nulliferror" "numbers" "off" "old" "old_table"
2058 "only" "operation" "optimistic" "option" "page" "partially" "password"
2059 "phrase" "plan" "precision" "primary" "priority" "privileges"
2060 "proc_info_size" "proc_par_name_len" "protocol" "quant" "range" "raw"
2061 "read" "record" "records" "references" "remote" "rename" "replication"
2062 "restart" "rewrite" "root" "row" "rule" "savepoint" "security"
2063 "sensitive" "sequence" "serializable" "server" "since" "size" "some"
2064 "startup" "statement" "station" "success" "sys_guid" "tables" "test"
2065 "timeout" "trace" "transaction" "translation" "trigger"
2066 "trigger_info_size" "true" "trunc" "uncommitted" "unicode" "unknown"
2067 "unlimited" "unlisted" "user" "utf8" "value" "varying" "volumes"
2068 "wait" "windows_code" "workspace" "write" "xml"
2071 ;; Linter Reserved
2072 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2073 "access" "action" "add" "address" "after" "all" "alter" "always" "and"
2074 "any" "append" "as" "asc" "ascic" "async" "at_begin" "at_end" "audit"
2075 "aud_obj_name_len" "backup" "base" "before" "between" "blobfile"
2076 "blobfiles" "blobpct" "brief" "browse" "by" "case" "cast" "check"
2077 "clear" "close" "column" "comment" "commit" "connect" "contains"
2078 "correct" "create" "delete" "desc" "disable" "disconnect" "distinct"
2079 "drop" "each" "ef" "else" "enable" "end" "event" "except" "exclude"
2080 "execute" "exists" "extract" "fetch" "finish" "for" "from" "get"
2081 "grant" "group" "having" "identified" "in" "index" "inner" "insert"
2082 "instead" "intersect" "into" "is" "isolation" "join" "left" "level"
2083 "like" "lock" "mode" "modify" "not" "nowait" "null" "of" "on" "open"
2084 "or" "order" "outer" "owner" "press" "prior" "procedure" "public"
2085 "purge" "rebuild" "resource" "restrict" "revoke" "right" "role"
2086 "rollback" "rownum" "select" "session" "set" "share" "shutdown"
2087 "start" "stop" "sync" "synchronize" "synonym" "sysdate" "table" "then"
2088 "to" "union" "unique" "unlock" "until" "update" "using" "values"
2089 "view" "when" "where" "with" "without"
2092 ;; Linter Functions
2093 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2094 "abs" "acos" "asin" "atan" "atan2" "avg" "ceil" "cos" "cosh" "divtime"
2095 "exp" "floor" "getbits" "getblob" "getbyte" "getlong" "getraw"
2096 "getstr" "gettext" "getword" "hextoraw" "lenblob" "length" "log"
2097 "lower" "lpad" "ltrim" "max" "min" "mod" "monthname" "nvl"
2098 "octet_length" "power" "rand" "rawtohex" "repeat_string"
2099 "right_substr" "round" "rpad" "rtrim" "sign" "sin" "sinh" "soundex"
2100 "sqrt" "sum" "tan" "tanh" "timeint_to_days" "to_char" "to_date"
2101 "to_gmtime" "to_localtime" "to_number" "trim" "upper" "decode"
2102 "substr" "substring" "chr" "dayname" "days" "greatest" "hex" "initcap"
2103 "instr" "least" "multime" "replace" "width"
2106 ;; Linter Data Types
2107 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2108 "bigint" "bitmap" "blob" "boolean" "char" "character" "date"
2109 "datetime" "dec" "decimal" "double" "float" "int" "integer" "nchar"
2110 "number" "numeric" "real" "smallint" "varbyte" "varchar" "byte"
2111 "cursor" "long"
2114 "Linter SQL keywords used by font-lock.
2116 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2117 regular expressions are created during compilation by calling the
2118 function `regexp-opt'.")
2120 (defvar sql-mode-ms-font-lock-keywords
2121 (eval-when-compile
2122 (list
2123 ;; MS isql/osql Commands
2124 (cons
2125 (concat
2126 "^\\(?:\\(?:set\\s-+\\(?:"
2127 (regexp-opt '(
2128 "datefirst" "dateformat" "deadlock_priority" "lock_timeout"
2129 "concat_null_yields_null" "cursor_close_on_commit"
2130 "disable_def_cnst_chk" "fips_flagger" "identity_insert" "language"
2131 "offsets" "quoted_identifier" "arithabort" "arithignore" "fmtonly"
2132 "nocount" "noexec" "numeric_roundabort" "parseonly"
2133 "query_governor_cost_limit" "rowcount" "textsize" "ansi_defaults"
2134 "ansi_null_dflt_off" "ansi_null_dflt_on" "ansi_nulls" "ansi_padding"
2135 "ansi_warnings" "forceplan" "showplan_all" "showplan_text"
2136 "statistics" "implicit_transactions" "remote_proc_transactions"
2137 "transaction" "xact_abort"
2138 ) t)
2139 "\\)\\)\\|go\\s-*\\|use\\s-+\\|setuser\\s-+\\|dbcc\\s-+\\).*$")
2140 'font-lock-doc-face)
2142 ;; MS Reserved
2143 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2144 "absolute" "add" "all" "alter" "and" "any" "as" "asc" "authorization"
2145 "avg" "backup" "begin" "between" "break" "browse" "bulk" "by"
2146 "cascade" "case" "check" "checkpoint" "close" "clustered" "coalesce"
2147 "column" "commit" "committed" "compute" "confirm" "constraint"
2148 "contains" "containstable" "continue" "controlrow" "convert" "count"
2149 "create" "cross" "current" "current_date" "current_time"
2150 "current_timestamp" "current_user" "database" "deallocate" "declare"
2151 "default" "delete" "deny" "desc" "disk" "distinct" "distributed"
2152 "double" "drop" "dummy" "dump" "else" "end" "errlvl" "errorexit"
2153 "escape" "except" "exec" "execute" "exists" "exit" "fetch" "file"
2154 "fillfactor" "first" "floppy" "for" "foreign" "freetext"
2155 "freetexttable" "from" "full" "goto" "grant" "group" "having"
2156 "holdlock" "identity" "identity_insert" "identitycol" "if" "in"
2157 "index" "inner" "insert" "intersect" "into" "is" "isolation" "join"
2158 "key" "kill" "last" "left" "level" "like" "lineno" "load" "max" "min"
2159 "mirrorexit" "national" "next" "nocheck" "nolock" "nonclustered" "not"
2160 "null" "nullif" "of" "off" "offsets" "on" "once" "only" "open"
2161 "opendatasource" "openquery" "openrowset" "option" "or" "order"
2162 "outer" "output" "over" "paglock" "percent" "perm" "permanent" "pipe"
2163 "plan" "precision" "prepare" "primary" "print" "prior" "privileges"
2164 "proc" "procedure" "processexit" "public" "raiserror" "read"
2165 "readcommitted" "readpast" "readtext" "readuncommitted" "reconfigure"
2166 "references" "relative" "repeatable" "repeatableread" "replication"
2167 "restore" "restrict" "return" "revoke" "right" "rollback" "rowcount"
2168 "rowguidcol" "rowlock" "rule" "save" "schema" "select" "serializable"
2169 "session_user" "set" "shutdown" "some" "statistics" "sum"
2170 "system_user" "table" "tablock" "tablockx" "tape" "temp" "temporary"
2171 "textsize" "then" "to" "top" "tran" "transaction" "trigger" "truncate"
2172 "tsequal" "uncommitted" "union" "unique" "update" "updatetext"
2173 "updlock" "use" "user" "values" "view" "waitfor" "when" "where"
2174 "while" "with" "work" "writetext" "collate" "function" "openxml"
2175 "returns"
2178 ;; MS Functions
2179 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2180 "@@connections" "@@cpu_busy" "@@cursor_rows" "@@datefirst" "@@dbts"
2181 "@@error" "@@fetch_status" "@@identity" "@@idle" "@@io_busy"
2182 "@@langid" "@@language" "@@lock_timeout" "@@max_connections"
2183 "@@max_precision" "@@nestlevel" "@@options" "@@pack_received"
2184 "@@pack_sent" "@@packet_errors" "@@procid" "@@remserver" "@@rowcount"
2185 "@@servername" "@@servicename" "@@spid" "@@textsize" "@@timeticks"
2186 "@@total_errors" "@@total_read" "@@total_write" "@@trancount"
2187 "@@version" "abs" "acos" "and" "app_name" "ascii" "asin" "atan" "atn2"
2188 "avg" "case" "cast" "ceiling" "char" "charindex" "coalesce"
2189 "col_length" "col_name" "columnproperty" "containstable" "convert"
2190 "cos" "cot" "count" "current_timestamp" "current_user" "cursor_status"
2191 "databaseproperty" "datalength" "dateadd" "datediff" "datename"
2192 "datepart" "day" "db_id" "db_name" "degrees" "difference" "exp"
2193 "file_id" "file_name" "filegroup_id" "filegroup_name"
2194 "filegroupproperty" "fileproperty" "floor" "formatmessage"
2195 "freetexttable" "fulltextcatalogproperty" "fulltextserviceproperty"
2196 "getansinull" "getdate" "grouping" "host_id" "host_name" "ident_incr"
2197 "ident_seed" "identity" "index_col" "indexproperty" "is_member"
2198 "is_srvrolemember" "isdate" "isnull" "isnumeric" "left" "len" "log"
2199 "log10" "lower" "ltrim" "max" "min" "month" "nchar" "newid" "nullif"
2200 "object_id" "object_name" "objectproperty" "openquery" "openrowset"
2201 "parsename" "patindex" "patindex" "permissions" "pi" "power"
2202 "quotename" "radians" "rand" "replace" "replicate" "reverse" "right"
2203 "round" "rtrim" "session_user" "sign" "sin" "soundex" "space" "sqrt"
2204 "square" "stats_date" "stdev" "stdevp" "str" "stuff" "substring" "sum"
2205 "suser_id" "suser_name" "suser_sid" "suser_sname" "system_user" "tan"
2206 "textptr" "textvalid" "typeproperty" "unicode" "upper" "user"
2207 "user_id" "user_name" "var" "varp" "year"
2210 ;; MS Variables
2211 '("\\b@[a-zA-Z0-9_]*\\b" . font-lock-variable-name-face)
2213 ;; MS Types
2214 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2215 "binary" "bit" "char" "character" "cursor" "datetime" "dec" "decimal"
2216 "double" "float" "image" "int" "integer" "money" "national" "nchar"
2217 "ntext" "numeric" "numeric" "nvarchar" "precision" "real"
2218 "smalldatetime" "smallint" "smallmoney" "text" "timestamp" "tinyint"
2219 "uniqueidentifier" "varbinary" "varchar" "varying"
2222 "Microsoft SQLServer SQL keywords used by font-lock.
2224 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2225 regular expressions are created during compilation by calling the
2226 function `regexp-opt'. Therefore, take a look at the source before
2227 you define your own `sql-mode-ms-font-lock-keywords'.")
2229 (defvar sql-mode-sybase-font-lock-keywords nil
2230 "Sybase SQL keywords used by font-lock.
2232 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2233 regular expressions are created during compilation by calling the
2234 function `regexp-opt'. Therefore, take a look at the source before
2235 you define your own `sql-mode-sybase-font-lock-keywords'.")
2237 (defvar sql-mode-informix-font-lock-keywords nil
2238 "Informix SQL keywords used by font-lock.
2240 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2241 regular expressions are created during compilation by calling the
2242 function `regexp-opt'. Therefore, take a look at the source before
2243 you define your own `sql-mode-informix-font-lock-keywords'.")
2245 (defvar sql-mode-interbase-font-lock-keywords nil
2246 "Interbase SQL keywords used by font-lock.
2248 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2249 regular expressions are created during compilation by calling the
2250 function `regexp-opt'. Therefore, take a look at the source before
2251 you define your own `sql-mode-interbase-font-lock-keywords'.")
2253 (defvar sql-mode-ingres-font-lock-keywords nil
2254 "Ingres SQL keywords used by font-lock.
2256 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2257 regular expressions are created during compilation by calling the
2258 function `regexp-opt'. Therefore, take a look at the source before
2259 you define your own `sql-mode-interbase-font-lock-keywords'.")
2261 (defvar sql-mode-solid-font-lock-keywords nil
2262 "Solid SQL keywords used by font-lock.
2264 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2265 regular expressions are created during compilation by calling the
2266 function `regexp-opt'. Therefore, take a look at the source before
2267 you define your own `sql-mode-solid-font-lock-keywords'.")
2269 (defvar sql-mode-mysql-font-lock-keywords
2270 (eval-when-compile
2271 (list
2272 ;; MySQL Functions
2273 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2274 "ascii" "avg" "bdmpolyfromtext" "bdmpolyfromwkb" "bdpolyfromtext"
2275 "bdpolyfromwkb" "benchmark" "bin" "bit_and" "bit_length" "bit_or"
2276 "bit_xor" "both" "cast" "char_length" "character_length" "coalesce"
2277 "concat" "concat_ws" "connection_id" "conv" "convert" "count"
2278 "curdate" "current_date" "current_time" "current_timestamp" "curtime"
2279 "elt" "encrypt" "export_set" "field" "find_in_set" "found_rows" "from"
2280 "geomcollfromtext" "geomcollfromwkb" "geometrycollectionfromtext"
2281 "geometrycollectionfromwkb" "geometryfromtext" "geometryfromwkb"
2282 "geomfromtext" "geomfromwkb" "get_lock" "group_concat" "hex" "ifnull"
2283 "instr" "interval" "isnull" "last_insert_id" "lcase" "leading"
2284 "length" "linefromtext" "linefromwkb" "linestringfromtext"
2285 "linestringfromwkb" "load_file" "locate" "lower" "lpad" "ltrim"
2286 "make_set" "master_pos_wait" "max" "mid" "min" "mlinefromtext"
2287 "mlinefromwkb" "mpointfromtext" "mpointfromwkb" "mpolyfromtext"
2288 "mpolyfromwkb" "multilinestringfromtext" "multilinestringfromwkb"
2289 "multipointfromtext" "multipointfromwkb" "multipolygonfromtext"
2290 "multipolygonfromwkb" "now" "nullif" "oct" "octet_length" "ord"
2291 "pointfromtext" "pointfromwkb" "polyfromtext" "polyfromwkb"
2292 "polygonfromtext" "polygonfromwkb" "position" "quote" "rand"
2293 "release_lock" "repeat" "replace" "reverse" "rpad" "rtrim" "soundex"
2294 "space" "std" "stddev" "substring" "substring_index" "sum" "sysdate"
2295 "trailing" "trim" "ucase" "unix_timestamp" "upper" "user" "variance"
2298 ;; MySQL Keywords
2299 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2300 "action" "add" "after" "against" "all" "alter" "and" "as" "asc"
2301 "auto_increment" "avg_row_length" "bdb" "between" "by" "cascade"
2302 "case" "change" "character" "check" "checksum" "close" "collate"
2303 "collation" "column" "columns" "comment" "committed" "concurrent"
2304 "constraint" "create" "cross" "data" "database" "default"
2305 "delay_key_write" "delayed" "delete" "desc" "directory" "disable"
2306 "distinct" "distinctrow" "do" "drop" "dumpfile" "duplicate" "else" "elseif"
2307 "enable" "enclosed" "end" "escaped" "exists" "fields" "first" "for"
2308 "force" "foreign" "from" "full" "fulltext" "global" "group" "handler"
2309 "having" "heap" "high_priority" "if" "ignore" "in" "index" "infile"
2310 "inner" "insert" "insert_method" "into" "is" "isam" "isolation" "join"
2311 "key" "keys" "last" "left" "level" "like" "limit" "lines" "load"
2312 "local" "lock" "low_priority" "match" "max_rows" "merge" "min_rows"
2313 "mode" "modify" "mrg_myisam" "myisam" "natural" "next" "no" "not"
2314 "null" "offset" "oj" "on" "open" "optionally" "or" "order" "outer"
2315 "outfile" "pack_keys" "partial" "password" "prev" "primary"
2316 "procedure" "quick" "raid0" "raid_type" "read" "references" "rename"
2317 "repeatable" "restrict" "right" "rollback" "rollup" "row_format"
2318 "savepoint" "select" "separator" "serializable" "session" "set"
2319 "share" "show" "sql_big_result" "sql_buffer_result" "sql_cache"
2320 "sql_calc_found_rows" "sql_no_cache" "sql_small_result" "starting"
2321 "straight_join" "striped" "table" "tables" "temporary" "terminated"
2322 "then" "to" "transaction" "truncate" "type" "uncommitted" "union"
2323 "unique" "unlock" "update" "use" "using" "values" "when" "where"
2324 "with" "write" "xor"
2327 ;; MySQL Data Types
2328 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2329 "bigint" "binary" "bit" "blob" "bool" "boolean" "char" "curve" "date"
2330 "datetime" "dec" "decimal" "double" "enum" "fixed" "float" "geometry"
2331 "geometrycollection" "int" "integer" "line" "linearring" "linestring"
2332 "longblob" "longtext" "mediumblob" "mediumint" "mediumtext"
2333 "multicurve" "multilinestring" "multipoint" "multipolygon"
2334 "multisurface" "national" "numeric" "point" "polygon" "precision"
2335 "real" "smallint" "surface" "text" "time" "timestamp" "tinyblob"
2336 "tinyint" "tinytext" "unsigned" "varchar" "year" "year2" "year4"
2337 "zerofill"
2340 "MySQL SQL keywords used by font-lock.
2342 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2343 regular expressions are created during compilation by calling the
2344 function `regexp-opt'. Therefore, take a look at the source before
2345 you define your own `sql-mode-mysql-font-lock-keywords'.")
2347 (defvar sql-mode-sqlite-font-lock-keywords
2348 (eval-when-compile
2349 (list
2350 ;; SQLite commands
2351 '("^[.].*$" . font-lock-doc-face)
2353 ;; SQLite Keyword
2354 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2355 "abort" "action" "add" "after" "all" "alter" "analyze" "and" "as"
2356 "asc" "attach" "autoincrement" "before" "begin" "between" "by"
2357 "cascade" "case" "cast" "check" "collate" "column" "commit" "conflict"
2358 "constraint" "create" "cross" "database" "default" "deferrable"
2359 "deferred" "delete" "desc" "detach" "distinct" "drop" "each" "else"
2360 "end" "escape" "except" "exclusive" "exists" "explain" "fail" "for"
2361 "foreign" "from" "full" "glob" "group" "having" "if" "ignore"
2362 "immediate" "in" "index" "indexed" "initially" "inner" "insert"
2363 "instead" "intersect" "into" "is" "isnull" "join" "key" "left" "like"
2364 "limit" "match" "natural" "no" "not" "notnull" "null" "of" "offset"
2365 "on" "or" "order" "outer" "plan" "pragma" "primary" "query" "raise"
2366 "references" "regexp" "reindex" "release" "rename" "replace"
2367 "restrict" "right" "rollback" "row" "savepoint" "select" "set" "table"
2368 "temp" "temporary" "then" "to" "transaction" "trigger" "union"
2369 "unique" "update" "using" "vacuum" "values" "view" "virtual" "when"
2370 "where"
2372 ;; SQLite Data types
2373 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2374 "int" "integer" "tinyint" "smallint" "mediumint" "bigint" "unsigned"
2375 "big" "int2" "int8" "character" "varchar" "varying" "nchar" "native"
2376 "nvarchar" "text" "clob" "blob" "real" "double" "precision" "float"
2377 "numeric" "number" "decimal" "boolean" "date" "datetime"
2379 ;; SQLite Functions
2380 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2381 ;; Core functions
2382 "abs" "changes" "coalesce" "glob" "ifnull" "hex" "last_insert_rowid"
2383 "length" "like" "load_extension" "lower" "ltrim" "max" "min" "nullif"
2384 "quote" "random" "randomblob" "replace" "round" "rtrim" "soundex"
2385 "sqlite_compileoption_get" "sqlite_compileoption_used"
2386 "sqlite_source_id" "sqlite_version" "substr" "total_changes" "trim"
2387 "typeof" "upper" "zeroblob"
2388 ;; Date/time functions
2389 "time" "julianday" "strftime"
2390 "current_date" "current_time" "current_timestamp"
2391 ;; Aggregate functions
2392 "avg" "count" "group_concat" "max" "min" "sum" "total"
2395 "SQLite SQL keywords used by font-lock.
2397 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2398 regular expressions are created during compilation by calling the
2399 function `regexp-opt'. Therefore, take a look at the source before
2400 you define your own `sql-mode-sqlite-font-lock-keywords'.")
2402 (defvar sql-mode-db2-font-lock-keywords nil
2403 "DB2 SQL keywords used by font-lock.
2405 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2406 regular expressions are created during compilation by calling the
2407 function `regexp-opt'. Therefore, take a look at the source before
2408 you define your own `sql-mode-db2-font-lock-keywords'.")
2410 (defvar sql-mode-font-lock-keywords nil
2411 "SQL keywords used by font-lock.
2413 Setting this variable directly no longer has any affect. Use
2414 `sql-product' and `sql-add-product-keywords' to control the
2415 highlighting rules in SQL mode.")
2419 ;;; SQL Product support functions
2421 (defun sql-read-product (prompt &optional initial)
2422 "Read a valid SQL product."
2423 (let ((init (or (and initial (symbol-name initial)) "ansi")))
2424 (intern (completing-read
2425 prompt
2426 (mapcar (lambda (info) (symbol-name (car info)))
2427 sql-product-alist)
2428 nil 'require-match
2429 init 'sql-product-history init))))
2431 (defun sql-add-product (product display &rest plist)
2432 "Add support for a database product in `sql-mode'.
2434 Add PRODUCT to `sql-product-alist' which enables `sql-mode' to
2435 properly support syntax highlighting and interactive interaction.
2436 DISPLAY is the name of the SQL product that will appear in the
2437 menu bar and in messages. PLIST initializes the product
2438 configuration."
2440 ;; Don't do anything if the product is already supported
2441 (if (assoc product sql-product-alist)
2442 (message "Product `%s' is already defined" product)
2444 ;; Add product to the alist
2445 (add-to-list 'sql-product-alist `((,product :name ,display . ,plist)))
2446 ;; Add a menu item to the SQL->Product menu
2447 (easy-menu-add-item sql-mode-menu '("Product")
2448 ;; Each product is represented by a radio
2449 ;; button with it's display name.
2450 `[,display
2451 (sql-set-product ',product)
2452 :style radio
2453 :selected (eq sql-product ',product)]
2454 ;; Maintain the product list in
2455 ;; (case-insensitive) alphabetic order of the
2456 ;; display names. Loop thru each keymap item
2457 ;; looking for an item whose display name is
2458 ;; after this product's name.
2459 (let ((next-item)
2460 (down-display (downcase display)))
2461 (map-keymap (lambda (k b)
2462 (when (and (not next-item)
2463 (string-lessp down-display
2464 (downcase (cadr b))))
2465 (setq next-item k)))
2466 (easy-menu-get-map sql-mode-menu '("Product")))
2467 next-item))
2468 product))
2470 (defun sql-del-product (product)
2471 "Remove support for PRODUCT in `sql-mode'."
2473 ;; Remove the menu item based on the display name
2474 (easy-menu-remove-item sql-mode-menu '("Product") (sql-get-product-feature product :name))
2475 ;; Remove the product alist item
2476 (setq sql-product-alist (assq-delete-all product sql-product-alist))
2477 nil)
2479 (defun sql-set-product-feature (product feature newvalue)
2480 "Set FEATURE of database PRODUCT to NEWVALUE.
2482 The PRODUCT must be a symbol which identifies the database
2483 product. The product must have already exist on the product
2484 list. See `sql-add-product' to add new products. The FEATURE
2485 argument must be a plist keyword accepted by
2486 `sql-product-alist'."
2488 (let* ((p (assoc product sql-product-alist))
2489 (v (plist-get (cdr p) feature)))
2490 (if p
2491 (if (and
2492 (member feature sql-indirect-features)
2493 (symbolp v))
2494 (set v newvalue)
2495 (setcdr p (plist-put (cdr p) feature newvalue)))
2496 (message "`%s' is not a known product; use `sql-add-product' to add it first." product))))
2498 (defun sql-get-product-feature (product feature &optional fallback not-indirect)
2499 "Lookup FEATURE associated with a SQL PRODUCT.
2501 If the FEATURE is nil for PRODUCT, and FALLBACK is specified,
2502 then the FEATURE associated with the FALLBACK product is
2503 returned.
2505 If the FEATURE is in the list `sql-indirect-features', and the
2506 NOT-INDIRECT parameter is not set, then the value of the symbol
2507 stored in the connect alist is returned.
2509 See `sql-product-alist' for a list of products and supported features."
2510 (let* ((p (assoc product sql-product-alist))
2511 (v (plist-get (cdr p) feature)))
2513 (if p
2514 ;; If no value and fallback, lookup feature for fallback
2515 (if (and (not v)
2516 fallback
2517 (not (eq product fallback)))
2518 (sql-get-product-feature fallback feature)
2520 (if (and
2521 (member feature sql-indirect-features)
2522 (not not-indirect)
2523 (symbolp v))
2524 (symbol-value v)
2526 (message "`%s' is not a known product; use `sql-add-product' to add it first." product)
2527 nil)))
2529 (defun sql-product-font-lock (keywords-only imenu)
2530 "Configure font-lock and imenu with product-specific settings.
2532 The KEYWORDS-ONLY flag is passed to font-lock to specify whether
2533 only keywords should be highlighted and syntactic highlighting
2534 skipped. The IMENU flag indicates whether `imenu-mode' should
2535 also be configured."
2537 (let
2538 ;; Get the product-specific syntax-alist.
2539 ((syntax-alist (sql-product-font-lock-syntax-alist)))
2541 ;; Get the product-specific keywords.
2542 (set (make-local-variable 'sql-mode-font-lock-keywords)
2543 (append
2544 (unless (eq sql-product 'ansi)
2545 (sql-get-product-feature sql-product :font-lock))
2546 ;; Always highlight ANSI keywords
2547 (sql-get-product-feature 'ansi :font-lock)
2548 ;; Fontify object names in CREATE, DROP and ALTER DDL
2549 ;; statements
2550 (list sql-mode-font-lock-object-name)))
2552 ;; Setup font-lock. Force re-parsing of `font-lock-defaults'.
2553 (kill-local-variable 'font-lock-set-defaults)
2554 (set (make-local-variable 'font-lock-defaults)
2555 (list 'sql-mode-font-lock-keywords
2556 keywords-only t syntax-alist))
2558 ;; Force font lock to reinitialize if it is already on
2559 ;; Otherwise, we can wait until it can be started.
2560 (when (and (fboundp 'font-lock-mode)
2561 (boundp 'font-lock-mode)
2562 font-lock-mode)
2563 (font-lock-mode-internal nil)
2564 (font-lock-mode-internal t))
2566 (add-hook 'font-lock-mode-hook
2567 (lambda ()
2568 ;; Provide defaults for new font-lock faces.
2569 (defvar font-lock-builtin-face
2570 (if (boundp 'font-lock-preprocessor-face)
2571 font-lock-preprocessor-face
2572 font-lock-keyword-face))
2573 (defvar font-lock-doc-face font-lock-string-face))
2574 nil t)
2576 ;; Setup imenu; it needs the same syntax-alist.
2577 (when imenu
2578 (setq imenu-syntax-alist syntax-alist))))
2580 ;;;###autoload
2581 (defun sql-add-product-keywords (product keywords &optional append)
2582 "Add highlighting KEYWORDS for SQL PRODUCT.
2584 PRODUCT should be a symbol, the name of a SQL product, such as
2585 `oracle'. KEYWORDS should be a list; see the variable
2586 `font-lock-keywords'. By default they are added at the beginning
2587 of the current highlighting list. If optional argument APPEND is
2588 `set', they are used to replace the current highlighting list.
2589 If APPEND is any other non-nil value, they are added at the end
2590 of the current highlighting list.
2592 For example:
2594 (sql-add-product-keywords 'ms
2595 '((\"\\\\b\\\\w+_t\\\\b\" . font-lock-type-face)))
2597 adds a fontification pattern to fontify identifiers ending in
2598 `_t' as data types."
2600 (let* ((sql-indirect-features nil)
2601 (font-lock-var (sql-get-product-feature product :font-lock))
2602 (old-val))
2604 (setq old-val (symbol-value font-lock-var))
2605 (set font-lock-var
2606 (if (eq append 'set)
2607 keywords
2608 (if append
2609 (append old-val keywords)
2610 (append keywords old-val))))))
2612 (defun sql-for-each-login (login-params body)
2613 "Iterates through login parameters and returns a list of results."
2615 (delq nil
2616 (mapcar
2617 (lambda (param)
2618 (let ((token (or (and (listp param) (car param)) param))
2619 (plist (or (and (listp param) (cdr param)) nil)))
2621 (funcall body token plist)))
2622 login-params)))
2626 ;;; Functions to switch highlighting
2628 (defun sql-product-syntax-table ()
2629 (let ((table (copy-syntax-table sql-mode-syntax-table)))
2630 (mapc (lambda (entry)
2631 (modify-syntax-entry (car entry) (cdr entry) table))
2632 (sql-get-product-feature sql-product :syntax-alist))
2633 table))
2635 (defun sql-product-font-lock-syntax-alist ()
2636 (append
2637 ;; Change all symbol character to word characters
2638 (mapcar
2639 (lambda (entry) (if (string= (substring (cdr entry) 0 1) "_")
2640 (cons (car entry)
2641 (concat "w" (substring (cdr entry) 1)))
2642 entry))
2643 (sql-get-product-feature sql-product :syntax-alist))
2644 '((?_ . "w"))))
2646 (defun sql-highlight-product ()
2647 "Turn on the font highlighting for the SQL product selected."
2648 (when (derived-mode-p 'sql-mode)
2649 ;; Enhance the syntax table for the product
2650 (set-syntax-table (sql-product-syntax-table))
2652 ;; Setup font-lock
2653 (sql-product-font-lock nil t)
2655 ;; Set the mode name to include the product.
2656 (setq mode-name (concat "SQL[" (or (sql-get-product-feature sql-product :name)
2657 (symbol-name sql-product)) "]"))))
2659 (defun sql-set-product (product)
2660 "Set `sql-product' to PRODUCT and enable appropriate highlighting."
2661 (interactive
2662 (list (sql-read-product "SQL product: ")))
2663 (if (stringp product) (setq product (intern product)))
2664 (when (not (assoc product sql-product-alist))
2665 (error "SQL product %s is not supported; treated as ANSI" product)
2666 (setq product 'ansi))
2668 ;; Save product setting and fontify.
2669 (setq sql-product product)
2670 (sql-highlight-product))
2673 ;;; Compatibility functions
2675 (if (not (fboundp 'comint-line-beginning-position))
2676 ;; comint-line-beginning-position is defined in Emacs 21
2677 (defun comint-line-beginning-position ()
2678 "Return the buffer position of the beginning of the line, after any prompt.
2679 The prompt is assumed to be any text at the beginning of the line
2680 matching the regular expression `comint-prompt-regexp', a buffer
2681 local variable."
2682 (save-excursion (comint-bol nil) (point))))
2684 ;;; Motion Functions
2686 (defun sql-statement-regexp (prod)
2687 (let* ((ansi-stmt (sql-get-product-feature 'ansi :statement))
2688 (prod-stmt (sql-get-product-feature prod :statement)))
2689 (concat "^\\<"
2690 (if prod-stmt
2691 ansi-stmt
2692 (concat "\\(" ansi-stmt "\\|" prod-stmt "\\)"))
2693 "\\>")))
2695 (defun sql-beginning-of-statement (arg)
2696 "Moves the cursor to the beginning of the current SQL statement."
2697 (interactive "p")
2699 (let ((here (point))
2700 (regexp (sql-statement-regexp sql-product))
2701 last next)
2703 ;; Go to the end of the statement before the start we desire
2704 (setq last (or (sql-end-of-statement (- arg))
2705 (point-min)))
2706 ;; And find the end after that
2707 (setq next (or (sql-end-of-statement 1)
2708 (point-max)))
2710 ;; Our start must be between them
2711 (goto-char last)
2712 ;; Find an beginning-of-stmt that's not in a comment
2713 (while (and (re-search-forward regexp next t 1)
2714 (nth 7 (syntax-ppss)))
2715 (goto-char (match-end 0)))
2716 (goto-char
2717 (if (match-data)
2718 (match-beginning 0)
2719 last))
2720 (beginning-of-line)
2721 ;; If we didn't move, try again
2722 (when (= here (point))
2723 (sql-beginning-of-statement (* 2 (sql-signum arg))))))
2725 (defun sql-end-of-statement (arg)
2726 "Moves the cursor to the end of the current SQL statement."
2727 (interactive "p")
2728 (let ((term (sql-get-product-feature sql-product :terminator))
2729 (re-search (if (> 0 arg) 're-search-backward 're-search-forward))
2730 (here (point))
2731 (n 0))
2732 (when (consp term)
2733 (setq term (car term)))
2734 ;; Iterate until we've moved the desired number of stmt ends
2735 (while (not (= (sql-signum arg) 0))
2736 ;; if we're looking at the terminator, jump by 2
2737 (if (or (and (> 0 arg) (looking-back term))
2738 (and (< 0 arg) (looking-at term)))
2739 (setq n 2)
2740 (setq n 1))
2741 ;; If we found another end-of-stmt
2742 (if (not (apply re-search term nil t n nil))
2743 (setq arg 0)
2744 ;; count it if we're not in a comment
2745 (unless (nth 7 (syntax-ppss))
2746 (setq arg (- arg (sql-signum arg))))))
2747 (goto-char (if (match-data)
2748 (match-end 0)
2749 here))))
2751 ;;; Small functions
2753 (defun sql-magic-go (arg)
2754 "Insert \"o\" and call `comint-send-input'.
2755 `sql-electric-stuff' must be the symbol `go'."
2756 (interactive "P")
2757 (self-insert-command (prefix-numeric-value arg))
2758 (if (and (equal sql-electric-stuff 'go)
2759 (save-excursion
2760 (comint-bol nil)
2761 (looking-at "go\\b")))
2762 (comint-send-input)))
2764 (defun sql-magic-semicolon (arg)
2765 "Insert semicolon and call `comint-send-input'.
2766 `sql-electric-stuff' must be the symbol `semicolon'."
2767 (interactive "P")
2768 (self-insert-command (prefix-numeric-value arg))
2769 (if (equal sql-electric-stuff 'semicolon)
2770 (comint-send-input)))
2772 (defun sql-accumulate-and-indent ()
2773 "Continue SQL statement on the next line."
2774 (interactive)
2775 (if (fboundp 'comint-accumulate)
2776 (comint-accumulate)
2777 (newline))
2778 (indent-according-to-mode))
2780 (defun sql-help-list-products (indent freep)
2781 "Generate listing of products available for use under SQLi.
2783 List products with :free-software attribute set to FREEP. Indent
2784 each line with INDENT."
2786 (let (sqli-func doc)
2787 (setq doc "")
2788 (dolist (p sql-product-alist)
2789 (setq sqli-func (intern (concat "sql-" (symbol-name (car p)))))
2791 (if (and (fboundp sqli-func)
2792 (eq (sql-get-product-feature (car p) :free-software) freep))
2793 (setq doc
2794 (concat doc
2795 indent
2796 (or (sql-get-product-feature (car p) :name)
2797 (symbol-name (car p)))
2798 ":\t"
2799 "\\["
2800 (symbol-name sqli-func)
2801 "]\n"))))
2802 doc))
2804 ;;;###autoload
2805 (defun sql-help ()
2806 "Show short help for the SQL modes.
2808 Use an entry function to open an interactive SQL buffer. This buffer is
2809 usually named `*SQL*'. The name of the major mode is SQLi.
2811 Use the following commands to start a specific SQL interpreter:
2813 \\\\FREE
2815 Other non-free SQL implementations are also supported:
2817 \\\\NONFREE
2819 But we urge you to choose a free implementation instead of these.
2821 You can also use \\[sql-product-interactive] to invoke the
2822 interpreter for the current `sql-product'.
2824 Once you have the SQLi buffer, you can enter SQL statements in the
2825 buffer. The output generated is appended to the buffer and a new prompt
2826 is generated. See the In/Out menu in the SQLi buffer for some functions
2827 that help you navigate through the buffer, the input history, etc.
2829 If you have a really complex SQL statement or if you are writing a
2830 procedure, you can do this in a separate buffer. Put the new buffer in
2831 `sql-mode' by calling \\[sql-mode]. The name of this buffer can be
2832 anything. The name of the major mode is SQL.
2834 In this SQL buffer (SQL mode), you can send the region or the entire
2835 buffer to the interactive SQL buffer (SQLi mode). The results are
2836 appended to the SQLi buffer without disturbing your SQL buffer."
2837 (interactive)
2839 ;; Insert references to loaded products into the help buffer string
2840 (let ((doc (documentation 'sql-help t))
2841 changedp)
2842 (setq changedp nil)
2844 ;; Insert FREE software list
2845 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]FREE\\s-*\n" doc 0)
2846 (setq doc (replace-match (sql-help-list-products (match-string 1 doc) t)
2847 t t doc 0)
2848 changedp t))
2850 ;; Insert non-FREE software list
2851 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]NONFREE\\s-*\n" doc 0)
2852 (setq doc (replace-match (sql-help-list-products (match-string 1 doc) nil)
2853 t t doc 0)
2854 changedp t))
2856 ;; If we changed the help text, save the change so that the help
2857 ;; sub-system will see it
2858 (when changedp
2859 (put 'sql-help 'function-documentation doc)))
2861 ;; Call help on this function
2862 (describe-function 'sql-help))
2864 (defun sql-read-passwd (prompt &optional default)
2865 "Read a password using PROMPT. Optional DEFAULT is password to start with."
2866 (read-passwd prompt nil default))
2868 (defun sql-get-login-ext (symbol prompt history-var plist)
2869 "Prompt user with extended login parameters.
2871 The global value of SYMBOL is the last value and the global value
2872 of the SYMBOL is set based on the user's input.
2874 If PLIST is nil, then the user is simply prompted for a string
2875 value.
2877 The property `:default' specifies the default value. If the
2878 `:number' property is non-nil then ask for a number.
2880 The `:file' property prompts for a file name that must match the
2881 regexp pattern specified in its value.
2883 The `:completion' property prompts for a string specified by its
2884 value. (The property value is used as the PREDICATE argument to
2885 `completing-read'.)"
2886 (set-default
2887 symbol
2888 (let* ((default (plist-get plist :default))
2889 (last-value (default-value symbol))
2890 (prompt-def
2891 (if default
2892 (if (string-match "\\(\\):[ \t]*\\'" prompt)
2893 (replace-match (format " (default \"%s\")" default) t t prompt 1)
2894 (replace-regexp-in-string "[ \t]*\\'"
2895 (format " (default \"%s\") " default)
2896 prompt t t))
2897 prompt))
2898 (use-dialog-box nil))
2899 (cond
2900 ((plist-member plist :file)
2901 (expand-file-name
2902 (read-file-name prompt
2903 (file-name-directory last-value) default t
2904 (file-name-nondirectory last-value)
2905 (when (plist-get plist :file)
2906 `(lambda (f)
2907 (string-match
2908 (concat "\\<" ,(plist-get plist :file) "\\>")
2909 (file-name-nondirectory f)))))))
2911 ((plist-member plist :completion)
2912 (completing-read prompt-def (plist-get plist :completion) nil t
2913 last-value history-var default))
2915 ((plist-get plist :number)
2916 (read-number prompt (or default last-value 0)))
2919 (let ((r (read-from-minibuffer prompt-def last-value nil nil history-var nil)))
2920 (if (string= "" r) (or default "") r)))))))
2922 (defun sql-get-login (&rest what)
2923 "Get username, password and database from the user.
2925 The variables `sql-user', `sql-password', `sql-server', and
2926 `sql-database' can be customized. They are used as the default values.
2927 Usernames, servers and databases are stored in `sql-user-history',
2928 `sql-server-history' and `database-history'. Passwords are not stored
2929 in a history.
2931 Parameter WHAT is a list of tokens passed as arguments in the
2932 function call. The function asks for the username if WHAT
2933 contains the symbol `user', for the password if it contains the
2934 symbol `password', for the server if it contains the symbol
2935 `server', and for the database if it contains the symbol
2936 `database'. The members of WHAT are processed in the order in
2937 which they are provided.
2939 Each token may also be a list with the token in the car and a
2940 plist of options as the cdr. The following properties are
2941 supported:
2943 :file <filename-regexp>
2944 :completion <list-of-strings-or-function>
2945 :default <default-value>
2946 :number t
2948 In order to ask the user for username, password and database, call the
2949 function like this: (sql-get-login 'user 'password 'database)."
2950 (interactive)
2951 (mapcar
2952 (lambda (w)
2953 (let ((token (or (and (consp w) (car w)) w))
2954 (plist (or (and (consp w) (cdr w)) nil)))
2956 (cond
2957 ((eq token 'user) ; user
2958 (sql-get-login-ext 'sql-user "User: " 'sql-user-history plist))
2960 ((eq token 'password) ; password
2961 (setq-default sql-password
2962 (sql-read-passwd "Password: " sql-password)))
2964 ((eq token 'server) ; server
2965 (sql-get-login-ext 'sql-server "Server: " 'sql-server-history plist))
2967 ((eq token 'database) ; database
2968 (sql-get-login-ext 'sql-database "Database: " 'sql-database-history plist))
2970 ((eq token 'port) ; port
2971 (sql-get-login-ext 'sql-port "Port: " nil (append '(:number t) plist))))))
2972 what))
2974 (defun sql-find-sqli-buffer (&optional product connection)
2975 "Returns the name of the current default SQLi buffer or nil.
2976 In order to qualify, the SQLi buffer must be alive, be in
2977 `sql-interactive-mode' and have a process."
2978 (let ((buf sql-buffer)
2979 (prod (or product sql-product)))
2981 ;; Current sql-buffer, if there is one.
2982 (and (sql-buffer-live-p buf prod connection)
2983 buf)
2984 ;; Global sql-buffer
2985 (and (setq buf (default-value 'sql-buffer))
2986 (sql-buffer-live-p buf prod connection)
2987 buf)
2988 ;; Look thru each buffer
2989 (car (apply 'append
2990 (mapcar (lambda (b)
2991 (and (sql-buffer-live-p b prod connection)
2992 (list (buffer-name b))))
2993 (buffer-list)))))))
2995 (defun sql-set-sqli-buffer-generally ()
2996 "Set SQLi buffer for all SQL buffers that have none.
2997 This function checks all SQL buffers for their SQLi buffer. If their
2998 SQLi buffer is nonexistent or has no process, it is set to the current
2999 default SQLi buffer. The current default SQLi buffer is determined
3000 using `sql-find-sqli-buffer'. If `sql-buffer' is set,
3001 `sql-set-sqli-hook' is run."
3002 (interactive)
3003 (save-excursion
3004 (let ((buflist (buffer-list))
3005 (default-buffer (sql-find-sqli-buffer)))
3006 (setq-default sql-buffer default-buffer)
3007 (while (not (null buflist))
3008 (let ((candidate (car buflist)))
3009 (set-buffer candidate)
3010 (if (and (derived-mode-p 'sql-mode)
3011 (not (sql-buffer-live-p sql-buffer)))
3012 (progn
3013 (setq sql-buffer default-buffer)
3014 (when default-buffer
3015 (run-hooks 'sql-set-sqli-hook)))))
3016 (setq buflist (cdr buflist))))))
3018 (defun sql-set-sqli-buffer ()
3019 "Set the SQLi buffer SQL strings are sent to.
3021 Call this function in a SQL buffer in order to set the SQLi buffer SQL
3022 strings are sent to. Calling this function sets `sql-buffer' and runs
3023 `sql-set-sqli-hook'.
3025 If you call it from a SQL buffer, this sets the local copy of
3026 `sql-buffer'.
3028 If you call it from anywhere else, it sets the global copy of
3029 `sql-buffer'."
3030 (interactive)
3031 (let ((default-buffer (sql-find-sqli-buffer)))
3032 (if (null default-buffer)
3033 (error "There is no suitable SQLi buffer")
3034 (let ((new-buffer (read-buffer "New SQLi buffer: " default-buffer t)))
3035 (if (null (sql-buffer-live-p new-buffer))
3036 (error "Buffer %s is not a working SQLi buffer" new-buffer)
3037 (when new-buffer
3038 (setq sql-buffer new-buffer)
3039 (run-hooks 'sql-set-sqli-hook)))))))
3041 (defun sql-show-sqli-buffer ()
3042 "Show the name of current SQLi buffer.
3044 This is the buffer SQL strings are sent to. It is stored in the
3045 variable `sql-buffer'. See `sql-help' on how to create such a buffer."
3046 (interactive)
3047 (if (or (null sql-buffer)
3048 (null (buffer-live-p (get-buffer sql-buffer))))
3049 (message "%s has no SQLi buffer set." (buffer-name (current-buffer)))
3050 (if (null (get-buffer-process sql-buffer))
3051 (message "Buffer %s has no process." sql-buffer)
3052 (message "Current SQLi buffer is %s." sql-buffer))))
3054 (defun sql-make-alternate-buffer-name ()
3055 "Return a string that can be used to rename a SQLi buffer.
3057 This is used to set `sql-alternate-buffer-name' within
3058 `sql-interactive-mode'.
3060 If the session was started with `sql-connect' then the alternate
3061 name would be the name of the connection.
3063 Otherwise, it uses the parameters identified by the :sqlilogin
3064 parameter.
3066 If all else fails, the alternate name would be the user and
3067 server/database name."
3069 (let ((name ""))
3071 ;; Build a name using the :sqli-login setting
3072 (setq name
3073 (apply 'concat
3074 (cdr
3075 (apply 'append nil
3076 (sql-for-each-login
3077 (sql-get-product-feature sql-product :sqli-login)
3078 (lambda (token plist)
3079 (cond
3080 ((eq token 'user)
3081 (unless (string= "" sql-user)
3082 (list "/" sql-user)))
3083 ((eq token 'port)
3084 (unless (or (not (numberp sql-port))
3085 (= 0 sql-port))
3086 (list ":" (number-to-string sql-port))))
3087 ((eq token 'server)
3088 (unless (string= "" sql-server)
3089 (list "."
3090 (if (plist-member plist :file)
3091 (file-name-nondirectory sql-server)
3092 sql-server))))
3093 ((eq token 'database)
3094 (unless (string= "" sql-database)
3095 (list "@"
3096 (if (plist-member plist :file)
3097 (file-name-nondirectory sql-database)
3098 sql-database))))
3100 ((eq token 'password) nil)
3101 (t nil))))))))
3103 ;; If there's a connection, use it and the name thus far
3104 (if sql-connection
3105 (format "<%s>%s" sql-connection (or name ""))
3107 ;; If there is no name, try to create something meaningful
3108 (if (string= "" (or name ""))
3109 (concat
3110 (if (string= "" sql-user)
3111 (if (string= "" (user-login-name))
3113 (concat (user-login-name) "/"))
3114 (concat sql-user "/"))
3115 (if (string= "" sql-database)
3116 (if (string= "" sql-server)
3117 (system-name)
3118 sql-server)
3119 sql-database))
3121 ;; Use the name we've got
3122 name))))
3124 (defun sql-rename-buffer (&optional new-name)
3125 "Rename a SQL interactive buffer.
3127 Prompts for the new name if command is preceded by
3128 \\[universal-argument]. If no buffer name is provided, then the
3129 `sql-alternate-buffer-name' is used.
3131 The actual buffer name set will be \"*SQL: NEW-NAME*\". If
3132 NEW-NAME is empty, then the buffer name will be \"*SQL*\"."
3133 (interactive "P")
3135 (if (not (derived-mode-p 'sql-interactive-mode))
3136 (message "Current buffer is not a SQL interactive buffer")
3138 (setq sql-alternate-buffer-name
3139 (cond
3140 ((stringp new-name) new-name)
3141 ((consp new-name)
3142 (read-string "Buffer name (\"*SQL: XXX*\"; enter `XXX'): "
3143 sql-alternate-buffer-name))
3144 (t sql-alternate-buffer-name)))
3146 (rename-buffer (if (string= "" sql-alternate-buffer-name)
3147 "*SQL*"
3148 (format "*SQL: %s*" sql-alternate-buffer-name))
3149 t)))
3151 (defun sql-copy-column ()
3152 "Copy current column to the end of buffer.
3153 Inserts SELECT or commas if appropriate."
3154 (interactive)
3155 (let ((column))
3156 (save-excursion
3157 (setq column (buffer-substring-no-properties
3158 (progn (forward-char 1) (backward-sexp 1) (point))
3159 (progn (forward-sexp 1) (point))))
3160 (goto-char (point-max))
3161 (let ((bol (comint-line-beginning-position)))
3162 (cond
3163 ;; if empty command line, insert SELECT
3164 ((= bol (point))
3165 (insert "SELECT "))
3166 ;; else if appending to INTO .* (, SELECT or ORDER BY, insert a comma
3167 ((save-excursion
3168 (re-search-backward "\\b\\(\\(into\\s-+\\S-+\\s-+(\\)\\|select\\|order by\\) .+"
3169 bol t))
3170 (insert ", "))
3171 ;; else insert a space
3173 (if (eq (preceding-char) ?\s)
3175 (insert " ")))))
3176 ;; in any case, insert the column
3177 (insert column)
3178 (message "%s" column))))
3180 ;; On Windows, SQL*Plus for Oracle turns on full buffering for stdout
3181 ;; if it is not attached to a character device; therefore placeholder
3182 ;; replacement by SQL*Plus is fully buffered. The workaround lets
3183 ;; Emacs query for the placeholders.
3185 (defvar sql-placeholder-history nil
3186 "History of placeholder values used.")
3188 (defun sql-placeholders-filter (string)
3189 "Replace placeholders in STRING.
3190 Placeholders are words starting with an ampersand like &this."
3192 (when sql-oracle-scan-on
3193 (while (string-match "&\\(\\sw+\\)" string)
3194 (setq string (replace-match
3195 (read-from-minibuffer
3196 (format "Enter value for %s: " (match-string 1 string))
3197 nil nil nil 'sql-placeholder-history)
3198 t t string))))
3199 string)
3201 ;; Using DB2 interactively, newlines must be escaped with " \".
3202 ;; The space before the backslash is relevant.
3204 (defun sql-escape-newlines-filter (string)
3205 "Escape newlines in STRING.
3206 Every newline in STRING will be preceded with a space and a backslash."
3207 (if (not sql-db2-escape-newlines)
3208 string
3209 (let ((result "") (start 0) mb me)
3210 (while (string-match "\n" string start)
3211 (setq mb (match-beginning 0)
3212 me (match-end 0)
3213 result (concat result
3214 (substring string start mb)
3215 (if (and (> mb 1)
3216 (string-equal " \\" (substring string (- mb 2) mb)))
3217 "" " \\\n"))
3218 start me))
3219 (concat result (substring string start)))))
3223 ;;; Input sender for SQLi buffers
3225 (defvar sql-output-newline-count 0
3226 "Number of newlines in the input string.
3228 Allows the suppression of continuation prompts.")
3230 (defvar sql-output-by-send nil
3231 "Non-nil if the command in the input was generated by `sql-send-string'.")
3233 (defun sql-input-sender (proc string)
3234 "Send STRING to PROC after applying filters."
3236 (let* ((product (with-current-buffer (process-buffer proc) sql-product))
3237 (filter (sql-get-product-feature product :input-filter)))
3239 ;; Apply filter(s)
3240 (cond
3241 ((not filter)
3242 nil)
3243 ((functionp filter)
3244 (setq string (funcall filter string)))
3245 ((listp filter)
3246 (mapc (lambda (f) (setq string (funcall f string))) filter))
3247 (t nil))
3249 ;; Count how many newlines in the string
3250 (setq sql-output-newline-count 0)
3251 (mapc (lambda (ch)
3252 (when (eq ch ?\n)
3253 (setq sql-output-newline-count (1+ sql-output-newline-count))))
3254 string)
3256 ;; Send the string
3257 (comint-simple-send proc string)))
3259 ;;; Strip out continuation prompts
3261 (defvar sql-preoutput-hold nil)
3263 (defun sql-interactive-remove-continuation-prompt (oline)
3264 "Strip out continuation prompts out of the OLINE.
3266 Added to the `comint-preoutput-filter-functions' hook in a SQL
3267 interactive buffer. If `sql-output-newline-count' is greater than
3268 zero, then an output line matching the continuation prompt is filtered
3269 out. If the count is zero, then a newline is inserted into the output
3270 to force the output from the query to appear on a new line.
3272 The complication to this filter is that the continuation prompts
3273 may arrive in multiple chunks. If they do, then the function
3274 saves any unfiltered output in a buffer and prepends that buffer
3275 to the next chunk to properly match the broken-up prompt.
3277 If the filter gets confused, it should reset and stop filtering
3278 to avoid deleting non-prompt output."
3280 (let (did-filter)
3281 (setq oline (concat (or sql-preoutput-hold "") oline)
3282 sql-preoutput-hold nil)
3284 (if (and comint-prompt-regexp
3285 (integerp sql-output-newline-count)
3286 (>= sql-output-newline-count 1))
3287 (progn
3288 (while (and (not (string= oline ""))
3289 (> sql-output-newline-count 0)
3290 (string-match comint-prompt-regexp oline)
3291 (= (match-beginning 0) 0))
3293 (setq oline (replace-match "" nil nil oline)
3294 sql-output-newline-count (1- sql-output-newline-count)
3295 did-filter t))
3297 (if (= sql-output-newline-count 0)
3298 (setq sql-output-newline-count nil
3299 oline (concat "\n" oline)
3300 sql-output-by-send nil)
3302 (setq sql-preoutput-hold oline
3303 oline ""))
3305 (unless did-filter
3306 (setq oline (or sql-preoutput-hold "")
3307 sql-preoutput-hold nil
3308 sql-output-newline-count nil)))
3310 (setq sql-output-newline-count nil))
3312 oline))
3314 ;;; Sending the region to the SQLi buffer.
3316 (defun sql-send-string (str)
3317 "Send the string STR to the SQL process."
3318 (interactive "sSQL Text: ")
3320 (let ((comint-input-sender-no-newline nil)
3321 (s (replace-regexp-in-string "[[:space:]\n\r]+\\'" "" str)))
3322 (if (sql-buffer-live-p sql-buffer)
3323 (progn
3324 ;; Ignore the hoping around...
3325 (save-excursion
3326 ;; Set product context
3327 (with-current-buffer sql-buffer
3328 ;; Send the string (trim the trailing whitespace)
3329 (sql-input-sender (get-buffer-process sql-buffer) s)
3331 ;; Send a command terminator if we must
3332 (if sql-send-terminator
3333 (sql-send-magic-terminator sql-buffer s sql-send-terminator))
3335 (message "Sent string to buffer %s." sql-buffer)))
3337 ;; Display the sql buffer
3338 (if sql-pop-to-buffer-after-send-region
3339 (pop-to-buffer sql-buffer)
3340 (display-buffer sql-buffer)))
3342 ;; We don't have no stinkin' sql
3343 (message "No SQL process started."))))
3345 (defun sql-send-region (start end)
3346 "Send a region to the SQL process."
3347 (interactive "r")
3348 (sql-send-string (buffer-substring-no-properties start end)))
3350 (defun sql-send-paragraph ()
3351 "Send the current paragraph to the SQL process."
3352 (interactive)
3353 (let ((start (save-excursion
3354 (backward-paragraph)
3355 (point)))
3356 (end (save-excursion
3357 (forward-paragraph)
3358 (point))))
3359 (sql-send-region start end)))
3361 (defun sql-send-buffer ()
3362 "Send the buffer contents to the SQL process."
3363 (interactive)
3364 (sql-send-region (point-min) (point-max)))
3366 (defun sql-send-magic-terminator (buf str terminator)
3367 "Send TERMINATOR to buffer BUF if its not present in STR."
3368 (let (comint-input-sender-no-newline pat term)
3369 ;; If flag is merely on(t), get product-specific terminator
3370 (if (eq terminator t)
3371 (setq terminator (sql-get-product-feature sql-product :terminator)))
3373 ;; If there is no terminator specified, use default ";"
3374 (unless terminator
3375 (setq terminator ";"))
3377 ;; Parse the setting into the pattern and the terminator string
3378 (cond ((stringp terminator)
3379 (setq pat (regexp-quote terminator)
3380 term terminator))
3381 ((consp terminator)
3382 (setq pat (car terminator)
3383 term (cdr terminator)))
3385 nil))
3387 ;; Check to see if the pattern is present in the str already sent
3388 (unless (and pat term
3389 (string-match (concat pat "\\'") str))
3390 (comint-simple-send (get-buffer-process buf) term)
3391 (setq sql-output-newline-count
3392 (if sql-output-newline-count
3393 (1+ sql-output-newline-count)
3394 1)))
3395 (setq sql-output-by-send t)))
3397 (defun sql-remove-tabs-filter (str)
3398 "Replace tab characters with spaces."
3399 (replace-regexp-in-string "\t" " " str nil t))
3401 (defun sql-toggle-pop-to-buffer-after-send-region (&optional value)
3402 "Toggle `sql-pop-to-buffer-after-send-region'.
3404 If given the optional parameter VALUE, sets
3405 `sql-toggle-pop-to-buffer-after-send-region' to VALUE."
3406 (interactive "P")
3407 (if value
3408 (setq sql-pop-to-buffer-after-send-region value)
3409 (setq sql-pop-to-buffer-after-send-region
3410 (null sql-pop-to-buffer-after-send-region))))
3414 ;;; Redirect output functions
3416 (defvar sql-debug-redirect nil
3417 "If non-nil, display messages related to the use of redirection.")
3419 (defun sql-str-literal (s)
3420 (concat "'" (replace-regexp-in-string "[']" "''" s) "'"))
3422 (defun sql-redirect (sqlbuf command &optional outbuf save-prior)
3423 "Execute the SQL command and send output to OUTBUF.
3425 SQLBUF must be an active SQL interactive buffer. OUTBUF may be
3426 an existing buffer, or the name of a non-existing buffer. If
3427 omitted the output is sent to a temporary buffer which will be
3428 killed after the command completes. COMMAND should be a string
3429 of commands accepted by the SQLi program. COMMAND may also be a
3430 list of SQLi command strings."
3432 (let* ((visible (and outbuf
3433 (not (string= " " (substring outbuf 0 1))))))
3434 (when visible
3435 (message "Executing SQL command..."))
3436 (if (consp command)
3437 (mapc (lambda (c) (sql-redirect-one sqlbuf c outbuf save-prior))
3438 command)
3439 (sql-redirect-one sqlbuf command outbuf save-prior))
3440 (when visible
3441 (message "Executing SQL command...done"))))
3443 (defun sql-redirect-one (sqlbuf command outbuf save-prior)
3444 (with-current-buffer sqlbuf
3445 (let ((buf (get-buffer-create (or outbuf " *SQL-Redirect*")))
3446 (proc (get-buffer-process (current-buffer)))
3447 (comint-prompt-regexp (sql-get-product-feature sql-product
3448 :prompt-regexp))
3449 (start nil))
3450 (with-current-buffer buf
3451 (setq view-read-only nil)
3452 (unless save-prior
3453 (erase-buffer))
3454 (goto-char (point-max))
3455 (unless (zerop (buffer-size))
3456 (insert "\n"))
3457 (setq start (point)))
3459 (when sql-debug-redirect
3460 (message ">>SQL> %S" command))
3462 ;; Run the command
3463 (comint-redirect-send-command-to-process command buf proc nil t)
3464 (while (null comint-redirect-completed)
3465 (accept-process-output nil 1))
3467 ;; Clean up the output results
3468 (with-current-buffer buf
3469 ;; Remove trailing whitespace
3470 (goto-char (point-max))
3471 (when (looking-back "[ \t\f\n\r]*" start)
3472 (delete-region (match-beginning 0) (match-end 0)))
3473 ;; Remove echo if there was one
3474 (goto-char start)
3475 (when (looking-at (concat "^" (regexp-quote command) "[\\n]"))
3476 (delete-region (match-beginning 0) (match-end 0)))
3477 ;; Remove Ctrl-Ms
3478 (goto-char start)
3479 (while (re-search-forward "\r+$" nil t)
3480 (replace-match "" t t))
3481 (goto-char start)))))
3483 (defun sql-redirect-value (sqlbuf command regexp &optional regexp-groups)
3484 "Execute the SQL command and return part of result.
3486 SQLBUF must be an active SQL interactive buffer. COMMAND should
3487 be a string of commands accepted by the SQLi program. From the
3488 output, the REGEXP is repeatedly matched and the list of
3489 REGEXP-GROUPS submatches is returned. This behaves much like
3490 \\[comint-redirect-results-list-from-process] but instead of
3491 returning a single submatch it returns a list of each submatch
3492 for each match."
3494 (let ((outbuf " *SQL-Redirect-values*")
3495 (results nil))
3496 (sql-redirect sqlbuf command outbuf nil)
3497 (with-current-buffer outbuf
3498 (while (re-search-forward regexp nil t)
3499 (push
3500 (cond
3501 ;; no groups-return all of them
3502 ((null regexp-groups)
3503 (let ((i (/ (length (match-data)) 2))
3504 (r nil))
3505 (while (> i 0)
3506 (setq i (1- i))
3507 (push (match-string i) r))
3509 ;; one group specified
3510 ((numberp regexp-groups)
3511 (match-string regexp-groups))
3512 ;; list of numbers; return the specified matches only
3513 ((consp regexp-groups)
3514 (mapcar (lambda (c)
3515 (cond
3516 ((numberp c) (match-string c))
3517 ((stringp c) (match-substitute-replacement c))
3518 (t (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s" c))))
3519 regexp-groups))
3520 ;; String is specified; return replacement string
3521 ((stringp regexp-groups)
3522 (match-substitute-replacement regexp-groups))
3524 (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s"
3525 regexp-groups)))
3526 results)))
3528 (when sql-debug-redirect
3529 (message ">>SQL> = %S" (reverse results)))
3531 (nreverse results)))
3533 (defun sql-execute (sqlbuf outbuf command enhanced arg)
3534 "Executes a command in a SQL interactive buffer and captures the output.
3536 The commands are run in SQLBUF and the output saved in OUTBUF.
3537 COMMAND must be a string, a function or a list of such elements.
3538 Functions are called with SQLBUF, OUTBUF and ARG as parameters;
3539 strings are formatted with ARG and executed.
3541 If the results are empty the OUTBUF is deleted, otherwise the
3542 buffer is popped into a view window. "
3543 (mapc
3544 (lambda (c)
3545 (cond
3546 ((stringp c)
3547 (sql-redirect sqlbuf (if arg (format c arg) c) outbuf) t)
3548 ((functionp c)
3549 (apply c sqlbuf outbuf enhanced arg nil))
3550 (t (error "Unknown sql-execute item %s" c))))
3551 (if (consp command) command (cons command nil)))
3553 (setq outbuf (get-buffer outbuf))
3554 (if (zerop (buffer-size outbuf))
3555 (kill-buffer outbuf)
3556 (let ((one-win (eq (selected-window)
3557 (get-lru-window))))
3558 (with-current-buffer outbuf
3559 (set-buffer-modified-p nil)
3560 (setq view-read-only t))
3561 (view-buffer-other-window outbuf)
3562 (when one-win
3563 (shrink-window-if-larger-than-buffer)))))
3565 (defun sql-execute-feature (sqlbuf outbuf feature enhanced arg)
3566 "List objects or details in a separate display buffer."
3567 (let (command)
3568 (with-current-buffer sqlbuf
3569 (setq command (sql-get-product-feature sql-product feature)))
3570 (unless command
3571 (error "%s does not support %s" sql-product feature))
3572 (when (consp command)
3573 (setq command (if enhanced
3574 (cdr command)
3575 (car command))))
3576 (sql-execute sqlbuf outbuf command enhanced arg)))
3578 (defvar sql-completion-object nil
3579 "A list of database objects used for completion.
3581 The list is maintained in SQL interactive buffers.")
3583 (defvar sql-completion-column nil
3584 "A list of column names used for completion.
3586 The list is maintained in SQL interactive buffers.")
3588 (defun sql-build-completions-1 (schema completion-list feature)
3589 "Generate a list of objects in the database for use as completions."
3590 (let ((f (sql-get-product-feature sql-product feature)))
3591 (when f
3592 (set completion-list
3593 (let (cl)
3594 (dolist (e (append (symbol-value completion-list)
3595 (apply f (current-buffer) (cons schema nil)))
3597 (unless (member e cl) (setq cl (cons e cl))))
3598 (sort cl (function string<)))))))
3600 (defun sql-build-completions (schema)
3601 "Generate a list of names in the database for use as completions."
3602 (sql-build-completions-1 schema 'sql-completion-object :completion-object)
3603 (sql-build-completions-1 schema 'sql-completion-column :completion-column))
3605 (defvar sql-completion-sqlbuf nil)
3607 (defun sql-try-completion (string collection &optional predicate)
3608 (when sql-completion-sqlbuf
3609 (with-current-buffer sql-completion-sqlbuf
3610 (let ((schema (and (string-match "\\`\\(\\sw\\(:?\\sw\\|\\s_\\)*\\)[.]" string)
3611 (downcase (match-string 1 string)))))
3613 ;; If we haven't loaded any object name yet, load local schema
3614 (unless sql-completion-object
3615 (sql-build-completions nil))
3617 ;; If they want another schema, load it if we haven't yet
3618 (when schema
3619 (let ((schema-dot (concat schema "."))
3620 (schema-len (1+ (length schema)))
3621 (names sql-completion-object)
3622 has-schema)
3624 (while (and (not has-schema) names)
3625 (setq has-schema (and
3626 (>= (length (car names)) schema-len)
3627 (string= schema-dot
3628 (downcase (substring (car names)
3629 0 schema-len))))
3630 names (cdr names)))
3631 (unless has-schema
3632 (sql-build-completions schema)))))
3634 ;; Try to find the completion
3635 (cond
3636 ((not predicate)
3637 (try-completion string sql-completion-object))
3638 ((eq predicate t)
3639 (all-completions string sql-completion-object))
3640 ((eq predicate 'lambda)
3641 (test-completion string sql-completion-object))
3642 ((eq (car predicate) 'boundaries)
3643 (completion-boundaries string sql-completion-object nil (cdr predicate)))))))
3645 (defun sql-read-table-name (prompt)
3646 "Read the name of a database table."
3647 (let* ((tname
3648 (and (buffer-local-value 'sql-contains-names (current-buffer))
3649 (thing-at-point-looking-at
3650 (concat "\\_<\\sw\\(:?\\sw\\|\\s_\\)*"
3651 "\\(?:[.]+\\sw\\(?:\\sw\\|\\s_\\)*\\)*\\_>"))
3652 (buffer-substring-no-properties (match-beginning 0)
3653 (match-end 0))))
3654 (sql-completion-sqlbuf (sql-find-sqli-buffer))
3655 (product (with-current-buffer sql-completion-sqlbuf sql-product))
3656 (completion-ignore-case t))
3658 (if (sql-get-product-feature product :completion-object)
3659 (completing-read prompt (function sql-try-completion)
3660 nil nil tname)
3661 (read-from-minibuffer prompt tname))))
3663 (defun sql-list-all (&optional enhanced)
3664 "List all database objects.
3665 With optional prefix argument ENHANCED, displays additional
3666 details or extends the listing to include other schemas objects."
3667 (interactive "P")
3668 (let ((sqlbuf (sql-find-sqli-buffer)))
3669 (unless sqlbuf
3670 (error "No SQL interactive buffer found"))
3671 (sql-execute-feature sqlbuf "*List All*" :list-all enhanced nil)
3672 (with-current-buffer sqlbuf
3673 ;; Contains the name of database objects
3674 (set (make-local-variable 'sql-contains-names) t)
3675 (set (make-local-variable 'sql-buffer) sqlbuf))))
3677 (defun sql-list-table (name &optional enhanced)
3678 "List the details of a database table named NAME.
3679 Displays the columns in the relation. With optional prefix argument
3680 ENHANCED, displays additional details about each column."
3681 (interactive
3682 (list (sql-read-table-name "Table name: ")
3683 current-prefix-arg))
3684 (let ((sqlbuf (sql-find-sqli-buffer)))
3685 (unless sqlbuf
3686 (error "No SQL interactive buffer found"))
3687 (unless name
3688 (error "No table name specified"))
3689 (sql-execute-feature sqlbuf (format "*List %s*" name)
3690 :list-table enhanced name)))
3693 ;;; SQL mode -- uses SQL interactive mode
3695 ;;;###autoload
3696 (define-derived-mode sql-mode prog-mode "SQL"
3697 "Major mode to edit SQL.
3699 You can send SQL statements to the SQLi buffer using
3700 \\[sql-send-region]. Such a buffer must exist before you can do this.
3701 See `sql-help' on how to create SQLi buffers.
3703 \\{sql-mode-map}
3704 Customization: Entry to this mode runs the `sql-mode-hook'.
3706 When you put a buffer in SQL mode, the buffer stores the last SQLi
3707 buffer created as its destination in the variable `sql-buffer'. This
3708 will be the buffer \\[sql-send-region] sends the region to. If this
3709 SQLi buffer is killed, \\[sql-send-region] is no longer able to
3710 determine where the strings should be sent to. You can set the
3711 value of `sql-buffer' using \\[sql-set-sqli-buffer].
3713 For information on how to create multiple SQLi buffers, see
3714 `sql-interactive-mode'.
3716 Note that SQL doesn't have an escape character unless you specify
3717 one. If you specify backslash as escape character in SQL, you
3718 must tell Emacs. Here's how to do that in your init file:
3720 \(add-hook 'sql-mode-hook
3721 (lambda ()
3722 (modify-syntax-entry ?\\\\ \".\" sql-mode-syntax-table)))"
3723 :abbrev-table sql-mode-abbrev-table
3724 (if sql-mode-menu
3725 (easy-menu-add sql-mode-menu)); XEmacs
3727 (set (make-local-variable 'comment-start) "--")
3728 ;; Make each buffer in sql-mode remember the "current" SQLi buffer.
3729 (make-local-variable 'sql-buffer)
3730 ;; Add imenu support for sql-mode. Note that imenu-generic-expression
3731 ;; is buffer-local, so we don't need a local-variable for it. SQL is
3732 ;; case-insensitive, that's why we have to set imenu-case-fold-search.
3733 (setq imenu-generic-expression sql-imenu-generic-expression
3734 imenu-case-fold-search t)
3735 ;; Make `sql-send-paragraph' work on paragraphs that contain indented
3736 ;; lines.
3737 (set (make-local-variable 'paragraph-separate) "[\f]*$")
3738 (set (make-local-variable 'paragraph-start) "[\n\f]")
3739 ;; Abbrevs
3740 (setq abbrev-all-caps 1)
3741 ;; Contains the name of database objects
3742 (set (make-local-variable 'sql-contains-names) t)
3743 ;; Catch changes to sql-product and highlight accordingly
3744 (add-hook 'hack-local-variables-hook 'sql-highlight-product t t))
3748 ;;; SQL interactive mode
3750 (put 'sql-interactive-mode 'mode-class 'special)
3752 (defun sql-interactive-mode ()
3753 "Major mode to use a SQL interpreter interactively.
3755 Do not call this function by yourself. The environment must be
3756 initialized by an entry function specific for the SQL interpreter.
3757 See `sql-help' for a list of available entry functions.
3759 \\[comint-send-input] after the end of the process' output sends the
3760 text from the end of process to the end of the current line.
3761 \\[comint-send-input] before end of process output copies the current
3762 line minus the prompt to the end of the buffer and sends it.
3763 \\[comint-copy-old-input] just copies the current line.
3764 Use \\[sql-accumulate-and-indent] to enter multi-line statements.
3766 If you want to make multiple SQL buffers, rename the `*SQL*' buffer
3767 using \\[rename-buffer] or \\[rename-uniquely] and start a new process.
3768 See `sql-help' for a list of available entry functions. The last buffer
3769 created by such an entry function is the current SQLi buffer. SQL
3770 buffers will send strings to the SQLi buffer current at the time of
3771 their creation. See `sql-mode' for details.
3773 Sample session using two connections:
3775 1. Create first SQLi buffer by calling an entry function.
3776 2. Rename buffer \"*SQL*\" to \"*Connection 1*\".
3777 3. Create a SQL buffer \"test1.sql\".
3778 4. Create second SQLi buffer by calling an entry function.
3779 5. Rename buffer \"*SQL*\" to \"*Connection 2*\".
3780 6. Create a SQL buffer \"test2.sql\".
3782 Now \\[sql-send-region] in buffer \"test1.sql\" will send the region to
3783 buffer \"*Connection 1*\", \\[sql-send-region] in buffer \"test2.sql\"
3784 will send the region to buffer \"*Connection 2*\".
3786 If you accidentally suspend your process, use \\[comint-continue-subjob]
3787 to continue it. On some operating systems, this will not work because
3788 the signals are not supported.
3790 \\{sql-interactive-mode-map}
3791 Customization: Entry to this mode runs the hooks on `comint-mode-hook'
3792 and `sql-interactive-mode-hook' (in that order). Before each input, the
3793 hooks on `comint-input-filter-functions' are run. After each SQL
3794 interpreter output, the hooks on `comint-output-filter-functions' are
3795 run.
3797 Variable `sql-input-ring-file-name' controls the initialization of the
3798 input ring history.
3800 Variables `comint-output-filter-functions', a hook, and
3801 `comint-scroll-to-bottom-on-input' and
3802 `comint-scroll-to-bottom-on-output' control whether input and output
3803 cause the window to scroll to the end of the buffer.
3805 If you want to make SQL buffers limited in length, add the function
3806 `comint-truncate-buffer' to `comint-output-filter-functions'.
3808 Here is an example for your init file. It keeps the SQLi buffer a
3809 certain length.
3811 \(add-hook 'sql-interactive-mode-hook
3812 \(function (lambda ()
3813 \(setq comint-output-filter-functions 'comint-truncate-buffer))))
3815 Here is another example. It will always put point back to the statement
3816 you entered, right above the output it created.
3818 \(setq comint-output-filter-functions
3819 \(function (lambda (STR) (comint-show-output))))"
3820 (delay-mode-hooks (comint-mode))
3822 ;; Get the `sql-product' for this interactive session.
3823 (set (make-local-variable 'sql-product)
3824 (or sql-interactive-product
3825 sql-product))
3827 ;; Setup the mode.
3828 (setq major-mode 'sql-interactive-mode)
3829 (setq mode-name
3830 (concat "SQLi[" (or (sql-get-product-feature sql-product :name)
3831 (symbol-name sql-product)) "]"))
3832 (use-local-map sql-interactive-mode-map)
3833 (if sql-interactive-mode-menu
3834 (easy-menu-add sql-interactive-mode-menu)) ; XEmacs
3835 (set-syntax-table sql-mode-syntax-table)
3837 ;; Note that making KEYWORDS-ONLY nil will cause havoc if you try
3838 ;; SELECT 'x' FROM DUAL with SQL*Plus, because the title of the column
3839 ;; will have just one quote. Therefore syntactic highlighting is
3840 ;; disabled for interactive buffers. No imenu support.
3841 (sql-product-font-lock t nil)
3843 ;; Enable commenting and uncommenting of the region.
3844 (set (make-local-variable 'comment-start) "--")
3845 ;; Abbreviation table init and case-insensitive. It is not activated
3846 ;; by default.
3847 (setq local-abbrev-table sql-mode-abbrev-table)
3848 (setq abbrev-all-caps 1)
3849 ;; Exiting the process will call sql-stop.
3850 (set-process-sentinel (get-buffer-process (current-buffer)) 'sql-stop)
3851 ;; Save the connection and login params
3852 (set (make-local-variable 'sql-user) sql-user)
3853 (set (make-local-variable 'sql-database) sql-database)
3854 (set (make-local-variable 'sql-server) sql-server)
3855 (set (make-local-variable 'sql-port) sql-port)
3856 (set (make-local-variable 'sql-connection) sql-connection)
3857 (setq-default sql-connection nil)
3858 ;; Contains the name of database objects
3859 (set (make-local-variable 'sql-contains-names) t)
3860 ;; Keep track of existing object names
3861 (set (make-local-variable 'sql-completion-object) nil)
3862 (set (make-local-variable 'sql-completion-column) nil)
3863 ;; Create a useful name for renaming this buffer later.
3864 (set (make-local-variable 'sql-alternate-buffer-name)
3865 (sql-make-alternate-buffer-name))
3866 ;; User stuff. Initialize before the hook.
3867 (set (make-local-variable 'sql-prompt-regexp)
3868 (sql-get-product-feature sql-product :prompt-regexp))
3869 (set (make-local-variable 'sql-prompt-length)
3870 (sql-get-product-feature sql-product :prompt-length))
3871 (set (make-local-variable 'sql-prompt-cont-regexp)
3872 (sql-get-product-feature sql-product :prompt-cont-regexp))
3873 (make-local-variable 'sql-output-newline-count)
3874 (make-local-variable 'sql-preoutput-hold)
3875 (make-local-variable 'sql-output-by-send)
3876 (add-hook 'comint-preoutput-filter-functions
3877 'sql-interactive-remove-continuation-prompt nil t)
3878 (make-local-variable 'sql-input-ring-separator)
3879 (make-local-variable 'sql-input-ring-file-name)
3880 ;; Run the mode hook (along with comint's hooks).
3881 (run-mode-hooks 'sql-interactive-mode-hook)
3882 ;; Set comint based on user overrides.
3883 (setq comint-prompt-regexp
3884 (if sql-prompt-cont-regexp
3885 (concat "\\(" sql-prompt-regexp
3886 "\\|" sql-prompt-cont-regexp "\\)")
3887 sql-prompt-regexp))
3888 (setq left-margin sql-prompt-length)
3889 ;; Install input sender
3890 (set (make-local-variable 'comint-input-sender) 'sql-input-sender)
3891 ;; People wanting a different history file for each
3892 ;; buffer/process/client/whatever can change separator and file-name
3893 ;; on the sql-interactive-mode-hook.
3894 (setq comint-input-ring-separator sql-input-ring-separator
3895 comint-input-ring-file-name sql-input-ring-file-name)
3896 ;; Calling the hook before calling comint-read-input-ring allows users
3897 ;; to set comint-input-ring-file-name in sql-interactive-mode-hook.
3898 (comint-read-input-ring t))
3900 (defun sql-stop (process event)
3901 "Called when the SQL process is stopped.
3903 Writes the input history to a history file using
3904 `comint-write-input-ring' and inserts a short message in the SQL buffer.
3906 This function is a sentinel watching the SQL interpreter process.
3907 Sentinels will always get the two parameters PROCESS and EVENT."
3908 (comint-write-input-ring)
3909 (if (and (eq (current-buffer) sql-buffer)
3910 (not buffer-read-only))
3911 (insert (format "\nProcess %s %s\n" process event))
3912 (message "Process %s %s" process event)))
3916 ;;; Connection handling
3918 (defun sql-read-connection (prompt &optional initial default)
3919 "Read a connection name."
3920 (let ((completion-ignore-case t))
3921 (completing-read prompt
3922 (mapcar (lambda (c) (car c))
3923 sql-connection-alist)
3924 nil t initial 'sql-connection-history default)))
3926 ;;;###autoload
3927 (defun sql-connect (connection &optional new-name)
3928 "Connect to an interactive session using CONNECTION settings.
3930 See `sql-connection-alist' to see how to define connections and
3931 their settings.
3933 The user will not be prompted for any login parameters if a value
3934 is specified in the connection settings."
3936 ;; Prompt for the connection from those defined in the alist
3937 (interactive
3938 (if sql-connection-alist
3939 (list (sql-read-connection "Connection: " nil '(nil))
3940 current-prefix-arg)
3941 nil))
3943 ;; Are there connections defined
3944 (if sql-connection-alist
3945 ;; Was one selected
3946 (when connection
3947 ;; Get connection settings
3948 (let ((connect-set (assoc connection sql-connection-alist)))
3949 ;; Settings are defined
3950 (if connect-set
3951 ;; Set the desired parameters
3952 (let (param-var login-params set-params rem-params)
3954 ;; :sqli-login params variable
3955 (setq param-var
3956 (sql-get-product-feature sql-product :sqli-login nil t))
3958 ;; :sqli-login params value
3959 (setq login-params
3960 (sql-get-product-feature sql-product :sqli-login))
3962 ;; Params in the connection
3963 (setq set-params
3964 (mapcar
3965 (lambda (v)
3966 (cond
3967 ((eq (car v) 'sql-user) 'user)
3968 ((eq (car v) 'sql-password) 'password)
3969 ((eq (car v) 'sql-server) 'server)
3970 ((eq (car v) 'sql-database) 'database)
3971 ((eq (car v) 'sql-port) 'port)
3972 (t (car v))))
3973 (cdr connect-set)))
3975 ;; the remaining params (w/o the connection params)
3976 (setq rem-params
3977 (sql-for-each-login login-params
3978 (lambda (token plist)
3979 (unless (member token set-params)
3980 (if plist (cons token plist) token)))))
3982 ;; Set the parameters and start the interactive session
3983 (mapc
3984 (lambda (vv)
3985 (set-default (car vv) (eval (cadr vv))))
3986 (cdr connect-set))
3987 (setq-default sql-connection connection)
3989 ;; Start the SQLi session with revised list of login parameters
3990 (eval `(let ((,param-var ',rem-params))
3991 (sql-product-interactive sql-product new-name))))
3993 (message "SQL Connection <%s> does not exist" connection)
3994 nil)))
3996 (message "No SQL Connections defined")
3997 nil))
3999 (defun sql-save-connection (name)
4000 "Captures the connection information of the current SQLi session.
4002 The information is appended to `sql-connection-alist' and
4003 optionally is saved to the user's init file."
4005 (interactive "sNew connection name: ")
4007 (unless (derived-mode-p 'sql-interactive-mode)
4008 (error "Not in a SQL interactive mode!"))
4010 ;; Capture the buffer local settings
4011 (let* ((buf (current-buffer))
4012 (connection (buffer-local-value 'sql-connection buf))
4013 (product (buffer-local-value 'sql-product buf))
4014 (user (buffer-local-value 'sql-user buf))
4015 (database (buffer-local-value 'sql-database buf))
4016 (server (buffer-local-value 'sql-server buf))
4017 (port (buffer-local-value 'sql-port buf)))
4019 (if connection
4020 (message "This session was started by a connection; it's already been saved.")
4022 (let ((login (sql-get-product-feature product :sqli-login))
4023 (alist sql-connection-alist)
4024 connect)
4026 ;; Remove the existing connection if the user says so
4027 (when (and (assoc name alist)
4028 (yes-or-no-p (format "Replace connection definition <%s>? " name)))
4029 (setq alist (assq-delete-all name alist)))
4031 ;; Add the new connection if it doesn't exist
4032 (if (assoc name alist)
4033 (message "Connection <%s> already exists" name)
4034 (setq connect
4035 (append (list name)
4036 (sql-for-each-login
4037 `(product ,@login)
4038 (lambda (token _plist)
4039 (cond
4040 ((eq token 'product) `(sql-product ',product))
4041 ((eq token 'user) `(sql-user ,user))
4042 ((eq token 'database) `(sql-database ,database))
4043 ((eq token 'server) `(sql-server ,server))
4044 ((eq token 'port) `(sql-port ,port)))))))
4046 (setq alist (append alist (list connect)))
4048 ;; confirm whether we want to save the connections
4049 (if (yes-or-no-p "Save the connections for future sessions? ")
4050 (customize-save-variable 'sql-connection-alist alist)
4051 (customize-set-variable 'sql-connection-alist alist)))))))
4053 (defun sql-connection-menu-filter (tail)
4054 "Generates menu entries for using each connection."
4055 (append
4056 (mapcar
4057 (lambda (conn)
4058 (vector
4059 (format "Connection <%s>\t%s" (car conn)
4060 (let ((sql-user "") (sql-database "")
4061 (sql-server "") (sql-port 0))
4062 (eval `(let ,(cdr conn) (sql-make-alternate-buffer-name)))))
4063 (list 'sql-connect (car conn))
4065 sql-connection-alist)
4066 tail))
4070 ;;; Entry functions for different SQL interpreters.
4072 ;;;###autoload
4073 (defun sql-product-interactive (&optional product new-name)
4074 "Run PRODUCT interpreter as an inferior process.
4076 If buffer `*SQL*' exists but no process is running, make a new process.
4077 If buffer exists and a process is running, just switch to buffer `*SQL*'.
4079 To specify the SQL product, prefix the call with
4080 \\[universal-argument]. To set the buffer name as well, prefix
4081 the call to \\[sql-product-interactive] with
4082 \\[universal-argument] \\[universal-argument].
4084 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4085 (interactive "P")
4087 ;; Handle universal arguments if specified
4088 (when (not (or executing-kbd-macro noninteractive))
4089 (when (and (consp product)
4090 (not (cdr product))
4091 (numberp (car product)))
4092 (when (>= (prefix-numeric-value product) 16)
4093 (when (not new-name)
4094 (setq new-name '(4)))
4095 (setq product '(4)))))
4097 ;; Get the value of product that we need
4098 (setq product
4099 (cond
4100 ((= (prefix-numeric-value product) 4) ; C-u, prompt for product
4101 (sql-read-product "SQL product: " sql-product))
4102 ((and product ; Product specified
4103 (symbolp product)) product)
4104 (t sql-product))) ; Default to sql-product
4106 ;; If we have a product and it has a interactive mode
4107 (if product
4108 (when (sql-get-product-feature product :sqli-comint-func)
4109 ;; If no new name specified, try to pop to an active SQL
4110 ;; interactive for the same product
4111 (let ((buf (sql-find-sqli-buffer product sql-connection)))
4112 (if (and (not new-name) buf)
4113 (pop-to-buffer buf)
4115 ;; We have a new name or sql-buffer doesn't exist or match
4116 ;; Start by remembering where we start
4117 (let ((start-buffer (current-buffer))
4118 new-sqli-buffer)
4120 ;; Get credentials.
4121 (apply 'sql-get-login (sql-get-product-feature product :sqli-login))
4123 ;; Connect to database.
4124 (message "Login...")
4125 (let ((sql-user (default-value 'sql-user))
4126 (sql-password (default-value 'sql-password))
4127 (sql-server (default-value 'sql-server))
4128 (sql-database (default-value 'sql-database))
4129 (sql-port (default-value 'sql-port)))
4130 (funcall (sql-get-product-feature product :sqli-comint-func)
4131 product
4132 (sql-get-product-feature product :sqli-options)))
4134 ;; Set SQLi mode.
4135 (let ((sql-interactive-product product))
4136 (sql-interactive-mode))
4138 ;; Set the new buffer name
4139 (setq new-sqli-buffer (current-buffer))
4140 (when new-name
4141 (sql-rename-buffer new-name))
4142 (set (make-local-variable 'sql-buffer)
4143 (buffer-name new-sqli-buffer))
4145 ;; Set `sql-buffer' in the start buffer
4146 (with-current-buffer start-buffer
4147 (when (derived-mode-p 'sql-mode)
4148 (setq sql-buffer (buffer-name new-sqli-buffer))
4149 (run-hooks 'sql-set-sqli-hook)))
4151 ;; All done.
4152 (message "Login...done")
4153 (run-hooks 'sql-login-hook)
4154 (pop-to-buffer new-sqli-buffer)))))
4155 (message "No default SQL product defined. Set `sql-product'.")))
4157 (defun sql-comint (product params)
4158 "Set up a comint buffer to run the SQL processor.
4160 PRODUCT is the SQL product. PARAMS is a list of strings which are
4161 passed as command line arguments."
4162 (let ((program (sql-get-product-feature product :sqli-program))
4163 (buf-name "SQL"))
4164 ;; Make sure we can find the program. `executable-find' does not
4165 ;; work for remote hosts; we suppress the check there.
4166 (unless (or (file-remote-p default-directory)
4167 (executable-find program))
4168 (error "Unable to locate SQL program \'%s\'" program))
4169 ;; Make sure buffer name is unique.
4170 (when (sql-buffer-live-p (format "*%s*" buf-name))
4171 (setq buf-name (format "SQL-%s" product))
4172 (when (sql-buffer-live-p (format "*%s*" buf-name))
4173 (let ((i 1))
4174 (while (sql-buffer-live-p
4175 (format "*%s*"
4176 (setq buf-name (format "SQL-%s%d" product i))))
4177 (setq i (1+ i))))))
4178 (set-buffer
4179 (apply 'make-comint buf-name program nil params))))
4181 ;;;###autoload
4182 (defun sql-oracle (&optional buffer)
4183 "Run sqlplus by Oracle as an inferior process.
4185 If buffer `*SQL*' exists but no process is running, make a new process.
4186 If buffer exists and a process is running, just switch to buffer
4187 `*SQL*'.
4189 Interpreter used comes from variable `sql-oracle-program'. Login uses
4190 the variables `sql-user', `sql-password', and `sql-database' as
4191 defaults, if set. Additional command line parameters can be stored in
4192 the list `sql-oracle-options'.
4194 The buffer is put in SQL interactive mode, giving commands for sending
4195 input. See `sql-interactive-mode'.
4197 To set the buffer name directly, use \\[universal-argument]
4198 before \\[sql-oracle]. Once session has started,
4199 \\[sql-rename-buffer] can be called separately to rename the
4200 buffer.
4202 To specify a coding system for converting non-ASCII characters
4203 in the input and output to the process, use \\[universal-coding-system-argument]
4204 before \\[sql-oracle]. You can also specify this with \\[set-buffer-process-coding-system]
4205 in the SQL buffer, after you start the process.
4206 The default comes from `process-coding-system-alist' and
4207 `default-process-coding-system'.
4209 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4210 (interactive "P")
4211 (sql-product-interactive 'oracle buffer))
4213 (defun sql-comint-oracle (product options)
4214 "Create comint buffer and connect to Oracle."
4215 ;; Produce user/password@database construct. Password without user
4216 ;; is meaningless; database without user/password is meaningless,
4217 ;; because "@param" will ask sqlplus to interpret the script
4218 ;; "param".
4219 (let ((parameter nil))
4220 (if (not (string= "" sql-user))
4221 (if (not (string= "" sql-password))
4222 (setq parameter (concat sql-user "/" sql-password))
4223 (setq parameter sql-user)))
4224 (if (and parameter (not (string= "" sql-database)))
4225 (setq parameter (concat parameter "@" sql-database)))
4226 (if parameter
4227 (setq parameter (nconc (list parameter) options))
4228 (setq parameter options))
4229 (sql-comint product parameter)))
4231 (defun sql-oracle-save-settings (sqlbuf)
4232 "Saves most SQL*Plus settings so they may be reset by \\[sql-redirect]."
4233 ;; Note: does not capture the following settings:
4235 ;; APPINFO
4236 ;; BTITLE
4237 ;; COMPATIBILITY
4238 ;; COPYTYPECHECK
4239 ;; MARKUP
4240 ;; RELEASE
4241 ;; REPFOOTER
4242 ;; REPHEADER
4243 ;; SQLPLUSCOMPATIBILITY
4244 ;; TTITLE
4245 ;; USER
4248 (append
4249 ;; (apply 'concat (append
4250 ;; '("SET")
4252 ;; option value...
4253 (sql-redirect-value
4254 sqlbuf
4255 (concat "SHOW ARRAYSIZE AUTOCOMMIT AUTOPRINT AUTORECOVERY AUTOTRACE"
4256 " CMDSEP COLSEP COPYCOMMIT DESCRIBE ECHO EDITFILE EMBEDDED"
4257 " ESCAPE FLAGGER FLUSH HEADING INSTANCE LINESIZE LNO LOBOFFSET"
4258 " LOGSOURCE LONG LONGCHUNKSIZE NEWPAGE NULL NUMFORMAT NUMWIDTH"
4259 " PAGESIZE PAUSE PNO RECSEP SERVEROUTPUT SHIFTINOUT SHOWMODE"
4260 " SPOOL SQLBLANKLINES SQLCASE SQLCODE SQLCONTINUE SQLNUMBER"
4261 " SQLPROMPT SUFFIX TAB TERMOUT TIMING TRIMOUT TRIMSPOOL VERIFY")
4262 "^.+$"
4263 "SET \\&")
4265 ;; option "c" (hex xx)
4266 (sql-redirect-value
4267 sqlbuf
4268 (concat "SHOW BLOCKTERMINATOR CONCAT DEFINE SQLPREFIX SQLTERMINATOR"
4269 " UNDERLINE HEADSEP RECSEPCHAR")
4270 "^\\(.+\\) (hex ..)$"
4271 "SET \\1")
4273 ;; FEEDBACK ON for 99 or more rows
4274 ;; feedback OFF
4275 (sql-redirect-value
4276 sqlbuf
4277 "SHOW FEEDBACK"
4278 "^\\(?:FEEDBACK ON for \\([[:digit:]]+\\) or more rows\\|feedback \\(OFF\\)\\)"
4279 "SET FEEDBACK \\1\\2")
4281 ;; wrap : lines will be wrapped
4282 ;; wrap : lines will be truncated
4283 (list (concat "SET WRAP "
4284 (if (string=
4285 (car (sql-redirect-value
4286 sqlbuf
4287 "SHOW WRAP"
4288 "^wrap : lines will be \\(wrapped\\|truncated\\)" 1))
4289 "wrapped")
4290 "ON" "OFF")))))
4292 (defun sql-oracle-restore-settings (sqlbuf saved-settings)
4293 "Restore the SQL*Plus settings in SAVED-SETTINGS."
4295 ;; Remove any settings that haven't changed
4296 (mapc
4297 (lambda (one-cur-setting)
4298 (setq saved-settings (delete one-cur-setting saved-settings)))
4299 (sql-oracle-save-settings sqlbuf))
4301 ;; Restore the changed settings
4302 (sql-redirect sqlbuf saved-settings))
4304 (defun sql-oracle-list-all (sqlbuf outbuf enhanced table-name)
4305 ;; Query from USER_OBJECTS or ALL_OBJECTS
4306 (let ((settings (sql-oracle-save-settings sqlbuf))
4307 (simple-sql
4308 (concat
4309 "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
4310 ", x.object_name AS SQL_EL_NAME "
4311 "FROM user_objects x "
4312 "WHERE x.object_type NOT LIKE '%% BODY' "
4313 "ORDER BY 2, 1;"))
4314 (enhanced-sql
4315 (concat
4316 "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
4317 ", x.owner ||'.'|| x.object_name AS SQL_EL_NAME "
4318 "FROM all_objects x "
4319 "WHERE x.object_type NOT LIKE '%% BODY' "
4320 "AND x.owner <> 'SYS' "
4321 "ORDER BY 2, 1;")))
4323 (sql-redirect sqlbuf
4324 (concat "SET LINESIZE 80 PAGESIZE 50000 TRIMOUT ON"
4325 " TAB OFF TIMING OFF FEEDBACK OFF"))
4327 (sql-redirect sqlbuf
4328 (list "COLUMN SQL_EL_TYPE HEADING \"Type\" FORMAT A19"
4329 "COLUMN SQL_EL_NAME HEADING \"Name\""
4330 (format "COLUMN SQL_EL_NAME FORMAT A%d"
4331 (if enhanced 60 35))))
4333 (sql-redirect sqlbuf
4334 (if enhanced enhanced-sql simple-sql)
4335 outbuf)
4337 (sql-redirect sqlbuf
4338 '("COLUMN SQL_EL_NAME CLEAR"
4339 "COLUMN SQL_EL_TYPE CLEAR"))
4341 (sql-oracle-restore-settings sqlbuf settings)))
4343 (defun sql-oracle-list-table (sqlbuf outbuf enhanced table-name)
4344 "Implements :list-table under Oracle."
4345 (let ((settings (sql-oracle-save-settings sqlbuf)))
4347 (sql-redirect sqlbuf
4348 (format
4349 (concat "SET LINESIZE %d PAGESIZE 50000"
4350 " DESCRIBE DEPTH 1 LINENUM OFF INDENT ON")
4351 (max 65 (min 120 (window-width)))))
4353 (sql-redirect sqlbuf (format "DESCRIBE %s" table-name)
4354 outbuf)
4356 (sql-oracle-restore-settings sqlbuf settings)))
4358 (defcustom sql-oracle-completion-types '("FUNCTION" "PACKAGE" "PROCEDURE"
4359 "SEQUENCE" "SYNONYM" "TABLE" "TRIGGER"
4360 "TYPE" "VIEW")
4361 "List of object types to include for completion under Oracle.
4363 See the distinct values in ALL_OBJECTS.OBJECT_TYPE for possible values."
4364 :version "24.1"
4365 :type '(repeat string)
4366 :group 'SQL)
4368 (defun sql-oracle-completion-object (sqlbuf schema)
4369 (sql-redirect-value
4370 sqlbuf
4371 (concat
4372 "SELECT CHR(1)||"
4373 (if schema
4374 (format "owner||'.'||object_name AS o FROM all_objects WHERE owner = %s AND "
4375 (sql-str-literal (upcase schema)))
4376 "object_name AS o FROM user_objects WHERE ")
4377 "temporary = 'N' AND generated = 'N' AND secondary = 'N' AND "
4378 "object_type IN ("
4379 (mapconcat (function sql-str-literal) sql-oracle-completion-types ",")
4380 ");")
4381 "^[\001]\\(.+\\)$" 1))
4384 ;;;###autoload
4385 (defun sql-sybase (&optional buffer)
4386 "Run isql by Sybase as an inferior process.
4388 If buffer `*SQL*' exists but no process is running, make a new process.
4389 If buffer exists and a process is running, just switch to buffer
4390 `*SQL*'.
4392 Interpreter used comes from variable `sql-sybase-program'. Login uses
4393 the variables `sql-server', `sql-user', `sql-password', and
4394 `sql-database' as defaults, if set. Additional command line parameters
4395 can be stored in the list `sql-sybase-options'.
4397 The buffer is put in SQL interactive mode, giving commands for sending
4398 input. See `sql-interactive-mode'.
4400 To set the buffer name directly, use \\[universal-argument]
4401 before \\[sql-sybase]. Once session has started,
4402 \\[sql-rename-buffer] can be called separately to rename the
4403 buffer.
4405 To specify a coding system for converting non-ASCII characters
4406 in the input and output to the process, use \\[universal-coding-system-argument]
4407 before \\[sql-sybase]. You can also specify this with \\[set-buffer-process-coding-system]
4408 in the SQL buffer, after you start the process.
4409 The default comes from `process-coding-system-alist' and
4410 `default-process-coding-system'.
4412 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4413 (interactive "P")
4414 (sql-product-interactive 'sybase buffer))
4416 (defun sql-comint-sybase (product options)
4417 "Create comint buffer and connect to Sybase."
4418 ;; Put all parameters to the program (if defined) in a list and call
4419 ;; make-comint.
4420 (let ((params options))
4421 (if (not (string= "" sql-server))
4422 (setq params (append (list "-S" sql-server) params)))
4423 (if (not (string= "" sql-database))
4424 (setq params (append (list "-D" sql-database) params)))
4425 (if (not (string= "" sql-password))
4426 (setq params (append (list "-P" sql-password) params)))
4427 (if (not (string= "" sql-user))
4428 (setq params (append (list "-U" sql-user) params)))
4429 (sql-comint product params)))
4433 ;;;###autoload
4434 (defun sql-informix (&optional buffer)
4435 "Run dbaccess by Informix as an inferior process.
4437 If buffer `*SQL*' exists but no process is running, make a new process.
4438 If buffer exists and a process is running, just switch to buffer
4439 `*SQL*'.
4441 Interpreter used comes from variable `sql-informix-program'. Login uses
4442 the variable `sql-database' as default, if set.
4444 The buffer is put in SQL interactive mode, giving commands for sending
4445 input. See `sql-interactive-mode'.
4447 To set the buffer name directly, use \\[universal-argument]
4448 before \\[sql-informix]. Once session has started,
4449 \\[sql-rename-buffer] can be called separately to rename the
4450 buffer.
4452 To specify a coding system for converting non-ASCII characters
4453 in the input and output to the process, use \\[universal-coding-system-argument]
4454 before \\[sql-informix]. You can also specify this with \\[set-buffer-process-coding-system]
4455 in the SQL buffer, after you start the process.
4456 The default comes from `process-coding-system-alist' and
4457 `default-process-coding-system'.
4459 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4460 (interactive "P")
4461 (sql-product-interactive 'informix buffer))
4463 (defun sql-comint-informix (product options)
4464 "Create comint buffer and connect to Informix."
4465 ;; username and password are ignored.
4466 (let ((db (if (string= "" sql-database)
4468 (if (string= "" sql-server)
4469 sql-database
4470 (concat sql-database "@" sql-server)))))
4471 (sql-comint product (append `(,db "-") options))))
4475 ;;;###autoload
4476 (defun sql-sqlite (&optional buffer)
4477 "Run sqlite as an inferior process.
4479 SQLite is free software.
4481 If buffer `*SQL*' exists but no process is running, make a new process.
4482 If buffer exists and a process is running, just switch to buffer
4483 `*SQL*'.
4485 Interpreter used comes from variable `sql-sqlite-program'. Login uses
4486 the variables `sql-user', `sql-password', `sql-database', and
4487 `sql-server' as defaults, if set. Additional command line parameters
4488 can be stored in the list `sql-sqlite-options'.
4490 The buffer is put in SQL interactive mode, giving commands for sending
4491 input. See `sql-interactive-mode'.
4493 To set the buffer name directly, use \\[universal-argument]
4494 before \\[sql-sqlite]. Once session has started,
4495 \\[sql-rename-buffer] can be called separately to rename the
4496 buffer.
4498 To specify a coding system for converting non-ASCII characters
4499 in the input and output to the process, use \\[universal-coding-system-argument]
4500 before \\[sql-sqlite]. You can also specify this with \\[set-buffer-process-coding-system]
4501 in the SQL buffer, after you start the process.
4502 The default comes from `process-coding-system-alist' and
4503 `default-process-coding-system'.
4505 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4506 (interactive "P")
4507 (sql-product-interactive 'sqlite buffer))
4509 (defun sql-comint-sqlite (product options)
4510 "Create comint buffer and connect to SQLite."
4511 ;; Put all parameters to the program (if defined) in a list and call
4512 ;; make-comint.
4513 (let ((params))
4514 (if (not (string= "" sql-database))
4515 (setq params (append (list (expand-file-name sql-database))
4516 params)))
4517 (setq params (append options params))
4518 (sql-comint product params)))
4520 (defun sql-sqlite-completion-object (sqlbuf schema)
4521 (sql-redirect-value sqlbuf ".tables" "\\sw\\(?:\\sw\\|\\s_\\)*" 0))
4525 ;;;###autoload
4526 (defun sql-mysql (&optional buffer)
4527 "Run mysql by TcX as an inferior process.
4529 Mysql versions 3.23 and up are free software.
4531 If buffer `*SQL*' exists but no process is running, make a new process.
4532 If buffer exists and a process is running, just switch to buffer
4533 `*SQL*'.
4535 Interpreter used comes from variable `sql-mysql-program'. Login uses
4536 the variables `sql-user', `sql-password', `sql-database', and
4537 `sql-server' as defaults, if set. Additional command line parameters
4538 can be stored in the list `sql-mysql-options'.
4540 The buffer is put in SQL interactive mode, giving commands for sending
4541 input. See `sql-interactive-mode'.
4543 To set the buffer name directly, use \\[universal-argument]
4544 before \\[sql-mysql]. Once session has started,
4545 \\[sql-rename-buffer] can be called separately to rename the
4546 buffer.
4548 To specify a coding system for converting non-ASCII characters
4549 in the input and output to the process, use \\[universal-coding-system-argument]
4550 before \\[sql-mysql]. You can also specify this with \\[set-buffer-process-coding-system]
4551 in the SQL buffer, after you start the process.
4552 The default comes from `process-coding-system-alist' and
4553 `default-process-coding-system'.
4555 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4556 (interactive "P")
4557 (sql-product-interactive 'mysql buffer))
4559 (defun sql-comint-mysql (product options)
4560 "Create comint buffer and connect to MySQL."
4561 ;; Put all parameters to the program (if defined) in a list and call
4562 ;; make-comint.
4563 (let ((params))
4564 (if (not (string= "" sql-database))
4565 (setq params (append (list sql-database) params)))
4566 (if (not (string= "" sql-server))
4567 (setq params (append (list (concat "--host=" sql-server)) params)))
4568 (if (not (= 0 sql-port))
4569 (setq params (append (list (concat "--port=" (number-to-string sql-port))) params)))
4570 (if (not (string= "" sql-password))
4571 (setq params (append (list (concat "--password=" sql-password)) params)))
4572 (if (not (string= "" sql-user))
4573 (setq params (append (list (concat "--user=" sql-user)) params)))
4574 (setq params (append options params))
4575 (sql-comint product params)))
4579 ;;;###autoload
4580 (defun sql-solid (&optional buffer)
4581 "Run solsql by Solid as an inferior process.
4583 If buffer `*SQL*' exists but no process is running, make a new process.
4584 If buffer exists and a process is running, just switch to buffer
4585 `*SQL*'.
4587 Interpreter used comes from variable `sql-solid-program'. Login uses
4588 the variables `sql-user', `sql-password', and `sql-server' as
4589 defaults, if set.
4591 The buffer is put in SQL interactive mode, giving commands for sending
4592 input. See `sql-interactive-mode'.
4594 To set the buffer name directly, use \\[universal-argument]
4595 before \\[sql-solid]. Once session has started,
4596 \\[sql-rename-buffer] can be called separately to rename the
4597 buffer.
4599 To specify a coding system for converting non-ASCII characters
4600 in the input and output to the process, use \\[universal-coding-system-argument]
4601 before \\[sql-solid]. You can also specify this with \\[set-buffer-process-coding-system]
4602 in the SQL buffer, after you start the process.
4603 The default comes from `process-coding-system-alist' and
4604 `default-process-coding-system'.
4606 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4607 (interactive "P")
4608 (sql-product-interactive 'solid buffer))
4610 (defun sql-comint-solid (product options)
4611 "Create comint buffer and connect to Solid."
4612 ;; Put all parameters to the program (if defined) in a list and call
4613 ;; make-comint.
4614 (let ((params options))
4615 ;; It only makes sense if both username and password are there.
4616 (if (not (or (string= "" sql-user)
4617 (string= "" sql-password)))
4618 (setq params (append (list sql-user sql-password) params)))
4619 (if (not (string= "" sql-server))
4620 (setq params (append (list sql-server) params)))
4621 (sql-comint product params)))
4625 ;;;###autoload
4626 (defun sql-ingres (&optional buffer)
4627 "Run sql by Ingres as an inferior process.
4629 If buffer `*SQL*' exists but no process is running, make a new process.
4630 If buffer exists and a process is running, just switch to buffer
4631 `*SQL*'.
4633 Interpreter used comes from variable `sql-ingres-program'. Login uses
4634 the variable `sql-database' as default, if set.
4636 The buffer is put in SQL interactive mode, giving commands for sending
4637 input. See `sql-interactive-mode'.
4639 To set the buffer name directly, use \\[universal-argument]
4640 before \\[sql-ingres]. Once session has started,
4641 \\[sql-rename-buffer] can be called separately to rename the
4642 buffer.
4644 To specify a coding system for converting non-ASCII characters
4645 in the input and output to the process, use \\[universal-coding-system-argument]
4646 before \\[sql-ingres]. You can also specify this with \\[set-buffer-process-coding-system]
4647 in the SQL buffer, after you start the process.
4648 The default comes from `process-coding-system-alist' and
4649 `default-process-coding-system'.
4651 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4652 (interactive "P")
4653 (sql-product-interactive 'ingres buffer))
4655 (defun sql-comint-ingres (product options)
4656 "Create comint buffer and connect to Ingres."
4657 ;; username and password are ignored.
4658 (sql-comint product
4659 (append (if (string= "" sql-database)
4661 (list sql-database))
4662 options)))
4666 ;;;###autoload
4667 (defun sql-ms (&optional buffer)
4668 "Run osql by Microsoft as an inferior process.
4670 If buffer `*SQL*' exists but no process is running, make a new process.
4671 If buffer exists and a process is running, just switch to buffer
4672 `*SQL*'.
4674 Interpreter used comes from variable `sql-ms-program'. Login uses the
4675 variables `sql-user', `sql-password', `sql-database', and `sql-server'
4676 as defaults, if set. Additional command line parameters can be stored
4677 in the list `sql-ms-options'.
4679 The buffer is put in SQL interactive mode, giving commands for sending
4680 input. See `sql-interactive-mode'.
4682 To set the buffer name directly, use \\[universal-argument]
4683 before \\[sql-ms]. Once session has started,
4684 \\[sql-rename-buffer] can be called separately to rename the
4685 buffer.
4687 To specify a coding system for converting non-ASCII characters
4688 in the input and output to the process, use \\[universal-coding-system-argument]
4689 before \\[sql-ms]. You can also specify this with \\[set-buffer-process-coding-system]
4690 in the SQL buffer, after you start the process.
4691 The default comes from `process-coding-system-alist' and
4692 `default-process-coding-system'.
4694 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4695 (interactive "P")
4696 (sql-product-interactive 'ms buffer))
4698 (defun sql-comint-ms (product options)
4699 "Create comint buffer and connect to Microsoft SQL Server."
4700 ;; Put all parameters to the program (if defined) in a list and call
4701 ;; make-comint.
4702 (let ((params options))
4703 (if (not (string= "" sql-server))
4704 (setq params (append (list "-S" sql-server) params)))
4705 (if (not (string= "" sql-database))
4706 (setq params (append (list "-d" sql-database) params)))
4707 (if (not (string= "" sql-user))
4708 (setq params (append (list "-U" sql-user) params)))
4709 (if (not (string= "" sql-password))
4710 (setq params (append (list "-P" sql-password) params))
4711 (if (string= "" sql-user)
4712 ;; if neither user nor password is provided, use system
4713 ;; credentials.
4714 (setq params (append (list "-E") params))
4715 ;; If -P is passed to ISQL as the last argument without a
4716 ;; password, it's considered null.
4717 (setq params (append params (list "-P")))))
4718 (sql-comint product params)))
4722 ;;;###autoload
4723 (defun sql-postgres (&optional buffer)
4724 "Run psql by Postgres as an inferior process.
4726 If buffer `*SQL*' exists but no process is running, make a new process.
4727 If buffer exists and a process is running, just switch to buffer
4728 `*SQL*'.
4730 Interpreter used comes from variable `sql-postgres-program'. Login uses
4731 the variables `sql-database' and `sql-server' as default, if set.
4732 Additional command line parameters can be stored in the list
4733 `sql-postgres-options'.
4735 The buffer is put in SQL interactive mode, giving commands for sending
4736 input. See `sql-interactive-mode'.
4738 To set the buffer name directly, use \\[universal-argument]
4739 before \\[sql-postgres]. Once session has started,
4740 \\[sql-rename-buffer] can be called separately to rename the
4741 buffer.
4743 To specify a coding system for converting non-ASCII characters
4744 in the input and output to the process, use \\[universal-coding-system-argument]
4745 before \\[sql-postgres]. You can also specify this with \\[set-buffer-process-coding-system]
4746 in the SQL buffer, after you start the process.
4747 The default comes from `process-coding-system-alist' and
4748 `default-process-coding-system'. If your output lines end with ^M,
4749 your might try undecided-dos as a coding system. If this doesn't help,
4750 Try to set `comint-output-filter-functions' like this:
4752 \(setq comint-output-filter-functions (append comint-output-filter-functions
4753 '(comint-strip-ctrl-m)))
4755 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4756 (interactive "P")
4757 (sql-product-interactive 'postgres buffer))
4759 (defun sql-comint-postgres (product options)
4760 "Create comint buffer and connect to Postgres."
4761 ;; username and password are ignored. Mark Stosberg suggest to add
4762 ;; the database at the end. Jason Beegan suggest using --pset and
4763 ;; pager=off instead of \\o|cat. The later was the solution by
4764 ;; Gregor Zych. Jason's suggestion is the default value for
4765 ;; sql-postgres-options.
4766 (let ((params options))
4767 (if (not (string= "" sql-database))
4768 (setq params (append params (list sql-database))))
4769 (if (not (string= "" sql-server))
4770 (setq params (append (list "-h" sql-server) params)))
4771 (if (not (string= "" sql-user))
4772 (setq params (append (list "-U" sql-user) params)))
4773 (if (not (= 0 sql-port))
4774 (setq params (append (list "-p" (number-to-string sql-port)) params)))
4775 (sql-comint product params)))
4777 (defun sql-postgres-completion-object (sqlbuf schema)
4778 (let (cl re fs a r)
4779 (sql-redirect sqlbuf "\\t on")
4780 (setq a (car (sql-redirect-value sqlbuf "\\a" "Output format is \\(.*\\)[.]$" 1)))
4781 (when (string= a "aligned")
4782 (sql-redirect sqlbuf "\\a"))
4783 (setq fs (or (car (sql-redirect-value sqlbuf "\\f" "Field separator is \"\\(.\\)[.]$" 1)) "|"))
4785 (setq re (concat "^\\([^" fs "]*\\)" fs "\\([^" fs "]*\\)" fs "[^" fs "]*" fs "[^" fs "]*$"))
4786 (setq cl (if (not schema)
4787 (sql-redirect-value sqlbuf "\\d" re '(1 2))
4788 (append (sql-redirect-value sqlbuf (format "\\dt %s.*" schema) re '(1 2))
4789 (sql-redirect-value sqlbuf (format "\\dv %s.*" schema) re '(1 2))
4790 (sql-redirect-value sqlbuf (format "\\ds %s.*" schema) re '(1 2)))))
4792 ;; Restore tuples and alignment to what they were
4793 (sql-redirect sqlbuf "\\t off")
4794 (when (not (string= a "aligned"))
4795 (sql-redirect sqlbuf "\\a"))
4797 ;; Return the list of table names (public schema name can be omitted)
4798 (mapcar (lambda (tbl)
4799 (if (string= (car tbl) "public")
4800 (cadr tbl)
4801 (format "%s.%s" (car tbl) (cadr tbl))))
4802 cl)))
4806 ;;;###autoload
4807 (defun sql-interbase (&optional buffer)
4808 "Run isql by Interbase as an inferior process.
4810 If buffer `*SQL*' exists but no process is running, make a new process.
4811 If buffer exists and a process is running, just switch to buffer
4812 `*SQL*'.
4814 Interpreter used comes from variable `sql-interbase-program'. Login
4815 uses the variables `sql-user', `sql-password', and `sql-database' as
4816 defaults, if set.
4818 The buffer is put in SQL interactive mode, giving commands for sending
4819 input. See `sql-interactive-mode'.
4821 To set the buffer name directly, use \\[universal-argument]
4822 before \\[sql-interbase]. Once session has started,
4823 \\[sql-rename-buffer] can be called separately to rename the
4824 buffer.
4826 To specify a coding system for converting non-ASCII characters
4827 in the input and output to the process, use \\[universal-coding-system-argument]
4828 before \\[sql-interbase]. You can also specify this with \\[set-buffer-process-coding-system]
4829 in the SQL buffer, after you start the process.
4830 The default comes from `process-coding-system-alist' and
4831 `default-process-coding-system'.
4833 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4834 (interactive "P")
4835 (sql-product-interactive 'interbase buffer))
4837 (defun sql-comint-interbase (product options)
4838 "Create comint buffer and connect to Interbase."
4839 ;; Put all parameters to the program (if defined) in a list and call
4840 ;; make-comint.
4841 (let ((params options))
4842 (if (not (string= "" sql-user))
4843 (setq params (append (list "-u" sql-user) params)))
4844 (if (not (string= "" sql-password))
4845 (setq params (append (list "-p" sql-password) params)))
4846 (if (not (string= "" sql-database))
4847 (setq params (cons sql-database params))) ; add to the front!
4848 (sql-comint product params)))
4852 ;;;###autoload
4853 (defun sql-db2 (&optional buffer)
4854 "Run db2 by IBM as an inferior process.
4856 If buffer `*SQL*' exists but no process is running, make a new process.
4857 If buffer exists and a process is running, just switch to buffer
4858 `*SQL*'.
4860 Interpreter used comes from variable `sql-db2-program'. There is not
4861 automatic login.
4863 The buffer is put in SQL interactive mode, giving commands for sending
4864 input. See `sql-interactive-mode'.
4866 If you use \\[sql-accumulate-and-indent] to send multiline commands to
4867 db2, newlines will be escaped if necessary. If you don't want that, set
4868 `comint-input-sender' back to `comint-simple-send' by writing an after
4869 advice. See the elisp manual for more information.
4871 To set the buffer name directly, use \\[universal-argument]
4872 before \\[sql-db2]. Once session has started,
4873 \\[sql-rename-buffer] can be called separately to rename the
4874 buffer.
4876 To specify a coding system for converting non-ASCII characters
4877 in the input and output to the process, use \\[universal-coding-system-argument]
4878 before \\[sql-db2]. You can also specify this with \\[set-buffer-process-coding-system]
4879 in the SQL buffer, after you start the process.
4880 The default comes from `process-coding-system-alist' and
4881 `default-process-coding-system'.
4883 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4884 (interactive "P")
4885 (sql-product-interactive 'db2 buffer))
4887 (defun sql-comint-db2 (product options)
4888 "Create comint buffer and connect to DB2."
4889 ;; Put all parameters to the program (if defined) in a list and call
4890 ;; make-comint.
4891 (sql-comint product options))
4893 ;;;###autoload
4894 (defun sql-linter (&optional buffer)
4895 "Run inl by RELEX as an inferior process.
4897 If buffer `*SQL*' exists but no process is running, make a new process.
4898 If buffer exists and a process is running, just switch to buffer
4899 `*SQL*'.
4901 Interpreter used comes from variable `sql-linter-program' - usually `inl'.
4902 Login uses the variables `sql-user', `sql-password', `sql-database' and
4903 `sql-server' as defaults, if set. Additional command line parameters
4904 can be stored in the list `sql-linter-options'. Run inl -h to get help on
4905 parameters.
4907 `sql-database' is used to set the LINTER_MBX environment variable for
4908 local connections, `sql-server' refers to the server name from the
4909 `nodetab' file for the network connection (dbc_tcp or friends must run
4910 for this to work). If `sql-password' is an empty string, inl will use
4911 an empty password.
4913 The buffer is put in SQL interactive mode, giving commands for sending
4914 input. See `sql-interactive-mode'.
4916 To set the buffer name directly, use \\[universal-argument]
4917 before \\[sql-linter]. Once session has started,
4918 \\[sql-rename-buffer] can be called separately to rename the
4919 buffer.
4921 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4922 (interactive "P")
4923 (sql-product-interactive 'linter buffer))
4925 (defun sql-comint-linter (product options)
4926 "Create comint buffer and connect to Linter."
4927 ;; Put all parameters to the program (if defined) in a list and call
4928 ;; make-comint.
4929 (let ((params options)
4930 (login nil)
4931 (old-mbx (getenv "LINTER_MBX")))
4932 (if (not (string= "" sql-user))
4933 (setq login (concat sql-user "/" sql-password)))
4934 (setq params (append (list "-u" login) params))
4935 (if (not (string= "" sql-server))
4936 (setq params (append (list "-n" sql-server) params)))
4937 (if (string= "" sql-database)
4938 (setenv "LINTER_MBX" nil)
4939 (setenv "LINTER_MBX" sql-database))
4940 (sql-comint product params)
4941 (setenv "LINTER_MBX" old-mbx)))
4945 (provide 'sql)
4947 ;;; sql.el ends here
4949 ; LocalWords: sql SQL SQLite sqlite Sybase Informix MySQL
4950 ; LocalWords: Postgres SQLServer SQLi