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