-
Notifications
You must be signed in to change notification settings - Fork 9
/
org-sql.el
3786 lines (3470 loc) · 166 KB
/
org-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
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
;;; org-sql.el --- Org-Mode SQL converter -*- lexical-binding: t; -*-
;; Copyright (C) 2021 Nathan Dwarshuis
;; Author: Nathan Dwarshuis <[email protected]>
;; Keywords: org-mode, data
;; Homepage: https://github.com/ndwarshuis/org-sql
;; Package-Requires: ((emacs "27.1") (s "1.13") (f "0.20.0") (dash "2.19.1") (org-ml "5.8.8"))
;; Version: 4.0.0
;; 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 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This code stores org buffers in a variety of SQL databases for use in
;; processing org-mode data outside of Emacs where SQL operations might be more
;; appropriate. Org files are stored according to the perspective of unique
;; org outline; any outline might reside in multiple identical files.
;; The rough process by which this occurs is:
;; 1) query state of org files on disk and in db (if any) and classify
;; files as 'updates', 'deletes', or 'inserts'
;; - updates: a file on disk is also in the database but the path on disk has
;; changed; this is the part that will be updated
;; - deletes: a file in the db is not on disk; therefore delete from db
;; - inserts: a file is on disk but not in the db, therefore insert into db
;; - NOTE: file equality will be assessed using a hash algorithm (eg md5)
;; - NOTE: in the case that a file on disk has changed and its path is also
;; in the db, this file will be deleted and reinserted
;; 2) convert the updates/deletes/inserts into database-specific SQL statements
;; - inserts will be constructed using `org-element'/`org-ml' from target
;; files on disk
;; 3) send SQL statements to the configured database
;; The code is arranged as follows:
;; - constants
;; - customization variables
;; - stateless functions
;; - stateful IO functions
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'dash)
(require 's)
(require 'f)
(require 'sql)
(require 'org)
(require 'org-clock)
(require 'org-ml)
;;;
;;; CONSTANTS
;;;
(eval-and-compile
(defconst org-sql--log-note-keys
'((:user . "%u")
(:user-full . "%U")
(:ts . "%t")
(:ts-active . "%T")
(:short-ts . "%d")
(:short-ts-active . "%D")
(:old-state . "%S")
(:new-state . "%s"))
"Keywords for placeholders used in `org-log-note-headings'.")
(defconst org-sql--log-note-replacements
(->> (-map #'cdr org-sql--log-note-keys) (--map (cons it it)))
"A list to simplify placeholders in `org-log-note-headings'.
This is only used in combination with `org-replace-escapes'")
(defconst org-sql--entry-keys
(append
(-map #'car org-sql--log-note-keys)
'(:outline-hash :note-text :header-text :old-ts :new-ts))
"Valid keys that may be used in logbook entry lists."))
(defconst org-sql--ignored-properties-default
'("ARCHIVE_ITAGS" "Effort")
"Property keys to be ignored when inserting in properties table.
It is assumed these are used elsewhere and thus it would be redundant
to store them. This is in addition to any properties specifified by
`org-sql-excluded-properties'.")
(defconst org-sql--content-timestamp-types
'(active active-range inactive inactive-range)
"Types of timestamps to include in the database.")
(eval-and-compile
(let ((outline_hash-char-length 32)
;; ASSUME all filesystems we would ever want to use have a path limit of
;; 255 chars (which is almost always true)
(file_path-varchar-length 255)
(tag-col '(:tag :desc "the text value of this tag"
:type varchar
:length 32))
(property-id-col '(:property_id :desc "id of this property"
:type integer))
(modifier-allowed-units '(hour day week month year)))
(cl-flet*
((mk-col
(default-desc fmt name other object notnull)
(let* ((d (if object (format fmt object) default-desc))
(k `(,name :desc ,d ,@other)))
(if notnull `(,@k :constraints (notnull)) k)))
(outline-hash-col
(&optional object notnull)
(mk-col "hash (MD5) of this org outline"
"hash (MD5) of the org outline with this %s"
:outline_hash `(:type char :length ,outline_hash-char-length)
object notnull))
(headline-id-col
(&optional object notnull)
(mk-col "id of this headline"
"id of the headline for this %s"
:headline_id '(:type integer) object notnull))
(timestamp-id-col
(&optional object notnull)
(mk-col "id of this timestamp"
"id of the timestamp for this %s"
:timestamp_id '(:type integer) object notnull))
(entry-id-col
(&optional object notnull)
(mk-col "id of this entry"
"id of the entry for this %s"
:entry_id '(:type integer) object notnull)))
;; NOTE double backticks to get the blocky rendering in Github
(defconst org-sql--table-alist
`((outlines
(desc "Each row stores the hash, size, and toplevel section for an org"
"file (here called an `outline`). Note that if there are"
"identical org files, only one `outline` will be stored in the"
"database (as determined by the unique hash) and the paths"
"shared the outline will be reflected in the `file_metadata`"
"table.")
(columns
,(outline-hash-col)
(:outline_size :desc "number of characters of the org outline"
:type integer
:constraints (notnull))
(:outline_lines :desc "number of lines in the org file"
:type integer
:constraints (notnull))
(:outline_preamble :desc "the content before the first headline"
:type text))
(constraints
(primary :keys (:outline_hash))))
(file_metadata
(desc "Each row stores filesystem metadata for one tracked org file.")
(columns
(:file_path :desc "path to org file"
:type varchar
:length ,file_path-varchar-length)
,(outline-hash-col "path" t)
(:file_uid :desc "UID of the file"
:type integer
:constraints (notnull))
(:file_gid :desc "GID of the file"
:type integer
:constraints (notnull))
(:file_modification_time :desc "time of the file's last modification"
:type integer
:constraints (notnull))
(:file_attr_change_time :desc "time of the file's last attribute change"
:type integer
:constraints (notnull))
(:file_modes :desc "permission mode bits for the file"
:type varchar
:length 10
:constraints (notnull)))
(constraints
(primary :keys (:file_path))
(foreign :ref outlines
:keys (:outline_hash)
:parent-keys (:outline_hash)
:on-delete cascade
:cardinality many-to-one)))
(headlines
(desc "Each row stores one headline in a given org outline.")
(columns
,(headline-id-col)
,(outline-hash-col "headline" t)
(:headline_text :desc ("raw text of the headline"
"without leading stars or tags")
:properties (:raw-value)
:type text
:constraints (notnull))
(:level :desc "the level of this headline"
:properties (:level)
:type integer
:constriants (notnull))
(:headline_index :desc "the order of this headline relative to its neighbors"
:type integer
:constriants (notnull))
(:keyword :desc "the TODO state keyword"
:properties (:todo-keyword)
:type text)
(:effort :desc "the value of the `Effort` property in minutes"
:type integer)
(:priority :desc "character value of the priority"
:properties (:priority)
:type text)
(:stats_cookie_type :desc ("type of the statistics cookie (the"
"`[n/d]` or `[p%]` at the end of some"
"headlines)")
:type enum
:allowed (fraction percent))
(:stats_cookie_value :desc "value of the statistics cookie (between 0 and 1)"
:type real)
(:is_archived :desc "TRUE if the headline has an ARCHIVE tag"
:properties (:archivedp)
:type boolean
:constraints (notnull))
(:is_commented :desc "TRUE if the headline has a COMMENT keyword"
:properties (:commentedp)
:type boolean
:constraints (notnull))
(:content :desc "the headline contents (everything after the planning entries, property-drawer, and/or logbook)"
:type text))
(constraints
(primary :keys (:headline_id))
(foreign :ref outlines
:keys (:outline_hash)
:parent-keys (:outline_hash)
:on-delete cascade
:cardinality many-or-none-to-one)))
(headline_closures
(desc "Each row stores the ancestor and depth of a headline"
"relationship. All headlines will have a 0-depth entry in which"
"`parent_id` and `headline_id` are equal.")
(columns
,(headline-id-col)
(:parent_id :desc "id of this headline's parent"
:type integer)
(:depth :desc "levels between this headline and the referred parent"
:type integer))
(constraints
(primary :keys (:headline_id :parent_id))
(foreign :ref headlines
:keys (:headline_id)
:parent-keys (:headline_id)
:on-delete cascade
:cardinality many-to-one)
(foreign :ref headlines
:keys (:parent_id)
:parent-keys (:headline_id)
:cardinality many-to-one)))
(timestamps
(desc "Each row stores one timestamp. Any timestamps in this"
"table that are not referenced in other tables are part of the"
"headlines's contents (the part after the logbook) or title.")
(columns
,(timestamp-id-col)
,(headline-id-col "timestamp" t)
(:raw_value :desc "text representation of this timestamp"
:properties (:raw-value)
:type text
:constraints (notnull))
(:is_active :desc "true if the timestamp is active"
:properties (:type)
:type boolean
:constraints (notnull))
(:time_start :desc "the start time (or only time) of this timestamp"
:properties (:year-start :month-start :day-start
:hour-start :minute-start)
:type integer
:constraints (notnull))
(:time_end :desc "the end time of this timestamp"
:properties (:year-end :month-end :day-end :hour-end
:minute-end)
:type integer)
(:start_is_long :desc ("true if the start time is in long format"
"(eg `[YYYY-MM-DD DOW HH:MM]` vs"
"`[YYYY-MM-DD DOW]`)")
:type boolean
:constraints (notnull))
(:end_is_long :desc ("true if the end time is in long format"
"(see `start_is_long`)")
:type boolean))
(constraints
(primary :keys (:timestamp_id))
(foreign :ref headlines
:keys (:headline_id)
:parent-keys (:headline_id)
:on-delete cascade
:cardinality many-or-none-to-one)))
(timestamp_warnings
(desc "Each row stores the warning component for a timestamp.")
(columns
,(timestamp-id-col "warning")
(:warning_value :desc "shift of this warning"
:properties (:warning-value)
:type integer)
(:warning_unit :desc "unit of this warning"
:properties (:warning-unit)
:type enum
:allowed ,modifier-allowed-units)
(:warning_type :desc "type of this warning"
:properties (:warning-type)
:type enum
:allowed (all first)))
(constraints
(primary :keys (:timestamp_id))
(foreign :ref timestamps
:keys (:timestamp_id)
:parent-keys (:timestamp_id)
:on-delete cascade
:cardinality one-or-none-to-one)))
(timestamp_repeaters
(desc "Each row stores the repeater component for a timestamp."
"If the repeater also has a habit appended to it, this will"
"be stored as well.")
(columns
,(timestamp-id-col "repeater")
(:repeater_value :desc "shift of this repeater"
:properties (:repeater-value)
:type integer
:constraints (notnull))
(:repeater_unit :desc "unit of this repeater"
:properties (:repeater-unit)
:type enum
:allowed ,modifier-allowed-units
:constraints (notnull))
(:repeater_type :desc "type of this repeater"
:type enum
:properties (:repeater-type)
:allowed (catch-up restart cumulate)
:constraints (notnull))
(:habit_value :desc "shift of this repeater's habit"
:type integer)
(:habit_unit :desc "unit of this repeaters habit"
:type enum
:allowed ,modifier-allowed-units))
(constraints
(primary :keys (:timestamp_id))
(foreign :ref timestamps
:keys (:timestamp_id)
:parent-keys (:timestamp_id)
:on-delete cascade
:cardinality one-or-none-to-one)))
(planning_entries
(desc "Each row denotes a timestamp which is a planning entry"
"(eg `DEADLINE`, `SCHEDULED`, or `CLOSED`).")
(columns
,(timestamp-id-col "planning entry" t)
(:planning_type :desc "the type of this planning entry"
:type enum
:length 9
:allowed (closed scheduled deadline)))
(constraints
(primary :keys (:timestamp_id))
(foreign :ref timestamps
:keys (:timestamp_id)
:parent-keys (:timestamp_id)
:on-delete cascade
:cardinality one-or-none-to-one)))
(file_tags
(desc "Each row stores one tag denoted by the `#+FILETAGS` keyword")
(columns
,(outline-hash-col "tag" t)
,tag-col)
(constraints
(primary :keys (:outline_hash :tag))
(foreign :ref outlines
:keys (:outline_hash)
:parent-keys (:outline_hash)
:on-delete cascade
:cardinality many-or-none-to-one)))
(headline_tags
(desc "Each row stores one tag attached to a headline. This includes"
"tags actively attached to a headlines as well as those in the"
"`ARCHIVE_ITAGS` property within archive files. The"
"`is_inherited` field will only be TRUE for the latter.")
(columns
,(headline-id-col "tag")
,tag-col
(:is_inherited :desc "TRUE if this tag is from the `ARCHIVE_ITAGS` property"
:type boolean
:constraints (notnull)))
(constraints
(primary :keys (:headline_id :tag :is_inherited))
(foreign :ref headlines
:keys (:headline_id)
:parent-keys (:headline_id)
:on-delete cascade
:cardinality many-or-none-to-one)))
(properties
(desc "Each row stores one property. Note this includes properties"
"under headlines as well as properties defined at the"
"file-level using `#+PROPERTY`.")
(columns
,(outline-hash-col "property" t)
,property-id-col
(:key_text :desc "this property's key"
:properties (:key)
:type text
:constraints (notnull))
(:val_text :desc "this property's value"
:properties (:value)
:type text
:constraints (notnull)))
(constraints
(primary :keys (:property_id))
(foreign :ref outlines
:keys (:outline_hash)
:parent-keys (:outline_hash)
:on-delete cascade
:cardinality many-or-none-to-one)))
(headline_properties
(desc "Each row stores a property under a headline.")
(columns
,(headline-id-col "property" t)
,property-id-col)
(constraints
(primary :keys (:property_id))
(foreign :ref properties
:keys (:property_id)
:parent-keys (:property_id)
:cardinality one-or-none-to-one)
;; :on-delete cascade)
(foreign :ref headlines
:keys (:headline_id)
:parent-keys (:headline_id)
:on-delete cascade
:cardinality many-or-none-to-one)))
(clocks
(desc "Each row stores one clock entry.")
(columns
(:clock_id :desc "id of this clock"
:type integer)
,(headline-id-col "clock" t)
(:time_start :desc "timestamp for the start of this clock"
:type integer)
(:time_end :desc "timestamp for the end of this clock"
:type integer)
(:clock_note :desc "the note entry beneath this clock"
:type text))
(constraints
(primary :keys (:clock_id))
(foreign :ref headlines
:keys (:headline_id)
:parent-keys (:headline_id)
:on-delete cascade
:cardinality many-or-none-to-one)))
(logbook_entries
(desc "Each row stores one logbook entry (except for clocks). Note"
"that the possible values of `entry_type` depend on"
"`org-log-note-headlines`. By default, the possible types are:"
"`reschedule`, `delschedule`, `redeadline`, `deldeadline`,"
"`state`, `done`, `note`, and `refile`. Note that while `clock-out`"
"is also a default type in `org-log-note-headings` but this"
"is already covered by the `clock_note` column in the `clocks`"
"table and thus won't be stored in this table.")
(columns
,(entry-id-col)
,(headline-id-col "logbook entry" t)
(:entry_type :desc "type of this entry"
:type text)
(:time_logged :desc "timestamp for when this entry was taken"
:type integer)
(:header :desc "the first line of this entry (usually standardized)"
:type text)
(:note :desc "the text underneath the header of this entry "
:type text))
(constraints
(primary :keys (:entry_id))
(foreign :ref headlines
:keys (:headline_id)
:parent-keys (:headline_id)
:on-delete cascade
:cardinality many-or-none-to-one)))
(state_changes
(desc "Each row stores the new and old states for logbook entries"
"of type `state`.")
(columns
,(entry-id-col "state change")
(:state_old :desc "former todo state keyword"
:type text
:constraints (notnull))
(:state_new :desc "updated todo state keyword"
:type text
:constraints (notnull)))
(constraints
(primary :keys (:entry_id))
(foreign :ref logbook_entries
:keys (:entry_id)
:parent-keys (:entry_id)
:on-delete cascade
:cardinality one-or-none-to-one)))
(planning_changes
(desc "Each row stores the former timestamp for logbook entries with"
"type `reschedule`, `delschedule`, `redeadline`, and"
"`deldeadline`.")
(columns
,(entry-id-col "planning change")
(:timestamp_id :desc "id of the former timestamp"
:type integer
:constraints (notnull unique)))
(constraints
(primary :keys (:entry_id))
(foreign :ref timestamps
:keys (:timestamp_id)
:parent-keys (:timestamp_id)
:cardinality one-or-none-to-one)
;; :on-delete cascade)
(foreign :ref logbook_entries
:keys (:entry_id)
:parent-keys (:entry_id)
:on-delete cascade
:cardinality one-or-none-to-one)))
(links
(desc "Each row stores one link.")
(columns
(:link_id :desc "id of this link"
:type integer)
,(headline-id-col "link" t)
(:link_path :desc "target of this link (eg url, file path, etc)"
:properties (:path)
:type text
:constraints (notnull))
(:link_text :desc "text of this link that isn't part of the path"
:type text)
(:link_type :desc "type of this link (eg http, mu4e, file, etc)"
:properties (:type)
:type text
:constraints (notnull)))
(constraints
(primary :keys (:link_id))
(foreign :ref headlines
:keys (:headline_id)
:parent-keys (:headline_id)
:on-delete cascade
:cardinality many-or-none-to-one))))
"Org-SQL database tables represented as an alist"))))
(eval-and-compile
(defconst org-sql-table-names
(--map (symbol-name (car it)) org-sql--table-alist)
"The names of all tables in the org-sql database."))
;; client executables
;; TODO what about the windows users?
(defconst org-sql--mysql-exe "mysql"
"The mysql client command.")
(defconst org-sql--psql-exe "psql"
"The postgres client command.")
(defconst org-sql--sqlite-exe "sqlite3"
"The sqlite client command.")
(defconst org-sql--sqlserver-exe "sqlcmd"
"The sqlserver client command.")
;; separator characters
;;
;; By default, most DBMS clients will dump their output (eg from a SELECT query)
;; as a newline-separated list of rows with field separated by some character
;; (usually '|'). This isn't ideal because org-files might contain newlines and
;; the field separator character, which makes the output ambiguous to parse.
;; Fortunately, some DBMSs allow the row and field separators to be changed.
;; Here I use the ASCII control characters group separator and record separator
;; for the row and field separators, which were made precisely for this purpose
;; because they cannot be typed on a keyboard (and thus shouldn't show up in an
;; org-file). Along the same lines, I use the unit separator in the case when I
;; need to aggregate strings and later separate them; the alternative is using
;; arrays which normally escape or do some other confusing thing when the
;; elements of the array contain newlines, backslashes, commas, etc.
(defconst org-sql--row-sep "\C-]"
"Character used for delimiting rows (when possible).")
(defconst org-sql--field-sep "\C-^"
"Character used for delimiting fields (when possible).")
(defconst org-sql--unit-sep "\C-_"
"Character used for delimiting array members (when possible).")
;; placeholder control characters
;;
;; Unfortunately, not all DBMSs allow the row and field separators to be
;; changed. Therefore, in order to prevent parsing ambiguity, the next best
;; solution is to tweak any queries to replace separator characters with
;; placeholders, and then swap these placeholders back when the query output is
;; deserialized. The rationale for these choices is the same as the
;; row/field/unit separators above; they shouldn't be typeable which means they
;; should never appear in an org buffer. See `org-sql--format-select-statement'
;; and `org-sql--compile-deserializers'.
(defconst org-sql--newline-placeholder "\a"
"Newline placeholder char where newlines are used as row separators.")
(defconst org-sql--tab-placeholder "\v"
"Tab placeholder char where tabs are used as field separators.")
;; Along the same lines, sometimes the user might want to represent the literal
;; 'NULL' string in a textual column. Use a non-typable character to represent
;; NULL so I can distinguish between NULL (nothing) and 'NULL' (the string)
(defconst org-sql--null-placeholder "\C-\\"
"Character to use in place of NULL.")
;;;
;;; CUSTOMIZATION OPTIONS
;;;
(defgroup org-sql nil
"Org mode SQL backend options."
:tag "Org SQL"
:group 'org)
;; TODO add sqlite pragma (synchronous and journalmode)
;; I could use `define-widget' here but it doesn't seem to work with a type this
;; complex (it lets me configure the type properly but then says MISCONFIGURED
;; when I come back, which makes no sense). On the bright side, this is much
;; more transparent; just make the repetitive bits of the type using a bunch of
;; functions
(eval-and-compile
(cl-flet*
((mk-option
(tag key value-type &optional default)
(let ((value (if default `(,value-type :value ,default) value-type)))
`(list :inline t :tag ,tag (const ,key) ,value)))
(mk-port
(n)
(mk-option "Port number" :port 'integer n))
(mk-db-choice
(tag sym required-keys &optional optional-keys)
`(cons :tag ,tag (const ,sym)
,(if optional-keys
`(list :tag "Required keys" :offset 2 ,@required-keys
(set :tag "Optional keys" :inline t ,@optional-keys))
`(list :tag "Required keys" :offset 2 ,@required-keys)))))
(let* ((database (mk-option "Database name" :database 'string "org_sql"))
(hostname (mk-option "Hostname/IP" :hostname 'string))
(username (mk-option "Username" :username 'string "org_sql"))
(password (mk-option "Password" :password 'string "org_sql@13243546"))
(schema (mk-option "Namespace (aka schema)" :schema 'string "org_sql"))
(args (mk-option "Additional args" :args '(repeat string)))
(env (mk-option "Environmental Vars" :env '(repeat (list string string))))
(def (mk-option "Defaults File" :defaults-file '(file :value "~/my.ini")))
(defx (mk-option "Defaults Extra File" :defaults-extra-file
'(file :value "~/my-extra.ini")))
(sfile (mk-option "Service File" :service-file
'(file :value "~/.pg_service.conf")))
(pfile (mk-option "Pass File" :pass-file '(file :value "~/.pgpass")))
(path (mk-option "Database path" :path '(string :value "~/org-sql.db")))
(unlogged (mk-option "Unlogged Tables" :unlogged 'boolean))
(server (mk-option "Server instance" :server
'(string :value "tcp:server\\instance_name,1433"))))
(defcustom org-sql-db-config
(list 'sqlite :path (expand-file-name "org-sql.db" org-directory))
"Configuration for the org-sql database.
This is a list like (DB-TYPE [KEY VAL] [[KEY VAL] ...]).
DB-TYPE is a symbol for the database to use and one of:
- `mysql': MySQL/MariaDB (requires the 'mysql' executable)
- `postgres': PostgresSQL (requires the 'psql' executable)
- `sqlite': SQLite (requires the 'sqlite3' executable)
- `sqlserver': SQL-Server (requires the 'sqlcmd' executable)
KEY and VAL form a plist and allowed combinations depend on
DB-TYPE.
Each database type requires one key to specify which database to
use. For SQLite, this key is `:path' and its value is a path to
the SQLite database file to use (or create if it doesn't exist).
For all others, this key is `:database' and specifies the name of
the database on the server (perhaps local) to which to connect.
All other keys are optional.
The following additional keys are database-specific:
SQLite
- none
Postgres
- `:hostname': (string) the hostname with which to connect
(corresponds to the `-h' flag)
- `:port': (integer) connection port (corresponds to the
`-p' flag)
- `:username': (string) the username to use (corresponds to the
`-U' flag)
- `:password': (string) the password to use (corresponds to the
`PGPASSWORD' environmental variable) NOTE use the `:pass-file'
or `:service-file' if you don't want to hardcode your password
- `:pass-file': (string) value to be supplied to the `PGPASSFILE'
environment variable
- `:service-file': (string) to be supplied to the `PGSERVICEFILE'
environment variable
- `:schema' (string) the schema to use
- `:args': (list of strings) arbitrary command line arguments
sent to `psql'
- `:env': (list of lists with strings like (ENV VAR))
environmental variables with which `psql' will run
- `:unlogged' (boolean) set to t to use unlogged tables and
potentially gain a huge speed improvement.
MySQL/MariaDB
- `:hostname': (string) the hostname with which to connect
(corresponds to the `-h' flag)
- `:port': (integer) connection port (corresponds to the
`-P' flag)
- `:username': (string) the username to use (corresponds to the
`-U' flag)
- `:password': (string) the password to use (corresponds to the
`-p' flag) NOTE use the `:defaults-file' or
`:defaults-extra-file' if you don't want to hardcode your
password
- `:defaults-file' (string) path to the be supplied to the
`--defaults-file' flag
- `:defaults-extra-file' (string): path to be supplied to the
`--defaults-extra-file' flag
- `:args': (list of strings) arbitrary command line arguments
sent to `mysql'
- `:env': (list of lists with strings like (ENV VAR))
environmental variables with which `mysql' will run
SQL-Server
- `:server': (string) the server instance (corresponds to the
`-S' flag)
- `:username': (string) the username to use (corresponds to the
`-U' flag)
- `:password': (string) the password to use (corresponds to the
`-P' flag) NOTE use the `:env' key to specify `SQLCMDINI'
which in turn can set the `SQLCMDPASSWORD' variable outside
emacs if you don't wish to hardcode this
- `:schema' (string) the schema to use
- `:args': (list of strings) arbitrary command line arguments
sent to `sqlcmd'
- `:env': (list of lists with strings like (ENV VAR))
environmental variables with which `sqlcmd' will run"
:type `(choice
,(mk-db-choice "MySQL/MariaDB" 'mysql `(,database)
`(,hostname
,(mk-port 3306)
,username
,password
,def
,defx
,args
,env))
,(mk-db-choice "PostgreSQL" 'postgres `(,database)
`(,hostname
,(mk-port 5432)
,username
,password
,schema
,pfile
,sfile
,unlogged
,args
,env))
,(mk-db-choice "SQLite" 'sqlite `(,path))
,(mk-db-choice "MS SQL-Server" 'sqlserver `(,database)
`(,server
,username
,password
,schema
,args
,env)))
:group 'org-sql))))
;; (defcustom org-sql-log-note-headings-overrides nil
;; "Alist of `org-log-note-headings' for specific files.
;; The car of each cell is the file path, and the cdr is another
;; alist like `org-log-note-headings' that will be used when
;; processing that file. This is useful if some files were created
;; with different patterns for their logbooks as Org-mode itself
;; does not provide any options to control this besides the global
;; `org-log-note-headings'."
;; :type '(alist :key-type string
;; :value-type (alist :key-type symbol
;; :value-type string))
;; :group 'org-sql)
(defcustom org-sql-async nil
"When t database updates will be asynchronous.
All admin operations will still be synchronous. Note that this
only spawns a process for the database client command; all
processing the needs to be performed on org files (parsing to
make the INSERT statements) will still be synchronous."
:type 'boolean
:group 'org-sql)
(defcustom org-sql-files nil
"A list of org files or directories to put into sql database.
Any directories in this list imply that all files within the
directly are added. Only files ending in .org or .org_archive are
considered. See function `org-sql-files'."
:type '(repeat :tag "List of files and directories" file)
:group 'org-sql)
(eval-and-compile
(let ((hook '(repeat
(choice
(cons :tag "SQL command" (const sql) string)
(cons :tag "SQL command (appended)" (const sql+) string)
(cons :tag "SQL file" (const file) file)
(cons :tag "SQL file (appended)" (const file+) file)))))
(defcustom org-sql-post-init-hooks nil
"Hooks to run after `org-sql-init-db'.
This is a list of 2-membered lists like (SYM STRING) called
'hooks'. The SYM of each hook is a symbol like `sql', `file',
`sql+', or `file+'. If `sql', the second member is a string
representing a SQL statement which will be executed. If 'file',
the second member is a path to a SQL file that will be executed.
The `+' suffix signifies that the SQL string or file of the hook
will be appended to the transaction sent by `org-sql-db-init' (eg
inside the \"BEGIN;...COMMIT;\" block).
These hooks are generally useful for running arbitrary SQL
statements after `org-sql' database operations. This could
include setting up additional indexes on tables, adding triggers,
defining and executing procedures, etc. See also
`org-sql-post-push-hooks', `org-sql-post-clear-hooks', and
`org-sql-pre-reset-hooks'."
:type hook
:group 'org-sql)
(defcustom org-sql-post-push-hooks nil
"Hooks to run after `org-sql-push-to-db'.
This works analogously to `org-sql-post-init-hooks'."
:type hook
:group 'org-sql)
(defcustom org-sql-post-clear-hooks nil
"Hooks to run after `org-sql-clear-db'.
This works analogously to `org-sql-post-init-hooks'."
:type hook
:group 'org-sql)
(defcustom org-sql-pre-reset-hooks nil
"Hooks to run before `org-sql-reset-db'.
This works analogously to `org-sql-post-init-hooks'."
:type hook
:group 'org-sql)))
(defcustom org-sql-excluded-properties nil
"List of properties to exclude from the database.
To exclude all set to `all' instead of a list of strings."
:type '(choice
(const "Ignore All" all)
(repeat :tag "List of properties to ignore" string))
:group 'org-sql)
(defcustom org-sql-exclude-inherited-tags nil
"If t don't include tags in the ARCHIVE_ITAGS property in the database."
:type 'boolean
:group 'org-sql)
(defcustom org-sql-excluded-tags nil
"List of tags to exclude when building the tags table.
To exclude all set to `all' instead of a list of strings."
:type '(choice
(const "Ignore All" all)
(repeat :tag "List of tags to ignore" string))
:group 'org-sql)
(defcustom org-sql-excluded-link-types nil
"List of link types to exclude when building the links table.
Each member should be a string and one of `org-link-types' or
\"file\", \"coderef\", \"custom-id\", \"fuzzy\", or \"id\". See org-element
API documentation or`org-element-link-parser' for details.
To exclude all set to `all' instead of a list of strings."
:type '(choice
(set :tag "List of types to ignore"
(const :tag "File paths" "file")
(const :tag "Source code references" "coderef")
(const :tag "Headline custom IDs" "custom-id")
(const :tag "Fuzzy target in parse trees" "fuzzy")
(const :tag "Headline IDs" "id")
(repeat :tag "Other types to ignore" string))
(const "Ignore all" all))
:group 'org-sql)
(defcustom org-sql-excluded-headline-planning-types nil
"List of headline planning timestamps to exclude in the database.
List members can be ':deadline', ':scheduled', or ':closed'. To
exclude none set to nil."
:type '(set :tag "List of types to include"
(const :tag "Deadline Timestamps" :deadline)
(const :tag "Scheduled Timestamps" :scheduled)
(const :tag "Closed Timestamps" :closed))
:group 'org-sql)
(defcustom org-sql-excluded-contents-timestamp-types nil
"List of timestamp types to exclude from headline content sections.
List members can be the symbols `active', `active-range', `inactive',
or `inactive-range'. To exclude none set to nil."
:type '(set :tag "List of types to include"
(const :tag "Active Timestamps" active)
(const :tag "Active Timestamp Ranges" active-range)
(const :tag "Inactive Timestamps" inactive)
(const :tag "Inactive Timestamp Ranges" inactive-range))
:group 'org-sql)
;; TODO what if they customize these keys?
(defcustom org-sql-excluded-logbook-types nil
"List of logbook entry types to exclude from the database.
List members are any of the keys from `org-log-note-headings' with the
exception of `clock-out' as these are treated as clock-notes (see
`org-sql-exclude-clock-notes'). To include none set to nil."
:type '(set :tag "List of types to include"
(const :tag "Clocks" clock)
(const :tag "Closing notes" done)
(const :tag "State changes" state)
(const :tag "Notes taken" note)
(const :tag "Rescheduled tasks" reschedule)
(const :tag "Unscheduled tasks" delschedule)
(const :tag "Redeadlined tasks" redeadline)
(const :tag "Undeadlined tasks" deldeadline)
(const :tag "Refiled tasks" refile))
:group 'org-sql)
(defcustom org-sql-exclude-clock-notes nil
"Set to t to store clock notes in the database.
Setting `org-sql-store-clocks' to nil will cause this variable to be
ignored."
:type 'boolean
:group 'org-sql)
(defcustom org-sql-exclude-headline-predicate nil
"A function that is called for each headline.
If it returns t, the current headline is to be excluded. Note
that excluding a headline will also exclude its children."
:type 'function
:group 'org-sql)
(defcustom org-sql-debug nil
"Set to t to enable high-level debugging of SQL transactions."
:type 'boolean
:group 'org-sql)
;;;
;;; STATELESS FUNCTIONS
;;;
;;; compile/macro checking
;; case selection statements for sql mode and type
(defun org-sql--sets-equal (list1 list2 &rest args)
"Return t if LIST1 and LIST2 are equal via set logic.
Either list may contain repeats, in which case nil is returned.
ARGS is a list of additional arguments to pass to `cl-subsetp'."
(and (equal (length list1) (length list2))
(apply #'cl-subsetp list1 list2 args)
(apply #'cl-subsetp list2 list1 args)))
(defmacro org-sql--case-type (type &rest alist-forms)
"Execute one of ALIST-FORMS depending on TYPE.
A compile error will be triggered if TYPE is invalid."
(declare (indent 1))
(-let (((&alist 'boolean 'char 'enum 'integer 'real 'text 'varchar)
(--splice (listp (car it))
(-let (((keys . form) it))
(--map (cons it form) keys))
alist-forms)))
(when (-any? #'null (list boolean char enum real integer text varchar))
(error "Must provide form for all types"))
`(cl-case ,type
(boolean ,@boolean)