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