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