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