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