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