forked from ndwarshuis/org-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorg-sql.el
2151 lines (1965 loc) · 88.2 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) 2020 Nathan Dwarshuis
;; Author: Nathan Dwarshuis <natedwarshuis@gmail.com>
;; Keywords: org-mode, data
;; Homepage: https://github.com/ndwarshuis/org-sql
;; Package-Requires: ((emacs "26.1") (s "1.12") (dash "2.15") (org-ml "4.0.0"))
;; Version: 1.0.2
;; 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.
;; 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 meta query language (MQL, an
;; internal, database agnostic representation of the SQL statements to be
;; sent)
;; - inserts will be constructed using `org-element'/`org-ml' from target
;; files on disk
;; 3) format MQL to database-specific SQL statements
;; 4) send SQL statements to the configured database
;; The code is roughly arranged as follows:
;; - constants
;; - customization variables
;; - stateless functions
;; - stateful IO functions
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'dash)
(require 's)
(require 'sql)
(require 'org)
(require 'org-ml)
;;;
;;; CONSTANTS
;;;
(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)
'(:file-path :headline-offset :entry-offset :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
(defconst org-sql--mql-schema
'((files
(desc . "Each row stores metadata for one tracked org file")
(columns
(:file_path :desc "path to the org file"
:type text)
(:md5 :desc "md5 checksum of the org file"
:type text
:constraints (notnull))
(:size :desc "size of the org file in bytes"
:type integer
:constraints (notnull)))
(constraints
(primary :keys (:file_path))))
(headlines
(desc . "Each row stores one headline in a given org file and its metadata")
(columns
(:file_path :desc "path to file containing the headline"
:type text)
(:headline_offset :desc "file offset of the headline's first character"
:type integer)
(:headline_text :desc "raw text of the headline"
:type text
:constraints (notnull))
(:keyword :desc "the TODO state keyword"
:type text)
(:effort :desc "the value of the Effort property in minutes"
:type integer)
(:priority :desc "character value of the priority"
:type text)
(:is_archived :desc "true if the headline has an archive tag"
:type boolean
:constraints (notnull))
(:is_commented :desc "true if the headline has a comment keyword"
:type boolean
:constraints (notnull))
(:content :desc "the headline contents"
:type text))
(constraints
(primary :keys (:file_path :headline_offset))
(foreign :ref files
:keys (:file_path)
:parent-keys (:file_path)
:on_delete cascade
:on_update cascade)))
(headline_closures
(desc . "Each row stores the ancestor and depth of a headline relationship (eg closure table)")
(columns
(:file_path :desc "path to the file containing this headline"
:type text)
(:headline_offset :desc "offset of this headline"
:type integer)
(:parent_offset :desc "offset of this headline's parent"
:type integer)
(:depth :desc "levels between this headline and the referred parent"
:type integer))
(constraints
(primary :keys (:file_path :headline_offset :parent_offset))
(foreign :ref headlines
:keys (:file_path :headline_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade)
(foreign :ref headlines
:keys (:file_path :parent_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade)))
(timestamps
(desc . "Each row stores one timestamp")
(columns
(:file_path :desc "path to the file containing this timestamp"
:type text)
(:headline_offset :desc "offset of the headline containing this timestamp"
:type integer
:constraints (notnull))
(:timestamp_offset :desc "offset of this timestamp"
:type integer)
(:raw_value :desc "text representation of this timestamp"
:type text
:constraints (notnull))
(:is_active :desc "true if the timestamp is active"
:type boolean
:constraints (notnull))
(:warning_type :desc "warning type of this timestamp"
:type enum
:allowed (all first))
(:warning_value :desc "warning shift of this timestamp"
:type integer)
(:warning_unit :desc "warning unit of this timestamp "
:type enum
:allowed (hour day week month year))
(:repeat_type :desc "repeater type of this timestamp"
:type enum
:allowed (catch-up restart cumulate))
(:repeat_value :desc "repeater shift of this timestamp"
:type integer)
(:repeat_unit :desc "repeater unit of this timestamp"
:type enum
:allowed (hour day week month year))
(:time_start :desc "the start time (or only time) of this timestamp"
:type integer
:constraints (notnull))
(:time_end :desc "the end time of this timestamp"
:type integer)
(:start_is_long :desc "true if the start time is in long format"
:type boolean
:constraints (notnull))
(:end_is_long :desc "true if the end time is in long format"
:type boolean))
(constraints
(primary :keys (:file_path :timestamp_offset))
(foreign :ref headlines
:keys (:file_path :headline_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade)))
(planning_entries
(desc . "Each row stores the metadata for headline planning timestamps.")
(columns
(:file_path :desc "path to the file containing the entry"
:type text)
(:headline_offset :desc "file offset of the headline with this tag"
:type integer)
(:planning_type :desc "the type of this planning entry"
:type enum
:allowed (closed scheduled deadline))
(:timestamp_offset :desc "file offset of this entries timestamp"
:type integer
:constraints (notnull)))
(constraints
(primary :keys (:file_path :headline_offset :planning_type))
(foreign :ref timestamps
:keys (:file_path :timestamp_offset)
:parent-keys (:file_path :timestamp_offset)
:on_delete cascade
:on_update cascade)))
(file_tags
(desc . "Each row stores one tag at the file level")
(columns
(:file_path :desc "path to the file containing the tag"
:type text)
(:tag :desc "the text value of this tag"
:type text))
(constraints
(primary :keys (:file_path :tag))
(foreign :ref files
:keys (:file_path)
:parent-keys (:file_path)
:on_delete cascade
:on_update cascade)))
(headline_tags
(desc . "Each row stores one tag")
(columns
(:file_path :desc "path to the file containing the tag"
:type text)
(:headline_offset :desc "file offset of the headline with this tag"
:type integer)
(:tag :desc "the text value of this tag"
:type text)
(:is_inherited :desc "true if this tag is from the ITAGS property"
:type boolean
:constraints (notnull)))
(constraints
(primary :keys (:file_path :headline_offset :tag :is_inherited))
(foreign :ref headlines
:keys (:file_path :headline_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade)))
(properties
(desc . "Each row stores one property")
(columns
(:file_path :desc "path to the file containing this property"
:type text)
(:property_offset :desc "file offset of this property in the org file"
:type integer)
(:key_text :desc "this property's key"
:type text
:constraints (notnull))
(:val_text :desc "this property's value"
:type text
:constraints (notnull)))
(constraints
(primary :keys (:file_path :property_offset))
(foreign :ref files
:keys (:file_path)
:parent-keys (:file_path)
:on_delete cascade
:on_update cascade)))
(file_properties
(desc . "Each row stores a property at the file level")
(columns
(:file_path :desc "path to file containin the property"
:type text)
(:property_offset :desc "file offset of this property in the org file"
:type integer))
(constraints
(primary :keys (:file_path :property_offset))
(foreign :ref files
:keys (:file_path)
:parent-keys (:file_path)
:on_delete cascade
:on_update cascade)
(foreign :ref properties
:keys (:file_path :property_offset)
:parent-keys (:file_path :property_offset)
:on_delete cascade
:on_update cascade)))
(headline_properties
(desc . "Each row stores a property at the headline level")
(columns
(:file_path :desc "path to file containin the property"
:type text)
(:property_offset :desc "file offset of this property in the org file"
:type integer)
(:headline_offset :desc "file offset of the headline with this property"
:type integer
:constraints (notnull)))
(constraints
(primary :keys (:file_path :property_offset))
(foreign :ref headlines
:keys (:file_path :headline_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade)))
(clocks
(desc . "Each row stores one clock entry")
(columns
(:file_path :desc "path to the file containing this clock"
:type text)
(:headline_offset :desc "offset of the headline with this clock"
:type integer
:constraints (notnull))
(:clock_offset :desc "file offset of this clock"
:type integer)
(: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 (:file_path :clock_offset))
(foreign :ref headlines
:keys (:file_path :headline_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade)))
(logbook_entries
(desc . "Each row stores one logbook entry (except for clocks)")
(columns
(:file_path :desc "path to the file containing this entry"
:type text)
(:headline_offset :desc "offset of the headline with this entry"
:type integer
:constraints (notnull))
(:entry_offset :desc "offset of this logbook entry"
:type integer)
(:entry_type :desc "type of this entry (see `org-log-note-headlines')"
: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 of this entry underneath the header"
:type text))
(constraints
(primary :keys (:file_path :entry_offset))
(foreign :ref headlines
:keys (:file_path :headline_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade)))
(state_changes
(desc . "Each row stores additional metadata for a state change logbook entry")
(columns
(:file_path :desc "path to the file containing this entry"
:type text)
(:entry_offset :desc "offset of the logbook entry for this state change"
:type integer)
(: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 (:file_path :entry_offset))
(foreign :ref logbook_entries
:keys (:file_path :entry_offset)
:parent-keys (:file_path :entry_offset)
:on_delete cascade
:on_update cascade)))
(planning_changes
(desc . "Each row stores additional metadata for a planning change logbook entry")
(columns
(:file_path :desc "path to the file containing this entry"
:type text)
(:entry_offset :desc "offset of the logbook entry for this planning change"
:type integer)
(:timestamp_offset :desc "offset of the former timestamp"
:type integer
:constraints (notnull)))
(constraints
(primary :keys (:file_path :entry_offset))
(foreign :ref timestamps
:keys (:file_path :timestamp_offset)
:parent-keys (:file_path :timestamp_offset)
:on_delete cascade
:on_update cascade)
(foreign :ref logbook_entries
:keys (:file_path :entry_offset)
:parent-keys (:file_path :entry_offset)
:on_delete cascade
:on_update cascade)))
(links
(desc . "Each rows stores one link")
(columns
(:file_path :desc "path to the file containing this link"
:type text)
(:headline_offset :desc "offset of the headline with this link"
:type integer
:constraints (notnull))
(:link_offset :desc "file offset of this link"
:type integer)
(:link_path :desc "target of this link (eg url, file path, etc)"
:type text
:constraints (notnull))
(:link_text :desc "text of this link"
:type text)
(:link_type :desc "type of this link (eg http, mu4e, file, etc)"
:type text
:constraints (notnull)))
(constraints
(primary :keys (:file_path :link_offset))
(foreign :ref headlines
:keys (:file_path :headline_offset)
:parent-keys (:file_path :headline_offset)
:on_delete cascade
:on_update cascade))))
"Org-SQL database schema represented in internal meta query
language (MQL, basically a giant list)"))
;; TODO what about the windows users?
(defconst org-sql--sqlite-exe "/usr/bin/sqlite3"
"The path to the sqlite client command.")
(defconst org-sql--psql-exe "/usr/bin/psql"
"The path to the postgres client command.")
(defconst org-sql--postgres-createdb-exe "/usr/bin/createdb"
"The path to the postgres 'create database' command.")
(defconst org-sql--postgres-dropdb-exe "/usr/bin/dropdb"
"The path to the postgres 'drop database' command.")
;;;
;;; CUSTOMIZATION OPTIONS
;;;
(defgroup org-sql nil
"Org mode SQL backend options."
:tag "Org SQL"
:group 'org)
;; TODO add sqlite pragma (synchronous and journalmode)
;; TODO add postgres transaction options
(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 OPTION-PLIST). The valid keys and
values in OPTION-PLIST depend on the DB-TYPE. Note that all
values in the OPTION-PLIST must be strings.
The following symbols are valid for DB-TYPE:
- `sqlite' (requires the `sqlite3' command)
- `postgres' (requires the `psql', `createdb', and `dropdb'
commands)
For 'sqlite', the following options are in OPTION-PLIST:
- `:path' (required): the path on disk to use for the database
file
For 'postgres', the following options are in OPTION-PLIST:
- `:database' (required): the name of the database to use
- `:hostname': the hostname for the database connection
- `:port': the port for the database connection
- `:username': the username for the database connection
- `:password': the password for the database connection (NOTE:
since setting this option will store the password in plain
text, consider using a `.pgpass' file\\)"
;; TODO add type
: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-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)
(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)
(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-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.
TYPE must be one of 'boolean', 'text', 'enum', or 'integer'."
(declare (indent 1))
(-let (((keys &as &alist 'boolean 'text 'enum 'integer) alist-forms))
(unless (-none? #'null keys)
(error "Must provide form for all types"))
`(cl-case ,type
(boolean ,@boolean)
(text ,@text)
(enum ,@enum)
(integer ,@integer)
(t (error "Invalid type: %s" ,type)))))
(defmacro org-sql--case-mode (mode &rest alist-forms)
"Execute one of ALIST-FORMS depending on MODE.
TYPE must be one of 'sqlite' or 'postgres'."
(declare (indent 1))
(-let (((keys &as &alist 'sqlite 'postgres) alist-forms))
(unless (-none? #'null keys)
(error "Must provide form for all modes"))
`(cl-case ,mode
(postgres ,@postgres)
(sqlite ,@sqlite)
(t (error "Invalid mode: %s" ,mode)))))
;; ensure integrity of the metaschema
(eval-when-compile
(defun org-sql--mql-schema-has-valid-keys (tbl-schema)
"Verify that TBL-SCHEMA has valid keys in its table constraints."
(-let* (((tbl-name . (&alist 'constraints 'columns)) tbl-schema)
(column-names (-map #'car columns)))
(cl-flet
((get-keys
(constraint)
(-let (((type . (&plist :keys)) constraint))
(cons type keys)))
(test-keys
(type keys)
(-some->> (-difference keys column-names)
(-map #'symbol-name)
(s-join ", ")
(error "Mismatched %s keys in table '%s': %s" type tbl-name))))
(--> (--filter (memq (car it) '(primary foreign)) constraints)
(-map #'get-keys it)
(--each it (test-keys (car it) (cdr it)))))))
(defun org-sql--mql-schema-has-valid-parent-keys (tbl-schema)
"Verify that TBL-SCHEMA has valid keys in its table foreign constraints."
(cl-flet
((is-valid
(foreign-meta tbl-name)
(-let* (((&plist :parent-keys :ref) foreign-meta)
(parent-meta (alist-get ref org-sql--mql-schema))
(parent-columns (-map #'car (alist-get 'columns parent-meta)))
(parent-primary (--> (alist-get 'constraints parent-meta)
(alist-get 'primary it)
(plist-get it :keys))))
;; any parent keys must have corresponding columns in the referred
;; table
(-some->> (-difference parent-keys parent-columns)
(-map #'symbol-name)
(s-join ", ")
(error "Mismatched foreign keys between %s and %s: %s" tbl-name ref))
;; This isn't strictly a requirement (but still good practice); make
;; sure the foreign key refer to the primary key in the parent table
(when (or (-difference parent-keys parent-primary)
(-difference parent-primary parent-keys))
(error "Mismatched foreign and primary keys between %s and %s" tbl-name ref)))))
(-let* (((tbl-name . meta) tbl-schema)
(foreign (->> (alist-get 'constraints meta)
(--filter (eq (car it) 'foreign))
(-map #'cdr))))
(--each foreign (is-valid it tbl-name)))))
(-each org-sql--mql-schema #'org-sql--mql-schema-has-valid-keys)
(-each org-sql--mql-schema #'org-sql--mql-schema-has-valid-parent-keys))
;; ensure MQL constructors are given the right input
(defun org-sql--mql-check-get-schema-keys (tbl-name)
"Return a list of columns for TBL-NAME.
The columns are retrieved from `org-sql--mql-schema'."
(let ((valid-keys (->> org-sql--mql-schema
(alist-get tbl-name)
(alist-get 'columns)
(-map #'car))))
(unless valid-keys (error "Invalid table name: %s" tbl-name))
valid-keys))
(defun org-sql--mql-check-columns-all (tbl-name plist)
"Test if keys in PLIST are valid column names for TBL-NAME.
All column keys must be in PLIST."
(declare (indent 2))
(let ((valid-keys (org-sql--mql-check-get-schema-keys tbl-name))
(input-keys (->> (-partition 2 plist)
(-map #'car))))
(-some->> (-difference valid-keys input-keys)
(error "Keys not given for table %s: %s" tbl-name))
(-some->> (-difference input-keys valid-keys)
(error "Keys not valid for table %s: %s" tbl-name))))
(defun org-sql--mql-check-columns-contains (tbl-name plist)
"Test if keys in PLIST are valid column names for TBL-NAME.
Only some of the column keys must be in PLIST."
(declare (indent 2))
(let ((valid-keys (org-sql--mql-check-get-schema-keys tbl-name))
(input-keys (->> (-partition 2 plist)
(-map #'car))))
(-some->> (-difference input-keys valid-keys)
(error "Keys not valid for table %s: %s" tbl-name))))
;;; data constructors
;; meta query language (MQL)
(defmacro org-sql--mql-insert (tbl-name &rest plist)
"Return an MQL-insert list for TBL-NAME.
PLIST is a property list of the columns and values to insert."
(declare (indent 1))
(org-sql--mql-check-columns-all tbl-name plist)
`(list ',tbl-name ,@plist))
(defmacro org-sql--add-mql-insert (acc tbl-name &rest plist)
"Add a new MQL-insert list for TBL-NAME to ACC.
PLIST is a property list of the columns and values to insert."
(declare (indent 2))
`(cons (org-sql--mql-insert ,tbl-name ,@plist) ,acc))
(defmacro org-sql--mql-update (tbl-name set where)
"Return an MQL-update list for TBL-NAME.
SET is a plist for the updated values of columns and WHERE is a plist of
columns that must be equal to the values in the plist in order for the update
to be applied."
(declare (indent 1))
(org-sql--mql-check-columns-contains tbl-name set)
(org-sql--mql-check-columns-contains tbl-name where)
`(list ',tbl-name
(list 'set ,@set)
(list 'where ,@where)))
(defmacro org-sql--mql-delete (tbl-name where)
"Return an MQL-delete list for TBL-NAME.
WHERE is a plist of columns that must be equal to the values in
the plist in order for the delete to be applied."
(org-sql--mql-check-columns-contains tbl-name where)
`(list ',tbl-name
(list 'where ,@where)))
;; TODO I forgot select
;; external state
(defun org-sql--to-fstate (file-path hash attributes log-note-headings
todo-keywords tree)
"Return a plist representing the state of an org buffer.
The plist will include:
- `:file-path': the path to this org file on disk (given by
FILE-PATH)
- `:md5': the hash of this org file (given by HASH)
- `:attributes': the ATTRIBUTES list for the file as returned via
`file-attributes'
- `:top-section': the org-element TREE representation of this
org-file's top section before the first headline
- `:headline': a list of org-element TREE headlines in this org
file
- `:log-note-matcher': a list of log-note-matchers for this org
file as returned by
`org-sql--build-log-note-heading-matchers' (which depends on
TODO-KEYWORDS and LOG-NOTE-HEADINGS)"
(let* ((children (org-ml-get-children tree))
(top-section (-some->> (assoc 'section children)
(org-ml-get-children))))
(list :file-path file-path
:md5 hash
:attributes attributes
:top-section top-section
:headlines (if top-section (cdr children) children)
:log-note-matcher (org-sql--build-log-note-heading-matchers
log-note-headings todo-keywords))))
(defun org-sql--to-fmeta (disk-path db-path hash)
"Return a plist representing org file status.
DISK-PATH is the path to the org file on disk, DB-PATH is the
path on disk recorded in the database for this org file, and HASH
is the md5 of this org file."
(list :disk-path disk-path :db-path db-path :hash hash))
;;; SQL string parsing functions
(defun org-sql--parse-output-to-plist (cols out)
"Parse SQL output string OUT to an plist representing the data.
COLS are the column names as symbols used to obtain OUT."
(unless (equal out "")
(->> (s-trim out)
(s-split "\n")
(--map (s-split "|" it))
(--map (-interleave cols it)))))
;;; MQL -> SQL string formatting functions
;; formatting function tree
(defun org-sql--compile-mql-format-function (mode type)
"Return SQL value formatting function.
The returned function will depend on the MODE and TYPE."
(cl-flet
((quote-string
(s)
(format "'%s'" s))
(escape-string
(newline s)
(let ((newline* (format "'||%s||'" newline)))
(->> (s-replace-regexp "'" "''" s)
(s-replace-regexp "\n" newline*)))))
;; TODO this could be way more elegant (build the lambda with forms)
(let ((formatter
(org-sql--case-type type
(boolean
(org-sql--case-mode mode
(postgres (lambda (b) (if (= b 1) "TRUE" "FALSE")))
(sqlite (lambda (b) (if (= b 1) "1" "0")))))
(enum (lambda (e) (quote-string (symbol-name e))))
(integer #'number-to-string)
(text
(org-sql--case-mode mode
(postgres
(lambda (s)
(quote-string (escape-string "chr(10)" s))))
(sqlite
(lambda (s)
(quote-string (escape-string "char(10)" s)))))))))
(lambda (s) (if s (funcall formatter s) "NULL")))))
(defun org-sql--compile-mql-schema-formatter-alist (mode mql-schema)
"Return an alist of formatting functions for MQL-SCHEMA.
MODE is the SQL mode. The alist will mirror MSL schema except that the
car for each column will be a formatting function."
(cl-flet
((get-type-function
(mql-column)
(-let* (((name . (&plist :type)) mql-column))
(cons name (org-sql--compile-mql-format-function mode type)))))
(-let* (((tbl-name . (&alist 'columns)) mql-schema))
(cons tbl-name (-map #'get-type-function columns)))))
;; helper functions
(defun org-sql--format-mql-plist (formatter-alist sep plist)
"Format a PLIST to a SQL-compliant string.
FORMATTER-ALIST is an alist of formatting functions matching the keys
in PLIST (whose keys in turn should match columns in the schema).
The keys and values will be formatted like \"key=val\" and
separated by SEP."
(let ((keys (->> (-slice plist 0 nil 2)
(-map #'org-sql--format-mql-column-name)))
(vals (->> (-partition 2 plist)
(--map (funcall (alist-get (car it) formatter-alist) (cadr it))))))
(-some->> (--zip-with (format "%s=%s" it other) keys vals)
(s-join sep))))
(defun org-sql--format-mql-column-name (column-name)
"Return SQL string representation of COLUMN-NAME."
(if (not (keywordp column-name)) (error "Not a keyword: %s" column-name)
(s-chop-prefix ":" (symbol-name column-name))))
;; create table
(defun org-sql--format-mql-schema-enum-types (mql-schema)
"Return a series of CREATE TYPE statements for MQL-SCHEMA.
The SQL statements will create all enum types found in
MQL-SCHEMA."
(cl-labels
((format-column
(table-name mql-column)
(-let* (((column-name . (&plist :type :allowed)) mql-column)
(column-name* (org-sql--format-mql-column-name column-name)))
(when (and (eq type 'enum) allowed)
(->> (--map (format "'%s'" it) allowed)
(s-join ",")
(format "CREATE TYPE enum_%s_%s AS ENUM (%s);" table-name column-name*)))))
(format-table
(mql-table)
(-let (((table-name . (&alist 'columns)) mql-table))
(-non-nil (--map (format-column table-name it) columns)))))
(-mapcat #'format-table mql-schema)))
(defun org-sql--format-mql-schema-column-constraints (mql-column-constraints)
"Return formatted column constraints for MQL-COLUMN-CONSTRAINTS."
(cl-flet
((format-constraint
(constraint)
(pcase constraint
('notnull "NOT NULL")
('unique "UNIQUE")
;; TODO add CHECK?
;; TODO add PRIMARY KEY?
(e (error "Unknown constraint %s" e)))))
(->> mql-column-constraints
(-map #'format-constraint)
(s-join " "))))
(defun org-sql--format-mql-schema-type (config tbl-name mql-column)
"Return SQL string for the type of MQL-COLUMN.
CONFIG is the `org-sql-db-config' list and TBL-NAME is the name
of the table."
(-let* (((column-name . (&plist :type)) mql-column)
(column-name* (org-sql--format-mql-column-name column-name)))
(org-sql--case-mode (car config)
(sqlite
(org-sql--case-type type
(enum "TEXT")
(text "TEXT")
(integer "INTEGER")
(boolean "INTEGER")))
(postgres
(org-sql--case-type type
(enum (format "enum_%s_%s" tbl-name column-name*))
(text "TEXT")
(integer "INTEGER")
(boolean "BOOLEAN"))))))
(defun org-sql--format-mql-schema-columns (config tbl-name mql-columns)
"Return SQL string for MQL-COLUMNS.
CONFIG is the `org-sql-db-config' list and TBL-NAME is the name
of the table."
(cl-flet
((format-column
(mql-column)
(-let* (((name . (&plist :constraints)) mql-column)
(name* (org-sql--format-mql-column-name name))
(type* (org-sql--format-mql-schema-type config tbl-name mql-column))
(column-str (format "%s %s" name* type*)))
(if (not constraints) column-str
(->> (org-sql--format-mql-schema-column-constraints constraints)
(format "%s %s" column-str))))))
(-map #'format-column mql-columns)))
(defun org-sql--format-mql-schema-table-constraints (mql-tbl-constraints)
"Return SQL string for MQL-TBL-CONSTRAINTS."
(cl-labels
((format-primary
(keyvals)
(-let* (((&plist :keys) keyvals))
(->> (-map #'org-sql--format-mql-column-name keys)
(s-join ",")
(format "PRIMARY KEY (%s)"))))
(format-foreign
(keyvals)
(-let* (((&plist :ref :keys :parent-keys :on_delete :on_update) keyvals)
(keys* (->> keys (-map #'org-sql--format-mql-column-name) (s-join ",")))
(parent-keys* (->> parent-keys
(-map #'org-sql--format-mql-column-name)
(s-join ",")))
(foreign-str (format "FOREIGN KEY (%s) REFERENCES %s (%s)"
keys* ref parent-keys*))
(on-delete* (-some->> on_delete
(symbol-name)
(upcase)
(format "ON DELETE %s")))
(on-update* (-some->> on_update
(symbol-name)