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