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