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