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