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