/
esqlite.el
1762 lines (1545 loc) · 59.5 KB
/
esqlite.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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; esqlite.el --- Manipulate sqlite file from Emacs
;; Author: Masahiro Hayashi <mhayashi1120@gmail.com>
;; Keywords: data
;; URL: https://github.com/mhayashi1120/Emacs-esqlite
;; Emacs: GNU Emacs 24 or later
;; Package-Requires: ((pcsv "1.3.3"))
;; Version: 0.3.1
;; 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 3, 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; esqlite.el is a implementation to handle sqlite database.
;; (version 3 or later)
;; Following functions are provided:
;; * Read sqlite row as list of string.
;; * Async read sqlite row as list of string.
;; * sqlite process with being stationed
;; * Construct sqlite SQL.
;; * Escape SQL value to construct SQL
;; * Some of basic utilities.
;; * NULL handling (denote as :null keyword)
;; Following environments are tested:
;; * Windows7 cygwin64 with fakecygpty (sqlite 3.8.2)
;; * Windows7 native binary (Not enough works)
;; * Debian Linux (sqlite 3.7.13)
;; ## Install:
;; Please install sqlite command. (http://www.sqlite.org/)
;; Please install this package from MELPA. (http://melpa.org/)
;; ## Usage:
;; See the online document:
;; https://github.com/mhayashi1120/Emacs-esqlite
;;; TODO:
;;; Code:
(require 'cl-lib)
(require 'pcsv)
(defgroup esqlite ()
"Manipulate sqlite database."
:prefix "esqlite-"
:group 'applications)
(defcustom esqlite-sqlite-program "sqlite3"
"Command name or path to command.
Default is the latest release of sqlite."
:group 'esqlite
:type '(choice file string))
;;;
;;; Basic utilities
;;;
(put 'esqlite-error 'error-conditions
'(error esqlite-error))
(put 'esqlite-error 'error-message "esqlite")
(put 'esqlite-unterminate-query 'error-conditions
'(error esqlite-error esqlite-unterminate-query))
(put 'esqlite-unterminate-query 'error-message "esqlite fatal")
(defun esqlite--error (fmt &rest args)
(let ((msg (apply 'format fmt args)))
(signal 'esqlite-error (list msg))))
(defun esqlite--fatal (symbol fmt &rest args)
(let ((msg (apply 'format fmt args)))
(signal symbol (list msg))))
(defun esqlite-parse-replace (string replace-table)
(cl-loop with table = replace-table
with prev
with constructor =
(if (multibyte-string-p string)
'concat
(lambda (lis)
(apply 'unibyte-string lis)))
for c across string
concat (let ((pair (assq c table)))
(cond
((not pair)
(setq table replace-table)
(prog1
(funcall constructor (nreverse (cons c prev)))
(setq prev nil)))
((stringp (cdr pair))
(when (multibyte-string-p (cdr pair))
(esqlite--error "Assert (must be a unibyte)"))
(setq table replace-table)
(setq prev nil)
(cdr pair))
((consp (cdr pair))
(setq prev (cons c prev))
(setq table (cdr pair))
nil)
(t
(esqlite--error "Assert (Not supported type)"))))))
(defun esqlite-object= (s1 s2)
"Return t if object name is equals in database."
(and (stringp s1)
(stringp s2)
(eq (compare-strings s1 nil nil s2 nil nil t) t)))
(defun esqlite-object-assoc (key alist)
"`assoc' with ignore case"
(assoc-string key alist t))
(defun esqlite-object-member (elt list)
"`member' with ignore case"
(member-ignore-case elt list))
(defun esqlite-object-rassoc (key alist)
"`rassoc' with ignore case"
(cl-loop for cell in alist
if (esqlite-object= key (cdr-safe cell))
return cell))
(defun esqlite-trim (text)
"Remove head/tail whitespaces from TEXT.
Do not use this function to huge TEXT."
;; sql query may be not a huge text.
;; so non-greedy match to text.
(if (string-match "\\`[\s\t\n]*\\(.*?\\)[\s\t\n]*\\'" text)
(match-string 1 text)
;; never reach here
text))
(defun esqlite-value= (value1 value2)
"Trinary logic to compare equality."
(cond
((or (eq value1 :null) (eq value2 :null))
:null)
((equal value1 value2))))
;;;
;;; URI filenames
;;;
;;;###autoload
(defun esqlite-filename-to-uri (file &optional queries)
"Construct URI filenames from FILE.
\(esqlite-filename-to-uri \"/path/to/sqlite.db\" '((\"mode\" \"ro\") (\"cache\" \"shared\")))
http://www.sqlite.org/uri.html
"
(when (memq system-type '(windows-nt))
(setq file (replace-regexp-in-string "\\\\" "/" file)))
(concat
"file:"
(and (file-name-absolute-p file) "/")
(mapconcat
'identity
(mapcar
(lambda (x)
(setq x (replace-regexp-in-string "[?]" "%3f" x))
(setq x (replace-regexp-in-string "#" "%23" x))
x)
(split-string file "/" t))
"/")
(and queries "?")
(and queries (url-build-query-string queries))))
(defun esqlite-uri-to-filename (uri)
"Extract filename from URI."
(cl-destructuring-bind (file _)
(esqlite-uri-parse uri)
file))
(defun esqlite-uri-parse (uri)
"Parse URI to filename and query parameters."
(unless (string-match "\\`file:\\(.*\\)" uri)
(error "Unable match file prefix %s" uri))
(let ((body (match-string 1 uri)))
(unless (string-match "\\`\\(.*?\\)\\(?:\\?\\(.*\\)\\)?\\'" body)
(error "Fatal parse error"))
(let* ((path (match-string 1 body))
(qs (match-string 2 body))
(file (url-unhex-string path))
(queries
(and qs
(url-parse-query-string qs))))
;; handle windows path
(when (string-match "\\`/\\([a-zA-Z]:/.*\\)" file)
(setq file (match-string 1 file)))
(list file queries))))
;;;
;;; System deps
;;;
(defcustom esqlite-mswin-fakecygpty-program "fakecygpty.exe"
"sqlite command on cygwin cannot work since no pty.
Please download and install fakecygpty (Google it!!)"
:group 'esqlite
:type '(choice file string))
(defun esqlite-mswin-native-p ()
(and (memq system-type '(windows-nt))
(not (esqlite-mswin-cygwin-p))))
(defun esqlite-mswin-cygwin-p ()
(and (memq system-type '(windows-nt))
(executable-find "cygpath")
(let ((program (executable-find esqlite-sqlite-program)))
(and program
;; check program is under the cygwin installed directory.
(let* ((rootdir
(let* ((line (esqlite-mswin-cygpath "/" "windows"))
(root (expand-file-name line)))
(file-name-as-directory root)))
(regexp (concat "\\`" (regexp-quote rootdir))))
(string-match regexp program))))
t))
(defun esqlite-mswin-cygpath (file type)
(with-temp-buffer
(let ((code (call-process "cygpath" nil t nil "-t" type file)))
(unless (= code 0)
(esqlite--error "cygpath failed with %d" code))
(goto-char (point-min))
(buffer-substring
(point-min) (point-at-eol)))))
;;;
;;; Basic utilities to handle esqlite i/o.
;;;
;;
;; Generate temporary name
;;
(defun esqlite--temp-null (query)
;; esqlite command nullvalue assigned to 20 chars (19 + null).
(esqlite--random-text query 19))
;; * random char restrict to `a-zA-Z0-9+/' (except last `=')
;; * md5 have 16 bytes
;; * base64 encode 16 bytes -> 44 chars
;; * to trim last `=', only use md5 first 15 bytes make (* 4 (/ 15 3)) 20 bytes
(defun esqlite--random-text (seed length)
(cl-loop for i from 0 to (/ (1- length) 20)
concat (md5 (format "%d:%s:%s" i (current-time) seed))
into hash
finally return
;; only first 15 bytes
(cl-loop for i from 0 below (- (length hash) 2) by 2
;; make random unibyte string
collect (let ((hex (substring hash i (+ i 2))))
(string-to-number hex 16))
into res
finally return
;; md5 hex fold to base64 area
(let* ((unibytes (apply 'unibyte-string res))
(b64 (base64-encode-string unibytes t)))
(substring b64 0 length)))))
(defun esqlite-unique-name (stream prefix &optional seed)
(cl-loop with objects = (esqlite-read-all-objects stream)
with full-name
while (let ((random-text (esqlite--random-text
(or seed "") 40)))
(setq full-name (format "%s_%s" prefix random-text))
(member full-name objects))
finally return full-name))
(defconst esqlite-control-code-regexp
"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
(defun esqlite--check-control-code (command)
;; except TAB, CR, LF
(when (string-match esqlite-control-code-regexp command)
(error "Invalid sql statement (May cause stall the process)")))
(defun esqlite--terminate-command (command)
(esqlite--check-control-code command)
(cond
((not (string-match "\n\\'" command))
(concat command "\n"))
(t
command)))
(defun esqlite--terminate-statement (sql)
(esqlite--check-control-code sql)
(cond
((not (string-match ";[\s\t\n]*\\'" sql))
(concat sql ";\n"))
((not (string-match "\n\\'" sql))
(concat sql "\n"))
(t sql)))
;;
;; constant / system dependent
;;
(defconst esqlite-rowid-columns
'("_ROWID_" "ROWID" "OID"))
;;;###autoload
(defconst esqlite-file-header-regexp "\\`SQLite format 3\x00"
"Now support only Sqlite3.")
;;;###autoload
(defun esqlite-file-guessed-database-p (file)
"Guess the FILE is a Sqlite database or not."
(and (file-regular-p file)
(with-temp-buffer
(insert-file-contents file nil 0 256)
(looking-at esqlite-file-header-regexp))))
;;;###autoload
(defun esqlite-sqlite-installed-p ()
"Return non-nil if `esqlite-sqlite-program' is installed."
(and (stringp esqlite-sqlite-program)
(executable-find esqlite-sqlite-program)))
(defun esqlite-check-sqlite-program ()
(unless (stringp esqlite-sqlite-program)
(esqlite--error "No valid sqlite program"))
(unless (executable-find esqlite-sqlite-program)
(esqlite--error "%s not found" esqlite-sqlite-program)))
(defun esqlite-sqlite-version ()
"Get sqlite command version as string."
(with-temp-buffer
(call-process esqlite-sqlite-program nil t nil "--version")
(goto-char (point-min))
(unless (looking-at "\\([0-9.]+\\)")
(error "Version not found"))
(match-string 1)))
;;FIXME try to fix async process in Mac OS
(defun esqlite--check-async-interface ()
(when (memq system-type '(darwin))
(esqlite--error
"Currently this system cannot handle async family.")))
;;
;; process
;;
(defvar esqlite-process-coding-system
(let* ((syseol (let ((type (coding-system-eol-type
;; guess esqlite command environment
default-terminal-coding-system)))
(cond
((or (symbolp type)
(numberp type))
type)
((vectorp type)
(coding-system-eol-type (aref type 0))))))
;; utf-8 as the default coding-system of Sqlite database.
(basecs 'utf-8)
(cs
(coding-system-change-eol-conversion basecs syseol)))
(cons cs cs))
"Temporarily change coding system by this hiding parameter.
Normally, no need to use this parameter.")
(defun esqlite--process-coding-system ()
(cond
((consp esqlite-process-coding-system)
esqlite-process-coding-system)
((coding-system-p esqlite-process-coding-system)
(cons esqlite-process-coding-system
esqlite-process-coding-system))
(t default-process-coding-system)))
(eval-and-compile
(defconst esqlite--prompt "sqlite> "))
;; continue prompt is empty.
;; otherwise, first row of SELECT contains the continue prompt.
(eval-and-compile
(defconst esqlite--prompt-continue " ...> "))
(defconst esqlite--prompt-re-any-continue
(eval-when-compile
(concat
"\\("
(regexp-opt (list esqlite--prompt esqlite--prompt-continue))
"*"
(regexp-quote esqlite--prompt-continue)
"\\)")))
(defconst esqlite--prompt-re-any-proceeding
(eval-when-compile
(concat
"\\("
(regexp-opt (list esqlite--prompt esqlite--prompt-continue))
"+\\)"
;; there is some char after continue/prompt
".")))
(defconst esqlite--prompt-re-next
(eval-when-compile
(concat
"\\("
(regexp-opt (list esqlite--prompt esqlite--prompt-continue))
"*\\)"
(regexp-quote esqlite--prompt)
"\\'")))
(defun esqlite--prompt-eob (regexp)
(save-excursion
(goto-char (point-max))
(forward-line 0)
(looking-at regexp)))
(defun esqlite--prompt-p ()
;; when executed sql contains newline, continue prompt displayed
;; before last prompt "sqlite> "
(esqlite--prompt-eob esqlite--prompt-re-next))
(defvar esqlite--default-init-file nil)
;; To avoid user initialization file ~/.sqliterc
(defun esqlite--default-init-file (&optional refresh)
(or (and (not refresh)
(stringp esqlite--default-init-file)
(file-exists-p esqlite--default-init-file)
esqlite--default-init-file)
(setq esqlite--default-init-file
(let ((file (make-temp-file "emacs-esqlite-")))
(with-temp-buffer
(insert (format ".prompt \"%s\" \"%s\"\n"
esqlite--prompt
esqlite--prompt-continue))
;; Later 3.8.6 "-csv" output contains CR (\r) before LF (\n)
(when (version<= "3.8.6" (esqlite-sqlite-version))
;; FIXME: This is working for "-csv" option
;; However, `.separator' first argument "," seems no effect for csv
;; I think that sqlite3 may be confusing specification.
;; `-newline' argument doesn't have such confusion.
;; I probably should use this option.
(insert ".separator \",\" \"\\n\"\n"))
(write-region (point-min) (point-max) file nil 'no-msg))
file))))
(defmacro esqlite--with-env (&rest form)
`(let ((process-environment (copy-sequence process-environment))
;; non pty resulting in echoing query.
(process-connection-type t)
(default-process-coding-system
(esqlite--process-coding-system)))
;; currently no meanings of this
;; in the future release may support i18n.
(setenv "LANG" "C")
;; execute process safety set the value.
(setenv "TERM" "dumb")
;; FIXME TODO:
;; suppress to save .sqlite_history to your home
;; curretly sqlite3 shell.c use low level api read from
;; /etc/passwd on Unix system
;; (setenv "HOME" esqlite--temp-homedir)
;; for windows
;; (setenv "USERPROFILE" esqlite--temp-homedir)
,@form))
(defmacro esqlite--with-process (proc &rest form)
(declare (indent 1) (debug t))
`(let ((buf (process-buffer ,proc)))
(when (buffer-live-p buf)
(with-current-buffer buf
,@form))))
(defmacro esqlite--with-parse (proc event &rest form)
"Execute FORM in PROC buffer with appended EVENT.
This form check syntax error report from esqlite command."
(declare (indent 2) (debug t))
`(esqlite--with-process proc
(save-excursion
(goto-char (point-max))
(insert event)
(goto-char (point-min))
,@form)))
(defun esqlite--start-process (buffer &rest args)
(esqlite--with-env
(let ((cmdline (cons esqlite-sqlite-program args))
(cygwinp (esqlite-mswin-cygwin-p)))
(when cygwinp
(unless esqlite-mswin-fakecygpty-program
(error "%s %s"
"esqlite on cygwin cannot work unless `fakecygpty'"
"see `esqlite-mswin-fakecygpty-program' settings"))
(setq cmdline
(cons esqlite-mswin-fakecygpty-program cmdline)))
(apply 'start-process "Esqlite" buffer cmdline))))
(defun esqlite--call-process-region (buffer start end &rest args)
(esqlite--with-env
(apply 'call-process-region
start end esqlite-sqlite-program nil buffer nil args)))
(defun esqlite--safe-expand-file (file-or-uri)
(cond
((string-match "\\`file:" file-or-uri)
;; URI Filenames:
;; http://www.sqlite.org/uri.html
file-or-uri)
(t
(expand-file-name file-or-uri))))
(defun esqlite--expand-db-name (file-or-uri)
(cond
((string-match "\\`file:" file-or-uri)
;; URI Filenames:
;; http://www.sqlite.org/uri.html
file-or-uri)
((esqlite-mswin-cygwin-p)
;; esqlite on cygwin cannot accept c:/hoge like path.
;; must convert /cygdrive/c/hoge
;; But seems accept such path in -init option.
(esqlite-mswin-cygpath file-or-uri "unix"))
(t
(expand-file-name file-or-uri))))
(defun esqlite--create-process-buffer ()
(generate-new-buffer " *esqlite work* "))
(defun esqlite-start-csv-process (file-or-key &optional query nullvalue &rest args)
"[Low level API] Start async sqlite process.
If QUERY is specified, exit immediately after execute the QUERY.
Cygwin: FILE name contains multibyte char, may fail to open FILE as database."
(let* ((init (esqlite--default-init-file))
(file (and (stringp file-or-key) file-or-key))
(key (and (symbolp file-or-key) file-or-key))
(db (and file (list (esqlite--expand-db-name file))))
(filename (and file (esqlite--safe-expand-file file)))
(null (or nullvalue (esqlite--temp-null query)))
(query (and query (esqlite--terminate-statement query)))
(args `(
"-interactive"
"-init" ,init
"-csv"
"-nullvalue" ,null
;; prior than preceeding args
,@args
,@db))
(buf (esqlite--create-process-buffer))
(proc (apply 'esqlite--start-process buf args)))
(process-put proc 'esqlite-init-file init)
(process-put proc 'esqlite-filename filename)
(process-put proc 'esqlite-null-value null)
(process-put proc 'esqlite-memory-key key)
(when query
;; to clear initializing message and first prompt
(esqlite--with-process proc
(esqlite--until-prompt proc)
(erase-buffer))
(process-send-string proc query)
;; imitate calling command
;; e.g. esqlite db.esqlite "select some,of,query from table"
(process-send-string proc ".exit\n"))
proc))
(defun esqlite-call-csv-process (file query &optional nullvalue &rest args)
"[Low level API] Call sqlite process.
Cygwin: FILE contains multibyte char, may fail to open FILE as database."
(let* ((init (esqlite--default-init-file))
(db (esqlite--expand-db-name file))
(null (or nullvalue (esqlite--temp-null query)))
(args `(
"-batch"
"-init" ,init
"-csv"
"-nullvalue" ,null
;; prior than preceeding args
,@args
,db)))
;; Do not use `call-process' this case. On windows if argument is
;; a multibyte string, command argument may be destroyed.
;; Although `call-process-region' may have same problem, but
;; decrease the risk of this.
;; For example, DB file might have a multibyte char.
(apply
'esqlite--call-process-region
(current-buffer)
;; `call-process-region' start argument accept string
(esqlite--terminate-statement query) nil
args)))
;;
;; Sqlite text -> Emacs data
;;
;; http://www.sqlite.org/syntaxdiagrams.html#numeric-literal
(defconst esqlite-numeric-literal-regexp
(eval-when-compile
(concat
"\\`"
"[+-]?"
"\\([0-9]+\\(\\.\\([0-9]*\\)\\)?\\|\\.[0-9]+\\)"
"\\(E[+-]?[0-9]+\\)?"
"\\'")))
(defun esqlite-numeric-text-p (text)
"Utility function to check TEXT is numeric."
(and (string-match esqlite-numeric-literal-regexp text)
t))
(defun esqlite-hex-to-bytes (hex)
"To get the hex blob data as a unibyte string.
NOTE: If BLOB data contains non text byte (null-byte), this
case `esqlite-*-read' function family may return truncated bytes.
This case you should use HEX Sqlite function in SQL and decode it
with this function.
This function is not checking hex is valid."
(apply 'unibyte-string
(cl-loop for start from 0 below (length hex) by 2
for end from (if (eq (logand (length hex) 1) 1) 1 2) by 2
collect (string-to-number (substring hex start end) 16))))
;;
;; sleep in process filter
;;
(defvar esqlite-sleep-second
;;FIXME
;; This check calculate response of external command which does not accept
;; from process output.
(apply 'min (cl-loop for _ in '(1 2 3 4 5)
collect
(let ((start (float-time)))
;; probablly every system have "echo" ...
(call-process "echo" nil nil nil "1")
(let ((end (float-time)))
(- end start))))))
(defun esqlite-sleep (proc)
;; Other code affect to buffer while `sleep-for'.
;; TODO why need save-excursion? timer? filter? I can't get clue.
(save-excursion
;; Achieve like a asynchronous behavior (ex: draw mode line)
(redisplay)
(accept-process-output proc esqlite-sleep-second)))
;;
;; handling sqlite prompt
;;
(defun esqlite--try-to-delete-halfway-prompt ()
(when (and
(or (looking-at esqlite--prompt-re-any-continue)
(looking-at esqlite--prompt-re-next)
(looking-at esqlite--prompt-re-any-proceeding))
(match-beginning 1))
(replace-match "" nil nil nil 1)))
;; delete continue prompt and return its count
(defun esqlite--try-to-delete-continue ()
(let ((i 0))
(catch 'done
(while t
(cond
((looking-at (concat (regexp-quote esqlite--prompt) "\\'"))
(throw 'done t))
((looking-at (concat (regexp-quote esqlite--prompt)))
(replace-match "" nil nil nil 0)
(setq i (1+ i)))
((looking-at (concat (regexp-quote esqlite--prompt-continue)))
(replace-match "" nil nil nil 0)
(setq i (1+ i)))
(t
(throw 'done t)))))
i))
;; read "Error:" sqlite message from current buffer
;; may delete some prompts if any.
(defun esqlite--read-syntax-error-at-point ()
(let* ((prompt-count (esqlite--try-to-delete-continue))
(errmsg (esqlite--read-syntax-error)))
(list prompt-count errmsg)))
(defun esqlite--read-syntax-error ()
(and (looking-at "^Error: \\(.*\\)")
(match-string 1)))
(defun esqlite--until-prompt (proc)
(while (and (not (process-get proc 'esqlite-stream-continue-prompt))
(eq (process-status proc) 'run)
(not (esqlite--prompt-p)))
(esqlite-sleep proc)))
;;
;; read csv from esqlite
;;
(defun esqlite--read-csv-line (&optional null)
(esqlite--try-to-delete-halfway-prompt)
(let ((errmsg (esqlite--read-syntax-error)))
(when errmsg
(esqlite--error "%s" errmsg)))
(let ((first (point))
(line (pcsv-read-line)))
;; end of line is not a newline.
;; means ouput is progressing, otherwise prompt.
(unless (bolp)
(goto-char first)
(signal 'invalid-read-syntax nil))
(cl-loop for datum in line
collect
;; handling `esqlite--temp-null'
(if (equal datum null)
:null
datum))))
(defun esqlite--read-csv-line-with-deletion (null)
(when (memq system-type '(
windows-nt
;; FIXME: more investigate
;; darwin may have \r in process buffer.
;; cleanup the CR just in case.
;; https://github.com/mhayashi1120/Emacs-esqlite/issues/2
darwin
))
;; wash unquoted carriage return
(save-excursion
(while (re-search-forward "\r$" nil t)
(replace-match ""))))
(let ((start (point))
(row (esqlite--read-csv-line null)))
(delete-region start (point))
row))
;; Call with one arg which is parsed row.
;; This variable is intended to use in local dynamic binding.
(defvar esqlite-read-callback nil)
;; See `esqlite--read-csv-with-deletion-0'
(defun esqlite--read-csv-with-deletion/callback (null callback)
(let (res)
(condition-case nil
(while (not (eobp))
(let ((start (point))
(row (esqlite--read-csv-line-with-deletion null)))
(setq res (cons row res))
(funcall callback row)))
;; output is proceeding from process
;; finish the reading
(invalid-read-syntax nil))
(nreverse res)))
;; See `esqlite--read-csv-with-deletion/callback'
(defun esqlite--read-csv-with-deletion-0 (null)
(let (res)
(condition-case nil
(while (not (eobp))
(let ((start (point))
(row (esqlite--read-csv-line-with-deletion null)))
(setq res (cons row res))))
;; output is proceeding from process
;; finish the reading
(invalid-read-syntax nil))
(nreverse res)))
(defun esqlite--read-csv-with-deletion (null)
"Read csv data from current point.
Delete csv data if reading was succeeded."
(if esqlite-read-callback
(esqlite--read-csv-with-deletion/callback
null esqlite-read-callback)
(esqlite--read-csv-with-deletion-0 null)))
;;
;; Escape text (Emacs data -> Sqlite text)
;;
(defun esqlite-escape--like-table (escape-char &optional override)
(let ((escape (or escape-char ?\\)))
(append
override
`((?\% . ,(format "%c%%" escape))
(?\_ . ,(format "%c_" escape))
(,escape . ,(format "%c%c" escape escape))))))
;;;###autoload
(defun esqlite-escape-string (string &optional quote-char)
"Escape STRING as a sqlite string object context.
Optional QUOTE-CHAR arg indicate quote-char
e.g.
\(let ((user-input \"a\\\"'b\"))
(format \"SELECT * FROM T WHERE a = '%s'\" \
\(esqlite-escape-string user-input ?\\')))
=> \"SELECT * FROM T WHERE a = 'a\\\"''b'\"
\(let ((user-input \"a\\\"'b\"))
(format \"SELECT * FROM T WHERE a = \\\"%s\\\"\" \
\(esqlite-escape-string user-input ?\\\")))
=> \"SELECT * FROM T WHERE a = \\\"a\\\"\\\"'b\\\"\"
"
(setq quote-char (or quote-char ?\'))
(esqlite-parse-replace
string
`((,quote-char . ,(format "%c%c" quote-char quote-char)))))
;;;###autoload
(defun esqlite-escape-like (query &optional escape-char)
"Escape QUERY as a sql LIKE context.
This function is not quote single-quote (') you should use with
`esqlite-escape-string' or `esqlite-format-text'.
ESCAPE-CHAR is optional char (default '\\') for escape sequence expressed
following esqlite syntax.
e.g. fuzzy search of \"100%\" text in `value' column in `hoge' table.
SELECT * FROM hoge WHERE value LIKE '%100\\%%' ESCAPE '\\'
To create the like pattern:
=> (concat \"%\" (esqlite-escape-like \"100%\" ?\\\\) \"%\")
=> \"%100\\%%\""
(unless (or (null escape-char)
(and (<= 0 escape-char)
(<= escape-char 127)))
(esqlite--error "escape-char must be a ascii"))
(esqlite-parse-replace
query
(esqlite-escape--like-table escape-char)))
;;;###autoload
(defun esqlite-format-text (string &optional quote-char)
"Convenience function to provide make quoted STRING in sql."
(setq quote-char (or quote-char ?\'))
(format "%c%s%c"
quote-char
(esqlite-escape-string string quote-char)
quote-char))
(defun esqlite-format-object (object)
(esqlite-format-text object ?\"))
(defun esqlite-format-value (object)
(cond
((stringp object)
(cond
(
;; unsafe ascii as a blob data.
;; some of exception, control chars must be escaped
;; as a blob
(string-match esqlite-control-code-regexp object)
(esqlite-format-blob object))
(
;; only ascii (printable chars) or empty string.
(or (string-match "\\`[\t\n\r\x20-\x7e]*\\'" object)
(multibyte-string-p object))
(esqlite-format-text object))
(t
;; unibyte string
(esqlite-format-blob object))))
((numberp object)
(prin1-to-string object))
((eq object :null) "null")
((listp object)
(mapconcat 'esqlite-format-value object ", "))
(t
(esqlite--error "Not a supported type"))))
(defun esqlite-format-blob (text)
(let ((unibyte
(cond
((not (stringp text))
(esqlite--error "Not a string"))
((multibyte-string-p text)
(encode-coding-string text 'utf-8))
(t text))))
(format "x'%s'" (mapconcat (lambda (x) (format "%02x" x))
unibyte ""))))
(eval-and-compile
(defvar esqlite-format--table
(eval-when-compile
'(
("s" . (lambda (x)
(cond
((stringp x) x)
((numberp x) (number-to-string x))
(t (prin1-to-string x)))))
("t" . esqlite-escape-string)
("T" . esqlite-format-text)
("l" . esqlite-escape-like)
("L" . (lambda (x)
(concat
(esqlite-format-text (esqlite-escape-like x))
" ESCAPE '\\' ")))
;; some database object
("o" . esqlite-format-object)
;; column list
("O" . (lambda (l)
(mapconcat (lambda (x) (esqlite-format-object x))
l ", ")))
;; some value list (string, number, list) with properly quoted
("V" . esqlite-format-value)
;; format byte string to x'ffee0011' like literal
("X" . esqlite-format-blob)
))))
;;;###autoload
(defun esqlite-prepare (fmt &rest keywords)
"Prepare SQL with FMT like `format'.
Prepared SQL statement may contain a text-property `esqlite-prepared'
which should not be removed by programmer.
FMT is a string or list of string.
each list item join with newline.
Following each directive accept arg which contains keyword name.
Undefined keyword is simply ignored.
e.g.
\(esqlite-prepare \"SELECT * FROM %o{some-table} WHERE id = %s{some-value}\"\
:some-table \"tbl\")
=> \"SELECT * FROM \"tbl\" WHERE id = %s{some-value}\"
%s: raw text (With no escape)
%t: escape text
%T: same as %t but with quote
%l: escape LIKE pattern escape char is '\\'
%L: similar to %l except that with quoting/escaping and ESCAPE statement
%o: escape db object with quote
%O: escape db objects with quote (joined by \", \")
%V: escape sql value(s) with quote if need
(if list, joined by \", \" without paren)
%X: escape text as hex notation.
multibyte string is encoded as utf-8 byte array."
(with-temp-buffer
(when (listp fmt)
(setq fmt (mapconcat 'identity fmt "\n")))
(insert fmt)
(goto-char (point-min))
(let ((fmt-regexp
(eval-when-compile
(concat
(regexp-opt (mapcar 'car esqlite-format--table) t)
;; keyword name
"\\(?:{\\(.+?\\)}\\)")))
(case-fold-search nil))
(while (search-forward "%" nil t)
(cond
((get-text-property (point) 'esqlite-prepared))
((eq (char-after) ?%)
(delete-char 1)
(put-text-property (1- (point)) (point) 'esqlite-prepared t))
((looking-at fmt-regexp)
(let* ((spec (match-string 1))
(varname (match-string 2))
(keysym (and varname (intern-soft (concat ":" varname))))
(fn (assoc-default spec esqlite-format--table))
(begin (1- (point)))
(end (match-end 0))
obj)
(unless fn
(esqlite--error "Invalid format character: `%%%s'" spec))
(unless (functionp fn)
(esqlite--error "Assert"))
(cond
((and keysym (plist-member keywords keysym))
;; Delete formatter directive
(delete-region begin end)
(setq obj (plist-get keywords keysym))
(let ((text (funcall fn obj)))
(insert text))
(put-text-property begin (point) 'esqlite-prepared t)))))
(t
(esqlite--error "No valid format")))))
(buffer-string)))
;;;###autoload
(defun esqlite-format (esqlite-fmt &rest esqlite-objects)
"This function is obsoleted should change to `esqlite-prepare'.
This function is not working under `lexical-binding' is t.