forked from kostafey/ejc-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ejc-sql.el
857 lines (784 loc) · 31.2 KB
/
ejc-sql.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
;;; ejc-sql.el --- Emacs SQL client uses Clojure JDBC. -*- lexical-binding: t -*-
;;; Copyright © 2012-2019 - Kostafey <[email protected]>
;; Author: Kostafey <[email protected]>
;; URL: https://github.com/kostafey/ejc-sql
;; Keywords: sql, jdbc
;; Version: 0.2
;; Package-Requires: ((emacs "25.1")(clomacs "0.0.3")(dash "2.12.1")(auto-complete "1.5.1")(spinner "1.7.1")(direx "1.0.0"))
;; This file is not part of GNU Emacs.
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 2, or (at your option)
;;; any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software Foundation,
;;; Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
;;; Commentary:
;; ejc-sql turns Emacs into simple SQL client, it uses JDBC connection to
;; databases via clojure/java.jdbc lib.
;; See README.md for detailed description.
;;; Code:
(require 'sql)
(require 'dash)
(require 'cl-lib)
(require 'ejc-lib)
(require 'ejc-direx)
(require 'ejc-format)
(require 'ejc-interaction)
(require 'ejc-result-mode)
(require 'ejc-result-buffer)
(require 'ejc-autocomplete)
(defvar-local ejc-db nil
"JDBC connection info for current SQL buffer.")
(defvar ejc-connections nil
"List of existing configured jdbc connections")
(defvar ejc-current-buffer-query nil
"Current SQL edit buffer lanched query.")
(defcustom ejc-temp-editor-buffer-name "ejc-sql-editor"
"Template name for buffers used to ad-hoc edit SQL scripts."
:group 'ejc-sql
:type 'string)
(defcustom ejc-temp-editor-file-path (expand-file-name "~/tmp/ejc-sql/")
"Directory to save temp ad-hoc SQL edit buffers contents."
:group 'ejc-sql
:type 'string)
(defcustom ejc-keymap-prefix (kbd "C-c e")
"ejc-sql keymap prefix."
:group 'ejc-sql
:type 'string)
(defcustom ejc-date-output-format "%d.%m.%Y %H:%M:%S"
"ejc-sql date output format."
:group 'ejc-sql
:type 'string)
(defcustom ejc-connection-validate-timeout 5
"The time in seconds to wait for the database connection validation."
:group 'ejc-sql
:type 'integer)
(defcustom ejc-org-mode-babel-wrapper t
"Add wrapper around org-mode default `org-babel-execute:sql'."
:type 'boolean
:safe #'booleanp
:group 'ejc-sql)
(defcustom ejc-org-mode-show-results t
"When t show SQL query results of `org-mode' code snippet in the same buffer.
An expected behaviour for `org-mode' users. Disable popup window with SQL
results. When nil, otherwise, provide `ejc-sql' users expected behaviour."
:group 'ejc-sql
:type 'boolean)
(defcustom ejc-jdbc-drivers
'("sqlite" [org.xerial/sqlite-jdbc "3.23.1"]
"h2" [com.h2database/h2 "1.4.199"]
"mysql" [mysql/mysql-connector-java "5.1.44"]
"postgresql" [postgresql/postgresql "9.3-1102.jdbc41"]
"sqlserver" [com.microsoft.sqlserver/mssql-jdbc "6.2.2.jre8"]
"oracle" [com.oracle.jdbc/ojdbc8 "12.2.0.1"])
"Artifacts used as JDBC drivers for each database type in Leiningen format."
:group 'ejc-sql
:type '(plist :key-type string :value-type (vector symbol string)))
(defvar-local ejc-replace-double-quotes nil
"When t replace double quotes with single ones in SQL before evaluation.")
(defvar ejc-sql-mode-keymap (make-keymap) "ejc-sql-mode keymap.")
(define-key ejc-sql-mode-keymap (kbd "C-c C-c") 'ejc-eval-user-sql-at-point)
(define-key ejc-sql-mode-keymap (kbd "C-h t") 'ejc-describe-table)
(define-key ejc-sql-mode-keymap (kbd "C-h d") 'ejc-describe-entity)
(define-key ejc-sql-mode-keymap (kbd "C-M-S-b") (lambda () (interactive) (ejc-previous-sql t)))
(define-key ejc-sql-mode-keymap (kbd "C-M-S-f") (lambda () (interactive) (ejc-next-sql t)))
(define-key ejc-sql-mode-keymap (kbd "C-M-b") 'ejc-previous-sql)
(define-key ejc-sql-mode-keymap (kbd "C-M-f") 'ejc-next-sql)
(define-key ejc-sql-mode-keymap (kbd "C-g") 'ejc-cancel-query)
(define-key ejc-sql-mode-keymap (kbd "M-.") 'ejc-describe-entity)
(define-key ejc-sql-mode-keymap (kbd "M-,") 'ejc-show-prev-result)
(defvar ejc-command-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "c") #'ejc-connect)
(define-key map (kbd "i") #'ejc-connect-interactive)
(define-key map (kbd "<up>") #'ejc-show-last-result)
(define-key map (kbd "t") #'ejc-show-tables-list)
(define-key map (kbd "v") #'ejc-show-views-list)
(define-key map (kbd "p") #'ejc-show-procedures-list)
(define-key map (kbd "T") #'ejc-show-user-types-list)
(define-key map (kbd "s") #'ejc-strinp-sql-at-point)
(define-key map (kbd "S") #'ejc-dress-sql-at-point)
(define-key map (kbd "f") #'ejc-format-sql-at-point)
map)
"Keymap for ejc-sql commands after `ejc-keymap-prefix'.")
(fset 'ejc-command-map ejc-command-map)
(define-key ejc-sql-mode-keymap ejc-keymap-prefix 'ejc-command-map)
(defvar ejc-sql-minor-mode-exit-hook nil
"*Functions to be called when `ejc-sql-mode' is exited.")
(defvar ejc-sql-minor-mode-hook nil
"*Functions to be called when `ejc-sql-mode' is entered.")
(defvar ejc-sql-mode nil)
(defvar ejc-conn-statistics (list)
"Keep connection usage statistics and offer most frequently used first
when `ejc-connect' is called.")
(defcustom ejc-conn-statistics-file (expand-file-name
"~/.ejc-sql/connection-statistics.el")
"Connection usage statistics data file location."
:group 'ejc-sql
:type 'string)
(defface ejc-separator-face
'((t :inherit font-lock-function-name-face))
"Face used to highlight SQL statement separators."
:group 'ejc-sql)
(defun ejc-refresh-font-lock ()
(funcall (if ejc-sql-mode
'font-lock-add-keywords
'font-lock-remove-keywords)
nil `((,(ejc-sql-separator-re) . 'ejc-separator-face)))
(if (fboundp 'font-lock-flush)
(font-lock-flush)
(when font-lock-mode
(with-no-warnings (font-lock-fontify-buffer)))))
;;;###autoload
(define-minor-mode ejc-sql-mode
"Toggle ejc-sql mode."
:lighter " ejc"
:keymap ejc-sql-mode-keymap
:group 'ejc
:global nil
(if ejc-sql-mode
(progn
(ejc-create-menu)
(ejc-refresh-font-lock)
(run-hooks 'ejc-sql-minor-mode-hook))
(progn
(ejc-refresh-font-lock)
(run-hooks 'ejc-sql-minor-mode-exit-hook))))
;;;###autoload
(defun ejc-create-menu ()
(define-key-after
ejc-sql-mode-keymap
[menu-bar ejc-menu]
(cons "ejc-sql" (make-sparse-keymap "ejc-sql mode"))
'tools )
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu ev]
'("Eval SQL" . ejc-eval-user-sql-at-point))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu fs]
'("Format SQL" . ejc-format-sql-at-point))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu ms]
'("Mark SQL" . ejc-mark-this-sql))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu tl]
'("Show tables list" . ejc-show-tables-list))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu cl]
'("Show constraints list" . ejc-show-constraints-list))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu pl]
'("Show procedures list" . ejc-show-procedures-list))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu ss]
'("Strip SQL" . ejc-strinp-sql-at-point))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu ds]
'("Dress SQL" . ejc-dress-sql-at-point))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu ol]
'("Open log" . ejc-open-log))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu sl]
'("Show last result" . ejc-show-last-result))
(define-key
ejc-sql-mode-keymap
[menu-bar ejc-menu qc]
'("Quit connection" . ejc-quit-connection)))
(cl-defun ejc-create-connection (connection-name
&key
;; ----------
;; DriverManager (preferred):
dbtype
dbname
host
port
;; others (may include :user and :password)
;; ----------
;; Raw:
connection-uri
;; others (may include :user and :password)
;; ----------
;; DriverManager (alternative / legacy style):
subprotocol
subname
;; ----------
;; Others:
user
password
classpath
separator
;; ----------
;; Optional:
classname)
"Add new connection configuration named CONNECTION-NAME.
It adds new connection to `ejc-connections' list or replace existing with the
same CONNECTION-NAME.
For more details about parameters see `get-connection' function in jdbc.clj:
`https://github.com/clojure/java.jdbc/blob/master/src/main/clojure/clojure/java/jdbc.clj'"
(setq ejc-connections
(-remove (lambda (x) (equal (car x) connection-name))
ejc-connections))
(setq ejc-connections
(cons (cons
connection-name
(let ((new-connection nil))
(-map (lambda (arg)
(if (cdr arg)
(setq new-connection
(cons arg new-connection))))
(list
(cons :dbtype dbtype)
(cons :dbname dbname)
(cons :host host)
(cons :port port)
(cons :connection-uri connection-uri)
(cons :subprotocol subprotocol)
(cons :subname subname)
(cons :user user)
(cons :password password)
(cons :classpath (file-truename classpath))
(cons :separator separator)
(cons :classname classname)))
new-connection))
ejc-connections)))
(defun ejc-find-connection (connection-name)
"Return pair with name CONNECTION-NAME and db connection structure from
`ejc-connections'."
(-find (lambda (x) (equal (car x) connection-name))
ejc-connections))
(defun ejc-load-conn-statistics ()
"Load connection usage statistics to `ejc-conn-statistics' var."
(setq ejc-conn-statistics
(ejc-load-from-file ejc-conn-statistics-file
:default (list)
:check 'ejc-plist-p)))
(defun ejc-update-conn-statistics (connection-name)
"Update connection usage statistics, persist it in `ejc-conn-statistics-file'"
(setq ejc-conn-statistics
(lax-plist-put
ejc-conn-statistics
connection-name
(1+ (or (lax-plist-get ejc-conn-statistics connection-name) 0))))
(ejc-save-to-file ejc-conn-statistics-file ejc-conn-statistics))
(defun ejc-set-mode-name (connection-name)
"Show CONNECTION-NAME as part of `mode-name' in `mode-line'."
(setq mode-name (format "%s->[%s]"
(car (split-string mode-name "->\\[.+\\]"))
connection-name)))
(cl-defun ejc-add-connection (&optional connection-name db)
"Add ejc connection information to current buffer.
If the current mode is `sql-mode' prepare buffer to operate as `ejc-sql-mode'."
(when (derived-mode-p 'sql-mode)
(sql-set-product (if db
(ejc-get-product-name db)
"ansi"))
(ejc-sql-mode t))
(setq-local ejc-connection-name connection-name)
(setq-local ejc-db db)
(ejc-set-mode-name connection-name))
(defun ejc-eval-org-snippet (&optional orig-fun body params)
"Used to eval SQL code in `org-mode' code snippets."
(if (or (not ejc-org-mode-babel-wrapper)
(and (cdr (assq :engine params))
(not
(yes-or-no-p
(concat "ejc-sql is enabled, ignore source block connection"
" header arguments and use ejc-sql to execute it? ")))))
(funcall orig-fun body params)
(let ((beg (save-excursion
(org-babel-mark-block)
(point)))
(end (save-excursion
(org-babel-mark-block)
(mark))))
(ejc-eval-user-sql-at-point
:beg beg
:end end
:sync ejc-org-mode-show-results
:display-result (not ejc-org-mode-show-results))
(if ejc-org-mode-show-results
(with-temp-buffer
(insert-file-contents (ejc-get-result-file-path))
(buffer-string))))))
(defun ejc-org-edit-special (orig-fun &rest args)
(if (and (equal "sql" (car (org-babel-get-src-block-info)))
(boundp 'ejc-db) ejc-db
(boundp 'ejc-connection-name) ejc-connection-name)
(let* ((db ejc-db)
(connection-name ejc-connection-name))
(apply orig-fun args)
(ejc-add-connection connection-name db))
(apply orig-fun args)))
(defun ejc-read-connection-name ()
"Read connection-name in minibuffer."
(ido-completing-read
"DataBase connection name: "
(let ((conn-list (mapcar 'car ejc-connections))
(conn-statistics (ejc-load-conn-statistics)))
(-sort (lambda (c1 c2)
(> (or (lax-plist-get conn-statistics c1) 0)
(or (lax-plist-get conn-statistics c2) 0)))
conn-list))))
;;;###autoload
(defun ejc-insert-connection-data (connection-name)
"Insert configured connection data to keep it between Emacs restarts.
Assume to be evaluated somewhere in .emacs or any file, loaded as Emacs
configuration."
(interactive
(list (or (and (boundp 'connection-name) connection-name)
(ejc-read-connection-name))))
(let ((connection-params (cdr (ejc-find-connection connection-name))))
(insert
(format "(ejc-create-connection\n \"%s\"%s)"
connection-name
(-reduce-from
(lambda (result x)
(concat result
(format "\n %s \"%s\""
(symbol-name (car x))
(cdr x))))
""
connection-params)))))
(defalias 'ejc-save-connection-data 'ejc-insert-connection-data)
(defun ejc-lein-artifact-to-path (artifact)
"Get ~/.m2 jar file path of artifact."
(if (not (vectorp artifact))
(error
"Expect leiningen artifact, e.g. [com.h2database/h2 \"1.4.199\"]."))
(let* ((group (car (split-string
(ejc-strip-text-properties (symbol-name (elt artifact 0)))
"/")))
(name (or (cadr (split-string
(ejc-strip-text-properties
(symbol-name (elt artifact 0))) "/"))
group))
(version (elt artifact 1)))
(format "~/.m2/repository/%s/%s/%s/%s-%s.jar"
(mapconcat 'identity (split-string group "\\.") "/")
name
version
name
version)))
(defun ejc-resolve-jdbc-driver (dbtype)
"Resolve and download artifacts (JDBC drivers) for DBTYPE.
Apropriate artifacts list located in `ejc-jdbc-drivers'."
(let* ((artifact (lax-plist-get ejc-jdbc-drivers dbtype))
(jar-path (ejc-lein-artifact-to-path artifact)))
(if (not (and (file-exists-p jar-path)
(if (> (file-attribute-size (file-attributes jar-path))
0)
t
;; If JDBC driver jar file is accidentally empty - it
;; should be deleted and reinstalled.
(progn (delete-file jar-path)
nil))))
(ejc-resolve-dependencies
:coordinates (vector artifact)
:repositories '(("central" . "https://repo1.maven.org/maven2/")
("clojars" . "https://clojars.org/repo"))))
jar-path))
;;;###autoload
(defun ejc-connect-interactive (connection-name)
"Create new connection interactively and connect to it."
(interactive
(list
(or (and (boundp 'connection-name) connection-name)
(read-string "DataBase new connection name: "))))
(let* ((db-types '(("MySQL" . "mysql")
("Oracle" . "oracle")
("MS SQL Server" . "sqlserver")
("H2" . "h2")
("SQLite" . "sqlite")
("PostgreSQL" . "postgresql")))
(dbtype (cdr (assoc-string
(ido-completing-read
"Database type: "
(cl-sort (-map 'car db-types)
'string-lessp :key 'downcase))
db-types)))
(properties
(-concat
(pcase dbtype
("sqlite"
`((:subprotocol . "sqlite")
(:subname . "")))
("h2"
`((:subprotocol . "h2")
(:subname . "")))
("mysql"
`((:dbtype . "mysql")
(:classname . "com.mysql.jdbc.Driver")
(:dbname . "")
(:host . "localhost")
(:port . "3306")))
("postgresql"
`((:dbtype . "postgresql")
(:dbname . "")
(:host . "localhost")
(:port . "5432")))
("sqlserver"
`((:dbtype . "sqlserver")
(:dbname . "")
(:host . "localhost")
(:port . "1433")))
("oracle"
`((:dbtype . "oracle")
(:dbname . "")
(:host . "localhost")
(:port . "1521"))))
'((:classpath . "")
(:user . "")
(:password . ""))))
(args
(-reduce-from
(lambda (memo p)
(-concat
memo
(list
(car p)
(case (car p)
(:dbtype (cdr p))
(:classpath (ejc-resolve-jdbc-driver dbtype))
(:classname (cdr p))
(:subprotocol (cdr p))
(:subname (if (member dbtype '("h2" "sqlite"))
(let ((fpath
(file-truename
(ido-read-file-name "DB file: "))))
(if (equal "h2" dbtype)
(concat "file://"
(file-name-sans-extension
(file-name-sans-extension
fpath))
";AUTO_SERVER=TRUE")
fpath))
(read-string "DataBase subname: " (cdr p))))
(:dbname (read-string "DataBase name: " (cdr p)))
(:host (read-string "Host: " (cdr p)))
(:port (read-string "Port: " (cdr p)))
(:user (read-string "User: "))
(:password (read-passwd "Password: "))))))
(list connection-name)
properties)))
(apply 'ejc-create-connection args)
(ejc-connect connection-name)))
;;;###autoload
(defun ejc-connect (connection-name)
"Connect to selected db."
(interactive (list
(or (and (boundp 'connection-name) connection-name)
(ejc-read-connection-name))))
(if-let ((db (cdr (ejc-find-connection connection-name))))
(progn
(ejc-update-conn-statistics connection-name)
(ejc-add-connection connection-name db)
(when (derived-mode-p 'org-mode)
(require 'ob-sql)
(advice-add 'org-babel-execute:sql :around 'ejc-eval-org-snippet)
(advice-add 'org-edit-special :around #'ejc-org-edit-special))
(message "Connection started...")
(clomacs-with-nrepl "ejc-sql"
(lambda (db connection-name)
(ejc-connect-to-db db)
(let ((validation-result
(ejc-validate-connection
:db db
:timeout ejc-connection-validate-timeout)))
(when (alist-get :status validation-result)
(ejc-set-mode-name connection-name)
(message (let ((msg (alist-get :message validation-result)))
(if (equal "Connected." msg)
(format
"Connected -> %s."
(propertize connection-name
'face 'font-lock-keyword-face))
msg))))))
:params (list db connection-name)))
(ejc-connect-interactive connection-name)))
;;;###autoload
(defun ejc-connect-existing-repl ()
"Connect to existing ejc-sql nREPL running process.
You can `cd` to your ejc-sql project folder (typically
'~/.emacs.d/elpa/ejc-sql-<version>') and launch nREPL via `lein repl`.
Then run in Emacs `ejc-connect-existing-repl', type HOST and PORT
from your `lein run` console output. Finally, use `ejc-connect' from
any SQL buffer to connect to exact database, as always. "
(interactive)
(let* ((params (cider-select-endpoint))
(host (car params))
(port (cdr params))
(current-repl-b-name (cider-connect (list :host host :port port)))
(ejc-repl-b-name (nrepl-repl-buffer-name
(list
:session-name "ejc-sql"
:repl-type "clj"
:host host
:port port))))
(with-current-buffer current-repl-b-name
(rename-buffer ejc-repl-b-name))))
(defun ejc-get-word-at-point (pos)
"Return SQL word around the point."
(interactive "d")
(let* ((char (char-after pos))
(str (char-to-string char)))
(save-excursion
(let* ((end (if (member str '(" " ")" "<" ">" "="))
(point)
(progn
(forward-sexp 1)
(point))))
(beg (progn
(forward-sexp -1)
(point)))
(sql-word (buffer-substring beg end)))
sql-word))))
(defun ejc-get-prompt-symbol-under-point (msg)
(let ((sql-symbol (if mark-active
(buffer-substring (mark) (point))
(ejc-get-word-at-point (point))))
(enable-recursive-minibuffers t)
val)
(setq val (completing-read
(if sql-symbol
(format "%s (default %s): " msg sql-symbol)
(format "%s: " msg))
obarray))
(list (if (equal val "")
sql-symbol
val))))
(defun ejc-check-connection ()
(unless (ejc-buffer-connected-p)
(error "Run M-x ejc-connect first!")))
(defun ejc-get-sql-from-string (sql)
(let* ((sql (replace-regexp-in-string ejc-clear-sql-regexp "" sql))
(sql (if ejc-replace-double-quotes
(replace-regexp-in-string "\"" "'" sql)
sql)))
sql))
(cl-defun ejc-eval-sql-and-log (db
sql
&key
start-time
rows-limit
append
sync
display-result
result-file)
(when sql
(spinner-start 'rotating-line)
(setq ejc-current-buffer-query (current-buffer))
(let* ((prepared-sql (ejc-get-sql-from-string sql)))
(ejc--eval-sql-and-log-print
db
prepared-sql
:start-time start-time
:rows-limit rows-limit
:append append
:sync sync
:display-result display-result
:result-file (or result-file
(ejc-next-result-file-path))))))
(defun ejc-message-query-done (start-time status)
(message
"%s SQL query at %s. Exec time %.03f"
(case status
(:done (propertize "Done" 'face 'font-lock-keyword-face))
(:error (propertize "Error" 'face 'error))
(:terminated (propertize "Terminated" 'face 'font-lock-keyword-face)))
(format-time-string ejc-date-output-format
(current-time))
(float-time (time-since start-time))))
(defun ejc-spinner-stop ()
"Stop spinner indicating current running query."
(if ejc-current-buffer-query
(with-current-buffer ejc-current-buffer-query
(spinner-stop))))
(cl-defun ejc-complete-query (result-file-path
&key
start-time
status
display-result
mode
connection-name
db)
"Called by Clojure side, when SQL evaluation thread completes."
(ejc-spinner-stop)
(if result-file-path
(setq ejc-result-file-path result-file-path))
(if display-result
(ejc-show-last-result :mode mode
:connection-name connection-name
:db db))
(if (and start-time status)
(ejc-message-query-done start-time status))
nil)
(cl-defun ejc-cancel-query (&key start-time)
"Terminate current (long) running query. Aimed to cancel SELECT queries.
Unsafe for INSERT/UPDATE/CREATE/ALTER queries."
(interactive)
(if (and (clomacs-get-connection "ejc-sql")
(ejc--is-query-running-p))
(let ((start-time (ejc--cancel-query)))
(ejc-spinner-stop)
(ejc-message-query-done start-time :terminated))
(keyboard-quit)))
(defun ejc-describe-table (table-name)
"Describe SQL table TABLE-NAME (default table name - word around the point)."
(interactive (ejc-get-prompt-symbol-under-point "Describe table"))
(ejc-check-connection)
(let* ((owner (car (split-string table-name "\\.")))
(table (cadr (split-string table-name "\\."))))
(when (not table)
(setq table owner)
(setq owner nil))
(ejc--describe-table :db ejc-db
:connection-name ejc-connection-name
:table table
:owner owner
:result-file (ejc-next-result-file-path))))
(defun ejc-describe-entity (entity-name)
"Describe SQL entity ENTITY-NAME - function, procedure, type or view
(default entity name - word around the point)."
(interactive (ejc-get-prompt-symbol-under-point "Describe entity"))
(ejc-check-connection)
(ejc-get-entity-description ejc-db
ejc-connection-name
entity-name
(ejc-next-result-file-path)))
(cl-defun ejc-eval-user-sql (sql &key rows-limit sync display-result)
"User starts SQL evaluation process."
(message "Processing SQL query...")
(ejc-eval-sql-and-log ejc-db
sql
:rows-limit rows-limit
:start-time (current-time)
:sync sync
:display-result display-result))
;;;###autoload
(defun ejc-eval-user-sql-region (beg end)
"Evaluate SQL bounded by the selection area."
(interactive "r")
(ejc-check-connection)
(let ((sql (buffer-substring beg end)))
(ejc-eval-user-sql sql
:display-result t)))
;;;###autoload
(cl-defun ejc-eval-user-sql-at-point (&key
sync
beg
end
(display-result t))
"Evaluate SQL bounded by the `ejc-sql-separator' or/and buffer
boundaries."
(interactive)
(ejc-check-connection)
(ejc-flash-this-sql :beg beg
:end end)
(ejc-eval-user-sql (ejc-get-sql-at-point :beg beg :end end)
:sync sync
:display-result display-result))
;;;###autoload
(defun ejc-show-tables-list ()
"Output tables list."
(interactive)
(ejc-check-connection)
(ejc-eval-user-sql
(ejc-select-db-meta-script ejc-db :all-tables)
:rows-limit 0
:display-result t))
;;;###autoload
(defun ejc-show-views-list ()
"Output views list."
(interactive)
(ejc-check-connection)
(ejc-eval-user-sql
(ejc-select-db-meta-script ejc-db :views)
:rows-limit 0
:display-result t))
;;;###autoload
(defun ejc-show-user-types-list (&optional owner)
"Output user types list."
(interactive)
(ejc-check-connection)
(ejc-eval-user-sql (ejc-select-db-meta-script ejc-db :types
:owner owner)))
;;;###autoload
(defun ejc-show-constraints-list (&optional owner table)
"Output constraints list."
(interactive)
(ejc-check-connection)
(ejc-eval-user-sql (ejc-select-db-meta-script ejc-db :constraints
:owner owner
:table table)))
;;;###autoload
(defun ejc-show-procedures-list ()
"Output procedures list."
(interactive)
(ejc-check-connection)
(ejc-eval-user-sql
(ejc-select-db-meta-script ejc-db :procedures
:owner (ejc-get-this-owner ejc-db))
:rows-limit 0
:display-result t))
;;;###autoload
(defun ejc-get-temp-editor-buffer (&optional num)
(interactive "P")
"Switch to buffer dedicated to ad-hoc edit and SQL scripts.
If the buffer is not exists - create it.
Buffer can be saved to file with `ejc-temp-editor-file' path."
(interactive)
(let* ((tmp-file-name (if num
(format "%s-%s"
ejc-temp-editor-buffer-name
(if (numberp num)
(int-to-string num)
num))
ejc-temp-editor-buffer-name))
(tmp-file-path (progn
(unless (file-exists-p ejc-temp-editor-file-path)
(make-directory ejc-temp-editor-file-path t))
(expand-file-name (concat tmp-file-name ".sql")
ejc-temp-editor-file-path)))
(tmp-buffer-name (format "*%s*" tmp-file-name)))
(if (get-buffer tmp-buffer-name)
(switch-to-buffer tmp-buffer-name)
(progn
(find-file tmp-file-path)
(rename-buffer tmp-buffer-name)
(sql-mode)
(auto-fill-mode t)
(auto-complete-mode t)
(ejc-ac-setup)
(ejc-add-connection)
(get-buffer tmp-buffer-name)))))
(defun ejc-open-log ()
(interactive)
(find-file-read-only (ejc-get-log-file-path))
(end-of-buffer))
;;;###autoload
(defun ejc-version ()
"Get the ejc-sql version as string."
(interactive)
(if (require 'pkg-info nil t)
(message "ejc-sql %s" (pkg-info-version-info 'ejc-sql))
(error "Cannot determine version without package pkg-info")))
(provide 'ejc-sql)
;;; ejc-sql.el ends here