1 ;;; sql.el --- specialized comint.el for SQL interpreters -*- lexical-binding: t -*-
3 ;; Copyright (C) 1998-2017 Free Software Foundation, Inc.
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Maintainer: Michael Mauger <michael@mauger.com>
8 ;; Keywords: comm languages processes
9 ;; URL: https://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 <https://www.gnu.org/licenses/>.
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 ;; https://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
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
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'.
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
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 [].
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
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
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
129 ;; (defcustom my-sql-xyz-program "ixyz"
130 ;; "Command to start ixyz by XyzDB."
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
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
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)
156 ;; (sql-set-product-feature 'xyz
157 ;; :sqli-options 'my-sql-xyz-options))
159 ;; (defun my-sql-comint-xyz (product options &optional buf-name)
160 ;; "Connect ti XyzDB in a comint buffer."
162 ;; ;; Do something with `sql-user', `sql-password',
163 ;; ;; `sql-database', and `sql-server'.
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))
175 ;; (sql-comint product params buf-name)))
177 ;; (sql-set-product-feature 'xyz
178 ;; :sqli-comint-func 'my-sql-comint-xyz)
180 ;; 6) Define a convenience function to invoke the SQL interpreter.
182 ;; (defun my-sql-xyz (&optional buffer)
183 ;; "Run ixyz by XyzDB as an inferior process."
185 ;; (sql-product-interactive 'xyz buffer))
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;
217 ;; Paul Sleigh <bat@flurf.net> -- MySQL keyword enhancement
218 ;; Andrew Schein <andrew@andrewschein.com> -- sql-port bug
219 ;; Ian Bjorhovde <idbjorh@dataproxy.com> -- db2 escape newlines
220 ;; incorrectly enabled by default
221 ;; Roman Scherer <roman.scherer@nugg.ad> -- Connection documentation
222 ;; Mark Wilkinson <wilkinsonmr@gmail.com> -- file-local variables ignored
223 ;; Simen Heggestøyl <simenheg@gmail.com> -- Postgres database completion
232 ;; Need the following to allow GNU Emacs 19 to compile the file.
234 (require 'regexp-opt
))
239 (defvar font-lock-keyword-face
)
240 (defvar font-lock-set-defaults
)
241 (defvar font-lock-string-face
)
243 ;;; Allow customization
246 "Running a SQL interpreter from within Emacs buffers."
251 ;; These five variables will be used as defaults, if set.
253 (defcustom sql-user
""
259 (defcustom sql-password
""
261 If you customize this, the value will be stored in your init
262 file. Since that is a plaintext file, this could be dangerous."
267 (defcustom sql-database
""
273 (defcustom sql-server
""
274 "Default server or host."
279 (defcustom sql-port
0
280 "Default port for connecting to a MySQL or Postgres server."
286 (defcustom sql-default-directory nil
287 "Default directory for SQL processes."
289 :type
'(choice (const nil
) string
)
293 ;; Login parameter type
295 (define-widget 'sql-login-params
'lazy
296 "Widget definition of the login parameters list"
297 :tag
"Login Parameters"
298 :type
'(set :tag
"Login Parameters"
302 (list :tag
"Specify a default"
305 :inline t
(const :default
) string
)))
307 (choice :tag
"server"
310 (list :tag
"Specify a default"
313 :inline t
(const :default
) string
))
315 (const :format
"" server
)
316 (const :format
"" :file
)
318 (list :tag
"completion"
319 (const :format
"" server
)
320 (const :format
"" :completion
)
321 (const :format
"" :must-match
)
323 :match-alternatives
(listp stringp
))))
324 (choice :tag
"database"
327 (list :tag
"Specify a default"
330 :inline t
(const :default
) string
))
332 (const :format
"" database
)
333 (const :format
"" :file
)
335 (list :tag
"completion"
336 (const :format
"" database
)
337 (const :format
"" :completion
)
338 (const :format
"" :must-match
)
340 :match-alternatives
(listp stringp
))))
343 ;; SQL Product support
345 (defvar sql-interactive-product nil
346 "Product under `sql-interactive-mode'.")
348 (defvar sql-connection nil
349 "Connection name if interactive session started by `sql-connect'.")
351 (defvar sql-product-alist
354 :font-lock sql-mode-ansi-font-lock-keywords
355 :statement sql-ansi-statement-starters
)
359 :font-lock sql-mode-db2-font-lock-keywords
360 :sqli-program sql-db2-program
361 :sqli-options sql-db2-options
362 :sqli-login sql-db2-login-params
363 :sqli-comint-func sql-comint-db2
364 :prompt-regexp
"^db2 => "
366 :prompt-cont-regexp
"^db2 (cont\\.) => "
367 :input-filter sql-escape-newlines-filter
)
371 :font-lock sql-mode-informix-font-lock-keywords
372 :sqli-program sql-informix-program
373 :sqli-options sql-informix-options
374 :sqli-login sql-informix-login-params
375 :sqli-comint-func sql-comint-informix
378 :syntax-alist
((?
{ .
"<") (?
} .
">")))
382 :font-lock sql-mode-ingres-font-lock-keywords
383 :sqli-program sql-ingres-program
384 :sqli-options sql-ingres-options
385 :sqli-login sql-ingres-login-params
386 :sqli-comint-func sql-comint-ingres
387 :prompt-regexp
"^\\* "
389 :prompt-cont-regexp
"^\\* ")
393 :font-lock sql-mode-interbase-font-lock-keywords
394 :sqli-program sql-interbase-program
395 :sqli-options sql-interbase-options
396 :sqli-login sql-interbase-login-params
397 :sqli-comint-func sql-comint-interbase
398 :prompt-regexp
"^SQL> "
403 :font-lock sql-mode-linter-font-lock-keywords
404 :sqli-program sql-linter-program
405 :sqli-options sql-linter-options
406 :sqli-login sql-linter-login-params
407 :sqli-comint-func sql-comint-linter
408 :prompt-regexp
"^SQL>"
413 :font-lock sql-mode-ms-font-lock-keywords
414 :sqli-program sql-ms-program
415 :sqli-options sql-ms-options
416 :sqli-login sql-ms-login-params
417 :sqli-comint-func sql-comint-ms
418 :prompt-regexp
"^[0-9]*>"
420 :syntax-alist
((?
@ .
"_"))
421 :terminator
("^go" .
"go"))
426 :font-lock sql-mode-mysql-font-lock-keywords
427 :sqli-program sql-mysql-program
428 :sqli-options sql-mysql-options
429 :sqli-login sql-mysql-login-params
430 :sqli-comint-func sql-comint-mysql
431 :list-all
"SHOW TABLES;"
432 :list-table
"DESCRIBE %s;"
433 :prompt-regexp
"^mysql> "
435 :prompt-cont-regexp
"^ -> "
436 :syntax-alist
((?
# .
"< b"))
437 :input-filter sql-remove-tabs-filter
)
441 :font-lock sql-mode-oracle-font-lock-keywords
442 :sqli-program sql-oracle-program
443 :sqli-options sql-oracle-options
444 :sqli-login sql-oracle-login-params
445 :sqli-comint-func sql-comint-oracle
446 :list-all sql-oracle-list-all
447 :list-table sql-oracle-list-table
448 :completion-object sql-oracle-completion-object
449 :prompt-regexp
"^SQL> "
451 :prompt-cont-regexp
"^\\(?:[ ][ ][1-9]\\|[ ][1-9][0-9]\\|[1-9][0-9]\\{2\\}\\)[ ]\\{2\\}"
452 :statement sql-oracle-statement-starters
453 :syntax-alist
((?$ .
"_") (?
# .
"_"))
454 :terminator
("\\(^/\\|;\\)$" .
"/")
455 :input-filter sql-placeholders-filter
)
460 :font-lock sql-mode-postgres-font-lock-keywords
461 :sqli-program sql-postgres-program
462 :sqli-options sql-postgres-options
463 :sqli-login sql-postgres-login-params
464 :sqli-comint-func sql-comint-postgres
465 :list-all
("\\d+" .
"\\dS+")
466 :list-table
("\\d+ %s" .
"\\dS+ %s")
467 :completion-object sql-postgres-completion-object
468 :prompt-regexp
"^[[:alnum:]_]*=[#>] "
470 :prompt-cont-regexp
"^[[:alnum:]_]*[-(][#>] "
471 :input-filter sql-remove-tabs-filter
472 :terminator
("\\(^\\s-*\\\\g$\\|;\\)" .
"\\g"))
476 :font-lock sql-mode-solid-font-lock-keywords
477 :sqli-program sql-solid-program
478 :sqli-options sql-solid-options
479 :sqli-login sql-solid-login-params
480 :sqli-comint-func sql-comint-solid
487 :font-lock sql-mode-sqlite-font-lock-keywords
488 :sqli-program sql-sqlite-program
489 :sqli-options sql-sqlite-options
490 :sqli-login sql-sqlite-login-params
491 :sqli-comint-func sql-comint-sqlite
493 :list-table
".schema %s"
494 :completion-object sql-sqlite-completion-object
495 :prompt-regexp
"^sqlite> "
497 :prompt-cont-regexp
"^ \\.\\.\\.> "
502 :font-lock sql-mode-sybase-font-lock-keywords
503 :sqli-program sql-sybase-program
504 :sqli-options sql-sybase-options
505 :sqli-login sql-sybase-login-params
506 :sqli-comint-func sql-comint-sybase
507 :prompt-regexp
"^SQL> "
509 :syntax-alist
((?
@ .
"_"))
510 :terminator
("^go" .
"go"))
514 :sqli-program sql-vertica-program
515 :sqli-options sql-vertica-options
516 :sqli-login sql-vertica-login-params
517 :sqli-comint-func sql-comint-vertica
518 :list-all
("\\d" .
"\\dS")
520 :prompt-regexp
"^[[:alnum:]_]*=[#>] "
522 :prompt-cont-regexp
"^[[:alnum:]_]*[-(][#>] ")
524 "An alist of product specific configuration settings.
526 Without an entry in this list a product will not be properly
527 highlighted and will not support `sql-interactive-mode'.
529 Each element in the list is in the following format:
531 (PRODUCT FEATURE VALUE ...)
533 where PRODUCT is the appropriate value of `sql-product'. The
534 product name is then followed by FEATURE-VALUE pairs. If a
535 FEATURE is not specified, its VALUE is treated as nil. FEATURE
536 may be any one of the following:
538 :name string containing the displayable name of
541 :free-software is the product Free (as in Freedom) software?
543 :font-lock name of the variable containing the product
544 specific font lock highlighting patterns.
546 :sqli-program name of the variable containing the product
547 specific interactive program name.
549 :sqli-options name of the variable containing the list
550 of product specific options.
552 :sqli-login name of the variable containing the list of
553 login parameters (i.e., user, password,
554 database and server) needed to connect to
557 :sqli-comint-func function of two arguments, PRODUCT
558 and OPTIONS, that will open a comint buffer
559 and connect to the database. PRODUCT is the
560 first argument to be passed to `sql-comint',
561 and OPTIONS should be included in its second
562 argument. The function should use the values
563 of `sql-user', `sql-password', `sql-database',
564 `sql-server' and `sql-port' to . Do product
565 specific configuration of comint in this
566 function. See `sql-comint-oracle' for an
567 example of such a function.
569 :list-all Command string or function which produces
570 a listing of all objects in the database.
571 If it's a cons cell, then the car
572 produces the standard list of objects and
573 the cdr produces an enhanced list of
574 objects. What \"enhanced\" means is
575 dependent on the SQL product and may not
576 exist. In general though, the
577 \"enhanced\" list should include visible
578 objects from other schemas.
580 :list-table Command string or function which produces
581 a detailed listing of a specific database
582 table. If its a cons cell, then the car
583 produces the standard list and the cdr
584 produces an enhanced list.
586 :completion-object A function that returns a list of
587 objects. Called with a single
588 parameter--if nil then list objects
589 accessible in the current schema, if
590 not-nil it is the name of a schema whose
591 objects should be listed.
593 :completion-column A function that returns a list of
594 columns. Called with a single
595 parameter--if nil then list objects
596 accessible in the current schema, if
597 not-nil it is the name of a schema whose
598 objects should be listed.
600 :prompt-regexp regular expression string that matches
601 the prompt issued by the product
604 :prompt-length length of the prompt on the line.
606 :prompt-cont-regexp regular expression string that matches
607 the continuation prompt issued by the
610 :input-filter function which can filter strings sent to
611 the command interpreter. It is also used
612 by the `sql-send-string',
613 `sql-send-region', `sql-send-paragraph'
614 and `sql-send-buffer' functions. The
615 function is passed the string sent to the
616 command interpreter and must return the
617 filtered string. May also be a list of
620 :statement name of a variable containing a regexp that
621 matches the beginning of SQL statements.
623 :terminator the terminator to be sent after a
624 `sql-send-string', `sql-send-region',
625 `sql-send-paragraph' and
626 `sql-send-buffer' command. May be the
627 literal string or a cons of a regexp to
628 match an existing terminator in the
629 string and the terminator to be used if
630 its absent. By default \";\".
632 :syntax-alist alist of syntax table entries to enable
633 special character treatment by font-lock
636 Other features can be stored but they will be ignored. However,
637 you can develop new functionality which is product independent by
638 using `sql-get-product-feature' to lookup the product specific
641 (defvar sql-indirect-features
642 '(:font-lock
:sqli-program
:sqli-options
:sqli-login
:statement
))
644 (defcustom sql-connection-alist nil
645 "An alist of connection parameters for interacting with a SQL product.
646 Each element of the alist is as follows:
648 (CONNECTION \(SQL-VARIABLE VALUE) ...)
650 Where CONNECTION is a case-insensitive string identifying the
651 connection, SQL-VARIABLE is the symbol name of a SQL mode
652 variable, and VALUE is the value to be assigned to the variable.
653 The most common SQL-VARIABLE settings associated with a
654 connection are: `sql-product', `sql-user', `sql-password',
655 `sql-port', `sql-server', and `sql-database'.
657 If a SQL-VARIABLE is part of the connection, it will not be
658 prompted for during login. The command `sql-connect' starts a
659 predefined SQLi session using the parameters from this list.
660 Connections defined here appear in the submenu SQL->Start... for
661 making new SQLi sessions."
662 :type
`(alist :key-type
(string :tag
"Connection")
665 (group (const :tag
"Product" sql-product
)
670 ,(or (plist-get (cdr prod-info
) :name
)
672 (symbol-name (car prod-info
))))
673 (quote ,(car prod-info
))))
675 (group (const :tag
"Username" sql-user
) string
)
676 (group (const :tag
"Password" sql-password
) string
)
677 (group (const :tag
"Server" sql-server
) string
)
678 (group (const :tag
"Database" sql-database
) string
)
679 (group (const :tag
"Port" sql-port
) integer
)
682 (symbol :tag
" Variable Symbol")
683 (sexp :tag
"Value Expression")))))
687 (defcustom sql-product
'ansi
688 "Select the SQL database product used.
689 This allows highlighting buffers properly when you open them."
691 ,@(mapcar (lambda (prod-info)
693 ,(or (plist-get (cdr prod-info
) :name
)
694 (capitalize (symbol-name (car prod-info
))))
699 (defvaralias 'sql-dialect
'sql-product
)
701 ;; misc customization of sql.el behavior
703 (defcustom sql-electric-stuff nil
704 "Treat some input as electric.
705 If set to the symbol `semicolon', then hitting `;' will send current
706 input in the SQLi buffer to the process.
707 If set to the symbol `go', then hitting `go' on a line by itself will
708 send current input in the SQLi buffer to the process.
709 If set to nil, then you must use \\[comint-send-input] in order to send
710 current input in the SQLi buffer to the process."
711 :type
'(choice (const :tag
"Nothing" nil
)
712 (const :tag
"The semicolon `;'" semicolon
)
713 (const :tag
"The string `go' by itself" go
))
717 (defcustom sql-send-terminator nil
718 "When non-nil, add a terminator to text sent to the SQL interpreter.
720 When text is sent to the SQL interpreter (via `sql-send-string',
721 `sql-send-region', `sql-send-paragraph' or `sql-send-buffer'), a
722 command terminator can be automatically sent as well. The
723 terminator is not sent, if the string sent already ends with the
726 If this value is t, then the default command terminator for the
727 SQL interpreter is sent. If this value is a string, then the
730 If the value is a cons cell of the form (PAT . TERM), then PAT is
731 a regexp used to match the terminator in the string and TERM is
732 the terminator to be sent. This form is useful if the SQL
733 interpreter has more than one way of submitting a SQL command.
734 The PAT regexp can match any of them, and TERM is the way we do
737 :type
'(choice (const :tag
"No Terminator" nil
)
738 (const :tag
"Default Terminator" t
)
739 (string :tag
"Terminator String")
740 (cons :tag
"Terminator Pattern and String"
741 (string :tag
"Terminator Pattern")
742 (string :tag
"Terminator String")))
746 (defvar sql-contains-names nil
747 "When non-nil, the current buffer contains database names.
749 Globally should be set to nil; it will be non-nil in `sql-mode',
750 `sql-interactive-mode' and list all buffers.")
752 (defvar sql-login-delay
7.5 ;; Secs
753 "Maximum number of seconds you are willing to wait for a login connection.")
755 (defcustom sql-pop-to-buffer-after-send-region nil
756 "When non-nil, pop to the buffer SQL statements are sent to.
758 After a call to `sql-sent-string', `sql-send-region',
759 `sql-send-paragraph' or `sql-send-buffer', the window is split
760 and the SQLi buffer is shown. If this variable is not nil, that
761 buffer's window will be selected by calling `pop-to-buffer'. If
762 this variable is nil, that buffer is shown using
767 ;; imenu support for sql-mode.
769 (defvar sql-imenu-generic-expression
770 ;; Items are in reverse order because they are rendered in reverse.
771 '(("Rules/Defaults" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*\\(?:rule\\|default\\)\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\s-+\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
772 ("Sequences" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*sequence\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
773 ("Triggers" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*trigger\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
774 ("Functions" "^\\s-*\\(?:create\\s-+\\(?:\\w+\\s-+\\)*\\)?function\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
775 ("Procedures" "^\\s-*\\(?:create\\s-+\\(?:\\w+\\s-+\\)*\\)?proc\\(?:edure\\)?\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
776 ("Packages" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*package\\s-+\\(?:body\\s-+\\)?\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
777 ("Types" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*type\\s-+\\(?:body\\s-+\\)?\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
778 ("Indexes" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*index\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1)
779 ("Tables/Views" "^\\s-*create\\s-+\\(?:\\w+\\s-+\\)*\\(?:table\\|view\\)\\s-+\\(?:if\\s-+not\\s-+exists\\s-+\\)?\\(\\(?:\\w+\\s-*[.]\\s-*\\)*\\w+\\)" 1))
780 "Define interesting points in the SQL buffer for `imenu'.
782 This is used to set `imenu-generic-expression' when SQL mode is
783 entered. Subsequent changes to `sql-imenu-generic-expression' will
784 not affect existing SQL buffers because imenu-generic-expression is
789 (defcustom sql-input-ring-file-name nil
790 "If non-nil, name of the file to read/write input history.
792 You have to set this variable if you want the history of your commands
793 saved from one Emacs session to the next. If this variable is set,
794 exiting the SQL interpreter in an SQLi buffer will write the input
795 history to the specified file. Starting a new process in a SQLi buffer
796 will read the input history from the specified file.
798 This is used to initialize `comint-input-ring-file-name'.
800 Note that the size of the input history is determined by the variable
801 `comint-input-ring-size'."
802 :type
'(choice (const :tag
"none" nil
)
806 (defcustom sql-input-ring-separator
"\n--\n"
807 "Separator between commands in the history file.
809 If set to \"\\n\", each line in the history file will be interpreted as
810 one command. Multi-line commands are split into several commands when
811 the input ring is initialized from a history file.
813 This variable used to initialize `comint-input-ring-separator'.
814 `comint-input-ring-separator' is part of Emacs 21; if your Emacs
815 does not have it, setting `sql-input-ring-separator' will have no
816 effect. In that case multiline commands will be split into several
817 commands when the input history is read, as if you had set
818 `sql-input-ring-separator' to \"\\n\"."
824 (defcustom sql-interactive-mode-hook
'()
825 "Hook for customizing `sql-interactive-mode'."
829 (defcustom sql-mode-hook
'()
830 "Hook for customizing `sql-mode'."
834 (defcustom sql-set-sqli-hook
'()
835 "Hook for reacting to changes of `sql-buffer'.
837 This is called by `sql-set-sqli-buffer' when the value of `sql-buffer'
842 (defcustom sql-login-hook
'()
843 "Hook for interacting with a buffer in `sql-interactive-mode'.
845 This hook is invoked in a buffer once it is ready to accept input
851 ;; Customization for ANSI
853 (defcustom sql-ansi-statement-starters
854 (regexp-opt '("create" "alter" "drop"
855 "select" "insert" "update" "delete" "merge"
857 "Regexp of keywords that start SQL commands.
859 All products share this list; products should define a regexp to
860 identify additional keywords in a variable defined by
861 the :statement feature."
866 ;; Customization for Oracle
868 (defcustom sql-oracle-program
"sqlplus"
869 "Command to start sqlplus by Oracle.
871 Starts `sql-interactive-mode' after doing some setup.
873 On Windows, \"sqlplus\" usually starts the sqlplus \"GUI\". In order
874 to start the sqlplus console, use \"plus33\" or something similar.
875 You will find the file in your Orant\\bin directory."
879 (defcustom sql-oracle-options
'("-L")
880 "List of additional options for `sql-oracle-program'."
881 :type
'(repeat string
)
885 (defcustom sql-oracle-login-params
'(user password database
)
886 "List of login parameters needed to connect to Oracle."
887 :type
'sql-login-params
891 (defcustom sql-oracle-statement-starters
892 (regexp-opt '("declare" "begin" "with"))
893 "Additional statement starting keywords in Oracle."
898 (defcustom sql-oracle-scan-on t
899 "Non-nil if placeholders should be replaced in Oracle SQLi.
901 When non-nil, Emacs will scan text sent to sqlplus and prompt
902 for replacement text for & placeholders as sqlplus does. This
903 is needed on Windows where SQL*Plus output is buffered and the
904 prompts are not shown until after the text is entered.
906 You need to issue the following command in SQL*Plus to be safe:
910 In older versions of SQL*Plus, this was the SET SCAN OFF command."
915 (defcustom sql-db2-escape-newlines nil
916 "Non-nil if newlines should be escaped by a backslash in DB2 SQLi.
918 When non-nil, Emacs will automatically insert a space and
919 backslash prior to every newline in multi-line SQL statements as
920 they are submitted to an interactive DB2 session."
925 ;; Customization for SQLite
927 (defcustom sql-sqlite-program
(or (executable-find "sqlite3")
928 (executable-find "sqlite")
930 "Command to start SQLite.
932 Starts `sql-interactive-mode' after doing some setup."
936 (defcustom sql-sqlite-options nil
937 "List of additional options for `sql-sqlite-program'."
938 :type
'(repeat string
)
942 (defcustom sql-sqlite-login-params
'((database :file nil
943 :must-match confirm
))
944 "List of login parameters needed to connect to SQLite."
945 :type
'sql-login-params
949 ;; Customization for MySQL
951 (defcustom sql-mysql-program
"mysql"
952 "Command to start mysql by TcX.
954 Starts `sql-interactive-mode' after doing some setup."
958 (defcustom sql-mysql-options nil
959 "List of additional options for `sql-mysql-program'.
960 The following list of options is reported to make things work
961 on Windows: \"-C\" \"-t\" \"-f\" \"-n\"."
962 :type
'(repeat string
)
966 (defcustom sql-mysql-login-params
'(user password database server
)
967 "List of login parameters needed to connect to MySQL."
968 :type
'sql-login-params
972 ;; Customization for Solid
974 (defcustom sql-solid-program
"solsql"
975 "Command to start SOLID SQL Editor.
977 Starts `sql-interactive-mode' after doing some setup."
981 (defcustom sql-solid-login-params
'(user password server
)
982 "List of login parameters needed to connect to Solid."
983 :type
'sql-login-params
987 ;; Customization for Sybase
989 (defcustom sql-sybase-program
"isql"
990 "Command to start isql by Sybase.
992 Starts `sql-interactive-mode' after doing some setup."
996 (defcustom sql-sybase-options nil
997 "List of additional options for `sql-sybase-program'.
998 Some versions of isql might require the -n option in order to work."
999 :type
'(repeat string
)
1003 (defcustom sql-sybase-login-params
'(server user password database
)
1004 "List of login parameters needed to connect to Sybase."
1005 :type
'sql-login-params
1009 ;; Customization for Informix
1011 (defcustom sql-informix-program
"dbaccess"
1012 "Command to start dbaccess by Informix.
1014 Starts `sql-interactive-mode' after doing some setup."
1018 (defcustom sql-informix-login-params
'(database)
1019 "List of login parameters needed to connect to Informix."
1020 :type
'sql-login-params
1024 ;; Customization for Ingres
1026 (defcustom sql-ingres-program
"sql"
1027 "Command to start sql by Ingres.
1029 Starts `sql-interactive-mode' after doing some setup."
1033 (defcustom sql-ingres-login-params
'(database)
1034 "List of login parameters needed to connect to Ingres."
1035 :type
'sql-login-params
1039 ;; Customization for Microsoft
1041 (defcustom sql-ms-program
"osql"
1042 "Command to start osql by Microsoft.
1044 Starts `sql-interactive-mode' after doing some setup."
1048 (defcustom sql-ms-options
'("-w" "300" "-n")
1049 ;; -w is the linesize
1050 "List of additional options for `sql-ms-program'."
1051 :type
'(repeat string
)
1055 (defcustom sql-ms-login-params
'(user password server database
)
1056 "List of login parameters needed to connect to Microsoft."
1057 :type
'sql-login-params
1061 ;; Customization for Postgres
1063 (defcustom sql-postgres-program
"psql"
1064 "Command to start psql by Postgres.
1066 Starts `sql-interactive-mode' after doing some setup."
1070 (defcustom sql-postgres-options
'("-P" "pager=off")
1071 "List of additional options for `sql-postgres-program'.
1072 The default setting includes the -P option which breaks older versions
1073 of the psql client (such as version 6.5.3). The -P option is equivalent
1074 to the --pset option. If you want the psql to prompt you for a user
1075 name, add the string \"-u\" to the list of options. If you want to
1076 provide a user name on the command line (newer versions such as 7.1),
1077 add your name with a \"-U\" prefix (such as \"-Umark\") to the list."
1078 :type
'(repeat string
)
1082 (defcustom sql-postgres-login-params
1083 `((user :default
,(user-login-name))
1084 (database :default
,(user-login-name)
1085 :completion
,(completion-table-dynamic
1086 (lambda (_) (sql-postgres-list-databases)))
1087 :must-match confirm
)
1089 "List of login parameters needed to connect to Postgres."
1090 :type
'sql-login-params
1094 (defun sql-postgres-list-databases ()
1095 "Return a list of available PostgreSQL databases."
1096 (when (executable-find sql-postgres-program
)
1099 (dolist (row (process-lines sql-postgres-program
"-ltX"))
1100 (when (string-match "^ \\([[:alnum:]-_]+\\) +|.*" row
)
1101 (push (match-string 1 row
) res
))))
1104 ;; Customization for Interbase
1106 (defcustom sql-interbase-program
"isql"
1107 "Command to start isql by Interbase.
1109 Starts `sql-interactive-mode' after doing some setup."
1113 (defcustom sql-interbase-options nil
1114 "List of additional options for `sql-interbase-program'."
1115 :type
'(repeat string
)
1119 (defcustom sql-interbase-login-params
'(user password database
)
1120 "List of login parameters needed to connect to Interbase."
1121 :type
'sql-login-params
1125 ;; Customization for DB2
1127 (defcustom sql-db2-program
"db2"
1128 "Command to start db2 by IBM.
1130 Starts `sql-interactive-mode' after doing some setup."
1134 (defcustom sql-db2-options nil
1135 "List of additional options for `sql-db2-program'."
1136 :type
'(repeat string
)
1140 (defcustom sql-db2-login-params nil
1141 "List of login parameters needed to connect to DB2."
1142 :type
'sql-login-params
1146 ;; Customization for Linter
1148 (defcustom sql-linter-program
"inl"
1149 "Command to start inl by RELEX.
1151 Starts `sql-interactive-mode' after doing some setup."
1155 (defcustom sql-linter-options nil
1156 "List of additional options for `sql-linter-program'."
1157 :type
'(repeat string
)
1161 (defcustom sql-linter-login-params
'(user password database server
)
1162 "Login parameters to needed to connect to Linter."
1163 :type
'sql-login-params
1169 ;;; Variables which do not need customization
1171 (defvar sql-user-history nil
1172 "History of usernames used.")
1174 (defvar sql-database-history nil
1175 "History of databases used.")
1177 (defvar sql-server-history nil
1178 "History of servers used.")
1180 ;; Passwords are not kept in a history.
1182 (defvar sql-product-history nil
1183 "History of products used.")
1185 (defvar sql-connection-history nil
1186 "History of connections used.")
1188 (defvar sql-buffer nil
1189 "Current SQLi buffer.
1191 The global value of `sql-buffer' is the name of the latest SQLi buffer
1192 created. Any SQL buffer created will make a local copy of this value.
1193 See `sql-interactive-mode' for more on multiple sessions. If you want
1194 to change the SQLi buffer a SQL mode sends its SQL strings to, change
1195 the local value of `sql-buffer' using \\[sql-set-sqli-buffer].")
1197 (defvar sql-prompt-regexp nil
1198 "Prompt used to initialize `comint-prompt-regexp'.
1200 You can change `sql-prompt-regexp' on `sql-interactive-mode-hook'.")
1202 (defvar sql-prompt-length
0
1203 "Prompt used to set `left-margin' in `sql-interactive-mode'.
1205 You can change `sql-prompt-length' on `sql-interactive-mode-hook'.")
1207 (defvar sql-prompt-cont-regexp nil
1208 "Prompt pattern of statement continuation prompts.")
1210 (defvar sql-alternate-buffer-name nil
1211 "Buffer-local string used to possibly rename the SQLi buffer.
1213 Used by `sql-rename-buffer'.")
1215 (defun sql-buffer-live-p (buffer &optional product connection
)
1216 "Return non-nil if the process associated with buffer is live.
1218 BUFFER can be a buffer object or a buffer name. The buffer must
1219 be a live buffer, have a running process attached to it, be in
1220 `sql-interactive-mode', and, if PRODUCT or CONNECTION are
1221 specified, it's `sql-product' or `sql-connection' must match."
1224 (setq buffer
(get-buffer buffer
))
1226 (buffer-live-p buffer
)
1227 (comint-check-proc buffer
)
1228 (with-current-buffer buffer
1229 (and (derived-mode-p 'sql-interactive-mode
)
1231 (eq product sql-product
))
1232 (or (not connection
)
1233 (eq connection sql-connection
)))))))
1235 ;; Keymap for sql-interactive-mode.
1237 (defvar sql-interactive-mode-map
1238 (let ((map (make-sparse-keymap)))
1239 (if (fboundp 'set-keymap-parent
)
1240 (set-keymap-parent map comint-mode-map
); Emacs
1241 (if (fboundp 'set-keymap-parents
)
1242 (set-keymap-parents map
(list comint-mode-map
)))); XEmacs
1243 (if (fboundp 'set-keymap-name
)
1244 (set-keymap-name map
'sql-interactive-mode-map
)); XEmacs
1245 (define-key map
(kbd "C-j") 'sql-accumulate-and-indent
)
1246 (define-key map
(kbd "C-c C-w") 'sql-copy-column
)
1247 (define-key map
(kbd "O") 'sql-magic-go
)
1248 (define-key map
(kbd "o") 'sql-magic-go
)
1249 (define-key map
(kbd ";") 'sql-magic-semicolon
)
1250 (define-key map
(kbd "C-c C-l a") 'sql-list-all
)
1251 (define-key map
(kbd "C-c C-l t") 'sql-list-table
)
1253 "Mode map used for `sql-interactive-mode'.
1254 Based on `comint-mode-map'.")
1256 ;; Keymap for sql-mode.
1258 (defvar sql-mode-map
1259 (let ((map (make-sparse-keymap)))
1260 (define-key map
(kbd "C-c C-c") 'sql-send-paragraph
)
1261 (define-key map
(kbd "C-c C-r") 'sql-send-region
)
1262 (define-key map
(kbd "C-c C-s") 'sql-send-string
)
1263 (define-key map
(kbd "C-c C-b") 'sql-send-buffer
)
1264 (define-key map
(kbd "C-c C-n") 'sql-send-line-and-next
)
1265 (define-key map
(kbd "C-c C-i") 'sql-product-interactive
)
1266 (define-key map
(kbd "C-c C-z") 'sql-show-sqli-buffer
)
1267 (define-key map
(kbd "C-c C-l a") 'sql-list-all
)
1268 (define-key map
(kbd "C-c C-l t") 'sql-list-table
)
1269 (define-key map
[remap beginning-of-defun
] 'sql-beginning-of-statement
)
1270 (define-key map
[remap end-of-defun
] 'sql-end-of-statement
)
1272 "Mode map used for `sql-mode'.")
1274 ;; easy menu for sql-mode.
1277 sql-mode-menu sql-mode-map
1278 "Menu for `sql-mode'."
1280 ["Send Paragraph" sql-send-paragraph
(sql-buffer-live-p sql-buffer
)]
1281 ["Send Region" sql-send-region
(and mark-active
1282 (sql-buffer-live-p sql-buffer
))]
1283 ["Send Buffer" sql-send-buffer
(sql-buffer-live-p sql-buffer
)]
1284 ["Send String" sql-send-string
(sql-buffer-live-p sql-buffer
)]
1286 ["List all objects" sql-list-all
(and (sql-buffer-live-p sql-buffer
)
1287 (sql-get-product-feature sql-product
:list-all
))]
1288 ["List table details" sql-list-table
(and (sql-buffer-live-p sql-buffer
)
1289 (sql-get-product-feature sql-product
:list-table
))]
1291 ["Start SQLi session" sql-product-interactive
1292 :visible
(not sql-connection-alist
)
1293 :enable
(sql-get-product-feature sql-product
:sqli-comint-func
)]
1295 :visible sql-connection-alist
1296 :filter sql-connection-menu-filter
1298 ["New SQLi Session" sql-product-interactive
(sql-get-product-feature sql-product
:sqli-comint-func
)])
1300 :visible sql-connection-alist
]
1301 ["Show SQLi buffer" sql-show-sqli-buffer t
]
1302 ["Set SQLi buffer" sql-set-sqli-buffer t
]
1303 ["Pop to SQLi buffer after send"
1304 sql-toggle-pop-to-buffer-after-send-region
1306 :selected sql-pop-to-buffer-after-send-region
]
1309 ,@(mapcar (lambda (prod-info)
1310 (let* ((prod (pop prod-info
))
1311 (name (or (plist-get prod-info
:name
)
1312 (capitalize (symbol-name prod
))))
1313 (cmd (intern (format "sql-highlight-%s-keywords" prod
))))
1314 (fset cmd
`(lambda () ,(format "Highlight %s SQL keywords." name
)
1316 (sql-set-product ',prod
)))
1319 :selected
`(eq sql-product
',prod
))))
1320 sql-product-alist
))))
1322 ;; easy menu for sql-interactive-mode.
1325 sql-interactive-mode-menu sql-interactive-mode-map
1326 "Menu for `sql-interactive-mode'."
1328 ["Rename Buffer" sql-rename-buffer t
]
1329 ["Save Connection" sql-save-connection
(not sql-connection
)]
1331 ["List all objects" sql-list-all
(sql-get-product-feature sql-product
:list-all
)]
1332 ["List table details" sql-list-table
(sql-get-product-feature sql-product
:list-table
)]))
1334 ;; Abbreviations -- if you want more of them, define them in your init
1335 ;; file. Abbrevs have to be enabled in your init file, too.
1337 (define-abbrev-table 'sql-mode-abbrev-table
1338 '(("ins" "insert" nil nil t
)
1339 ("upd" "update" nil nil t
)
1340 ("del" "delete" nil nil t
)
1341 ("sel" "select" nil nil t
)
1342 ("proc" "procedure" nil nil t
)
1343 ("func" "function" nil nil t
)
1344 ("cr" "create" nil nil t
))
1345 "Abbrev table used in `sql-mode' and `sql-interactive-mode'.")
1349 (defvar sql-mode-syntax-table
1350 (let ((table (make-syntax-table)))
1351 ;; C-style comments /**/ (see elisp manual "Syntax Flags"))
1352 (modify-syntax-entry ?
/ ". 14" table
)
1353 (modify-syntax-entry ?
* ". 23" table
)
1354 ;; double-dash starts comments
1355 (modify-syntax-entry ?-
". 12b" table
)
1356 ;; newline and formfeed end comments
1357 (modify-syntax-entry ?
\n "> b" table
)
1358 (modify-syntax-entry ?
\f "> b" table
)
1359 ;; single quotes (') delimit strings
1360 (modify-syntax-entry ?
' "\"" table
)
1361 ;; double quotes (") don't delimit strings
1362 (modify-syntax-entry ?
\" "." table
)
1363 ;; Make these all punctuation
1364 (mapc (lambda (c) (modify-syntax-entry c
"." table
))
1365 (string-to-list "!#$%&+,.:;<=>?@\\|"))
1367 "Syntax table used in `sql-mode' and `sql-interactive-mode'.")
1369 ;; Font lock support
1371 (defvar sql-mode-font-lock-object-name
1373 (list (concat "^\\s-*\\(?:create\\|drop\\|alter\\)\\s-+" ;; lead off with CREATE, DROP or ALTER
1374 "\\(?:\\w+\\s-+\\)*" ;; optional intervening keywords
1375 "\\(?:table\\|view\\|\\(?:package\\|type\\)\\(?:\\s-+body\\)?\\|proc\\(?:edure\\)?"
1376 "\\|function\\|trigger\\|sequence\\|rule\\|default\\)\\s-+"
1377 "\\(?:if\\s-+not\\s-+exists\\s-+\\)?" ;; IF NOT EXISTS
1378 "\\(\\w+\\(?:\\s-*[.]\\s-*\\w+\\)*\\)")
1379 1 'font-lock-function-name-face
))
1381 "Pattern to match the names of top-level objects.
1383 The pattern matches the name in a CREATE, DROP or ALTER
1384 statement. The format of variable should be a valid
1385 `font-lock-keywords' entry.")
1387 ;; While there are international and American standards for SQL, they
1388 ;; are not followed closely, and most vendors offer significant
1389 ;; capabilities beyond those defined in the standard specifications.
1391 ;; SQL mode provides support for highlighting based on the product. In
1392 ;; addition to highlighting the product keywords, any ANSI keywords not
1393 ;; used by the product are also highlighted. This will help identify
1394 ;; keywords that could be restricted in future versions of the product
1395 ;; or might be a problem if ported to another product.
1397 ;; To reduce the complexity and size of the regular expressions
1398 ;; generated to match keywords, ANSI keywords are filtered out of
1399 ;; product keywords if they are equivalent. To do this, we define a
1400 ;; function `sql-font-lock-keywords-builder' that removes any keywords
1401 ;; that are matched by the ANSI patterns and results in the same face
1402 ;; being applied. For this to work properly, we must play some games
1403 ;; with the execution and compile time behavior. This code is a
1404 ;; little tricky but works properly.
1406 ;; When defining the keywords for individual products you should
1407 ;; include all of the keywords that you want matched. The filtering
1408 ;; against the ANSI keywords will be automatic if you use the
1409 ;; `sql-font-lock-keywords-builder' function and follow the
1410 ;; implementation pattern used for the other products in this file.
1413 (defvar sql-mode-ansi-font-lock-keywords
)
1414 (setq sql-mode-ansi-font-lock-keywords nil
))
1417 (defun sql-font-lock-keywords-builder (face boundaries
&rest keywords
)
1418 "Generation of regexp matching any one of KEYWORDS."
1420 (let ((bdy (or boundaries
'("\\b" .
"\\b")))
1423 ;; Remove keywords that are defined in ANSI
1425 ;; (dolist (k keywords)
1427 ;; (dolist (a sql-mode-ansi-font-lock-keywords)
1428 ;; (when (and (eq face (cdr a))
1429 ;; (eq (string-match (car a) k 0) 0)
1430 ;; (eq (match-end 0) (length k)))
1431 ;; (setq kwd (delq k kwd))
1432 ;; (throw 'next nil)))))
1434 ;; Create a properly formed font-lock-keywords item
1435 (cons (concat (car bdy
)
1440 (defun sql-regexp-abbrev (keyword)
1441 (let ((brk (string-match "[~]" keyword
))
1442 (len (length keyword
))
1447 (setq re
(substring keyword
0 brk
)
1451 (setq re
(concat re sep
(substring keyword brk i
))
1454 (concat re
"\\)?"))))
1456 (defun sql-regexp-abbrev-list (&rest keyw-list
)
1460 (setq re
(concat re sep
(sql-regexp-abbrev (car keyw-list
)))
1462 keyw-list
(cdr keyw-list
)))
1463 (concat re
"\\)\\>"))))
1466 (setq sql-mode-ansi-font-lock-keywords
1468 ;; ANSI Non Reserved keywords
1469 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1470 "ada" "asensitive" "assignment" "asymmetric" "atomic" "between"
1471 "bitvar" "called" "catalog_name" "chain" "character_set_catalog"
1472 "character_set_name" "character_set_schema" "checked" "class_origin"
1473 "cobol" "collation_catalog" "collation_name" "collation_schema"
1474 "column_name" "command_function" "command_function_code" "committed"
1475 "condition_number" "connection_name" "constraint_catalog"
1476 "constraint_name" "constraint_schema" "contains" "cursor_name"
1477 "datetime_interval_code" "datetime_interval_precision" "defined"
1478 "definer" "dispatch" "dynamic_function" "dynamic_function_code"
1479 "existing" "exists" "final" "fortran" "generated" "granted"
1480 "hierarchy" "hold" "implementation" "infix" "insensitive" "instance"
1481 "instantiable" "invoker" "key_member" "key_type" "length" "m"
1482 "message_length" "message_octet_length" "message_text" "method" "more"
1483 "mumps" "name" "nullable" "number" "options" "overlaps" "overriding"
1484 "parameter_mode" "parameter_name" "parameter_ordinal_position"
1485 "parameter_specific_catalog" "parameter_specific_name"
1486 "parameter_specific_schema" "pascal" "pli" "position" "repeatable"
1487 "returned_length" "returned_octet_length" "returned_sqlstate"
1488 "routine_catalog" "routine_name" "routine_schema" "row_count" "scale"
1489 "schema_name" "security" "self" "sensitive" "serializable"
1490 "server_name" "similar" "simple" "source" "specific_name" "style"
1491 "subclass_origin" "sublist" "symmetric" "system" "table_name"
1492 "transaction_active" "transactions_committed"
1493 "transactions_rolled_back" "transform" "transforms" "trigger_catalog"
1494 "trigger_name" "trigger_schema" "type" "uncommitted" "unnamed"
1495 "user_defined_type_catalog" "user_defined_type_name"
1496 "user_defined_type_schema"
1499 ;; ANSI Reserved keywords
1500 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1501 "absolute" "action" "add" "admin" "after" "aggregate" "alias" "all"
1502 "allocate" "alter" "and" "any" "are" "as" "asc" "assertion" "at"
1503 "authorization" "before" "begin" "both" "breadth" "by" "call"
1504 "cascade" "cascaded" "case" "catalog" "check" "class" "close"
1505 "collate" "collation" "column" "commit" "completion" "connect"
1506 "connection" "constraint" "constraints" "constructor" "continue"
1507 "corresponding" "create" "cross" "cube" "current" "cursor" "cycle"
1508 "data" "day" "deallocate" "declare" "default" "deferrable" "deferred"
1509 "delete" "depth" "deref" "desc" "describe" "descriptor" "destroy"
1510 "destructor" "deterministic" "diagnostics" "dictionary" "disconnect"
1511 "distinct" "domain" "drop" "dynamic" "each" "else" "end" "equals"
1512 "escape" "every" "except" "exception" "exec" "execute" "external"
1513 "false" "fetch" "first" "for" "foreign" "found" "free" "from" "full"
1514 "function" "general" "get" "global" "go" "goto" "grant" "group"
1515 "grouping" "having" "host" "hour" "identity" "ignore" "immediate" "in"
1516 "indicator" "initialize" "initially" "inner" "inout" "input" "insert"
1517 "intersect" "into" "is" "isolation" "iterate" "join" "key" "language"
1518 "last" "lateral" "leading" "left" "less" "level" "like" "limit"
1519 "local" "locator" "map" "match" "minute" "modifies" "modify" "module"
1520 "month" "names" "natural" "new" "next" "no" "none" "not" "null" "of"
1521 "off" "old" "on" "only" "open" "operation" "option" "or" "order"
1522 "ordinality" "out" "outer" "output" "pad" "parameter" "parameters"
1523 "partial" "path" "postfix" "prefix" "preorder" "prepare" "preserve"
1524 "primary" "prior" "privileges" "procedure" "public" "read" "reads"
1525 "recursive" "references" "referencing" "relative" "restrict" "result"
1526 "return" "returns" "revoke" "right" "role" "rollback" "rollup"
1527 "routine" "rows" "savepoint" "schema" "scroll" "search" "second"
1528 "section" "select" "sequence" "session" "set" "sets" "size" "some"
1529 "space" "specific" "specifictype" "sql" "sqlexception" "sqlstate"
1530 "sqlwarning" "start" "state" "statement" "static" "structure" "table"
1531 "temporary" "terminate" "than" "then" "timezone_hour"
1532 "timezone_minute" "to" "trailing" "transaction" "translation"
1533 "trigger" "true" "under" "union" "unique" "unknown" "unnest" "update"
1534 "usage" "using" "value" "values" "variable" "view" "when" "whenever"
1535 "where" "with" "without" "work" "write" "year"
1539 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1540 "abs" "avg" "bit_length" "cardinality" "cast" "char_length"
1541 "character_length" "coalesce" "convert" "count" "current_date"
1542 "current_path" "current_role" "current_time" "current_timestamp"
1543 "current_user" "extract" "localtime" "localtimestamp" "lower" "max"
1544 "min" "mod" "nullif" "octet_length" "overlay" "placing" "session_user"
1545 "substring" "sum" "system_user" "translate" "treat" "trim" "upper"
1550 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1551 "array" "binary" "bit" "blob" "boolean" "char" "character" "clob"
1552 "date" "dec" "decimal" "double" "float" "int" "integer" "interval"
1553 "large" "national" "nchar" "nclob" "numeric" "object" "precision"
1554 "real" "ref" "row" "scope" "smallint" "time" "timestamp" "varchar"
1558 (defvar sql-mode-ansi-font-lock-keywords
1559 (eval-when-compile sql-mode-ansi-font-lock-keywords
)
1560 "ANSI SQL keywords used by font-lock.
1562 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1563 regular expressions are created during compilation by calling the
1564 function `regexp-opt'. Therefore, take a look at the source before
1565 you define your own `sql-mode-ansi-font-lock-keywords'. You may want
1566 to add functions and PL/SQL keywords.")
1568 (defun sql--oracle-show-reserved-words ()
1569 ;; This function is for use by the maintainer of SQL.EL only.
1570 (if (or (and (not (derived-mode-p 'sql-mode
))
1571 (not (derived-mode-p 'sql-interactive-mode
)))
1573 (not (eq sql-product
'oracle
)))
1574 (user-error "Not an Oracle buffer")
1576 (let ((b "*RESERVED WORDS*"))
1577 (sql-execute sql-buffer b
1580 ", reserved AS \"Res\" "
1581 ", res_type AS \"Type\" "
1582 ", res_attr AS \"Attr\" "
1583 ", res_semi AS \"Semi\" "
1584 ", duplicate AS \"Dup\" "
1585 "FROM V$RESERVED_WORDS "
1587 "AND SUBSTR(keyword, 1, 1) BETWEEN 'A' AND 'Z' "
1588 "ORDER BY 2 DESC, 3 DESC, 4 DESC, 5 DESC, 6 DESC, 1;")
1590 (with-current-buffer b
1591 (set (make-local-variable 'sql-product
) 'oracle
)
1592 (sql-product-font-lock t nil
)
1593 (font-lock-mode +1)))))
1595 (defvar sql-mode-oracle-font-lock-keywords
1598 ;; Oracle SQL*Plus Commands
1599 ;; Only recognized in they start in column 1 and the
1600 ;; abbreviation is followed by a space or the end of line.
1601 (list (concat "^" (sql-regexp-abbrev "rem~ark") "\\(?:\\s-.*\\)?$")
1602 0 'font-lock-comment-face t
)
1607 (sql-regexp-abbrev-list
1608 "[@]\\{1,2\\}" "acc~ept" "a~ppend" "archive" "attribute"
1609 "bre~ak" "bti~tle" "c~hange" "cl~ear" "col~umn" "conn~ect"
1610 "copy" "def~ine" "del" "desc~ribe" "disc~onnect" "ed~it"
1611 "exec~ute" "exit" "get" "help" "ho~st" "[$]" "i~nput" "l~ist"
1612 "passw~ord" "pau~se" "pri~nt" "pro~mpt" "quit" "recover"
1613 "repf~ooter" "reph~eader" "r~un" "sav~e" "sho~w" "shutdown"
1614 "spo~ol" "sta~rt" "startup" "store" "tim~ing" "tti~tle"
1615 "undef~ine" "var~iable" "whenever")
1618 (sql-regexp-abbrev "comp~ute")
1620 (sql-regexp-abbrev-list
1621 "avg" "cou~nt" "min~imum" "max~imum" "num~ber" "sum"
1625 (concat "\\(?:set\\s-+"
1626 (sql-regexp-abbrev-list
1627 "appi~nfo" "array~size" "auto~commit" "autop~rint"
1628 "autorecovery" "autot~race" "blo~ckterminator"
1629 "cmds~ep" "colsep" "com~patibility" "con~cat"
1630 "copyc~ommit" "copytypecheck" "def~ine" "describe"
1631 "echo" "editf~ile" "emb~edded" "esc~ape" "feed~back"
1632 "flagger" "flu~sh" "hea~ding" "heads~ep" "instance"
1633 "lin~esize" "lobof~fset" "long" "longc~hunksize"
1634 "mark~up" "newp~age" "null" "numf~ormat" "num~width"
1635 "pages~ize" "pau~se" "recsep" "recsepchar"
1636 "scan" "serverout~put" "shift~inout" "show~mode"
1637 "sqlbl~anklines" "sqlc~ase" "sqlco~ntinue"
1638 "sqln~umber" "sqlpluscompat~ibility" "sqlpre~fix"
1639 "sqlp~rompt" "sqlt~erminator" "suf~fix" "tab"
1640 "term~out" "ti~me" "timi~ng" "trim~out" "trims~pool"
1641 "und~erline" "ver~ify" "wra~p")
1644 "\\)\\(?:\\s-.*\\)?\\(?:[-]\n.*\\)*$")
1645 0 'font-lock-doc-face t
)
1646 '("&?&\\(?:\\sw\\|\\s_\\)+[.]?" 0 font-lock-preprocessor-face t
)
1648 ;; Oracle PL/SQL Attributes (Declare these first to match %TYPE correctly)
1649 (sql-font-lock-keywords-builder 'font-lock-builtin-face
'("%" .
"\\b")
1650 "bulk_exceptions" "bulk_rowcount" "found" "isopen" "notfound"
1651 "rowcount" "rowtype" "type"
1654 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1655 "abs" "acos" "add_months" "appendchildxml" "ascii" "asciistr" "asin"
1656 "atan" "atan2" "avg" "bfilename" "bin_to_num" "bitand" "cardinality"
1657 "cast" "ceil" "chartorowid" "chr" "cluster_id" "cluster_probability"
1658 "cluster_set" "coalesce" "collect" "compose" "concat" "convert" "corr"
1659 "connect_by_root" "connect_by_iscycle" "connect_by_isleaf"
1660 "corr_k" "corr_s" "cos" "cosh" "count" "covar_pop" "covar_samp"
1661 "cube_table" "cume_dist" "current_date" "current_timestamp" "cv"
1662 "dataobj_to_partition" "dbtimezone" "decode" "decompose" "deletexml"
1663 "dense_rank" "depth" "deref" "dump" "empty_blob" "empty_clob"
1664 "existsnode" "exp" "extract" "extractvalue" "feature_id" "feature_set"
1665 "feature_value" "first" "first_value" "floor" "from_tz" "greatest"
1666 "grouping" "grouping_id" "group_id" "hextoraw" "initcap"
1667 "insertchildxml" "insertchildxmlafter" "insertchildxmlbefore"
1668 "insertxmlafter" "insertxmlbefore" "instr" "instr2" "instr4" "instrb"
1669 "instrc" "iteration_number" "lag" "last" "last_day" "last_value"
1670 "lead" "least" "length" "length2" "length4" "lengthb" "lengthc"
1671 "listagg" "ln" "lnnvl" "localtimestamp" "log" "lower" "lpad" "ltrim"
1672 "make_ref" "max" "median" "min" "mod" "months_between" "nanvl" "nchr"
1673 "new_time" "next_day" "nlssort" "nls_charset_decl_len"
1674 "nls_charset_id" "nls_charset_name" "nls_initcap" "nls_lower"
1675 "nls_upper" "nth_value" "ntile" "nullif" "numtodsinterval"
1676 "numtoyminterval" "nvl" "nvl2" "ora_dst_affected" "ora_dst_convert"
1677 "ora_dst_error" "ora_hash" "path" "percentile_cont" "percentile_disc"
1678 "percent_rank" "power" "powermultiset" "powermultiset_by_cardinality"
1679 "prediction" "prediction_bounds" "prediction_cost"
1680 "prediction_details" "prediction_probability" "prediction_set"
1681 "presentnnv" "presentv" "previous" "rank" "ratio_to_report" "rawtohex"
1682 "rawtonhex" "ref" "reftohex" "regexp_count" "regexp_instr" "regexp_like"
1683 "regexp_replace" "regexp_substr" "regr_avgx" "regr_avgy" "regr_count"
1684 "regr_intercept" "regr_r2" "regr_slope" "regr_sxx" "regr_sxy"
1685 "regr_syy" "remainder" "replace" "round" "rowidtochar" "rowidtonchar"
1686 "row_number" "rpad" "rtrim" "scn_to_timestamp" "sessiontimezone" "set"
1687 "sign" "sin" "sinh" "soundex" "sqrt" "stats_binomial_test"
1688 "stats_crosstab" "stats_f_test" "stats_ks_test" "stats_mode"
1689 "stats_mw_test" "stats_one_way_anova" "stats_t_test_indep"
1690 "stats_t_test_indepu" "stats_t_test_one" "stats_t_test_paired"
1691 "stats_wsr_test" "stddev" "stddev_pop" "stddev_samp" "substr"
1692 "substr2" "substr4" "substrb" "substrc" "sum" "sysdate" "systimestamp"
1693 "sys_connect_by_path" "sys_context" "sys_dburigen" "sys_extract_utc"
1694 "sys_guid" "sys_typeid" "sys_xmlagg" "sys_xmlgen" "tan" "tanh"
1695 "timestamp_to_scn" "to_binary_double" "to_binary_float" "to_blob"
1696 "to_char" "to_clob" "to_date" "to_dsinterval" "to_lob" "to_multi_byte"
1697 "to_nchar" "to_nclob" "to_number" "to_single_byte" "to_timestamp"
1698 "to_timestamp_tz" "to_yminterval" "translate" "treat" "trim" "trunc"
1699 "tz_offset" "uid" "unistr" "updatexml" "upper" "user" "userenv"
1700 "value" "variance" "var_pop" "var_samp" "vsize" "width_bucket"
1701 "xmlagg" "xmlcast" "xmlcdata" "xmlcolattval" "xmlcomment" "xmlconcat"
1702 "xmldiff" "xmlelement" "xmlexists" "xmlforest" "xmlisvalid" "xmlparse"
1703 "xmlpatch" "xmlpi" "xmlquery" "xmlroot" "xmlsequence" "xmlserialize"
1704 "xmltable" "xmltransform"
1707 ;; See the table V$RESERVED_WORDS
1709 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1710 "abort" "access" "accessed" "account" "activate" "add" "admin"
1711 "advise" "after" "agent" "aggregate" "all" "allocate" "allow" "alter"
1712 "always" "analyze" "ancillary" "and" "any" "apply" "archive"
1713 "archivelog" "array" "as" "asc" "associate" "at" "attribute"
1714 "attributes" "audit" "authenticated" "authid" "authorization" "auto"
1715 "autoallocate" "automatic" "availability" "backup" "before" "begin"
1716 "behalf" "between" "binding" "bitmap" "block" "blocksize" "body"
1717 "both" "buffer_pool" "build" "by" "cache" "call" "cancel"
1718 "cascade" "case" "category" "certificate" "chained" "change" "check"
1719 "checkpoint" "child" "chunk" "class" "clear" "clone" "close" "cluster"
1720 "column" "column_value" "columns" "comment" "commit" "committed"
1721 "compatibility" "compile" "complete" "composite_limit" "compress"
1722 "compute" "connect" "connect_time" "consider" "consistent"
1723 "constraint" "constraints" "constructor" "contents" "context"
1724 "continue" "controlfile" "corruption" "cost" "cpu_per_call"
1725 "cpu_per_session" "create" "cross" "cube" "current" "currval" "cycle"
1726 "dangling" "data" "database" "datafile" "datafiles" "day" "ddl"
1727 "deallocate" "debug" "default" "deferrable" "deferred" "definer"
1728 "delay" "delete" "demand" "desc" "determines" "deterministic"
1729 "dictionary" "dimension" "directory" "disable" "disassociate"
1730 "disconnect" "distinct" "distinguished" "distributed" "dml" "drop"
1731 "each" "element" "else" "enable" "end" "equals_path" "escape"
1732 "estimate" "except" "exceptions" "exchange" "excluding" "exists"
1733 "expire" "explain" "extent" "external" "externally"
1734 "failed_login_attempts" "fast" "file" "final" "finish" "flush" "for"
1735 "force" "foreign" "freelist" "freelists" "freepools" "fresh" "from"
1736 "full" "function" "functions" "generated" "global" "global_name"
1737 "globally" "grant" "group" "grouping" "groups" "guard" "hash"
1738 "hashkeys" "having" "heap" "hierarchy" "id" "identified" "identifier"
1739 "idle_time" "immediate" "in" "including" "increment" "index" "indexed"
1740 "indexes" "indextype" "indextypes" "indicator" "initial" "initialized"
1741 "initially" "initrans" "inner" "insert" "instance" "instantiable"
1742 "instead" "intersect" "into" "invalidate" "is" "isolation" "java"
1743 "join" "keep" "key" "kill" "language" "left" "less" "level"
1744 "levels" "library" "like" "like2" "like4" "likec" "limit" "link"
1745 "list" "lob" "local" "location" "locator" "lock" "log" "logfile"
1746 "logging" "logical" "logical_reads_per_call"
1747 "logical_reads_per_session" "managed" "management" "manual" "map"
1748 "mapping" "master" "matched" "materialized" "maxdatafiles"
1749 "maxextents" "maximize" "maxinstances" "maxlogfiles" "maxloghistory"
1750 "maxlogmembers" "maxsize" "maxtrans" "maxvalue" "member" "memory"
1751 "merge" "migrate" "minextents" "minimize" "minimum" "minus" "minvalue"
1752 "mode" "modify" "monitoring" "month" "mount" "move" "movement" "name"
1753 "named" "natural" "nested" "never" "new" "next" "nextval" "no"
1754 "noarchivelog" "noaudit" "nocache" "nocompress" "nocopy" "nocycle"
1755 "nodelay" "noforce" "nologging" "nomapping" "nomaxvalue" "nominimize"
1756 "nominvalue" "nomonitoring" "none" "noorder" "noparallel" "norely"
1757 "noresetlogs" "noreverse" "normal" "norowdependencies" "nosort"
1758 "noswitch" "not" "nothing" "notimeout" "novalidate" "nowait" "null"
1759 "nulls" "object" "of" "off" "offline" "oidindex" "old" "on" "online"
1760 "only" "open" "operator" "optimal" "option" "or" "order"
1761 "organization" "out" "outer" "outline" "over" "overflow" "overriding"
1762 "package" "packages" "parallel" "parallel_enable" "parameters"
1763 "parent" "partition" "partitions" "password" "password_grace_time"
1764 "password_life_time" "password_lock_time" "password_reuse_max"
1765 "password_reuse_time" "password_verify_function" "pctfree"
1766 "pctincrease" "pctthreshold" "pctused" "pctversion" "percent"
1767 "performance" "permanent" "pfile" "physical" "pipelined" "pivot" "plan"
1768 "post_transaction" "pragma" "prebuilt" "preserve" "primary" "private"
1769 "private_sga" "privileges" "procedure" "profile" "protection" "public"
1770 "purge" "query" "quiesce" "quota" "range" "read" "reads" "rebuild"
1771 "records_per_block" "recover" "recovery" "recycle" "reduced" "ref"
1772 "references" "referencing" "refresh" "register" "reject" "relational"
1773 "rely" "rename" "reset" "resetlogs" "resize" "resolve" "resolver"
1774 "resource" "restrict" "restrict_references" "restricted" "result"
1775 "resumable" "resume" "retention" "return" "returning" "reuse"
1776 "reverse" "revoke" "rewrite" "right" "rnds" "rnps" "role" "roles"
1777 "rollback" "rollup" "row" "rowdependencies" "rownum" "rows" "sample"
1778 "savepoint" "scan" "schema" "scn" "scope" "segment" "select"
1779 "selectivity" "self" "sequence" "serializable" "session"
1780 "sessions_per_user" "set" "sets" "settings" "shared" "shared_pool"
1781 "shrink" "shutdown" "siblings" "sid" "single" "size" "skip" "some"
1782 "sort" "source" "space" "specification" "spfile" "split" "standby"
1783 "start" "statement_id" "static" "statistics" "stop" "storage" "store"
1784 "structure" "subpartition" "subpartitions" "substitutable"
1785 "successful" "supplemental" "suspend" "switch" "switchover" "synonym"
1786 "sys" "system" "table" "tables" "tablespace" "tempfile" "template"
1787 "temporary" "test" "than" "then" "thread" "through" "time_zone"
1788 "timeout" "to" "trace" "transaction" "trigger" "triggers" "truncate"
1789 "trust" "type" "types" "unarchived" "under" "under_path" "undo"
1790 "uniform" "union" "unique" "unlimited" "unlock" "unpivot" "unquiesce"
1791 "unrecoverable" "until" "unusable" "unused" "update" "upgrade" "usage"
1792 "use" "using" "validate" "validation" "value" "values" "variable"
1793 "varray" "version" "view" "wait" "when" "whenever" "where" "with"
1794 "without" "wnds" "wnps" "work" "write" "xmldata" "xmlschema" "xmltype"
1797 ;; Oracle Data Types
1798 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1799 "bfile" "binary_double" "binary_float" "blob" "byte" "char" "charbyte"
1800 "clob" "date" "day" "float" "interval" "local" "long" "longraw"
1801 "minute" "month" "nchar" "nclob" "number" "nvarchar2" "raw" "rowid" "second"
1802 "time" "timestamp" "urowid" "varchar2" "with" "year" "zone"
1805 ;; Oracle PL/SQL Functions
1806 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1807 "delete" "trim" "extend" "exists" "first" "last" "count" "limit"
1808 "prior" "next" "sqlcode" "sqlerrm"
1811 ;; Oracle PL/SQL Reserved words
1812 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1813 "all" "alter" "and" "any" "as" "asc" "at" "begin" "between" "by"
1814 "case" "check" "clusters" "cluster" "colauth" "columns" "compress"
1815 "connect" "crash" "create" "cursor" "declare" "default" "desc"
1816 "distinct" "drop" "else" "end" "exception" "exclusive" "fetch" "for"
1817 "from" "function" "goto" "grant" "group" "having" "identified" "if"
1818 "in" "index" "indexes" "insert" "intersect" "into" "is" "like" "lock"
1819 "minus" "mode" "nocompress" "not" "nowait" "null" "of" "on" "option"
1820 "or" "order" "overlaps" "procedure" "public" "resource" "revoke"
1821 "select" "share" "size" "sql" "start" "subtype" "tabauth" "table"
1822 "then" "to" "type" "union" "unique" "update" "values" "view" "views"
1823 "when" "where" "with"
1826 "raise_application_error"
1829 ;; Oracle PL/SQL Keywords
1830 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
1831 "a" "add" "agent" "aggregate" "array" "attribute" "authid" "avg"
1832 "bfile_base" "binary" "blob_base" "block" "body" "both" "bound" "bulk"
1833 "byte" "c" "call" "calling" "cascade" "char" "char_base" "character"
1834 "charset" "charsetform" "charsetid" "clob_base" "close" "collect"
1835 "comment" "commit" "committed" "compiled" "constant" "constructor"
1836 "context" "continue" "convert" "count" "current" "customdatum"
1837 "dangling" "data" "date" "date_base" "day" "define" "delete"
1838 "deterministic" "double" "duration" "element" "elsif" "empty" "escape"
1839 "except" "exceptions" "execute" "exists" "exit" "external" "final"
1840 "fixed" "float" "forall" "force" "general" "hash" "heap" "hidden"
1841 "hour" "immediate" "including" "indicator" "indices" "infinite"
1842 "instantiable" "int" "interface" "interval" "invalidate" "isolation"
1843 "java" "language" "large" "leading" "length" "level" "library" "like2"
1844 "like4" "likec" "limit" "limited" "local" "long" "loop" "map" "max"
1845 "maxlen" "member" "merge" "min" "minute" "mod" "modify" "month"
1846 "multiset" "name" "nan" "national" "native" "nchar" "new" "nocopy"
1847 "number_base" "object" "ocicoll" "ocidate" "ocidatetime" "ociduration"
1848 "ociinterval" "ociloblocator" "ocinumber" "ociraw" "ociref"
1849 "ocirefcursor" "ocirowid" "ocistring" "ocitype" "old" "only" "opaque"
1850 "open" "operator" "oracle" "oradata" "organization" "orlany" "orlvary"
1851 "others" "out" "overriding" "package" "parallel_enable" "parameter"
1852 "parameters" "parent" "partition" "pascal" "pipe" "pipelined" "pragma"
1853 "precision" "prior" "private" "raise" "range" "raw" "read" "record"
1854 "ref" "reference" "relies_on" "rem" "remainder" "rename" "result"
1855 "result_cache" "return" "returning" "reverse" "rollback" "row"
1856 "sample" "save" "savepoint" "sb1" "sb2" "sb4" "second" "segment"
1857 "self" "separate" "sequence" "serializable" "set" "short" "size_t"
1858 "some" "sparse" "sqlcode" "sqldata" "sqlname" "sqlstate" "standard"
1859 "static" "stddev" "stored" "string" "struct" "style" "submultiset"
1860 "subpartition" "substitutable" "sum" "synonym" "tdo" "the" "time"
1861 "timestamp" "timezone_abbr" "timezone_hour" "timezone_minute"
1862 "timezone_region" "trailing" "transaction" "transactional" "trusted"
1863 "ub1" "ub2" "ub4" "under" "unsigned" "untrusted" "use" "using"
1864 "valist" "value" "variable" "variance" "varray" "varying" "void"
1865 "while" "work" "wrapped" "write" "year" "zone"
1867 "autonomous_transaction" "exception_init" "inline"
1868 "restrict_references" "serially_reusable"
1871 ;; Oracle PL/SQL Data Types
1872 (sql-font-lock-keywords-builder 'font-lock-type-face nil
1873 "\"BINARY LARGE OBJECT\"" "\"CHAR LARGE OBJECT\"" "\"CHAR VARYING\""
1874 "\"CHARACTER LARGE OBJECT\"" "\"CHARACTER VARYING\""
1875 "\"DOUBLE PRECISION\"" "\"INTERVAL DAY TO SECOND\""
1876 "\"INTERVAL YEAR TO MONTH\"" "\"LONG RAW\"" "\"NATIONAL CHAR\""
1877 "\"NATIONAL CHARACTER LARGE OBJECT\"" "\"NATIONAL CHARACTER\""
1878 "\"NCHAR LARGE OBJECT\"" "\"NCHAR\"" "\"NCLOB\"" "\"NVARCHAR2\""
1879 "\"TIME WITH TIME ZONE\"" "\"TIMESTAMP WITH LOCAL TIME ZONE\""
1880 "\"TIMESTAMP WITH TIME ZONE\""
1881 "bfile" "bfile_base" "binary_double" "binary_float" "binary_integer"
1882 "blob" "blob_base" "boolean" "char" "character" "char_base" "clob"
1883 "clob_base" "cursor" "date" "day" "dec" "decimal"
1884 "dsinterval_unconstrained" "float" "int" "integer" "interval" "local"
1885 "long" "mlslabel" "month" "natural" "naturaln" "nchar_cs" "number"
1886 "number_base" "numeric" "pls_integer" "positive" "positiven" "raw"
1887 "real" "ref" "rowid" "second" "signtype" "simple_double"
1888 "simple_float" "simple_integer" "smallint" "string" "time" "timestamp"
1889 "timestamp_ltz_unconstrained" "timestamp_tz_unconstrained"
1890 "timestamp_unconstrained" "time_tz_unconstrained" "time_unconstrained"
1891 "to" "urowid" "varchar" "varchar2" "with" "year"
1892 "yminterval_unconstrained" "zone"
1895 ;; Oracle PL/SQL Exceptions
1896 (sql-font-lock-keywords-builder 'font-lock-warning-face nil
1897 "access_into_null" "case_not_found" "collection_is_null"
1898 "cursor_already_open" "dup_val_on_index" "invalid_cursor"
1899 "invalid_number" "login_denied" "no_data_found" "no_data_needed"
1900 "not_logged_on" "program_error" "rowtype_mismatch" "self_is_null"
1901 "storage_error" "subscript_beyond_count" "subscript_outside_limit"
1902 "sys_invalid_rowid" "timeout_on_resource" "too_many_rows"
1903 "value_error" "zero_divide"
1906 "Oracle SQL keywords used by font-lock.
1908 This variable is used by `sql-mode' and `sql-interactive-mode'. The
1909 regular expressions are created during compilation by calling the
1910 function `regexp-opt'. Therefore, take a look at the source before
1911 you define your own `sql-mode-oracle-font-lock-keywords'. You may want
1912 to add functions and PL/SQL keywords.")
1914 (defvar sql-mode-postgres-font-lock-keywords
1917 ;; Postgres psql commands
1918 '("^\\s-*\\\\.*$" . font-lock-doc-face
)
1920 ;; Postgres unreserved words but may have meaning
1921 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
"a"
1922 "abs" "absent" "according" "ada" "alias" "allocate" "are" "array_agg"
1923 "asensitive" "atomic" "attribute" "attributes" "avg" "base64"
1924 "bernoulli" "bit_length" "bitvar" "blob" "blocked" "bom" "breadth" "c"
1925 "call" "cardinality" "catalog_name" "ceil" "ceiling" "char_length"
1926 "character_length" "character_set_catalog" "character_set_name"
1927 "character_set_schema" "characters" "checked" "class_origin" "clob"
1928 "cobol" "collation" "collation_catalog" "collation_name"
1929 "collation_schema" "collect" "column_name" "columns"
1930 "command_function" "command_function_code" "completion" "condition"
1931 "condition_number" "connect" "connection_name" "constraint_catalog"
1932 "constraint_name" "constraint_schema" "constructor" "contains"
1933 "control" "convert" "corr" "corresponding" "count" "covar_pop"
1934 "covar_samp" "cube" "cume_dist" "current_default_transform_group"
1935 "current_path" "current_transform_group_for_type" "cursor_name"
1936 "datalink" "datetime_interval_code" "datetime_interval_precision" "db"
1937 "defined" "degree" "dense_rank" "depth" "deref" "derived" "describe"
1938 "descriptor" "destroy" "destructor" "deterministic" "diagnostics"
1939 "disconnect" "dispatch" "dlnewcopy" "dlpreviouscopy" "dlurlcomplete"
1940 "dlurlcompleteonly" "dlurlcompletewrite" "dlurlpath" "dlurlpathonly"
1941 "dlurlpathwrite" "dlurlscheme" "dlurlserver" "dlvalue" "dynamic"
1942 "dynamic_function" "dynamic_function_code" "element" "empty"
1943 "end-exec" "equals" "every" "exception" "exec" "existing" "exp" "file"
1944 "filter" "final" "first_value" "flag" "floor" "fortran" "found" "free"
1945 "fs" "fusion" "g" "general" "generated" "get" "go" "goto" "grouping"
1946 "hex" "hierarchy" "host" "id" "ignore" "implementation" "import"
1947 "indent" "indicator" "infix" "initialize" "instance" "instantiable"
1948 "integrity" "intersection" "iterate" "k" "key_member" "key_type" "lag"
1949 "last_value" "lateral" "lead" "length" "less" "library" "like_regex"
1950 "link" "ln" "locator" "lower" "m" "map" "matched" "max"
1951 "max_cardinality" "member" "merge" "message_length"
1952 "message_octet_length" "message_text" "method" "min" "mod" "modifies"
1953 "modify" "module" "more" "multiset" "mumps" "namespace" "nclob"
1954 "nesting" "new" "nfc" "nfd" "nfkc" "nfkd" "nil" "normalize"
1955 "normalized" "nth_value" "ntile" "nullable" "number"
1956 "occurrences_regex" "octet_length" "octets" "old" "open" "operation"
1957 "ordering" "ordinality" "others" "output" "overriding" "p" "pad"
1958 "parameter" "parameter_mode" "parameter_name"
1959 "parameter_ordinal_position" "parameter_specific_catalog"
1960 "parameter_specific_name" "parameter_specific_schema" "parameters"
1961 "pascal" "passing" "passthrough" "percent_rank" "percentile_cont"
1962 "percentile_disc" "permission" "pli" "position_regex" "postfix"
1963 "power" "prefix" "preorder" "public" "rank" "reads" "recovery" "ref"
1964 "referencing" "regr_avgx" "regr_avgy" "regr_count" "regr_intercept"
1965 "regr_r2" "regr_slope" "regr_sxx" "regr_sxy" "regr_syy" "requiring"
1966 "respect" "restore" "result" "return" "returned_cardinality"
1967 "returned_length" "returned_octet_length" "returned_sqlstate" "rollup"
1968 "routine" "routine_catalog" "routine_name" "routine_schema"
1969 "row_count" "row_number" "scale" "schema_name" "scope" "scope_catalog"
1970 "scope_name" "scope_schema" "section" "selective" "self" "sensitive"
1971 "server_name" "sets" "size" "source" "space" "specific"
1972 "specific_name" "specifictype" "sql" "sqlcode" "sqlerror"
1973 "sqlexception" "sqlstate" "sqlwarning" "sqrt" "state" "static"
1974 "stddev_pop" "stddev_samp" "structure" "style" "subclass_origin"
1975 "sublist" "submultiset" "substring_regex" "sum" "system_user" "t"
1976 "table_name" "tablesample" "terminate" "than" "ties" "timezone_hour"
1977 "timezone_minute" "token" "top_level_count" "transaction_active"
1978 "transactions_committed" "transactions_rolled_back" "transform"
1979 "transforms" "translate" "translate_regex" "translation"
1980 "trigger_catalog" "trigger_name" "trigger_schema" "trim_array"
1981 "uescape" "under" "unlink" "unnamed" "unnest" "untyped" "upper" "uri"
1982 "usage" "user_defined_type_catalog" "user_defined_type_code"
1983 "user_defined_type_name" "user_defined_type_schema" "var_pop"
1984 "var_samp" "varbinary" "variable" "whenever" "width_bucket" "within"
1985 "xmlagg" "xmlbinary" "xmlcast" "xmlcomment" "xmldeclaration"
1986 "xmldocument" "xmlexists" "xmliterate" "xmlnamespaces" "xmlquery"
1987 "xmlschema" "xmltable" "xmltext" "xmlvalidate"
1990 ;; Postgres non-reserved words
1991 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
1992 "abort" "absolute" "access" "action" "add" "admin" "after" "aggregate"
1993 "also" "alter" "always" "assertion" "assignment" "at" "attribute" "backward"
1994 "before" "begin" "between" "by" "cache" "called" "cascade" "cascaded"
1995 "catalog" "chain" "characteristics" "checkpoint" "class" "close"
1996 "cluster" "coalesce" "comment" "comments" "commit" "committed"
1997 "configuration" "connection" "constraints" "content" "continue"
1998 "conversion" "copy" "cost" "createdb" "createrole" "createuser" "csv"
1999 "current" "cursor" "cycle" "data" "database" "day" "deallocate" "dec"
2000 "declare" "defaults" "deferred" "definer" "delete" "delimiter"
2001 "delimiters" "dictionary" "disable" "discard" "document" "domain"
2002 "drop" "each" "enable" "encoding" "encrypted" "enum" "escape"
2003 "exclude" "excluding" "exclusive" "execute" "exists" "explain"
2004 "extension" "external" "extract" "family" "first" "float" "following" "force"
2005 "forward" "function" "functions" "global" "granted" "greatest"
2006 "handler" "header" "hold" "hour" "identity" "if" "immediate"
2007 "immutable" "implicit" "including" "increment" "index" "indexes"
2008 "inherit" "inherits" "inline" "inout" "input" "insensitive" "insert"
2009 "instead" "invoker" "isolation" "key" "label" "language" "large" "last"
2010 "lc_collate" "lc_ctype" "leakproof" "least" "level" "listen" "load" "local"
2011 "location" "lock" "login" "mapping" "match" "maxvalue" "minute"
2012 "minvalue" "mode" "month" "move" "names" "national" "nchar"
2013 "next" "no" "nocreatedb" "nocreaterole" "nocreateuser" "noinherit"
2014 "nologin" "none" "noreplication" "nosuperuser" "nothing" "notify" "nowait" "nullif"
2015 "nulls" "object" "of" "off" "oids" "operator" "option" "options" "out"
2016 "overlay" "owned" "owner" "parser" "partial" "partition" "passing" "password"
2017 "plans" "position" "preceding" "precision" "prepare" "prepared" "preserve" "prior"
2018 "privileges" "procedural" "procedure" "quote" "range" "read"
2019 "reassign" "recheck" "recursive" "ref" "reindex" "relative" "release"
2020 "rename" "repeatable" "replace" "replica" "replication" "reset" "restart" "restrict"
2021 "returns" "revoke" "role" "rollback" "row" "rows" "rule" "savepoint"
2022 "schema" "scroll" "search" "second" "security" "sequence"
2023 "serializable" "server" "session" "set" "setof" "share" "show"
2024 "simple" "snapshot" "stable" "standalone" "start" "statement" "statistics"
2025 "stdin" "stdout" "storage" "strict" "strip" "substring" "superuser"
2026 "sysid" "system" "tables" "tablespace" "temp" "template" "temporary"
2027 "transaction" "treat" "trim" "truncate" "trusted" "type" "types"
2028 "unbounded" "uncommitted" "unencrypted" "unlisten" "unlogged" "until"
2029 "update" "vacuum" "valid" "validate" "validator" "value" "values" "varying" "version"
2030 "view" "volatile" "whitespace" "without" "work" "wrapper" "write"
2031 "xmlattributes" "xmlconcat" "xmlelement" "xmlexists" "xmlforest" "xmlparse"
2032 "xmlpi" "xmlroot" "xmlserialize" "year" "yes" "zone"
2035 ;; Postgres Reserved
2036 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2037 "all" "analyse" "analyze" "and" "array" "asc" "as" "asymmetric"
2038 "authorization" "binary" "both" "case" "cast" "check" "collate"
2039 "column" "concurrently" "constraint" "create" "cross"
2040 "current_catalog" "current_date" "current_role" "current_schema"
2041 "current_time" "current_timestamp" "current_user" "default"
2042 "deferrable" "desc" "distinct" "do" "else" "end" "except" "false"
2043 "fetch" "foreign" "for" "freeze" "from" "full" "grant" "group"
2044 "having" "ilike" "initially" "inner" "in" "intersect" "into" "isnull"
2045 "is" "join" "leading" "left" "like" "limit" "localtime"
2046 "localtimestamp" "natural" "notnull" "not" "null" "offset"
2047 "only" "on" "order" "or" "outer" "overlaps" "over" "placing" "primary"
2048 "references" "returning" "right" "select" "session_user" "similar"
2049 "some" "symmetric" "table" "then" "to" "trailing" "true" "union"
2050 "unique" "user" "using" "variadic" "verbose" "when" "where" "window"
2054 ;; Postgres PL/pgSQL
2055 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2056 "assign" "if" "case" "loop" "while" "for" "foreach" "exit" "elsif" "return"
2057 "raise" "execsql" "dynexecute" "perform" "getdiag" "open" "fetch" "move" "close"
2060 ;; Postgres Data Types
2061 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2062 "bigint" "bigserial" "bit" "bool" "boolean" "box" "bytea" "char"
2063 "character" "cidr" "circle" "date" "decimal" "double" "float4"
2064 "float8" "inet" "int" "int2" "int4" "int8" "integer" "interval" "line"
2065 "lseg" "macaddr" "money" "name" "numeric" "path" "point" "polygon"
2066 "precision" "real" "serial" "serial4" "serial8" "sequences" "smallint" "text"
2067 "time" "timestamp" "timestamptz" "timetz" "tsquery" "tsvector"
2068 "txid_snapshot" "unknown" "uuid" "varbit" "varchar" "varying" "without"
2072 "Postgres SQL keywords used by font-lock.
2074 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2075 regular expressions are created during compilation by calling the
2076 function `regexp-opt'. Therefore, take a look at the source before
2077 you define your own `sql-mode-postgres-font-lock-keywords'.")
2079 (defvar sql-mode-linter-font-lock-keywords
2083 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2084 "autocommit" "autoinc" "autorowid" "cancel" "cascade" "channel"
2085 "committed" "count" "countblob" "cross" "current" "data" "database"
2086 "datafile" "datafiles" "datesplit" "dba" "dbname" "default" "deferred"
2087 "denied" "description" "device" "difference" "directory" "error"
2088 "escape" "euc" "exclusive" "external" "extfile" "false" "file"
2089 "filename" "filesize" "filetime" "filter" "findblob" "first" "foreign"
2090 "full" "fuzzy" "global" "granted" "ignore" "immediate" "increment"
2091 "indexes" "indexfile" "indexfiles" "indextime" "initial" "integrity"
2092 "internal" "key" "last_autoinc" "last_rowid" "limit" "linter"
2093 "linter_file_device" "linter_file_size" "linter_name_length" "ln"
2094 "local" "login" "maxisn" "maxrow" "maxrowid" "maxvalue" "message"
2095 "minvalue" "module" "names" "national" "natural" "new" "new_table"
2096 "no" "node" "noneuc" "nulliferror" "numbers" "off" "old" "old_table"
2097 "only" "operation" "optimistic" "option" "page" "partially" "password"
2098 "phrase" "plan" "precision" "primary" "priority" "privileges"
2099 "proc_info_size" "proc_par_name_len" "protocol" "quant" "range" "raw"
2100 "read" "record" "records" "references" "remote" "rename" "replication"
2101 "restart" "rewrite" "root" "row" "rule" "savepoint" "security"
2102 "sensitive" "sequence" "serializable" "server" "since" "size" "some"
2103 "startup" "statement" "station" "success" "sys_guid" "tables" "test"
2104 "timeout" "trace" "transaction" "translation" "trigger"
2105 "trigger_info_size" "true" "trunc" "uncommitted" "unicode" "unknown"
2106 "unlimited" "unlisted" "user" "utf8" "value" "varying" "volumes"
2107 "wait" "windows_code" "workspace" "write" "xml"
2111 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2112 "access" "action" "add" "address" "after" "all" "alter" "always" "and"
2113 "any" "append" "as" "asc" "ascic" "async" "at_begin" "at_end" "audit"
2114 "aud_obj_name_len" "backup" "base" "before" "between" "blobfile"
2115 "blobfiles" "blobpct" "brief" "browse" "by" "case" "cast" "check"
2116 "clear" "close" "column" "comment" "commit" "connect" "contains"
2117 "correct" "create" "delete" "desc" "disable" "disconnect" "distinct"
2118 "drop" "each" "ef" "else" "enable" "end" "event" "except" "exclude"
2119 "execute" "exists" "extract" "fetch" "finish" "for" "from" "get"
2120 "grant" "group" "having" "identified" "in" "index" "inner" "insert"
2121 "instead" "intersect" "into" "is" "isolation" "join" "left" "level"
2122 "like" "lock" "mode" "modify" "not" "nowait" "null" "of" "on" "open"
2123 "or" "order" "outer" "owner" "press" "prior" "procedure" "public"
2124 "purge" "rebuild" "resource" "restrict" "revoke" "right" "role"
2125 "rollback" "rownum" "select" "session" "set" "share" "shutdown"
2126 "start" "stop" "sync" "synchronize" "synonym" "sysdate" "table" "then"
2127 "to" "union" "unique" "unlock" "until" "update" "using" "values"
2128 "view" "when" "where" "with" "without"
2132 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2133 "abs" "acos" "asin" "atan" "atan2" "avg" "ceil" "cos" "cosh" "divtime"
2134 "exp" "floor" "getbits" "getblob" "getbyte" "getlong" "getraw"
2135 "getstr" "gettext" "getword" "hextoraw" "lenblob" "length" "log"
2136 "lower" "lpad" "ltrim" "max" "min" "mod" "monthname" "nvl"
2137 "octet_length" "power" "rand" "rawtohex" "repeat_string"
2138 "right_substr" "round" "rpad" "rtrim" "sign" "sin" "sinh" "soundex"
2139 "sqrt" "sum" "tan" "tanh" "timeint_to_days" "to_char" "to_date"
2140 "to_gmtime" "to_localtime" "to_number" "trim" "upper" "decode"
2141 "substr" "substring" "chr" "dayname" "days" "greatest" "hex" "initcap"
2142 "instr" "least" "multime" "replace" "width"
2145 ;; Linter Data Types
2146 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2147 "bigint" "bitmap" "blob" "boolean" "char" "character" "date"
2148 "datetime" "dec" "decimal" "double" "float" "int" "integer" "nchar"
2149 "number" "numeric" "real" "smallint" "varbyte" "varchar" "byte"
2153 "Linter SQL keywords used by font-lock.
2155 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2156 regular expressions are created during compilation by calling the
2157 function `regexp-opt'.")
2159 (defvar sql-mode-ms-font-lock-keywords
2162 ;; MS isql/osql Commands
2165 "^\\(?:\\(?:set\\s-+\\(?:"
2167 "datefirst" "dateformat" "deadlock_priority" "lock_timeout"
2168 "concat_null_yields_null" "cursor_close_on_commit"
2169 "disable_def_cnst_chk" "fips_flagger" "identity_insert" "language"
2170 "offsets" "quoted_identifier" "arithabort" "arithignore" "fmtonly"
2171 "nocount" "noexec" "numeric_roundabort" "parseonly"
2172 "query_governor_cost_limit" "rowcount" "textsize" "ansi_defaults"
2173 "ansi_null_dflt_off" "ansi_null_dflt_on" "ansi_nulls" "ansi_padding"
2174 "ansi_warnings" "forceplan" "showplan_all" "showplan_text"
2175 "statistics" "implicit_transactions" "remote_proc_transactions"
2176 "transaction" "xact_abort"
2178 "\\)\\)\\|go\\s-*\\|use\\s-+\\|setuser\\s-+\\|dbcc\\s-+\\).*$")
2179 'font-lock-doc-face
)
2182 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2183 "absolute" "add" "all" "alter" "and" "any" "as" "asc" "authorization"
2184 "avg" "backup" "begin" "between" "break" "browse" "bulk" "by"
2185 "cascade" "case" "check" "checkpoint" "close" "clustered" "coalesce"
2186 "column" "commit" "committed" "compute" "confirm" "constraint"
2187 "contains" "containstable" "continue" "controlrow" "convert" "count"
2188 "create" "cross" "current" "current_date" "current_time"
2189 "current_timestamp" "current_user" "database" "deallocate" "declare"
2190 "default" "delete" "deny" "desc" "disk" "distinct" "distributed"
2191 "double" "drop" "dummy" "dump" "else" "end" "errlvl" "errorexit"
2192 "escape" "except" "exec" "execute" "exists" "exit" "fetch" "file"
2193 "fillfactor" "first" "floppy" "for" "foreign" "freetext"
2194 "freetexttable" "from" "full" "goto" "grant" "group" "having"
2195 "holdlock" "identity" "identity_insert" "identitycol" "if" "in"
2196 "index" "inner" "insert" "intersect" "into" "is" "isolation" "join"
2197 "key" "kill" "last" "left" "level" "like" "lineno" "load" "max" "min"
2198 "mirrorexit" "national" "next" "nocheck" "nolock" "nonclustered" "not"
2199 "null" "nullif" "of" "off" "offsets" "on" "once" "only" "open"
2200 "opendatasource" "openquery" "openrowset" "option" "or" "order"
2201 "outer" "output" "over" "paglock" "percent" "perm" "permanent" "pipe"
2202 "plan" "precision" "prepare" "primary" "print" "prior" "privileges"
2203 "proc" "procedure" "processexit" "public" "raiserror" "read"
2204 "readcommitted" "readpast" "readtext" "readuncommitted" "reconfigure"
2205 "references" "relative" "repeatable" "repeatableread" "replication"
2206 "restore" "restrict" "return" "revoke" "right" "rollback" "rowcount"
2207 "rowguidcol" "rowlock" "rule" "save" "schema" "select" "serializable"
2208 "session_user" "set" "shutdown" "some" "statistics" "sum"
2209 "system_user" "table" "tablock" "tablockx" "tape" "temp" "temporary"
2210 "textsize" "then" "to" "top" "tran" "transaction" "trigger" "truncate"
2211 "tsequal" "uncommitted" "union" "unique" "update" "updatetext"
2212 "updlock" "use" "user" "values" "view" "waitfor" "when" "where"
2213 "while" "with" "work" "writetext" "collate" "function" "openxml"
2218 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2219 "@@connections" "@@cpu_busy" "@@cursor_rows" "@@datefirst" "@@dbts"
2220 "@@error" "@@fetch_status" "@@identity" "@@idle" "@@io_busy"
2221 "@@langid" "@@language" "@@lock_timeout" "@@max_connections"
2222 "@@max_precision" "@@nestlevel" "@@options" "@@pack_received"
2223 "@@pack_sent" "@@packet_errors" "@@procid" "@@remserver" "@@rowcount"
2224 "@@servername" "@@servicename" "@@spid" "@@textsize" "@@timeticks"
2225 "@@total_errors" "@@total_read" "@@total_write" "@@trancount"
2226 "@@version" "abs" "acos" "and" "app_name" "ascii" "asin" "atan" "atn2"
2227 "avg" "case" "cast" "ceiling" "char" "charindex" "coalesce"
2228 "col_length" "col_name" "columnproperty" "containstable" "convert"
2229 "cos" "cot" "count" "current_timestamp" "current_user" "cursor_status"
2230 "databaseproperty" "datalength" "dateadd" "datediff" "datename"
2231 "datepart" "day" "db_id" "db_name" "degrees" "difference" "exp"
2232 "file_id" "file_name" "filegroup_id" "filegroup_name"
2233 "filegroupproperty" "fileproperty" "floor" "formatmessage"
2234 "freetexttable" "fulltextcatalogproperty" "fulltextserviceproperty"
2235 "getansinull" "getdate" "grouping" "host_id" "host_name" "ident_incr"
2236 "ident_seed" "identity" "index_col" "indexproperty" "is_member"
2237 "is_srvrolemember" "isdate" "isnull" "isnumeric" "left" "len" "log"
2238 "log10" "lower" "ltrim" "max" "min" "month" "nchar" "newid" "nullif"
2239 "object_id" "object_name" "objectproperty" "openquery" "openrowset"
2240 "parsename" "patindex" "patindex" "permissions" "pi" "power"
2241 "quotename" "radians" "rand" "replace" "replicate" "reverse" "right"
2242 "round" "rtrim" "session_user" "sign" "sin" "soundex" "space" "sqrt"
2243 "square" "stats_date" "stdev" "stdevp" "str" "stuff" "substring" "sum"
2244 "suser_id" "suser_name" "suser_sid" "suser_sname" "system_user" "tan"
2245 "textptr" "textvalid" "typeproperty" "unicode" "upper" "user"
2246 "user_id" "user_name" "var" "varp" "year"
2250 '("\\b@[a-zA-Z0-9_]*\\b" . font-lock-variable-name-face
)
2253 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2254 "binary" "bit" "char" "character" "cursor" "datetime" "dec" "decimal"
2255 "double" "float" "image" "int" "integer" "money" "national" "nchar"
2256 "ntext" "numeric" "numeric" "nvarchar" "precision" "real"
2257 "smalldatetime" "smallint" "smallmoney" "text" "timestamp" "tinyint"
2258 "uniqueidentifier" "varbinary" "varchar" "varying"
2261 "Microsoft SQLServer SQL keywords used by font-lock.
2263 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2264 regular expressions are created during compilation by calling the
2265 function `regexp-opt'. Therefore, take a look at the source before
2266 you define your own `sql-mode-ms-font-lock-keywords'.")
2268 (defvar sql-mode-sybase-font-lock-keywords nil
2269 "Sybase SQL keywords used by font-lock.
2271 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2272 regular expressions are created during compilation by calling the
2273 function `regexp-opt'. Therefore, take a look at the source before
2274 you define your own `sql-mode-sybase-font-lock-keywords'.")
2276 (defvar sql-mode-informix-font-lock-keywords nil
2277 "Informix SQL keywords used by font-lock.
2279 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2280 regular expressions are created during compilation by calling the
2281 function `regexp-opt'. Therefore, take a look at the source before
2282 you define your own `sql-mode-informix-font-lock-keywords'.")
2284 (defvar sql-mode-interbase-font-lock-keywords nil
2285 "Interbase SQL keywords used by font-lock.
2287 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2288 regular expressions are created during compilation by calling the
2289 function `regexp-opt'. Therefore, take a look at the source before
2290 you define your own `sql-mode-interbase-font-lock-keywords'.")
2292 (defvar sql-mode-ingres-font-lock-keywords nil
2293 "Ingres SQL keywords used by font-lock.
2295 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2296 regular expressions are created during compilation by calling the
2297 function `regexp-opt'. Therefore, take a look at the source before
2298 you define your own `sql-mode-interbase-font-lock-keywords'.")
2300 (defvar sql-mode-solid-font-lock-keywords nil
2301 "Solid SQL keywords used by font-lock.
2303 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2304 regular expressions are created during compilation by calling the
2305 function `regexp-opt'. Therefore, take a look at the source before
2306 you define your own `sql-mode-solid-font-lock-keywords'.")
2308 (defvar sql-mode-mysql-font-lock-keywords
2312 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2313 "ascii" "avg" "bdmpolyfromtext" "bdmpolyfromwkb" "bdpolyfromtext"
2314 "bdpolyfromwkb" "benchmark" "bin" "bit_and" "bit_length" "bit_or"
2315 "bit_xor" "both" "cast" "char_length" "character_length" "coalesce"
2316 "concat" "concat_ws" "connection_id" "conv" "convert" "count"
2317 "curdate" "current_date" "current_time" "current_timestamp" "curtime"
2318 "elt" "encrypt" "export_set" "field" "find_in_set" "found_rows" "from"
2319 "geomcollfromtext" "geomcollfromwkb" "geometrycollectionfromtext"
2320 "geometrycollectionfromwkb" "geometryfromtext" "geometryfromwkb"
2321 "geomfromtext" "geomfromwkb" "get_lock" "group_concat" "hex" "ifnull"
2322 "instr" "interval" "isnull" "last_insert_id" "lcase" "leading"
2323 "length" "linefromtext" "linefromwkb" "linestringfromtext"
2324 "linestringfromwkb" "load_file" "locate" "lower" "lpad" "ltrim"
2325 "make_set" "master_pos_wait" "max" "mid" "min" "mlinefromtext"
2326 "mlinefromwkb" "mpointfromtext" "mpointfromwkb" "mpolyfromtext"
2327 "mpolyfromwkb" "multilinestringfromtext" "multilinestringfromwkb"
2328 "multipointfromtext" "multipointfromwkb" "multipolygonfromtext"
2329 "multipolygonfromwkb" "now" "nullif" "oct" "octet_length" "ord"
2330 "pointfromtext" "pointfromwkb" "polyfromtext" "polyfromwkb"
2331 "polygonfromtext" "polygonfromwkb" "position" "quote" "rand"
2332 "release_lock" "repeat" "replace" "reverse" "rpad" "rtrim" "soundex"
2333 "space" "std" "stddev" "substring" "substring_index" "sum" "sysdate"
2334 "trailing" "trim" "ucase" "unix_timestamp" "upper" "user" "variance"
2338 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2339 "action" "add" "after" "against" "all" "alter" "and" "as" "asc"
2340 "auto_increment" "avg_row_length" "bdb" "between" "by" "cascade"
2341 "case" "change" "character" "check" "checksum" "close" "collate"
2342 "collation" "column" "columns" "comment" "committed" "concurrent"
2343 "constraint" "create" "cross" "data" "database" "default"
2344 "delay_key_write" "delayed" "delete" "desc" "directory" "disable"
2345 "distinct" "distinctrow" "do" "drop" "dumpfile" "duplicate" "else" "elseif"
2346 "enable" "enclosed" "end" "escaped" "exists" "fields" "first" "for"
2347 "force" "foreign" "from" "full" "fulltext" "global" "group" "handler"
2348 "having" "heap" "high_priority" "if" "ignore" "in" "index" "infile"
2349 "inner" "insert" "insert_method" "into" "is" "isam" "isolation" "join"
2350 "key" "keys" "last" "left" "level" "like" "limit" "lines" "load"
2351 "local" "lock" "low_priority" "match" "max_rows" "merge" "min_rows"
2352 "mode" "modify" "mrg_myisam" "myisam" "natural" "next" "no" "not"
2353 "null" "offset" "oj" "on" "open" "optionally" "or" "order" "outer"
2354 "outfile" "pack_keys" "partial" "password" "prev" "primary"
2355 "procedure" "quick" "raid0" "raid_type" "read" "references" "rename"
2356 "repeatable" "restrict" "right" "rollback" "rollup" "row_format"
2357 "savepoint" "select" "separator" "serializable" "session" "set"
2358 "share" "show" "sql_big_result" "sql_buffer_result" "sql_cache"
2359 "sql_calc_found_rows" "sql_no_cache" "sql_small_result" "starting"
2360 "straight_join" "striped" "table" "tables" "temporary" "terminated"
2361 "then" "to" "transaction" "truncate" "type" "uncommitted" "union"
2362 "unique" "unlock" "update" "use" "using" "values" "when" "where"
2363 "with" "write" "xor"
2367 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2368 "bigint" "binary" "bit" "blob" "bool" "boolean" "char" "curve" "date"
2369 "datetime" "dec" "decimal" "double" "enum" "fixed" "float" "geometry"
2370 "geometrycollection" "int" "integer" "line" "linearring" "linestring"
2371 "longblob" "longtext" "mediumblob" "mediumint" "mediumtext"
2372 "multicurve" "multilinestring" "multipoint" "multipolygon"
2373 "multisurface" "national" "numeric" "point" "polygon" "precision"
2374 "real" "smallint" "surface" "text" "time" "timestamp" "tinyblob"
2375 "tinyint" "tinytext" "unsigned" "varchar" "year" "year2" "year4"
2379 "MySQL SQL keywords used by font-lock.
2381 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2382 regular expressions are created during compilation by calling the
2383 function `regexp-opt'. Therefore, take a look at the source before
2384 you define your own `sql-mode-mysql-font-lock-keywords'.")
2386 (defvar sql-mode-sqlite-font-lock-keywords
2390 '("^[.].*$" . font-lock-doc-face
)
2393 (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
2394 "abort" "action" "add" "after" "all" "alter" "analyze" "and" "as"
2395 "asc" "attach" "autoincrement" "before" "begin" "between" "by"
2396 "cascade" "case" "cast" "check" "collate" "column" "commit" "conflict"
2397 "constraint" "create" "cross" "database" "default" "deferrable"
2398 "deferred" "delete" "desc" "detach" "distinct" "drop" "each" "else"
2399 "end" "escape" "except" "exclusive" "exists" "explain" "fail" "for"
2400 "foreign" "from" "full" "glob" "group" "having" "if" "ignore"
2401 "immediate" "in" "index" "indexed" "initially" "inner" "insert"
2402 "instead" "intersect" "into" "is" "isnull" "join" "key" "left" "like"
2403 "limit" "match" "natural" "no" "not" "notnull" "null" "of" "offset"
2404 "on" "or" "order" "outer" "plan" "pragma" "primary" "query" "raise"
2405 "references" "regexp" "reindex" "release" "rename" "replace"
2406 "restrict" "right" "rollback" "row" "savepoint" "select" "set" "table"
2407 "temp" "temporary" "then" "to" "transaction" "trigger" "union"
2408 "unique" "update" "using" "vacuum" "values" "view" "virtual" "when"
2411 ;; SQLite Data types
2412 (sql-font-lock-keywords-builder 'font-lock-type-face nil
2413 "int" "integer" "tinyint" "smallint" "mediumint" "bigint" "unsigned"
2414 "big" "int2" "int8" "character" "varchar" "varying" "nchar" "native"
2415 "nvarchar" "text" "clob" "blob" "real" "double" "precision" "float"
2416 "numeric" "number" "decimal" "boolean" "date" "datetime"
2419 (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
2421 "abs" "changes" "coalesce" "glob" "ifnull" "hex" "last_insert_rowid"
2422 "length" "like" "load_extension" "lower" "ltrim" "max" "min" "nullif"
2423 "quote" "random" "randomblob" "replace" "round" "rtrim" "soundex"
2424 "sqlite_compileoption_get" "sqlite_compileoption_used"
2425 "sqlite_source_id" "sqlite_version" "substr" "total_changes" "trim"
2426 "typeof" "upper" "zeroblob"
2427 ;; Date/time functions
2428 "time" "julianday" "strftime"
2429 "current_date" "current_time" "current_timestamp"
2430 ;; Aggregate functions
2431 "avg" "count" "group_concat" "max" "min" "sum" "total"
2434 "SQLite SQL keywords used by font-lock.
2436 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2437 regular expressions are created during compilation by calling the
2438 function `regexp-opt'. Therefore, take a look at the source before
2439 you define your own `sql-mode-sqlite-font-lock-keywords'.")
2441 (defvar sql-mode-db2-font-lock-keywords nil
2442 "DB2 SQL keywords used by font-lock.
2444 This variable is used by `sql-mode' and `sql-interactive-mode'. The
2445 regular expressions are created during compilation by calling the
2446 function `regexp-opt'. Therefore, take a look at the source before
2447 you define your own `sql-mode-db2-font-lock-keywords'.")
2449 (defvar sql-mode-font-lock-keywords nil
2450 "SQL keywords used by font-lock.
2452 Setting this variable directly no longer has any affect. Use
2453 `sql-product' and `sql-add-product-keywords' to control the
2454 highlighting rules in SQL mode.")
2458 ;;; SQL Product support functions
2460 (defun sql-read-product (prompt &optional initial
)
2461 "Read a valid SQL product."
2462 (let ((init (or (and initial
(symbol-name initial
)) "ansi")))
2463 (intern (completing-read
2465 (mapcar (lambda (info) (symbol-name (car info
)))
2468 init
'sql-product-history init
))))
2470 (defun sql-add-product (product display
&rest plist
)
2471 "Add support for a database product in `sql-mode'.
2473 Add PRODUCT to `sql-product-alist' which enables `sql-mode' to
2474 properly support syntax highlighting and interactive interaction.
2475 DISPLAY is the name of the SQL product that will appear in the
2476 menu bar and in messages. PLIST initializes the product
2479 ;; Don't do anything if the product is already supported
2480 (if (assoc product sql-product-alist
)
2481 (user-error "Product `%s' is already defined" product
)
2483 ;; Add product to the alist
2484 (add-to-list 'sql-product-alist
`(,product
:name
,display .
,plist
))
2485 ;; Add a menu item to the SQL->Product menu
2486 (easy-menu-add-item sql-mode-menu
'("Product")
2487 ;; Each product is represented by a radio
2488 ;; button with it's display name.
2490 (sql-set-product ',product
)
2492 :selected
(eq sql-product
',product
)]
2493 ;; Maintain the product list in
2494 ;; (case-insensitive) alphabetic order of the
2495 ;; display names. Loop thru each keymap item
2496 ;; looking for an item whose display name is
2497 ;; after this product's name.
2499 (down-display (downcase display
)))
2500 (map-keymap (lambda (k b
)
2501 (when (and (not next-item
)
2502 (string-lessp down-display
2503 (downcase (cadr b
))))
2504 (setq next-item k
)))
2505 (easy-menu-get-map sql-mode-menu
'("Product")))
2509 (defun sql-del-product (product)
2510 "Remove support for PRODUCT in `sql-mode'."
2512 ;; Remove the menu item based on the display name
2513 (easy-menu-remove-item sql-mode-menu
'("Product") (sql-get-product-feature product
:name
))
2514 ;; Remove the product alist item
2515 (setq sql-product-alist
(assq-delete-all product sql-product-alist
))
2518 (defun sql-set-product-feature (product feature newvalue
)
2519 "Set FEATURE of database PRODUCT to NEWVALUE.
2521 The PRODUCT must be a symbol which identifies the database
2522 product. The product must have already exist on the product
2523 list. See `sql-add-product' to add new products. The FEATURE
2524 argument must be a plist keyword accepted by
2525 `sql-product-alist'."
2527 (let* ((p (assoc product sql-product-alist
))
2528 (v (plist-get (cdr p
) feature
)))
2531 (member feature sql-indirect-features
)
2534 (setcdr p
(plist-put (cdr p
) feature newvalue
)))
2535 (error "`%s' is not a known product; use `sql-add-product' to add it first." product
))))
2537 (defun sql-get-product-feature (product feature
&optional fallback not-indirect
)
2538 "Lookup FEATURE associated with a SQL PRODUCT.
2540 If the FEATURE is nil for PRODUCT, and FALLBACK is specified,
2541 then the FEATURE associated with the FALLBACK product is
2544 If the FEATURE is in the list `sql-indirect-features', and the
2545 NOT-INDIRECT parameter is not set, then the value of the symbol
2546 stored in the connect alist is returned.
2548 See `sql-product-alist' for a list of products and supported features."
2549 (let* ((p (assoc product sql-product-alist
))
2550 (v (plist-get (cdr p
) feature
)))
2553 ;; If no value and fallback, lookup feature for fallback
2556 (not (eq product fallback
)))
2557 (sql-get-product-feature fallback feature
)
2560 (member feature sql-indirect-features
)
2565 (error "`%s' is not a known product; use `sql-add-product' to add it first." product
)
2568 (defun sql-product-font-lock (keywords-only imenu
)
2569 "Configure font-lock and imenu with product-specific settings.
2571 The KEYWORDS-ONLY flag is passed to font-lock to specify whether
2572 only keywords should be highlighted and syntactic highlighting
2573 skipped. The IMENU flag indicates whether `imenu-mode' should
2574 also be configured."
2577 ;; Get the product-specific syntax-alist.
2578 ((syntax-alist (sql-product-font-lock-syntax-alist)))
2580 ;; Get the product-specific keywords.
2581 (set (make-local-variable 'sql-mode-font-lock-keywords
)
2583 (unless (eq sql-product
'ansi
)
2584 (sql-get-product-feature sql-product
:font-lock
))
2585 ;; Always highlight ANSI keywords
2586 (sql-get-product-feature 'ansi
:font-lock
)
2587 ;; Fontify object names in CREATE, DROP and ALTER DDL
2589 (list sql-mode-font-lock-object-name
)))
2591 ;; Setup font-lock. Force re-parsing of `font-lock-defaults'.
2592 (kill-local-variable 'font-lock-set-defaults
)
2593 (set (make-local-variable 'font-lock-defaults
)
2594 (list 'sql-mode-font-lock-keywords
2595 keywords-only t syntax-alist
))
2597 ;; Force font lock to reinitialize if it is already on
2598 ;; Otherwise, we can wait until it can be started.
2599 (when (and (fboundp 'font-lock-mode
)
2600 (boundp 'font-lock-mode
)
2602 (font-lock-mode-internal nil
)
2603 (font-lock-mode-internal t
))
2605 (add-hook 'font-lock-mode-hook
2607 ;; Provide defaults for new font-lock faces.
2608 (defvar font-lock-builtin-face
2609 (if (boundp 'font-lock-preprocessor-face
)
2610 font-lock-preprocessor-face
2611 font-lock-keyword-face
))
2612 (defvar font-lock-doc-face font-lock-string-face
))
2615 ;; Setup imenu; it needs the same syntax-alist.
2617 (setq imenu-syntax-alist syntax-alist
))))
2620 (defun sql-add-product-keywords (product keywords
&optional append
)
2621 "Add highlighting KEYWORDS for SQL PRODUCT.
2623 PRODUCT should be a symbol, the name of a SQL product, such as
2624 `oracle'. KEYWORDS should be a list; see the variable
2625 `font-lock-keywords'. By default they are added at the beginning
2626 of the current highlighting list. If optional argument APPEND is
2627 `set', they are used to replace the current highlighting list.
2628 If APPEND is any other non-nil value, they are added at the end
2629 of the current highlighting list.
2633 (sql-add-product-keywords \\='ms
2634 \\='((\"\\\\b\\\\w+_t\\\\b\" . font-lock-type-face)))
2636 adds a fontification pattern to fontify identifiers ending in
2637 `_t' as data types."
2639 (let* ((sql-indirect-features nil
)
2640 (font-lock-var (sql-get-product-feature product
:font-lock
))
2643 (setq old-val
(symbol-value font-lock-var
))
2645 (if (eq append
'set
)
2648 (append old-val keywords
)
2649 (append keywords old-val
))))))
2651 (defun sql-for-each-login (login-params body
)
2652 "Iterate through login parameters and return a list of results."
2656 (let ((token (or (car-safe param
) param
))
2657 (plist (cdr-safe param
)))
2658 (funcall body token plist
)))
2663 ;;; Functions to switch highlighting
2665 (defun sql-product-syntax-table ()
2666 (let ((table (copy-syntax-table sql-mode-syntax-table
)))
2667 (mapc (lambda (entry)
2668 (modify-syntax-entry (car entry
) (cdr entry
) table
))
2669 (sql-get-product-feature sql-product
:syntax-alist
))
2672 (defun sql-product-font-lock-syntax-alist ()
2674 ;; Change all symbol character to word characters
2676 (lambda (entry) (if (string= (substring (cdr entry
) 0 1) "_")
2678 (concat "w" (substring (cdr entry
) 1)))
2680 (sql-get-product-feature sql-product
:syntax-alist
))
2683 (defun sql-highlight-product ()
2684 "Turn on the font highlighting for the SQL product selected."
2685 (when (derived-mode-p 'sql-mode
)
2686 ;; Enhance the syntax table for the product
2687 (set-syntax-table (sql-product-syntax-table))
2690 (sql-product-font-lock nil t
)
2692 ;; Set the mode name to include the product.
2693 (setq mode-name
(concat "SQL[" (or (sql-get-product-feature sql-product
:name
)
2694 (symbol-name sql-product
)) "]"))))
2696 (defun sql-set-product (product)
2697 "Set `sql-product' to PRODUCT and enable appropriate highlighting."
2699 (list (sql-read-product "SQL product: ")))
2700 (if (stringp product
) (setq product
(intern product
)))
2701 (when (not (assoc product sql-product-alist
))
2702 (user-error "SQL product %s is not supported; treated as ANSI" product
)
2703 (setq product
'ansi
))
2705 ;; Save product setting and fontify.
2706 (setq sql-product product
)
2707 (sql-highlight-product))
2710 ;;; Compatibility functions
2712 (if (not (fboundp 'comint-line-beginning-position
))
2713 ;; comint-line-beginning-position is defined in Emacs 21
2714 (defun comint-line-beginning-position ()
2715 "Return the buffer position of the beginning of the line, after any prompt.
2716 The prompt is assumed to be any text at the beginning of the line
2717 matching the regular expression `comint-prompt-regexp', a buffer
2719 (save-excursion (comint-bol nil
) (point))))
2723 ;; Needs a lot more love than I can provide. --Stef
2727 ;; (defconst sql-smie-grammar
2728 ;; (smie-prec2->grammar
2730 ;; ;; Partly based on http://www.h2database.com/html/grammar.html
2731 ;; '((cmd ("SELECT" select-exp "FROM" select-table-exp)
2733 ;; (select-exp ("*") (exp) (exp "AS" column-alias))
2735 ;; (select-table-exp (table-exp "WHERE" exp) (table-exp))
2737 ;; (exp ("CASE" exp "WHEN" exp "THEN" exp "ELSE" exp "END")
2738 ;; ("CASE" exp "WHEN" exp "THEN" exp "END"))
2739 ;; ;; Random ad-hoc additions.
2740 ;; (foo (foo "," foo))
2742 ;; '((assoc ",")))))
2744 ;; (defun sql-smie-rules (kind token)
2745 ;; (pcase (cons kind token)
2746 ;; (`(:list-intro . ,_) t)
2747 ;; (`(:before . "(") (smie-rule-parent))))
2749 ;;; Motion Functions
2751 (defun sql-statement-regexp (prod)
2752 (let* ((ansi-stmt (sql-get-product-feature 'ansi
:statement
))
2753 (prod-stmt (sql-get-product-feature prod
:statement
)))
2757 (concat "\\(" ansi-stmt
"\\|" prod-stmt
"\\)"))
2760 (defun sql-beginning-of-statement (arg)
2761 "Move to the beginning of the current SQL statement."
2764 (let ((here (point))
2765 (regexp (sql-statement-regexp sql-product
))
2768 ;; Go to the end of the statement before the start we desire
2769 (setq last
(or (sql-end-of-statement (- arg
))
2771 ;; And find the end after that
2772 (setq next
(or (sql-end-of-statement 1)
2775 ;; Our start must be between them
2777 ;; Find an beginning-of-stmt that's not in a comment
2778 (while (and (re-search-forward regexp next t
1)
2779 (nth 7 (syntax-ppss)))
2780 (goto-char (match-end 0)))
2786 ;; If we didn't move, try again
2787 (when (= here
(point))
2788 (sql-beginning-of-statement (* 2 (cl-signum arg
))))))
2790 (defun sql-end-of-statement (arg)
2791 "Move to the end of the current SQL statement."
2793 (let ((term (sql-get-product-feature sql-product
:terminator
))
2794 (re-search (if (> 0 arg
) 're-search-backward
're-search-forward
))
2798 (setq term
(car term
)))
2799 ;; Iterate until we've moved the desired number of stmt ends
2800 (while (not (= (cl-signum arg
) 0))
2801 ;; if we're looking at the terminator, jump by 2
2802 (if (or (and (> 0 arg
) (looking-back term nil
))
2803 (and (< 0 arg
) (looking-at term
)))
2806 ;; If we found another end-of-stmt
2807 (if (not (apply re-search term nil t n nil
))
2809 ;; count it if we're not in a comment
2810 (unless (nth 7 (syntax-ppss))
2811 (setq arg
(- arg
(cl-signum arg
))))))
2812 (goto-char (if (match-data)
2818 (defun sql-magic-go (arg)
2819 "Insert \"o\" and call `comint-send-input'.
2820 `sql-electric-stuff' must be the symbol `go'."
2822 (self-insert-command (prefix-numeric-value arg
))
2823 (if (and (equal sql-electric-stuff
'go
)
2826 (looking-at "go\\b")))
2827 (comint-send-input)))
2828 (put 'sql-magic-go
'delete-selection t
)
2830 (defun sql-magic-semicolon (arg)
2831 "Insert semicolon and call `comint-send-input'.
2832 `sql-electric-stuff' must be the symbol `semicolon'."
2834 (self-insert-command (prefix-numeric-value arg
))
2835 (if (equal sql-electric-stuff
'semicolon
)
2836 (comint-send-input)))
2837 (put 'sql-magic-semicolon
'delete-selection t
)
2839 (defun sql-accumulate-and-indent ()
2840 "Continue SQL statement on the next line."
2842 (if (fboundp 'comint-accumulate
)
2845 (indent-according-to-mode))
2847 (defun sql-help-list-products (indent freep
)
2848 "Generate listing of products available for use under SQLi.
2850 List products with :free-software attribute set to FREEP. Indent
2851 each line with INDENT."
2853 (let (sqli-func doc
)
2855 (dolist (p sql-product-alist
)
2856 (setq sqli-func
(intern (concat "sql-" (symbol-name (car p
)))))
2858 (if (and (fboundp sqli-func
)
2859 (eq (sql-get-product-feature (car p
) :free-software
) freep
))
2863 (or (sql-get-product-feature (car p
) :name
)
2864 (symbol-name (car p
)))
2867 (symbol-name sqli-func
)
2872 "Show short help for the SQL modes."
2874 (describe-function 'sql-help
))
2875 (put 'sql-help
'function-documentation
'(sql--make-help-docstring))
2877 (defvar sql--help-docstring
2878 "Show short help for the SQL modes.
2879 Use an entry function to open an interactive SQL buffer. This buffer is
2880 usually named `*SQL*'. The name of the major mode is SQLi.
2882 Use the following commands to start a specific SQL interpreter:
2886 Other non-free SQL implementations are also supported:
2890 But we urge you to choose a free implementation instead of these.
2892 You can also use \\[sql-product-interactive] to invoke the
2893 interpreter for the current `sql-product'.
2895 Once you have the SQLi buffer, you can enter SQL statements in the
2896 buffer. The output generated is appended to the buffer and a new prompt
2897 is generated. See the In/Out menu in the SQLi buffer for some functions
2898 that help you navigate through the buffer, the input history, etc.
2900 If you have a really complex SQL statement or if you are writing a
2901 procedure, you can do this in a separate buffer. Put the new buffer in
2902 `sql-mode' by calling \\[sql-mode]. The name of this buffer can be
2903 anything. The name of the major mode is SQL.
2905 In this SQL buffer (SQL mode), you can send the region or the entire
2906 buffer to the interactive SQL buffer (SQLi mode). The results are
2907 appended to the SQLi buffer without disturbing your SQL buffer.")
2909 (defun sql--make-help-docstring ()
2910 "Return a docstring for `sql-help' listing loaded SQL products."
2911 (let ((doc sql--help-docstring
))
2912 ;; Insert FREE software list
2913 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]FREE\\s-*$" doc
0)
2914 (setq doc
(replace-match (sql-help-list-products (match-string 1 doc
) t
)
2916 ;; Insert non-FREE software list
2917 (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]NONFREE\\s-*$" doc
0)
2918 (setq doc
(replace-match (sql-help-list-products (match-string 1 doc
) nil
)
2922 (defun sql-default-value (var)
2923 "Fetch the value of a variable.
2925 If the current buffer is in `sql-interactive-mode', then fetch
2926 the global value, otherwise use the buffer local value."
2927 (if (derived-mode-p 'sql-interactive-mode
)
2929 (buffer-local-value var
(current-buffer))))
2931 (defun sql-get-login-ext (symbol prompt history-var plist
)
2932 "Prompt user with extended login parameters.
2934 The global value of SYMBOL is the last value and the global value
2935 of the SYMBOL is set based on the user's input.
2937 If PLIST is nil, then the user is simply prompted for a string
2940 The property `:default' specifies the default value. If the
2941 `:number' property is non-nil then ask for a number.
2943 The `:file' property prompts for a file name that must match the
2944 regexp pattern specified in its value.
2946 The `:completion' property prompts for a string specified by its
2947 value. (The property value is used as the PREDICATE argument to
2948 `completing-read'.)"
2951 (let* ((default (plist-get plist
:default
))
2952 (last-value (sql-default-value symbol
))
2955 (if (string-match "\\(\\):[ \t]*\\'" prompt
)
2956 (replace-match (format " (default \"%s\")" default
) t t prompt
1)
2957 (replace-regexp-in-string "[ \t]*\\'"
2958 (format " (default \"%s\") " default
)
2961 (use-dialog-box nil
))
2963 ((plist-member plist
:file
)
2965 (read-file-name prompt
2966 (file-name-directory last-value
)
2968 (plist-get plist
:must-match
)
2969 (file-name-nondirectory last-value
)
2970 (when (plist-get plist
:file
)
2972 (if (not (file-regular-p f
))
2975 (concat "\\<" ,(plist-get plist
:file
) "\\>")
2976 (file-name-nondirectory f
))))))))
2977 (if (string= file-name
"")
2979 (expand-file-name file-name
))))
2981 ((plist-member plist
:completion
)
2982 (completing-read prompt-def
2983 (plist-get plist
:completion
)
2985 (plist-get plist
:must-match
)
2990 ((plist-get plist
:number
)
2991 (read-number prompt
(or default last-value
0)))
2994 (read-string prompt-def last-value history-var default
))))))
2996 (defun sql-get-login (&rest what
)
2997 "Get username, password and database from the user.
2999 The variables `sql-user', `sql-password', `sql-server', and
3000 `sql-database' can be customized. They are used as the default values.
3001 Usernames, servers and databases are stored in `sql-user-history',
3002 `sql-server-history' and `database-history'. Passwords are not stored
3005 Parameter WHAT is a list of tokens passed as arguments in the
3006 function call. The function asks for the username if WHAT
3007 contains the symbol `user', for the password if it contains the
3008 symbol `password', for the server if it contains the symbol
3009 `server', and for the database if it contains the symbol
3010 `database'. The members of WHAT are processed in the order in
3011 which they are provided.
3013 Each token may also be a list with the token in the car and a
3014 plist of options as the cdr. The following properties are
3017 :file <filename-regexp>
3018 :completion <list-of-strings-or-function>
3019 :default <default-value>
3022 In order to ask the user for username, password and database, call the
3023 function like this: (sql-get-login \\='user \\='password \\='database)."
3025 (let ((plist (cdr-safe w
)))
3026 (pcase (or (car-safe w
) w
)
3028 (sql-get-login-ext 'sql-user
"User: " 'sql-user-history plist
))
3031 (setq-default sql-password
3032 (read-passwd "Password: " nil
(sql-default-value 'sql-password
))))
3035 (sql-get-login-ext 'sql-server
"Server: " 'sql-server-history plist
))
3038 (sql-get-login-ext 'sql-database
"Database: "
3039 'sql-database-history plist
))
3042 (sql-get-login-ext 'sql-port
"Port: "
3043 nil
(append '(:number t
) plist
)))))))
3045 (defun sql-find-sqli-buffer (&optional product connection
)
3046 "Return the name of the current default SQLi buffer or nil.
3047 In order to qualify, the SQLi buffer must be alive, be in
3048 `sql-interactive-mode' and have a process."
3049 (let ((buf sql-buffer
)
3050 (prod (or product sql-product
)))
3052 ;; Current sql-buffer, if there is one.
3053 (and (sql-buffer-live-p buf prod connection
)
3055 ;; Global sql-buffer
3056 (and (setq buf
(default-value 'sql-buffer
))
3057 (sql-buffer-live-p buf prod connection
)
3059 ;; Look thru each buffer
3060 (car (apply #'append
3062 (and (sql-buffer-live-p b prod connection
)
3063 (list (buffer-name b
))))
3066 (defun sql-set-sqli-buffer-generally ()
3067 "Set SQLi buffer for all SQL buffers that have none.
3068 This function checks all SQL buffers for their SQLi buffer. If their
3069 SQLi buffer is nonexistent or has no process, it is set to the current
3070 default SQLi buffer. The current default SQLi buffer is determined
3071 using `sql-find-sqli-buffer'. If `sql-buffer' is set,
3072 `sql-set-sqli-hook' is run."
3075 (let ((buflist (buffer-list))
3076 (default-buffer (sql-find-sqli-buffer)))
3077 (setq-default sql-buffer default-buffer
)
3078 (while (not (null buflist
))
3079 (let ((candidate (car buflist
)))
3080 (set-buffer candidate
)
3081 (if (and (derived-mode-p 'sql-mode
)
3082 (not (sql-buffer-live-p sql-buffer
)))
3084 (setq sql-buffer default-buffer
)
3085 (when default-buffer
3086 (run-hooks 'sql-set-sqli-hook
)))))
3087 (setq buflist
(cdr buflist
))))))
3089 (defun sql-set-sqli-buffer ()
3090 "Set the SQLi buffer SQL strings are sent to.
3092 Call this function in a SQL buffer in order to set the SQLi buffer SQL
3093 strings are sent to. Calling this function sets `sql-buffer' and runs
3094 `sql-set-sqli-hook'.
3096 If you call it from a SQL buffer, this sets the local copy of
3099 If you call it from anywhere else, it sets the global copy of
3102 (let ((default-buffer (sql-find-sqli-buffer)))
3103 (if (null default-buffer
)
3104 (sql-product-interactive)
3105 (let ((new-buffer (read-buffer "New SQLi buffer: " default-buffer t
)))
3106 (if (null (sql-buffer-live-p new-buffer
))
3107 (user-error "Buffer %s is not a working SQLi buffer" new-buffer
)
3109 (setq sql-buffer new-buffer
)
3110 (run-hooks 'sql-set-sqli-hook
)))))))
3112 (defun sql-show-sqli-buffer ()
3113 "Display the current SQLi buffer.
3115 This is the buffer SQL strings are sent to.
3116 It is stored in the variable `sql-buffer'.
3118 See also `sql-help' on how to create such a buffer."
3120 (unless (and sql-buffer
(buffer-live-p (get-buffer sql-buffer
))
3121 (get-buffer-process sql-buffer
))
3122 (sql-set-sqli-buffer))
3123 (display-buffer sql-buffer
))
3125 (defun sql-make-alternate-buffer-name ()
3126 "Return a string that can be used to rename a SQLi buffer.
3127 This is used to set `sql-alternate-buffer-name' within
3128 `sql-interactive-mode'.
3130 If the session was started with `sql-connect' then the alternate
3131 name would be the name of the connection.
3133 Otherwise, it uses the parameters identified by the :sqlilogin
3136 If all else fails, the alternate name would be the user and
3137 server/database name."
3141 ;; Build a name using the :sqli-login setting
3147 (sql-get-product-feature sql-product
:sqli-login
)
3148 (lambda (token plist
)
3151 (unless (string= "" sql-user
)
3152 (list "/" sql-user
)))
3154 (unless (or (not (numberp sql-port
))
3156 (list ":" (number-to-string sql-port
))))
3158 (unless (string= "" sql-server
)
3160 (if (plist-member plist
:file
)
3161 (file-name-nondirectory sql-server
)
3164 (unless (string= "" sql-database
)
3166 (if (plist-member plist
:file
)
3167 (file-name-nondirectory sql-database
)
3173 ;; If there's a connection, use it and the name thus far
3175 (format "<%s>%s" sql-connection
(or name
""))
3177 ;; If there is no name, try to create something meaningful
3178 (if (string= "" (or name
""))
3180 (if (string= "" sql-user
)
3181 (if (string= "" (user-login-name))
3183 (concat (user-login-name) "/"))
3184 (concat sql-user
"/"))
3185 (if (string= "" sql-database
)
3186 (if (string= "" sql-server
)
3191 ;; Use the name we've got
3194 (defun sql-rename-buffer (&optional new-name
)
3195 "Rename a SQL interactive buffer.
3197 Prompts for the new name if command is preceded by
3198 \\[universal-argument]. If no buffer name is provided, then the
3199 `sql-alternate-buffer-name' is used.
3201 The actual buffer name set will be \"*SQL: NEW-NAME*\". If
3202 NEW-NAME is empty, then the buffer name will be \"*SQL*\"."
3205 (if (not (derived-mode-p 'sql-interactive-mode
))
3206 (user-error "Current buffer is not a SQL interactive buffer")
3208 (setq sql-alternate-buffer-name
3210 ((stringp new-name
) new-name
)
3212 (read-string "Buffer name (\"*SQL: XXX*\"; enter `XXX'): "
3213 sql-alternate-buffer-name
))
3214 (t sql-alternate-buffer-name
)))
3216 (setq sql-alternate-buffer-name
(substring-no-properties sql-alternate-buffer-name
))
3217 (rename-buffer (if (string= "" sql-alternate-buffer-name
)
3219 (format "*SQL: %s*" sql-alternate-buffer-name
))
3222 (defun sql-copy-column ()
3223 "Copy current column to the end of buffer.
3224 Inserts SELECT or commas if appropriate."
3228 (setq column
(buffer-substring-no-properties
3229 (progn (forward-char 1) (backward-sexp 1) (point))
3230 (progn (forward-sexp 1) (point))))
3231 (goto-char (point-max))
3232 (let ((bol (comint-line-beginning-position)))
3234 ;; if empty command line, insert SELECT
3237 ;; else if appending to INTO .* (, SELECT or ORDER BY, insert a comma
3239 (re-search-backward "\\b\\(\\(into\\s-+\\S-+\\s-+(\\)\\|select\\|order by\\) .+"
3242 ;; else insert a space
3244 (if (eq (preceding-char) ?\s
)
3247 ;; in any case, insert the column
3249 (message "%s" column
))))
3251 ;; On Windows, SQL*Plus for Oracle turns on full buffering for stdout
3252 ;; if it is not attached to a character device; therefore placeholder
3253 ;; replacement by SQL*Plus is fully buffered. The workaround lets
3254 ;; Emacs query for the placeholders.
3256 (defvar sql-placeholder-history nil
3257 "History of placeholder values used.")
3259 (defun sql-placeholders-filter (string)
3260 "Replace placeholders in STRING.
3261 Placeholders are words starting with an ampersand like &this."
3263 (when sql-oracle-scan-on
3264 (while (string-match "&?&\\(\\(?:\\sw\\|\\s_\\)+\\)[.]?" string
)
3265 (setq string
(replace-match
3266 (read-from-minibuffer
3267 (format "Enter value for %s: " (match-string 1 string
))
3268 nil nil nil
'sql-placeholder-history
)
3272 ;; Using DB2 interactively, newlines must be escaped with " \".
3273 ;; The space before the backslash is relevant.
3275 (defun sql-escape-newlines-filter (string)
3276 "Escape newlines in STRING.
3277 Every newline in STRING will be preceded with a space and a backslash."
3278 (if (not sql-db2-escape-newlines
)
3280 (let ((result "") (start 0) mb me
)
3281 (while (string-match "\n" string start
)
3282 (setq mb
(match-beginning 0)
3284 result
(concat result
3285 (substring string start mb
)
3287 (string-equal " \\" (substring string
(- mb
2) mb
)))
3290 (concat result
(substring string start
)))))
3294 ;;; Input sender for SQLi buffers
3296 (defvar sql-output-newline-count
0
3297 "Number of newlines in the input string.
3299 Allows the suppression of continuation prompts.")
3301 (defun sql-input-sender (proc string
)
3302 "Send STRING to PROC after applying filters."
3304 (let* ((product (buffer-local-value 'sql-product
(process-buffer proc
)))
3305 (filter (sql-get-product-feature product
:input-filter
)))
3312 (setq string
(funcall filter string
)))
3314 (mapc (lambda (f) (setq string
(funcall f string
))) filter
))
3317 ;; Count how many newlines in the string
3318 (setq sql-output-newline-count
3319 (apply #'+ (mapcar (lambda (ch)
3320 (if (eq ch ?
\n) 1 0)) string
)))
3323 (comint-simple-send proc string
)))
3325 ;;; Strip out continuation prompts
3327 (defvar sql-preoutput-hold nil
)
3329 (defun sql-starts-with-prompt-re ()
3330 "Anchor the prompt expression at the beginning of the output line.
3331 Remove the start of line regexp."
3332 (concat "\\`" comint-prompt-regexp
))
3334 (defun sql-ends-with-prompt-re ()
3335 "Anchor the prompt expression at the end of the output line.
3336 Match a SQL prompt or a password prompt."
3337 (concat "\\(?:\\(?:" sql-prompt-regexp
"\\)\\|"
3338 "\\(?:" comint-password-prompt-regexp
"\\)\\)\\'"))
3340 (defun sql-interactive-remove-continuation-prompt (oline)
3341 "Strip out continuation prompts out of the OLINE.
3343 Added to the `comint-preoutput-filter-functions' hook in a SQL
3344 interactive buffer. If `sql-output-newline-count' is greater than
3345 zero, then an output line matching the continuation prompt is filtered
3346 out. If the count is zero, then a newline is inserted into the output
3347 to force the output from the query to appear on a new line.
3349 The complication to this filter is that the continuation prompts
3350 may arrive in multiple chunks. If they do, then the function
3351 saves any unfiltered output in a buffer and prepends that buffer
3352 to the next chunk to properly match the broken-up prompt.
3354 If the filter gets confused, it should reset and stop filtering
3355 to avoid deleting non-prompt output."
3357 ;; continue gathering lines of text iff
3358 ;; + we know what a prompt looks like, and
3359 ;; + there is held text, or
3360 ;; + there are continuation prompt yet to come, or
3361 ;; + not just a prompt string
3362 (when (and comint-prompt-regexp
3363 (or (> (length (or sql-preoutput-hold
"")) 0)
3364 (> (or sql-output-newline-count
0) 0)
3365 (not (or (string-match sql-prompt-regexp oline
)
3366 (string-match sql-prompt-cont-regexp oline
)))))
3369 (let (prompt-found last-nl
)
3371 ;; Add this text to what's left from the last pass
3372 (setq oline
(concat sql-preoutput-hold oline
)
3373 sql-preoutput-hold
"")
3375 ;; If we are looking for multiple prompts
3376 (when (and (integerp sql-output-newline-count
)
3377 (>= sql-output-newline-count
1))
3378 ;; Loop thru each starting prompt and remove it
3379 (let ((start-re (sql-starts-with-prompt-re)))
3380 (while (and (not (string= oline
""))
3381 (> sql-output-newline-count
0)
3382 (string-match start-re oline
))
3383 (setq oline
(replace-match "" nil nil oline
)
3384 sql-output-newline-count
(1- sql-output-newline-count
)
3387 ;; If we've found all the expected prompts, stop looking
3388 (if (= sql-output-newline-count
0)
3389 (setq sql-output-newline-count nil
3390 oline
(concat "\n" oline
))
3392 ;; Still more possible prompts, leave them for the next pass
3393 (setq sql-preoutput-hold oline
3396 ;; If no prompts were found, stop looking
3397 (unless prompt-found
3398 (setq sql-output-newline-count nil
3399 oline
(concat oline sql-preoutput-hold
)
3400 sql-preoutput-hold
""))
3402 ;; Break up output by physical lines if we haven't hit the final prompt
3403 (let ((end-re (sql-ends-with-prompt-re)))
3404 (unless (and (not (string= oline
""))
3405 (string-match end-re oline
)
3406 (>= (match-end 0) (length oline
)))
3407 ;; Find everything upto the last nl
3409 (while (string-match "\n" oline last-nl
)
3410 (setq last-nl
(match-end 0)))
3411 ;; Hold after the last nl, return upto last nl
3412 (setq sql-preoutput-hold
(concat (substring oline last-nl
)
3414 oline
(substring oline
0 last-nl
)))))))
3417 ;;; Sending the region to the SQLi buffer.
3419 (defun sql-send-string (str)
3420 "Send the string STR to the SQL process."
3421 (interactive "sSQL Text: ")
3423 (let ((comint-input-sender-no-newline nil
)
3424 (s (replace-regexp-in-string "[[:space:]\n\r]+\\'" "" str
)))
3425 (if (sql-buffer-live-p sql-buffer
)
3427 ;; Ignore the hoping around...
3429 ;; Set product context
3430 (with-current-buffer sql-buffer
3431 ;; Send the string (trim the trailing whitespace)
3432 (sql-input-sender (get-buffer-process sql-buffer
) s
)
3434 ;; Send a command terminator if we must
3435 (if sql-send-terminator
3436 (sql-send-magic-terminator sql-buffer s sql-send-terminator
))
3438 (message "Sent string to buffer %s" sql-buffer
)))
3440 ;; Display the sql buffer
3441 (if sql-pop-to-buffer-after-send-region
3442 (pop-to-buffer sql-buffer
)
3443 (display-buffer sql-buffer
)))
3445 ;; We don't have no stinkin' sql
3446 (user-error "No SQL process started"))))
3448 (defun sql-send-region (start end
)
3449 "Send a region to the SQL process."
3451 (sql-send-string (buffer-substring-no-properties start end
)))
3453 (defun sql-send-paragraph ()
3454 "Send the current paragraph to the SQL process."
3456 (let ((start (save-excursion
3457 (backward-paragraph)
3459 (end (save-excursion
3462 (sql-send-region start end
)))
3464 (defun sql-send-buffer ()
3465 "Send the buffer contents to the SQL process."
3467 (sql-send-region (point-min) (point-max)))
3469 (defun sql-send-line-and-next ()
3470 "Send the current line to the SQL process and go to the next line."
3472 (sql-send-region (line-beginning-position 1) (line-beginning-position 2))
3473 (beginning-of-line 2)
3474 (while (forward-comment 1))) ; skip all comments and whitespace
3476 (defun sql-send-magic-terminator (buf str terminator
)
3477 "Send TERMINATOR to buffer BUF if its not present in STR."
3478 (let (comint-input-sender-no-newline pat term
)
3479 ;; If flag is merely on(t), get product-specific terminator
3480 (if (eq terminator t
)
3481 (setq terminator
(sql-get-product-feature sql-product
:terminator
)))
3483 ;; If there is no terminator specified, use default ";"
3485 (setq terminator
";"))
3487 ;; Parse the setting into the pattern and the terminator string
3488 (cond ((stringp terminator
)
3489 (setq pat
(regexp-quote terminator
)
3492 (setq pat
(car terminator
)
3493 term
(cdr terminator
)))
3497 ;; Check to see if the pattern is present in the str already sent
3498 (unless (and pat term
3499 (string-match (concat pat
"\\'") str
))
3500 (comint-simple-send (get-buffer-process buf
) term
)
3501 (setq sql-output-newline-count
3502 (if sql-output-newline-count
3503 (1+ sql-output-newline-count
)
3506 (defun sql-remove-tabs-filter (str)
3507 "Replace tab characters with spaces."
3508 (replace-regexp-in-string "\t" " " str nil t
))
3510 (defun sql-toggle-pop-to-buffer-after-send-region (&optional value
)
3511 "Toggle `sql-pop-to-buffer-after-send-region'.
3513 If given the optional parameter VALUE, sets
3514 `sql-toggle-pop-to-buffer-after-send-region' to VALUE."
3517 (setq sql-pop-to-buffer-after-send-region value
)
3518 (setq sql-pop-to-buffer-after-send-region
3519 (null sql-pop-to-buffer-after-send-region
))))
3523 ;;; Redirect output functions
3525 (defvar sql-debug-redirect nil
3526 "If non-nil, display messages related to the use of redirection.")
3528 (defun sql-str-literal (s)
3529 (concat "'" (replace-regexp-in-string "[']" "''" s
) "'"))
3531 (defun sql-redirect (sqlbuf command
&optional outbuf save-prior
)
3532 "Execute the SQL command and send output to OUTBUF.
3534 SQLBUF must be an active SQL interactive buffer. OUTBUF may be
3535 an existing buffer, or the name of a non-existing buffer. If
3536 omitted the output is sent to a temporary buffer which will be
3537 killed after the command completes. COMMAND should be a string
3538 of commands accepted by the SQLi program. COMMAND may also be a
3539 list of SQLi command strings."
3541 (let* ((visible (and outbuf
3542 (not (string= " " (substring outbuf
0 1))))))
3544 (message "Executing SQL command..."))
3546 (mapc (lambda (c) (sql-redirect-one sqlbuf c outbuf save-prior
))
3548 (sql-redirect-one sqlbuf command outbuf save-prior
))
3550 (message "Executing SQL command...done"))))
3552 (defun sql-redirect-one (sqlbuf command outbuf save-prior
)
3554 (with-current-buffer sqlbuf
3555 (let ((buf (get-buffer-create (or outbuf
" *SQL-Redirect*")))
3556 (proc (get-buffer-process (current-buffer)))
3557 (comint-prompt-regexp (sql-get-product-feature sql-product
3560 (with-current-buffer buf
3561 (setq-local view-no-disable-on-exit t
)
3565 (goto-char (point-max))
3566 (unless (zerop (buffer-size))
3568 (setq start
(point)))
3570 (when sql-debug-redirect
3571 (message ">>SQL> %S" command
))
3574 (let ((inhibit-quit t
)
3575 comint-preoutput-filter-functions
)
3577 (comint-redirect-send-command-to-process command buf proc nil t
)
3578 (while (or quit-flag
(null comint-redirect-completed
))
3579 (accept-process-output nil
1)))
3582 (comint-redirect-cleanup)
3583 ;; Clean up the output results
3584 (with-current-buffer buf
3585 ;; Remove trailing whitespace
3586 (goto-char (point-max))
3587 (when (looking-back "[ \t\f\n\r]*" start
)
3588 (delete-region (match-beginning 0) (match-end 0)))
3589 ;; Remove echo if there was one
3591 (when (looking-at (concat "^" (regexp-quote command
) "[\\n]"))
3592 (delete-region (match-beginning 0) (match-end 0)))
3595 (while (re-search-forward "\r+$" nil t
)
3596 (replace-match "" t t
))
3597 (goto-char start
))))))))
3599 (defun sql-redirect-value (sqlbuf command regexp
&optional regexp-groups
)
3600 "Execute the SQL command and return part of result.
3602 SQLBUF must be an active SQL interactive buffer. COMMAND should
3603 be a string of commands accepted by the SQLi program. From the
3604 output, the REGEXP is repeatedly matched and the list of
3605 REGEXP-GROUPS submatches is returned. This behaves much like
3606 \\[comint-redirect-results-list-from-process] but instead of
3607 returning a single submatch it returns a list of each submatch
3610 (let ((outbuf " *SQL-Redirect-values*")
3612 (sql-redirect sqlbuf command outbuf nil
)
3613 (with-current-buffer outbuf
3614 (while (re-search-forward regexp nil t
)
3617 ;; no groups-return all of them
3618 ((null regexp-groups
)
3619 (let ((i (/ (length (match-data)) 2))
3623 (push (match-string i
) r
))
3625 ;; one group specified
3626 ((numberp regexp-groups
)
3627 (match-string regexp-groups
))
3628 ;; list of numbers; return the specified matches only
3629 ((consp regexp-groups
)
3632 ((numberp c
) (match-string c
))
3633 ((stringp c
) (match-substitute-replacement c
))
3634 (t (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s" c
))))
3636 ;; String is specified; return replacement string
3637 ((stringp regexp-groups
)
3638 (match-substitute-replacement regexp-groups
))
3640 (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s"
3644 (when sql-debug-redirect
3645 (message ">>SQL> = %S" (reverse results
)))
3647 (nreverse results
)))
3649 (defun sql-execute (sqlbuf outbuf command enhanced arg
)
3650 "Execute a command in a SQL interactive buffer and capture the output.
3652 The commands are run in SQLBUF and the output saved in OUTBUF.
3653 COMMAND must be a string, a function or a list of such elements.
3654 Functions are called with SQLBUF, OUTBUF and ARG as parameters;
3655 strings are formatted with ARG and executed.
3657 If the results are empty the OUTBUF is deleted, otherwise the
3658 buffer is popped into a view window."
3663 (sql-redirect sqlbuf
(if arg
(format c arg
) c
) outbuf
) t
)
3665 (apply c sqlbuf outbuf enhanced arg nil
))
3666 (t (error "Unknown sql-execute item %s" c
))))
3667 (if (consp command
) command
(cons command nil
)))
3669 (setq outbuf
(get-buffer outbuf
))
3670 (if (zerop (buffer-size outbuf
))
3671 (kill-buffer outbuf
)
3672 (let ((one-win (eq (selected-window)
3674 (with-current-buffer outbuf
3675 (set-buffer-modified-p nil
)
3676 (setq-local revert-buffer-function
3677 (lambda (_ignore-auto _noconfirm
)
3678 (sql-execute sqlbuf
(buffer-name outbuf
)
3679 command enhanced arg
)))
3681 (pop-to-buffer outbuf
)
3683 (shrink-window-if-larger-than-buffer)))))
3685 (defun sql-execute-feature (sqlbuf outbuf feature enhanced arg
)
3686 "List objects or details in a separate display buffer."
3688 (product (buffer-local-value 'sql-product
(get-buffer sqlbuf
))))
3689 (setq command
(sql-get-product-feature product feature
))
3691 (error "%s does not support %s" product feature
))
3692 (when (consp command
)
3693 (setq command
(if enhanced
3696 (sql-execute sqlbuf outbuf command enhanced arg
)))
3698 (defvar sql-completion-object nil
3699 "A list of database objects used for completion.
3701 The list is maintained in SQL interactive buffers.")
3703 (defvar sql-completion-column nil
3704 "A list of column names used for completion.
3706 The list is maintained in SQL interactive buffers.")
3708 (defun sql-build-completions-1 (schema completion-list feature
)
3709 "Generate a list of objects in the database for use as completions."
3710 (let ((f (sql-get-product-feature sql-product feature
)))
3712 (set completion-list
3714 (dolist (e (append (symbol-value completion-list
)
3715 (apply f
(current-buffer) (cons schema nil
)))
3717 (unless (member e cl
) (setq cl
(cons e cl
))))
3718 (sort cl
#'string
<))))))
3720 (defun sql-build-completions (schema)
3721 "Generate a list of names in the database for use as completions."
3722 (sql-build-completions-1 schema
'sql-completion-object
:completion-object
)
3723 (sql-build-completions-1 schema
'sql-completion-column
:completion-column
))
3725 (defvar sql-completion-sqlbuf nil
)
3727 (defun sql--completion-table (string pred action
)
3728 (when sql-completion-sqlbuf
3729 (with-current-buffer sql-completion-sqlbuf
3730 (let ((schema (and (string-match "\\`\\(\\sw\\(:?\\sw\\|\\s_\\)*\\)[.]" string
)
3731 (downcase (match-string 1 string
)))))
3733 ;; If we haven't loaded any object name yet, load local schema
3734 (unless sql-completion-object
3735 (sql-build-completions nil
))
3737 ;; If they want another schema, load it if we haven't yet
3739 (let ((schema-dot (concat schema
"."))
3740 (schema-len (1+ (length schema
)))
3741 (names sql-completion-object
)
3744 (while (and (not has-schema
) names
)
3745 (setq has-schema
(and
3746 (>= (length (car names
)) schema-len
)
3748 (downcase (substring (car names
)
3752 (sql-build-completions schema
)))))
3754 ;; Try to find the completion
3755 (complete-with-action action sql-completion-object string pred
))))
3757 (defun sql-read-table-name (prompt)
3758 "Read the name of a database table."
3760 (and (buffer-local-value 'sql-contains-names
(current-buffer))
3761 (thing-at-point-looking-at
3762 (concat "\\_<\\sw\\(:?\\sw\\|\\s_\\)*"
3763 "\\(?:[.]+\\sw\\(?:\\sw\\|\\s_\\)*\\)*\\_>"))
3764 (buffer-substring-no-properties (match-beginning 0)
3766 (sql-completion-sqlbuf (sql-find-sqli-buffer))
3767 (product (when sql-completion-sqlbuf
3768 (with-current-buffer sql-completion-sqlbuf sql-product
)))
3769 (completion-ignore-case t
))
3772 (if (sql-get-product-feature product
:completion-object
)
3773 (completing-read prompt
#'sql--completion-table
3775 (read-from-minibuffer prompt tname
))
3776 (user-error "There is no active SQLi buffer"))))
3778 (defun sql-list-all (&optional enhanced
)
3779 "List all database objects.
3780 With optional prefix argument ENHANCED, displays additional
3781 details or extends the listing to include other schemas objects."
3783 (let ((sqlbuf (sql-find-sqli-buffer)))
3785 (user-error "No SQL interactive buffer found"))
3786 (sql-execute-feature sqlbuf
"*List All*" :list-all enhanced nil
)
3787 (with-current-buffer sqlbuf
3788 ;; Contains the name of database objects
3789 (set (make-local-variable 'sql-contains-names
) t
)
3790 (set (make-local-variable 'sql-buffer
) sqlbuf
))))
3792 (defun sql-list-table (name &optional enhanced
)
3793 "List the details of a database table named NAME.
3794 Displays the columns in the relation. With optional prefix argument
3795 ENHANCED, displays additional details about each column."
3797 (list (sql-read-table-name "Table name: ")
3798 current-prefix-arg
))
3799 (let ((sqlbuf (sql-find-sqli-buffer)))
3801 (user-error "No SQL interactive buffer found"))
3803 (user-error "No table name specified"))
3804 (sql-execute-feature sqlbuf
(format "*List %s*" name
)
3805 :list-table enhanced name
)))
3808 ;;; SQL mode -- uses SQL interactive mode
3811 (define-derived-mode sql-mode prog-mode
"SQL"
3812 "Major mode to edit SQL.
3814 You can send SQL statements to the SQLi buffer using
3815 \\[sql-send-region]. Such a buffer must exist before you can do this.
3816 See `sql-help' on how to create SQLi buffers.
3819 Customization: Entry to this mode runs the `sql-mode-hook'.
3821 When you put a buffer in SQL mode, the buffer stores the last SQLi
3822 buffer created as its destination in the variable `sql-buffer'. This
3823 will be the buffer \\[sql-send-region] sends the region to. If this
3824 SQLi buffer is killed, \\[sql-send-region] is no longer able to
3825 determine where the strings should be sent to. You can set the
3826 value of `sql-buffer' using \\[sql-set-sqli-buffer].
3828 For information on how to create multiple SQLi buffers, see
3829 `sql-interactive-mode'.
3831 Note that SQL doesn't have an escape character unless you specify
3832 one. If you specify backslash as escape character in SQL, you
3833 must tell Emacs. Here's how to do that in your init file:
3835 \(add-hook \\='sql-mode-hook
3837 (modify-syntax-entry ?\\\\ \".\" sql-mode-syntax-table)))"
3839 :abbrev-table sql-mode-abbrev-table
3842 (easy-menu-add sql-mode-menu
)); XEmacs
3844 ;; (smie-setup sql-smie-grammar #'sql-smie-rules)
3845 (set (make-local-variable 'comment-start
) "--")
3846 ;; Make each buffer in sql-mode remember the "current" SQLi buffer.
3847 (make-local-variable 'sql-buffer
)
3848 ;; Add imenu support for sql-mode. Note that imenu-generic-expression
3849 ;; is buffer-local, so we don't need a local-variable for it. SQL is
3850 ;; case-insensitive, that's why we have to set imenu-case-fold-search.
3851 (setq imenu-generic-expression sql-imenu-generic-expression
3852 imenu-case-fold-search t
)
3853 ;; Make `sql-send-paragraph' work on paragraphs that contain indented
3855 (set (make-local-variable 'paragraph-separate
) "[\f]*$")
3856 (set (make-local-variable 'paragraph-start
) "[\n\f]")
3858 (setq-local abbrev-all-caps
1)
3859 ;; Contains the name of database objects
3860 (set (make-local-variable 'sql-contains-names
) t
)
3861 ;; Set syntax and font-face highlighting
3862 ;; Catch changes to sql-product and highlight accordingly
3863 (sql-set-product (or sql-product
'ansi
)) ; Fixes bug#13591
3864 (add-hook 'hack-local-variables-hook
'sql-highlight-product t t
))
3868 ;;; SQL interactive mode
3870 (put 'sql-interactive-mode
'mode-class
'special
)
3871 (put 'sql-interactive-mode
'custom-mode-group
'SQL
)
3873 (defun sql-interactive-mode ()
3874 "Major mode to use a SQL interpreter interactively.
3876 Do not call this function by yourself. The environment must be
3877 initialized by an entry function specific for the SQL interpreter.
3878 See `sql-help' for a list of available entry functions.
3880 \\[comint-send-input] after the end of the process' output sends the
3881 text from the end of process to the end of the current line.
3882 \\[comint-send-input] before end of process output copies the current
3883 line minus the prompt to the end of the buffer and sends it.
3884 \\[comint-copy-old-input] just copies the current line.
3885 Use \\[sql-accumulate-and-indent] to enter multi-line statements.
3887 If you want to make multiple SQL buffers, rename the `*SQL*' buffer
3888 using \\[rename-buffer] or \\[rename-uniquely] and start a new process.
3889 See `sql-help' for a list of available entry functions. The last buffer
3890 created by such an entry function is the current SQLi buffer. SQL
3891 buffers will send strings to the SQLi buffer current at the time of
3892 their creation. See `sql-mode' for details.
3894 Sample session using two connections:
3896 1. Create first SQLi buffer by calling an entry function.
3897 2. Rename buffer \"*SQL*\" to \"*Connection 1*\".
3898 3. Create a SQL buffer \"test1.sql\".
3899 4. Create second SQLi buffer by calling an entry function.
3900 5. Rename buffer \"*SQL*\" to \"*Connection 2*\".
3901 6. Create a SQL buffer \"test2.sql\".
3903 Now \\[sql-send-region] in buffer \"test1.sql\" will send the region to
3904 buffer \"*Connection 1*\", \\[sql-send-region] in buffer \"test2.sql\"
3905 will send the region to buffer \"*Connection 2*\".
3907 If you accidentally suspend your process, use \\[comint-continue-subjob]
3908 to continue it. On some operating systems, this will not work because
3909 the signals are not supported.
3911 \\{sql-interactive-mode-map}
3912 Customization: Entry to this mode runs the hooks on `comint-mode-hook'
3913 and `sql-interactive-mode-hook' (in that order). Before each input, the
3914 hooks on `comint-input-filter-functions' are run. After each SQL
3915 interpreter output, the hooks on `comint-output-filter-functions' are
3918 Variable `sql-input-ring-file-name' controls the initialization of the
3921 Variables `comint-output-filter-functions', a hook, and
3922 `comint-scroll-to-bottom-on-input' and
3923 `comint-scroll-to-bottom-on-output' control whether input and output
3924 cause the window to scroll to the end of the buffer.
3926 If you want to make SQL buffers limited in length, add the function
3927 `comint-truncate-buffer' to `comint-output-filter-functions'.
3929 Here is an example for your init file. It keeps the SQLi buffer a
3932 \(add-hook \\='sql-interactive-mode-hook
3933 (function (lambda ()
3934 (setq comint-output-filter-functions \\='comint-truncate-buffer))))
3936 Here is another example. It will always put point back to the statement
3937 you entered, right above the output it created.
3939 \(setq comint-output-filter-functions
3940 (function (lambda (STR) (comint-show-output))))"
3941 (delay-mode-hooks (comint-mode))
3943 ;; Get the `sql-product' for this interactive session.
3944 (set (make-local-variable 'sql-product
)
3945 (or sql-interactive-product
3949 (setq major-mode
'sql-interactive-mode
)
3951 (concat "SQLi[" (or (sql-get-product-feature sql-product
:name
)
3952 (symbol-name sql-product
)) "]"))
3953 (use-local-map sql-interactive-mode-map
)
3954 (if sql-interactive-mode-menu
3955 (easy-menu-add sql-interactive-mode-menu
)) ; XEmacs
3956 (set-syntax-table sql-mode-syntax-table
)
3958 ;; Note that making KEYWORDS-ONLY nil will cause havoc if you try
3959 ;; SELECT 'x' FROM DUAL with SQL*Plus, because the title of the column
3960 ;; will have just one quote. Therefore syntactic highlighting is
3961 ;; disabled for interactive buffers. No imenu support.
3962 (sql-product-font-lock t nil
)
3964 ;; Enable commenting and uncommenting of the region.
3965 (set (make-local-variable 'comment-start
) "--")
3966 ;; Abbreviation table init and case-insensitive. It is not activated
3968 (setq local-abbrev-table sql-mode-abbrev-table
)
3969 (setq abbrev-all-caps
1)
3970 ;; Exiting the process will call sql-stop.
3971 (set-process-sentinel (get-buffer-process (current-buffer)) 'sql-stop
)
3972 ;; Save the connection and login params
3973 (set (make-local-variable 'sql-user
) sql-user
)
3974 (set (make-local-variable 'sql-database
) sql-database
)
3975 (set (make-local-variable 'sql-server
) sql-server
)
3976 (set (make-local-variable 'sql-port
) sql-port
)
3977 (set (make-local-variable 'sql-connection
) sql-connection
)
3978 (setq-default sql-connection nil
)
3979 ;; Contains the name of database objects
3980 (set (make-local-variable 'sql-contains-names
) t
)
3981 ;; Keep track of existing object names
3982 (set (make-local-variable 'sql-completion-object
) nil
)
3983 (set (make-local-variable 'sql-completion-column
) nil
)
3984 ;; Create a useful name for renaming this buffer later.
3985 (set (make-local-variable 'sql-alternate-buffer-name
)
3986 (sql-make-alternate-buffer-name))
3987 ;; User stuff. Initialize before the hook.
3988 (set (make-local-variable 'sql-prompt-regexp
)
3989 (sql-get-product-feature sql-product
:prompt-regexp
))
3990 (set (make-local-variable 'sql-prompt-length
)
3991 (sql-get-product-feature sql-product
:prompt-length
))
3992 (set (make-local-variable 'sql-prompt-cont-regexp
)
3993 (sql-get-product-feature sql-product
:prompt-cont-regexp
))
3994 (make-local-variable 'sql-output-newline-count
)
3995 (make-local-variable 'sql-preoutput-hold
)
3996 (add-hook 'comint-preoutput-filter-functions
3997 'sql-interactive-remove-continuation-prompt nil t
)
3998 (make-local-variable 'sql-input-ring-separator
)
3999 (make-local-variable 'sql-input-ring-file-name
)
4000 ;; Run the mode hook (along with comint's hooks).
4001 (run-mode-hooks 'sql-interactive-mode-hook
)
4002 ;; Set comint based on user overrides.
4003 (setq comint-prompt-regexp
4004 (if sql-prompt-cont-regexp
4005 (concat "\\(" sql-prompt-regexp
4006 "\\|" sql-prompt-cont-regexp
"\\)")
4008 (setq left-margin sql-prompt-length
)
4009 ;; Install input sender
4010 (set (make-local-variable 'comint-input-sender
) 'sql-input-sender
)
4011 ;; People wanting a different history file for each
4012 ;; buffer/process/client/whatever can change separator and file-name
4013 ;; on the sql-interactive-mode-hook.
4015 ((comint-input-ring-separator sql-input-ring-separator
)
4016 (comint-input-ring-file-name sql-input-ring-file-name
))
4017 (comint-read-input-ring t
)))
4019 (defun sql-stop (process event
)
4020 "Called when the SQL process is stopped.
4022 Writes the input history to a history file using
4023 `comint-write-input-ring' and inserts a short message in the SQL buffer.
4025 This function is a sentinel watching the SQL interpreter process.
4026 Sentinels will always get the two parameters PROCESS and EVENT."
4027 (with-current-buffer (process-buffer process
)
4029 ((comint-input-ring-separator sql-input-ring-separator
)
4030 (comint-input-ring-file-name sql-input-ring-file-name
))
4031 (comint-write-input-ring))
4033 (if (not buffer-read-only
)
4034 (insert (format "\nProcess %s %s\n" process event
))
4035 (message "Process %s %s" process event
))))
4039 ;;; Connection handling
4041 (defun sql-read-connection (prompt &optional initial default
)
4042 "Read a connection name."
4043 (let ((completion-ignore-case t
))
4044 (completing-read prompt
4045 (mapcar (lambda (c) (car c
))
4046 sql-connection-alist
)
4047 nil t initial
'sql-connection-history default
)))
4050 (defun sql-connect (connection &optional buf-name
)
4051 "Connect to an interactive session using CONNECTION settings.
4053 See `sql-connection-alist' to see how to define connections and
4056 The user will not be prompted for any login parameters if a value
4057 is specified in the connection settings."
4059 ;; Prompt for the connection from those defined in the alist
4061 (if sql-connection-alist
4062 (list (sql-read-connection "Connection: ")
4064 (user-error "No SQL Connections defined")))
4066 ;; Are there connections defined
4067 (if sql-connection-alist
4070 ;; Get connection settings
4071 (let ((connect-set (cdr (assoc-string connection sql-connection-alist t
))))
4072 ;; Settings are defined
4074 ;; Set the desired parameters
4075 (let (param-var login-params set-vars rem-vars
)
4076 ;; Set the parameters and start the interactive session
4077 (dolist (vv connect-set
)
4078 (let ((var (car vv
))
4080 (set-default var
(eval val
))))
4081 (setq-default sql-connection connection
)
4083 ;; :sqli-login params variable
4085 (sql-get-product-feature sql-product
:sqli-login nil t
))
4087 ;; :sqli-login params value
4088 (setq login-params
(symbol-value param-var
))
4090 ;; Params set in the connection
4096 (`sql-password
'password
)
4097 (`sql-server
'server
)
4098 (`sql-database
'database
)
4103 ;; the remaining params (w/o the connection params)
4105 (sql-for-each-login login-params
4107 (unless (member var set-vars
)
4108 (if vals
(cons var vals
) var
)))))
4110 ;; Start the SQLi session with revised list of login parameters
4111 (eval `(let ((,param-var
',rem-vars
))
4112 (sql-product-interactive
4114 ',(or buf-name
(format "<%s>" connection
))))))
4116 (user-error "SQL Connection <%s> does not exist" connection
)
4119 (user-error "No SQL Connections defined")
4122 (defun sql-save-connection (name)
4123 "Captures the connection information of the current SQLi session.
4125 The information is appended to `sql-connection-alist' and
4126 optionally is saved to the user's init file."
4128 (interactive "sNew connection name: ")
4130 (unless (derived-mode-p 'sql-interactive-mode
)
4131 (user-error "Not in a SQL interactive mode!"))
4133 ;; Capture the buffer local settings
4134 (let* ((buf (current-buffer))
4135 (connection (buffer-local-value 'sql-connection buf
))
4136 (product (buffer-local-value 'sql-product buf
))
4137 (user (buffer-local-value 'sql-user buf
))
4138 (database (buffer-local-value 'sql-database buf
))
4139 (server (buffer-local-value 'sql-server buf
))
4140 (port (buffer-local-value 'sql-port buf
)))
4143 (message "This session was started by a connection; it's already been saved.")
4145 (let ((login (sql-get-product-feature product
:sqli-login
))
4146 (alist sql-connection-alist
)
4149 ;; Remove the existing connection if the user says so
4150 (when (and (assoc name alist
)
4151 (yes-or-no-p (format "Replace connection definition <%s>? " name
)))
4152 (setq alist
(assq-delete-all name alist
)))
4154 ;; Add the new connection if it doesn't exist
4155 (if (assoc name alist
)
4156 (user-error "Connection <%s> already exists" name
)
4161 (lambda (token _plist
)
4163 (`product
`(sql-product ',product
))
4164 (`user
`(sql-user ,user
))
4165 (`database
`(sql-database ,database
))
4166 (`server
`(sql-server ,server
))
4167 (`port
`(sql-port ,port
)))))))
4169 (setq alist
(append alist
(list connect
)))
4171 ;; confirm whether we want to save the connections
4172 (if (yes-or-no-p "Save the connections for future sessions? ")
4173 (customize-save-variable 'sql-connection-alist alist
)
4174 (customize-set-variable 'sql-connection-alist alist
)))))))
4176 (defun sql-connection-menu-filter (tail)
4177 "Generate menu entries for using each connection."
4182 (format "Connection <%s>\t%s" (car conn
)
4183 (let ((sql-user "") (sql-database "")
4184 (sql-server "") (sql-port 0))
4185 (eval `(let ,(cdr conn
) (sql-make-alternate-buffer-name)))))
4186 (list 'sql-connect
(car conn
))
4188 sql-connection-alist
)
4193 ;;; Entry functions for different SQL interpreters.
4195 (defun sql-product-interactive (&optional product new-name
)
4196 "Run PRODUCT interpreter as an inferior process.
4198 If buffer `*SQL*' exists but no process is running, make a new process.
4199 If buffer exists and a process is running, just switch to buffer `*SQL*'.
4201 To specify the SQL product, prefix the call with
4202 \\[universal-argument]. To set the buffer name as well, prefix
4203 the call to \\[sql-product-interactive] with
4204 \\[universal-argument] \\[universal-argument].
4206 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4209 ;; Handle universal arguments if specified
4210 (when (not (or executing-kbd-macro noninteractive
))
4211 (when (and (consp product
)
4213 (numberp (car product
)))
4214 (when (>= (prefix-numeric-value product
) 16)
4215 (when (not new-name
)
4216 (setq new-name
'(4)))
4217 (setq product
'(4)))))
4219 ;; Get the value of product that we need
4222 ((= (prefix-numeric-value product
) 4) ; C-u, prompt for product
4223 (sql-read-product "SQL product: " sql-product
))
4224 ((and product
; Product specified
4225 (symbolp product
)) product
)
4226 (t sql-product
))) ; Default to sql-product
4228 ;; If we have a product and it has a interactive mode
4230 (when (sql-get-product-feature product
:sqli-comint-func
)
4231 ;; If no new name specified, try to pop to an active SQL
4232 ;; interactive for the same product
4233 (let ((buf (sql-find-sqli-buffer product sql-connection
)))
4234 (if (and (not new-name
) buf
)
4237 ;; We have a new name or sql-buffer doesn't exist or match
4238 ;; Start by remembering where we start
4239 (let ((start-buffer (current-buffer))
4240 new-sqli-buffer rpt
)
4243 (apply #'sql-get-login
4244 (sql-get-product-feature product
:sqli-login
))
4246 ;; Connect to database.
4247 (setq rpt
(make-progress-reporter "Login"))
4249 (let ((sql-user (default-value 'sql-user
))
4250 (sql-password (default-value 'sql-password
))
4251 (sql-server (default-value 'sql-server
))
4252 (sql-database (default-value 'sql-database
))
4253 (sql-port (default-value 'sql-port
))
4254 (default-directory (or sql-default-directory
4255 default-directory
)))
4256 (funcall (sql-get-product-feature product
:sqli-comint-func
)
4258 (sql-get-product-feature product
:sqli-options
)
4259 (if (and new-name
(string-prefix-p "SQL" new-name t
))
4261 (concat "SQL: " new-name
))))
4264 (let ((sql-interactive-product product
))
4265 (sql-interactive-mode))
4267 ;; Set the new buffer name
4268 (setq new-sqli-buffer
(current-buffer))
4269 (set (make-local-variable 'sql-buffer
)
4270 (buffer-name new-sqli-buffer
))
4272 ;; Set `sql-buffer' in the start buffer
4273 (with-current-buffer start-buffer
4274 (when (derived-mode-p 'sql-mode
)
4275 (setq sql-buffer
(buffer-name new-sqli-buffer
))
4276 (run-hooks 'sql-set-sqli-hook
)))
4278 ;; Make sure the connection is complete
4279 ;; (Sometimes start up can be slow)
4280 ;; and call the login hook
4281 (let ((proc (get-buffer-process new-sqli-buffer
))
4282 (secs sql-login-delay
)
4284 (while (and (memq (process-status proc
) '(open run
))
4285 (or (accept-process-output proc step
)
4286 (<= 0.0 (setq secs
(- secs step
))))
4287 (progn (goto-char (point-max))
4288 (not (re-search-backward sql-prompt-regexp
0 t
))))
4289 (progress-reporter-update rpt
)))
4291 (goto-char (point-max))
4292 (when (re-search-backward sql-prompt-regexp nil t
)
4293 (run-hooks 'sql-login-hook
))
4296 (progress-reporter-done rpt
)
4297 (pop-to-buffer new-sqli-buffer
)
4298 (goto-char (point-max))
4299 (current-buffer)))))
4300 (user-error "No default SQL product defined. Set `sql-product'.")))
4302 (defun sql-comint (product params
&optional buf-name
)
4303 "Set up a comint buffer to run the SQL processor.
4305 PRODUCT is the SQL product. PARAMS is a list of strings which are
4306 passed as command line arguments. BUF-NAME is the name of the new
4307 buffer. If nil, a name is chosen for it."
4309 (let ((program (sql-get-product-feature product
:sqli-program
)))
4310 ;; Make sure we can find the program. `executable-find' does not
4311 ;; work for remote hosts; we suppress the check there.
4312 (unless (or (file-remote-p default-directory
)
4313 (executable-find program
))
4314 (error "Unable to locate SQL program `%s'" program
))
4316 ;; Make sure buffer name is unique.
4317 ;; if not specified, try *SQL* then *SQL-product*, then *SQL-product1*, ...
4318 ;; otherwise, use *buf-name*
4320 (unless (string-match-p "\\`[*].*[*]\\'" buf-name
)
4321 (setq buf-name
(concat "*" buf-name
"*")))
4322 (setq buf-name
"*SQL*")
4323 (when (sql-buffer-live-p buf-name
)
4324 (setq buf-name
(format "*SQL-%s*" product
)))
4326 (while (sql-buffer-live-p buf-name
)
4327 (setq buf-name
(format "*SQL-%s%d*" product i
)
4329 (set-text-properties 0 (length buf-name
) nil buf-name
)
4331 ;; Start the command interpreter in the buffer
4332 ;; PROC-NAME is BUF-NAME without enclosing asterisks
4333 (let ((proc-name (replace-regexp-in-string "\\`[*]\\(.*\\)[*]\\'" "\\1" buf-name
)))
4335 (apply #'make-comint-in-buffer
4336 proc-name buf-name program nil params
)))))
4339 (defun sql-oracle (&optional buffer
)
4340 "Run sqlplus by Oracle as an inferior process.
4342 If buffer `*SQL*' exists but no process is running, make a new process.
4343 If buffer exists and a process is running, just switch to buffer
4346 Interpreter used comes from variable `sql-oracle-program'. Login uses
4347 the variables `sql-user', `sql-password', and `sql-database' as
4348 defaults, if set. Additional command line parameters can be stored in
4349 the list `sql-oracle-options'.
4351 The buffer is put in SQL interactive mode, giving commands for sending
4352 input. See `sql-interactive-mode'.
4354 To set the buffer name directly, use \\[universal-argument]
4355 before \\[sql-oracle]. Once session has started,
4356 \\[sql-rename-buffer] can be called separately to rename the
4359 To specify a coding system for converting non-ASCII characters
4360 in the input and output to the process, use \\[universal-coding-system-argument]
4361 before \\[sql-oracle]. You can also specify this with \\[set-buffer-process-coding-system]
4362 in the SQL buffer, after you start the process.
4363 The default comes from `process-coding-system-alist' and
4364 `default-process-coding-system'.
4366 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4368 (sql-product-interactive 'oracle buffer
))
4370 (defun sql-comint-oracle (product options
&optional buf-name
)
4371 "Create comint buffer and connect to Oracle."
4372 ;; Produce user/password@database construct. Password without user
4373 ;; is meaningless; database without user/password is meaningless,
4374 ;; because "@param" will ask sqlplus to interpret the script
4376 (let (parameter nlslang coding
)
4377 (if (not (string= "" sql-user
))
4378 (if (not (string= "" sql-password
))
4379 (setq parameter
(concat sql-user
"/" sql-password
))
4380 (setq parameter sql-user
)))
4381 (if (and parameter
(not (string= "" sql-database
)))
4382 (setq parameter
(concat parameter
"@" sql-database
)))
4383 ;; options must appear before the logon parameters
4385 (setq parameter
(append options
(list parameter
)))
4386 (setq parameter options
))
4387 (sql-comint product parameter buf-name
)
4388 ;; Set process coding system to agree with the interpreter
4389 (setq nlslang
(or (getenv "NLS_LANG") "")
4391 ;; Are we missing any common NLS character sets
4392 '(("US8PC437" . cp437
)
4393 ("EL8PC737" . cp737
)
4394 ("WE8PC850" . cp850
)
4395 ("EE8PC852" . cp852
)
4396 ("TR8PC857" . cp857
)
4397 ("WE8PC858" . cp858
)
4398 ("IS8PC861" . cp861
)
4399 ("IW8PC1507" . cp862
)
4401 ("RU8PC866" . cp866
)
4402 ("US7ASCII" . us-ascii
)
4404 ("AL32UTF8" . utf-8
)
4405 ("AL16UTF16" . utf-16
))
4407 (when (string-match (format "\\.%s\\'" (car cs
)) nlslang
)
4408 (setq coding
(cdr cs
)))))
4409 (set-buffer-process-coding-system coding coding
)))
4411 (defun sql-oracle-save-settings (sqlbuf)
4412 "Save most SQL*Plus settings so they may be reset by \\[sql-redirect]."
4413 ;; Note: does not capture the following settings:
4423 ;; SQLPLUSCOMPATIBILITY
4429 ;; (apply #'concat (append
4435 (concat "SHOW ARRAYSIZE AUTOCOMMIT AUTOPRINT AUTORECOVERY AUTOTRACE"
4436 " CMDSEP COLSEP COPYCOMMIT DESCRIBE ECHO EDITFILE EMBEDDED"
4437 " ESCAPE FLAGGER FLUSH HEADING INSTANCE LINESIZE LNO LOBOFFSET"
4438 " LOGSOURCE LONG LONGCHUNKSIZE NEWPAGE NULL NUMFORMAT NUMWIDTH"
4439 " PAGESIZE PAUSE PNO RECSEP SERVEROUTPUT SHIFTINOUT SHOWMODE"
4440 " SPOOL SQLBLANKLINES SQLCASE SQLCODE SQLCONTINUE SQLNUMBER"
4441 " SQLPROMPT SUFFIX TAB TERMOUT TIMING TRIMOUT TRIMSPOOL VERIFY")
4445 ;; option "c" (hex xx)
4448 (concat "SHOW BLOCKTERMINATOR CONCAT DEFINE SQLPREFIX SQLTERMINATOR"
4449 " UNDERLINE HEADSEP RECSEPCHAR")
4450 "^\\(.+\\) (hex ..)$"
4453 ;; FEEDBACK ON for 99 or more rows
4458 "^\\(?:FEEDBACK ON for \\([[:digit:]]+\\) or more rows\\|feedback \\(OFF\\)\\)"
4459 "SET FEEDBACK \\1\\2")
4461 ;; wrap : lines will be wrapped
4462 ;; wrap : lines will be truncated
4463 (list (concat "SET WRAP "
4465 (car (sql-redirect-value
4468 "^wrap : lines will be \\(wrapped\\|truncated\\)" 1))
4472 (defun sql-oracle-restore-settings (sqlbuf saved-settings
)
4473 "Restore the SQL*Plus settings in SAVED-SETTINGS."
4475 ;; Remove any settings that haven't changed
4477 (lambda (one-cur-setting)
4478 (setq saved-settings
(delete one-cur-setting saved-settings
)))
4479 (sql-oracle-save-settings sqlbuf
))
4481 ;; Restore the changed settings
4482 (sql-redirect sqlbuf saved-settings
))
4484 (defun sql-oracle--list-object-name (obj-name)
4485 (format "CASE WHEN REGEXP_LIKE (%s, q'/^[A-Z0-9_#$]+$/','c') THEN %s ELSE '\"'|| %s ||'\"' END "
4486 obj-name obj-name obj-name
))
4488 (defun sql-oracle-list-all (sqlbuf outbuf enhanced _table-name
)
4489 ;; Query from USER_OBJECTS or ALL_OBJECTS
4490 (let ((settings (sql-oracle-save-settings sqlbuf
))
4493 "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
4494 ", " (sql-oracle--list-object-name "x.object_name") " AS SQL_EL_NAME "
4495 "FROM user_objects x "
4496 "WHERE x.object_type NOT LIKE '%% BODY' "
4500 "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
4501 ", " (sql-oracle--list-object-name "x.owner")
4502 " ||'.'|| " (sql-oracle--list-object-name "x.object_name") " AS SQL_EL_NAME "
4503 "FROM all_objects x "
4504 "WHERE x.object_type NOT LIKE '%% BODY' "
4505 "AND x.owner <> 'SYS' "
4508 (sql-redirect sqlbuf
4509 (concat "SET LINESIZE 80 PAGESIZE 50000 TRIMOUT ON"
4510 " TAB OFF TIMING OFF FEEDBACK OFF"))
4512 (sql-redirect sqlbuf
4513 (list "COLUMN SQL_EL_TYPE HEADING \"Type\" FORMAT A19"
4514 "COLUMN SQL_EL_NAME HEADING \"Name\""
4515 (format "COLUMN SQL_EL_NAME FORMAT A%d"
4516 (if enhanced
60 35))))
4518 (sql-redirect sqlbuf
4519 (if enhanced enhanced-sql simple-sql
)
4522 (sql-redirect sqlbuf
4523 '("COLUMN SQL_EL_NAME CLEAR"
4524 "COLUMN SQL_EL_TYPE CLEAR"))
4526 (sql-oracle-restore-settings sqlbuf settings
)))
4528 (defun sql-oracle-list-table (sqlbuf outbuf _enhanced table-name
)
4529 "Implements :list-table under Oracle."
4530 (let ((settings (sql-oracle-save-settings sqlbuf
)))
4532 (sql-redirect sqlbuf
4534 (concat "SET LINESIZE %d PAGESIZE 50000"
4535 " DESCRIBE DEPTH 1 LINENUM OFF INDENT ON")
4536 (max 65 (min 120 (window-width)))))
4538 (sql-redirect sqlbuf
(format "DESCRIBE %s" table-name
)
4541 (sql-oracle-restore-settings sqlbuf settings
)))
4543 (defcustom sql-oracle-completion-types
'("FUNCTION" "PACKAGE" "PROCEDURE"
4544 "SEQUENCE" "SYNONYM" "TABLE" "TRIGGER"
4546 "List of object types to include for completion under Oracle.
4548 See the distinct values in ALL_OBJECTS.OBJECT_TYPE for possible values."
4550 :type
'(repeat string
)
4553 (defun sql-oracle-completion-object (sqlbuf schema
)
4559 (concat "CASE WHEN REGEXP_LIKE (owner, q'/^[A-Z0-9_#$]+$/','c') THEN owner ELSE '\"'|| owner ||'\"' END "
4561 "CASE WHEN REGEXP_LIKE (object_name, q'/^[A-Z0-9_#$]+$/','c') THEN object_name ELSE '\"'|| object_name ||'\"' END "
4562 " AS o FROM all_objects "
4563 (format "WHERE owner = %s AND "
4564 (sql-str-literal (if (string-match "^[\"]\\(.+\\)[\"]$" schema
)
4565 (match-string 1 schema
) (upcase schema
)))))
4566 (concat "CASE WHEN REGEXP_LIKE (object_name, q'/^[A-Z0-9_#$]+$/','c') THEN object_name ELSE '\"'|| object_name ||'\"' END "
4567 " AS o FROM user_objects WHERE "))
4568 "temporary = 'N' AND generated = 'N' AND secondary = 'N' AND "
4570 (mapconcat (function sql-str-literal
) sql-oracle-completion-types
",")
4572 "^[\001]\\(.+\\)$" 1))
4576 (defun sql-sybase (&optional buffer
)
4577 "Run isql by Sybase as an inferior process.
4579 If buffer `*SQL*' exists but no process is running, make a new process.
4580 If buffer exists and a process is running, just switch to buffer
4583 Interpreter used comes from variable `sql-sybase-program'. Login uses
4584 the variables `sql-server', `sql-user', `sql-password', and
4585 `sql-database' as defaults, if set. Additional command line parameters
4586 can be stored in the list `sql-sybase-options'.
4588 The buffer is put in SQL interactive mode, giving commands for sending
4589 input. See `sql-interactive-mode'.
4591 To set the buffer name directly, use \\[universal-argument]
4592 before \\[sql-sybase]. Once session has started,
4593 \\[sql-rename-buffer] can be called separately to rename the
4596 To specify a coding system for converting non-ASCII characters
4597 in the input and output to the process, use \\[universal-coding-system-argument]
4598 before \\[sql-sybase]. You can also specify this with \\[set-buffer-process-coding-system]
4599 in the SQL buffer, after you start the process.
4600 The default comes from `process-coding-system-alist' and
4601 `default-process-coding-system'.
4603 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4605 (sql-product-interactive 'sybase buffer
))
4607 (defun sql-comint-sybase (product options
&optional buf-name
)
4608 "Create comint buffer and connect to Sybase."
4609 ;; Put all parameters to the program (if defined) in a list and call
4613 (if (not (string= "" sql-user
))
4614 (list "-U" sql-user
))
4615 (if (not (string= "" sql-password
))
4616 (list "-P" sql-password
))
4617 (if (not (string= "" sql-database
))
4618 (list "-D" sql-database
))
4619 (if (not (string= "" sql-server
))
4620 (list "-S" sql-server
))
4622 (sql-comint product params buf-name
)))
4627 (defun sql-informix (&optional buffer
)
4628 "Run dbaccess by Informix as an inferior process.
4630 If buffer `*SQL*' exists but no process is running, make a new process.
4631 If buffer exists and a process is running, just switch to buffer
4634 Interpreter used comes from variable `sql-informix-program'. Login uses
4635 the variable `sql-database' as default, if set.
4637 The buffer is put in SQL interactive mode, giving commands for sending
4638 input. See `sql-interactive-mode'.
4640 To set the buffer name directly, use \\[universal-argument]
4641 before \\[sql-informix]. Once session has started,
4642 \\[sql-rename-buffer] can be called separately to rename the
4645 To specify a coding system for converting non-ASCII characters
4646 in the input and output to the process, use \\[universal-coding-system-argument]
4647 before \\[sql-informix]. You can also specify this with \\[set-buffer-process-coding-system]
4648 in the SQL buffer, after you start the process.
4649 The default comes from `process-coding-system-alist' and
4650 `default-process-coding-system'.
4652 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4654 (sql-product-interactive 'informix buffer
))
4656 (defun sql-comint-informix (product options
&optional buf-name
)
4657 "Create comint buffer and connect to Informix."
4658 ;; username and password are ignored.
4659 (let ((db (if (string= "" sql-database
)
4661 (if (string= "" sql-server
)
4663 (concat sql-database
"@" sql-server
)))))
4664 (sql-comint product
(append `(,db
"-") options
) buf-name
)))
4669 (defun sql-sqlite (&optional buffer
)
4670 "Run sqlite as an inferior process.
4672 SQLite is free software.
4674 If buffer `*SQL*' exists but no process is running, make a new process.
4675 If buffer exists and a process is running, just switch to buffer
4678 Interpreter used comes from variable `sql-sqlite-program'. Login uses
4679 the variables `sql-user', `sql-password', `sql-database', and
4680 `sql-server' as defaults, if set. Additional command line parameters
4681 can be stored in the list `sql-sqlite-options'.
4683 The buffer is put in SQL interactive mode, giving commands for sending
4684 input. See `sql-interactive-mode'.
4686 To set the buffer name directly, use \\[universal-argument]
4687 before \\[sql-sqlite]. Once session has started,
4688 \\[sql-rename-buffer] can be called separately to rename the
4691 To specify a coding system for converting non-ASCII characters
4692 in the input and output to the process, use \\[universal-coding-system-argument]
4693 before \\[sql-sqlite]. You can also specify this with \\[set-buffer-process-coding-system]
4694 in the SQL buffer, after you start the process.
4695 The default comes from `process-coding-system-alist' and
4696 `default-process-coding-system'.
4698 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4700 (sql-product-interactive 'sqlite buffer
))
4702 (defun sql-comint-sqlite (product options
&optional buf-name
)
4703 "Create comint buffer and connect to SQLite."
4704 ;; Put all parameters to the program (if defined) in a list and call
4708 (if (not (string= "" sql-database
))
4709 `(,(expand-file-name sql-database
))))))
4710 (sql-comint product params buf-name
)))
4712 (defun sql-sqlite-completion-object (sqlbuf _schema
)
4713 (sql-redirect-value sqlbuf
".tables" "\\sw\\(?:\\sw\\|\\s_\\)*" 0))
4718 (defun sql-mysql (&optional buffer
)
4719 "Run mysql by TcX as an inferior process.
4721 Mysql versions 3.23 and up are free software.
4723 If buffer `*SQL*' exists but no process is running, make a new process.
4724 If buffer exists and a process is running, just switch to buffer
4727 Interpreter used comes from variable `sql-mysql-program'. Login uses
4728 the variables `sql-user', `sql-password', `sql-database', and
4729 `sql-server' as defaults, if set. Additional command line parameters
4730 can be stored in the list `sql-mysql-options'.
4732 The buffer is put in SQL interactive mode, giving commands for sending
4733 input. See `sql-interactive-mode'.
4735 To set the buffer name directly, use \\[universal-argument]
4736 before \\[sql-mysql]. Once session has started,
4737 \\[sql-rename-buffer] can be called separately to rename the
4740 To specify a coding system for converting non-ASCII characters
4741 in the input and output to the process, use \\[universal-coding-system-argument]
4742 before \\[sql-mysql]. You can also specify this with \\[set-buffer-process-coding-system]
4743 in the SQL buffer, after you start the process.
4744 The default comes from `process-coding-system-alist' and
4745 `default-process-coding-system'.
4747 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4749 (sql-product-interactive 'mysql buffer
))
4751 (defun sql-comint-mysql (product options
&optional buf-name
)
4752 "Create comint buffer and connect to MySQL."
4753 ;; Put all parameters to the program (if defined) in a list and call
4758 (if (not (string= "" sql-user
))
4759 (list (concat "--user=" sql-user
)))
4760 (if (not (string= "" sql-password
))
4761 (list (concat "--password=" sql-password
)))
4762 (if (not (= 0 sql-port
))
4763 (list (concat "--port=" (number-to-string sql-port
))))
4764 (if (not (string= "" sql-server
))
4765 (list (concat "--host=" sql-server
)))
4766 (if (not (string= "" sql-database
))
4767 (list sql-database
)))))
4768 (sql-comint product params buf-name
)))
4773 (defun sql-solid (&optional buffer
)
4774 "Run solsql by Solid as an inferior process.
4776 If buffer `*SQL*' exists but no process is running, make a new process.
4777 If buffer exists and a process is running, just switch to buffer
4780 Interpreter used comes from variable `sql-solid-program'. Login uses
4781 the variables `sql-user', `sql-password', and `sql-server' as
4784 The buffer is put in SQL interactive mode, giving commands for sending
4785 input. See `sql-interactive-mode'.
4787 To set the buffer name directly, use \\[universal-argument]
4788 before \\[sql-solid]. Once session has started,
4789 \\[sql-rename-buffer] can be called separately to rename the
4792 To specify a coding system for converting non-ASCII characters
4793 in the input and output to the process, use \\[universal-coding-system-argument]
4794 before \\[sql-solid]. You can also specify this with \\[set-buffer-process-coding-system]
4795 in the SQL buffer, after you start the process.
4796 The default comes from `process-coding-system-alist' and
4797 `default-process-coding-system'.
4799 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4801 (sql-product-interactive 'solid buffer
))
4803 (defun sql-comint-solid (product options
&optional buf-name
)
4804 "Create comint buffer and connect to Solid."
4805 ;; Put all parameters to the program (if defined) in a list and call
4809 (if (not (string= "" sql-server
))
4811 ;; It only makes sense if both username and password are there.
4812 (if (not (or (string= "" sql-user
)
4813 (string= "" sql-password
)))
4814 (list sql-user sql-password
))
4816 (sql-comint product params buf-name
)))
4821 (defun sql-ingres (&optional buffer
)
4822 "Run sql by Ingres as an inferior process.
4824 If buffer `*SQL*' exists but no process is running, make a new process.
4825 If buffer exists and a process is running, just switch to buffer
4828 Interpreter used comes from variable `sql-ingres-program'. Login uses
4829 the variable `sql-database' as default, if set.
4831 The buffer is put in SQL interactive mode, giving commands for sending
4832 input. See `sql-interactive-mode'.
4834 To set the buffer name directly, use \\[universal-argument]
4835 before \\[sql-ingres]. Once session has started,
4836 \\[sql-rename-buffer] can be called separately to rename the
4839 To specify a coding system for converting non-ASCII characters
4840 in the input and output to the process, use \\[universal-coding-system-argument]
4841 before \\[sql-ingres]. You can also specify this with \\[set-buffer-process-coding-system]
4842 in the SQL buffer, after you start the process.
4843 The default comes from `process-coding-system-alist' and
4844 `default-process-coding-system'.
4846 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4848 (sql-product-interactive 'ingres buffer
))
4850 (defun sql-comint-ingres (product options
&optional buf-name
)
4851 "Create comint buffer and connect to Ingres."
4852 ;; username and password are ignored.
4854 (append (if (string= "" sql-database
)
4856 (list sql-database
))
4863 (defun sql-ms (&optional buffer
)
4864 "Run osql by Microsoft as an inferior process.
4866 If buffer `*SQL*' exists but no process is running, make a new process.
4867 If buffer exists and a process is running, just switch to buffer
4870 Interpreter used comes from variable `sql-ms-program'. Login uses the
4871 variables `sql-user', `sql-password', `sql-database', and `sql-server'
4872 as defaults, if set. Additional command line parameters can be stored
4873 in the list `sql-ms-options'.
4875 The buffer is put in SQL interactive mode, giving commands for sending
4876 input. See `sql-interactive-mode'.
4878 To set the buffer name directly, use \\[universal-argument]
4879 before \\[sql-ms]. Once session has started,
4880 \\[sql-rename-buffer] can be called separately to rename the
4883 To specify a coding system for converting non-ASCII characters
4884 in the input and output to the process, use \\[universal-coding-system-argument]
4885 before \\[sql-ms]. You can also specify this with \\[set-buffer-process-coding-system]
4886 in the SQL buffer, after you start the process.
4887 The default comes from `process-coding-system-alist' and
4888 `default-process-coding-system'.
4890 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4892 (sql-product-interactive 'ms buffer
))
4894 (defun sql-comint-ms (product options
&optional buf-name
)
4895 "Create comint buffer and connect to Microsoft SQL Server."
4896 ;; Put all parameters to the program (if defined) in a list and call
4900 (if (not (string= "" sql-user
))
4901 (list "-U" sql-user
))
4902 (if (not (string= "" sql-database
))
4903 (list "-d" sql-database
))
4904 (if (not (string= "" sql-server
))
4905 (list "-S" sql-server
))
4908 (if (not (string= "" sql-password
))
4909 `("-P" ,sql-password
,@params
)
4910 (if (string= "" sql-user
)
4911 ;; If neither user nor password is provided, use system
4914 ;; If -P is passed to ISQL as the last argument without a
4915 ;; password, it's considered null.
4917 (sql-comint product params buf-name
)))
4922 (defun sql-postgres (&optional buffer
)
4923 "Run psql by Postgres as an inferior process.
4925 If buffer `*SQL*' exists but no process is running, make a new process.
4926 If buffer exists and a process is running, just switch to buffer
4929 Interpreter used comes from variable `sql-postgres-program'. Login uses
4930 the variables `sql-database' and `sql-server' as default, if set.
4931 Additional command line parameters can be stored in the list
4932 `sql-postgres-options'.
4934 The buffer is put in SQL interactive mode, giving commands for sending
4935 input. See `sql-interactive-mode'.
4937 To set the buffer name directly, use \\[universal-argument]
4938 before \\[sql-postgres]. Once session has started,
4939 \\[sql-rename-buffer] can be called separately to rename the
4942 To specify a coding system for converting non-ASCII characters
4943 in the input and output to the process, use \\[universal-coding-system-argument]
4944 before \\[sql-postgres]. You can also specify this with \\[set-buffer-process-coding-system]
4945 in the SQL buffer, after you start the process.
4946 The default comes from `process-coding-system-alist' and
4947 `default-process-coding-system'. If your output lines end with ^M,
4948 your might try undecided-dos as a coding system. If this doesn't help,
4949 Try to set `comint-output-filter-functions' like this:
4951 \(setq comint-output-filter-functions (append comint-output-filter-functions
4952 \\='(comint-strip-ctrl-m)))
4954 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
4956 (sql-product-interactive 'postgres buffer
))
4958 (defun sql-comint-postgres (product options
&optional buf-name
)
4959 "Create comint buffer and connect to Postgres."
4960 ;; username and password are ignored. Mark Stosberg suggests to add
4961 ;; the database at the end. Jason Beegan suggests using --pset and
4962 ;; pager=off instead of \\o|cat. The later was the solution by
4963 ;; Gregor Zych. Jason's suggestion is the default value for
4964 ;; sql-postgres-options.
4967 (if (not (= 0 sql-port
))
4968 (list "-p" (number-to-string sql-port
)))
4969 (if (not (string= "" sql-user
))
4970 (list "-U" sql-user
))
4971 (if (not (string= "" sql-server
))
4972 (list "-h" sql-server
))
4974 (if (not (string= "" sql-database
))
4975 (list sql-database
)))))
4976 (sql-comint product params buf-name
)))
4978 (defun sql-postgres-completion-object (sqlbuf schema
)
4979 (sql-redirect sqlbuf
"\\t on")
4982 (car (sql-redirect-value
4984 "Output format is \\(.*\\)[.]$" 1)))))
4986 (sql-redirect sqlbuf
"\\a"))
4987 (let* ((fs (or (car (sql-redirect-value
4988 sqlbuf
"\\f" "Field separator is \"\\(.\\)[.]$" 1))
4990 (re (concat "^\\([^" fs
"]*\\)" fs
"\\([^" fs
"]*\\)"
4991 fs
"[^" fs
"]*" fs
"[^" fs
"]*$"))
4992 (cl (if (not schema
)
4993 (sql-redirect-value sqlbuf
"\\d" re
'(1 2))
4994 (append (sql-redirect-value
4995 sqlbuf
(format "\\dt %s.*" schema
) re
'(1 2))
4997 sqlbuf
(format "\\dv %s.*" schema
) re
'(1 2))
4999 sqlbuf
(format "\\ds %s.*" schema
) re
'(1 2))))))
5001 ;; Restore tuples and alignment to what they were.
5002 (sql-redirect sqlbuf
"\\t off")
5004 (sql-redirect sqlbuf
"\\a"))
5006 ;; Return the list of table names (public schema name can be omitted)
5007 (mapcar (lambda (tbl)
5008 (if (string= (car tbl
) "public")
5009 (format "\"%s\"" (cadr tbl
))
5010 (format "\"%s\".\"%s\"" (car tbl
) (cadr tbl
))))
5016 (defun sql-interbase (&optional buffer
)
5017 "Run isql by Interbase as an inferior process.
5019 If buffer `*SQL*' exists but no process is running, make a new process.
5020 If buffer exists and a process is running, just switch to buffer
5023 Interpreter used comes from variable `sql-interbase-program'. Login
5024 uses the variables `sql-user', `sql-password', and `sql-database' as
5027 The buffer is put in SQL interactive mode, giving commands for sending
5028 input. See `sql-interactive-mode'.
5030 To set the buffer name directly, use \\[universal-argument]
5031 before \\[sql-interbase]. Once session has started,
5032 \\[sql-rename-buffer] can be called separately to rename the
5035 To specify a coding system for converting non-ASCII characters
5036 in the input and output to the process, use \\[universal-coding-system-argument]
5037 before \\[sql-interbase]. You can also specify this with \\[set-buffer-process-coding-system]
5038 in the SQL buffer, after you start the process.
5039 The default comes from `process-coding-system-alist' and
5040 `default-process-coding-system'.
5042 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
5044 (sql-product-interactive 'interbase buffer
))
5046 (defun sql-comint-interbase (product options
&optional buf-name
)
5047 "Create comint buffer and connect to Interbase."
5048 ;; Put all parameters to the program (if defined) in a list and call
5052 (if (not (string= "" sql-database
))
5053 (list sql-database
)) ; Add to the front!
5054 (if (not (string= "" sql-password
))
5055 (list "-p" sql-password
))
5056 (if (not (string= "" sql-user
))
5057 (list "-u" sql-user
))
5059 (sql-comint product params buf-name
)))
5064 (defun sql-db2 (&optional buffer
)
5065 "Run db2 by IBM as an inferior process.
5067 If buffer `*SQL*' exists but no process is running, make a new process.
5068 If buffer exists and a process is running, just switch to buffer
5071 Interpreter used comes from variable `sql-db2-program'. There is not
5074 The buffer is put in SQL interactive mode, giving commands for sending
5075 input. See `sql-interactive-mode'.
5077 If you use \\[sql-accumulate-and-indent] to send multiline commands to
5078 db2, newlines will be escaped if necessary. If you don't want that, set
5079 `comint-input-sender' back to `comint-simple-send' by writing an after
5080 advice. See the elisp manual for more information.
5082 To set the buffer name directly, use \\[universal-argument]
5083 before \\[sql-db2]. Once session has started,
5084 \\[sql-rename-buffer] can be called separately to rename the
5087 To specify a coding system for converting non-ASCII characters
5088 in the input and output to the process, use \\[universal-coding-system-argument]
5089 before \\[sql-db2]. You can also specify this with \\[set-buffer-process-coding-system]
5090 in the SQL buffer, after you start the process.
5091 The default comes from `process-coding-system-alist' and
5092 `default-process-coding-system'.
5094 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
5096 (sql-product-interactive 'db2 buffer
))
5098 (defun sql-comint-db2 (product options
&optional buf-name
)
5099 "Create comint buffer and connect to DB2."
5100 ;; Put all parameters to the program (if defined) in a list and call
5102 (sql-comint product options buf-name
))
5105 (defun sql-linter (&optional buffer
)
5106 "Run inl by RELEX as an inferior process.
5108 If buffer `*SQL*' exists but no process is running, make a new process.
5109 If buffer exists and a process is running, just switch to buffer
5112 Interpreter used comes from variable `sql-linter-program' - usually `inl'.
5113 Login uses the variables `sql-user', `sql-password', `sql-database' and
5114 `sql-server' as defaults, if set. Additional command line parameters
5115 can be stored in the list `sql-linter-options'. Run inl -h to get help on
5118 `sql-database' is used to set the LINTER_MBX environment variable for
5119 local connections, `sql-server' refers to the server name from the
5120 `nodetab' file for the network connection (dbc_tcp or friends must run
5121 for this to work). If `sql-password' is an empty string, inl will use
5124 The buffer is put in SQL interactive mode, giving commands for sending
5125 input. See `sql-interactive-mode'.
5127 To set the buffer name directly, use \\[universal-argument]
5128 before \\[sql-linter]. Once session has started,
5129 \\[sql-rename-buffer] can be called separately to rename the
5132 \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
5134 (sql-product-interactive 'linter buffer
))
5136 (defun sql-comint-linter (product options
&optional buf-name
)
5137 "Create comint buffer and connect to Linter."
5138 ;; Put all parameters to the program (if defined) in a list and call
5141 (if (not (string= "" sql-user
))
5142 (concat sql-user
"/" sql-password
)))
5145 (if (not (string= "" sql-server
))
5146 (list "-n" sql-server
))
5149 (cl-letf (((getenv "LINTER_MBX")
5150 (unless (string= "" sql-database
) sql-database
)))
5151 (sql-comint product params buf-name
))))
5155 (defcustom sql-vertica-program
"vsql"
5156 "Command to start the Vertica client."
5161 (defcustom sql-vertica-options
'("-P" "pager=off")
5162 "List of additional options for `sql-vertica-program'.
5163 The default value disables the internal pager."
5165 :type
'(repeat string
)
5168 (defcustom sql-vertica-login-params
'(user password database server
)
5169 "List of login parameters needed to connect to Vertica."
5171 :type
'sql-login-params
5174 (defun sql-comint-vertica (product options
&optional buf-name
)
5175 "Create comint buffer and connect to Vertica."
5178 (and (not (string= "" sql-server
))
5179 (list "-h" sql-server
))
5180 (and (not (string= "" sql-database
))
5181 (list "-d" sql-database
))
5182 (and (not (string= "" sql-password
))
5183 (list "-w" sql-password
))
5184 (and (not (string= "" sql-user
))
5185 (list "-U" sql-user
))
5190 (defun sql-vertica (&optional buffer
)
5191 "Run vsql as an inferior process."
5193 (sql-product-interactive 'vertica buffer
))
5198 ;;; sql.el ends here
5200 ; LocalWords: sql SQL SQLite sqlite Sybase Informix MySQL
5201 ; LocalWords: Postgres SQLServer SQLi