-
Notifications
You must be signed in to change notification settings - Fork 0
/
zekell.py
executable file
·1446 lines (1088 loc) · 40.9 KB
/
zekell.py
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
#! /usr/bin/env python3
from pprint import pprint
import subprocess as sp
import string
from textwrap import dedent
from argparse import ArgumentParser
import datetime as dt
import copy
import json
from string import Template
from pathlib import Path
import re
import subprocess
# 3.5+ then!
from typing import Optional, Iterable, Tuple, Union, overload
import sqlite3 as sql
# when package, needs to be managed
# SCHEMA_PATH = Path('./schema.sql')
SCHEMA_PATH = Path(__file__).parent / Path('./schema.sql')
# > Config
default_config = {
"zk_paths": {
"main": "~/zekell"
},
"current_zk_path": "main",
"note_extension": ".md",
# "editor_shell_command": "vim, {}"
"editor_shell_command": "subl, -n, {}"
}
default_config_path = Path('~/.zekell_config').expanduser()
def write_default_config(output_path: Path = default_config_path):
output_path.touch(exist_ok=True)
output_path.write_text(
json.dumps(default_config))
def get_config():
if not default_config_path.exists():
return default_config
else:
base_config = copy.deepcopy(default_config)
base_config.update(
json.loads(
default_config_path.read_text()))
return base_config
config = get_config()
# >> Set global consts from config
# MAIN ONE IS ZK_PATH ... how to deal with path depends on how this library is called
# probably best to contextualise the path at calling before passing note_path variables
# down to functions
NOTE_EXTENSION = config['note_extension']
ZK_PATH = Path(config['zk_paths'][config['current_zk_path']]).expanduser()
ZK_DB = Path('zekell.db')
ZK_DB_PATH = ZK_PATH / ZK_DB
# > Objects & Consts
note_name_template = Template('$id $title').substitute
note_file_name_template = Template('$id $title'+NOTE_EXTENSION).substitute
note_name_pattern = re.compile(r'^(\d{10,14}) (.*)')
# make link_pattern more permissive so that title/comment can be anything?
link_pattern = re.compile(r'\[(.*?)\]\(\/(\d{10,14})\)')
# non greedy for contents so that don't accidentally match whole file!
front_matter_pattern = re.compile(r'(?s)^---\n(.+?)\n---')
# links to notes to be created on parsing ... add later ... nice to have
# Must have a title (at least one character) and no id, but a slash!
# new_link_pattern = re.compile(r'\[([\w\- ]+)\]\(\/\)')
class DB:
def __init__(self, conn: sql.Connection, cursor: sql.Cursor):
self.conn = conn
self.cursor = cursor
def ex(
self, query: Union[str, list, tuple],
params: Optional[Union[list, tuple]] = None):
"""Execute query and return fetchall and commit
If query is a list (of queries/statements), then they will be run as a batch
with `commit` being run only after all have been executed.
Passing params along with a list of queries/statements requires params to be
a list/tuple of lists/tuples, with the inner lists/tuples containing the params
for each query.
If params are None, no params are used for a list of queries
If one of the elements in the outer list of params is None, then no params are used
for the corresponding query
Examples
--------
>>> db.ex('select * from notes')
>>> db.ex('select * from notes where id = ?', [123])
>>> db.ex('select * from note_links where parent_id = ? and child_id = ?', [123, 789])
>>> db.ex(
[
'select * from notes',
'select * from notes where id = ? or id = ?'],
[
None,
[123, 456]
]
)
"""
if isinstance(query, (list, tuple)):
# check that arguments appropriate for batch operation
if not (
(
isinstance(params, (list, tuple))
and
all(
isinstance(
p, (list, tuple, type(None)))
for p in params
)
and
(len(query) == len(params))
)
or
isinstance(query, (list, tuple))
):
raise ValueError(
'''If running batch, query must be list of queries and,
if provided, params a list of lists of parameters,
with the outer list with the same length as the query list'''
)
else:
if params is None:
params = [None for _ in query]
with self.conn: # auto commit/rollback
for q, p in zip(query, params):
if p:
self.cursor.execute(q, p)
else:
self.cursor.execute(q)
output = self.cursor.fetchall()
else: # if not batch
with self.conn: # auto commit/rollback
if params:
self.cursor.execute(query, params)
else:
self.cursor.execute(query)
output = self.cursor.fetchall()
return output
class NoteName:
def __init__(self, id: int, title: Optional[str] = None):
self.id = id
self._title = title
@property
def title(self):
return '' if not self._title else self._title
class Note:
def __init__(
self,
name: NoteName,
frontmatter: Optional[str] = None,
body: Optional[str] = None,
tags: Optional[list] = None,
links: Optional[list] = None
):
self.name = name
self.id = name.id
self.title = name.title
self.frontmatter = frontmatter
self.body = body
self.tags: list = [] if tags is None else tags
self.links: list = [] if links is None else links
class NoteError(ValueError):
pass
# > Table Creation
def db_connection(db_path: Path, new: bool = False) -> DB:
if not db_path.exists() and not new:
raise ValueError('Db Path exists already!')
elif new:
db_path.touch()
conn = sql.connect(db_path)
cursor = conn.cursor()
db = DB(conn, cursor)
# foreign keys on and check
db.cursor.execute('pragma foreign_keys = ON')
db.cursor.execute('pragma foreign_keys;')
fk_check = db.cursor.fetchone()
if fk_check[0] != 1:
raise sql.DatabaseError('Foreign Keys not enabled')
return db
def db_init(db: DB):
with open(SCHEMA_PATH, 'r') as f:
schema = f.read()
db.cursor.executescript(schema)
##############
# PREVIOUS CREATION CODE DEPRECATED WITH INIT
##############
# > Add to Tables
# >> Notes
def make_mod_time() -> float:
"timestamp of right now in UTC (for recording modified times)"
return dt.datetime.utcnow().timestamp()
def get_note_mod_time(note_path: Path) -> float:
"modified time of a file, according to OS, as timestamp, in UTC time"
file_mtime = note_path.stat().st_mtime
# file_mtime is in system/OS timezone
# utcfromtimestamp gives time in UTC timezone
return dt.datetime.utcfromtimestamp(file_mtime).timestamp()
def make_new_note_id() -> int:
now = int(dt.datetime.utcnow().strftime('%Y%m%d%H%M%S'))
return now
def make_note_name_string(note_name: NoteName) -> str:
return '{id} {title}'.format(
id = note_name.id,
title = '' if not note_name.title else note_name.title
)
def make_note_file_name(note_name: NoteName) -> str:
return '{note_name}{ext}'.format(
note_name = make_note_name_string(note_name),
ext = NOTE_EXTENSION)
def parse_note_name(source: Union[str, Path]) -> NoteName:
if isinstance(source, Path):
source_string = source.stem
else:
source_string = source
note_name = note_name_pattern.search(source_string)
if not note_name:
raise NoteError(
'Note file name ({}) not valid for note found at {}'
.format(source)
)
note_id = int(note_name.group(1))
note_title: str = note_name.group(2)
return NoteName(id=note_id, title=note_title)
def is_note_id_unique(db: DB, note_id: int) -> bool:
# this could probably done faster?
# perhaps a try-except on an insert would be fastest, to rely on sqlite's internals
# but, not sure how to accurately catch a unique constraint problem
# as they're not exposed (until oct 2021) by python API
# BEST approach may be to only to this when necessary ... after a try-except
output = db.ex('select count(*) from notes where id = ?', [note_id])
return output[0][0] == 0
def make_unique_new_note_id(db: DB):
"Check that unique and increment up to 5 times until unique if necessary"
new_id = make_new_note_id()
# try to ensure unique by waiting for id to be unique
if not is_note_id_unique(db, new_id):
for _ in range(5): # retry for 5 seconds
new_id += 1
if is_note_id_unique(db, new_id):
break
else: # if no break
raise NoteError(
'Could not generate unique id for new note (last try: {})'.format(new_id))
return new_id
def make_batch_new_note_ids(db: DB, n: int) -> list:
"Make multiple new note ids by incrementing by one n times"
base_id = make_unique_new_note_id(db)
new_ids = [base_id + i for i in range(1, n+1)]
return new_ids
# >> Links
def add_note_link(db: DB, parent_id: int, child_id: int):
"""Add link between parent and child
Unique constraint errors are skipped with "insert or ignore"
Foreign key constraint is not ignored/skipped
"""
insert_stmt = (
'''
insert or ignore
into note_links(parent_note_id, child_note_id)
values(?, ?)''',
[parent_id, child_id]
)
try:
db.ex(*insert_stmt)
# presuming to be a foreign key constrant (as unique is ignored)
except sql.IntegrityError as _:
raise NoteError('Child note with id ({}), cited in {}, does not exist'.format(
child_id, parent_id))
def update_note_links(
db: DB, parent_id: int,
child_ids: Union[int, list, tuple]):
# rewrite db.ex to not do batch but instead have a flag for whether to commit
# that way, can manually hold multiple queries until the end, then commit
# should be more flexible
# or not ...
delete_stmt = '''delete from note_links where parent_note_id = ?'''
insert_stmt = '''
insert or ignore
into note_links(parent_note_id, child_note_id)
values(?, ?)'''
if isinstance(child_ids, (list, tuple)):
db.ex(
query = [
delete_stmt,
*[insert_stmt for _ in child_ids]],
params = [
[parent_id],
*[(parent_id, child_id) for child_id in child_ids] ]
)
else:
db.ex(
query=[
delete_stmt,
insert_stmt],
params = [
[parent_id],
[parent_id, child_ids]]
)
# >> Tags
def check_root_tag_unique(db: DB, tag_name: str):
query = """
select * from tags where tag = ? and parent_id IS NULL
"""
output = db.ex(query, [tag_name])
if output:
raise sql.IntegrityError('Root tag not unique')
tag_path_pattern = re.compile(r'[a-zA-Z_][a-zA-Z_\/]*[a-zA-Z_]')
def is_valid_tag_path(tag_path: str):
return tag_path_pattern.fullmatch(tag_path)
def check_valid_tag_path(tag_path: str):
if not is_valid_tag_path(tag_path):
raise NoteError('tag path ({}) is not valid (must fullmatch with {})'.format(
tag_path, tag_path_pattern.pattern))
def get_tag_id(db: DB, tag: str, parent_id: Optional[int]) -> int:
# sqlite: "is" works with null, "=" doesn't
result = db.ex(
'select id from tags where tag = ? and parent_id is ?',
[tag, parent_id]
)
return result[0][0]
def get_tag_path_id(db: DB, tag_path: str) -> int:
check_valid_tag_path(tag_path)
result = db.ex(
'select id from full_tag_paths where full_tag_path = ?',
[tag_path])
return result[0][0]
def get_all_full_tag_path(db: DB) -> list:
paths = [
tp[0] for tp
in db.ex('select full_tag_path from full_tag_paths')
]
return paths
def add_tag(
db: DB, tag: str,
parent_id: Optional[int] = None):
# Manually check that root tag is unique
# necessary as NULL (parent of root tags) is always unique
if not parent_id:
check_root_tag_unique(db, tag)
query = """
insert into tags(tag, parent_id)
values(?, ?)
"""
db.ex(query, [tag, parent_id])
def add_new_tag_path(db: DB, new_tag_path: str):
"""Add tags necessary for new_tag_path to refer to an extant tag
return None if necessary tags already exist
return id of newly created tag (leaf) if new tag(s) created
"""
check_valid_tag_path(new_tag_path)
paths = get_all_full_tag_path(db)
## BUG HERE
# if new_tag_path is a single string with no hierarchy (no slash)
# it is still treated as a full path, despite lack of slashes
# and a parent that is a sub-string will be found if it exists in
# the previously existing paths
if new_tag_path in paths:
# tag already in database
# shouldn't happen, but just in case
return
# quick fix ... check if hierarchical
if '/' in new_tag_path:
new_path_parents = [ # get longest match from all tag_paths
tag_path for tag_path
in paths
if new_tag_path.startswith(tag_path) # ensure parent is at start
# if tag_path in new_tag_path
]
# find max according to most levels in common
new_path_parent = max(
new_path_parents,
key = lambda s: len(s.split('/')),
default=None)
# just a simple top level tag
else:
new_tag = new_tag_path
add_tag(db, new_tag, parent_id=None)
new_id = get_tag_id(db, new_tag, parent_id=None)
return new_id
# no match or match does not start from beginning or is not SUB-string (ie too long)
# then new path is all new tags
if not new_path_parent or not (new_tag_path.find(new_path_parent) == 0):
new_path_parent_id = None
# whole path is new!
new_tags = new_tag_path.split('/')
else:
new_path_parent_id = get_tag_path_id(db, new_path_parent)
# get list of new tags that need to be added with new_path_parent at root
new_tags = new_tag_path[len(new_path_parent)+1:].split('/')
for new_tag in new_tags:
print(new_tag, new_path_parent_id)
add_tag(db, new_tag, parent_id = new_path_parent_id)
new_id = get_tag_id(db, new_tag, parent_id=new_path_parent_id)
# now use new tag as parent id for the next
new_path_parent_id = new_id
# return id of new tag
return new_id # type: ignore
def add_note_tag(db, note_id: int, tag_id: int):
db.ex('''
insert into note_tags(note_id, tag_id) values(?,?)''',
[note_id, tag_id]
)
def update_note_tags(db, note_id: int, tag_ids: Union[int, list, tuple]):
delete_stmt = '''delete from note_tags where note_id = ?'''
insert_stmt = '''
insert into note_tags(note_id, tag_id)
values(?, ?)'''
if isinstance(tag_ids, (list, tuple)):
db.ex(
query = [
delete_stmt,
*[insert_stmt for _ in tag_ids]],
params = [
[note_id],
*[(note_id, tag_id) for tag_id in tag_ids]]
)
else:
db.ex(
query = [
delete_stmt,
insert_stmt],
params = [
[note_id],
[note_id, tag_ids]]
)
# >> Parsing notes
def parse_note_body(body: str) -> Tuple[str, list, list]:
"""Returns frontmatter, tags and links
tags is list of strings of full_tag_path
links is list of note_ids (str)
"""
# parse front matter
front_matter = front_matter_pattern.match(body)
# unsure if notes need frontmatter ... at the moment ... no
# if not front_matter:
# raise NoteError('Note contains no valid front matter')
metadata = {}
front_matter_text = ''
if front_matter:
front_matter_text = front_matter.group(1)
for line in front_matter_text.splitlines():
key, value = [token.strip() for token in line.split(':')]
if key == 'tags':
# ensure no repeat tags ... convert back to list for cleanness downstream
tags = list(
set([token.strip() for token in value.split(',')])
)
for tag in tags:
# catch invalid tags early
check_valid_tag_path(tag)
metadata[key] = tags
else:
metadata[key] = value
# parse links
links = link_pattern.findall(body)
# convert set back to list for cleanness downstream
link_ids = list(set(link[1] for link in links))
tags = metadata.get('tags', [])
return front_matter_text, tags, link_ids
def parse_note(note_path: Path) -> Note:
"""Read and parse text of a note to get all necessary data
"""
note_name = parse_note_name(note_path)
with open(note_path) as f:
body = f.read()
front_matter_text, tags, link_ids = parse_note_body(body)
note = Note(
name = note_name,
frontmatter=front_matter_text,
body=body,
tags=tags,
links=link_ids
)
return note
def stage_note(db: DB, note_path: Path):
"Add a note to the staging table"
note_name = parse_note_name(note_path)
db.ex('insert or ignore into staged_notes(id, title, note_path, add_time) values(?,?,?,?)',
[note_name.id, note_name.title, note_path.as_posix(), make_mod_time()])
def make_new_note(db: DB, title: Optional[str] = None):
"""Create a new note with ID formed by current time and provided title
Content intended to be added by another function. This is for initialisation
"""
# get id
new_id = make_new_note_id()
# use try block to check uniqueness of id as sqlite check is prob better than manual query
try:
db.ex('insert into notes(id, title) values(?, ?)', [new_id, title])
except sql.IntegrityError:
new_id = make_unique_new_note_id(db)
db.ex('insert into notes(id, title) values(?, ?)', [new_id, title])
note_name = NoteName(new_id, title)
note_path = (ZK_PATH / Path(make_note_file_name(note_name)))
note_path.touch(exist_ok=False)
# add entry in staged table
stage_note(db, note_path)
# db.ex('insert into staged_notes(id, title, note_path, add_time) values(?,?,?,?)',
# [note_name.id, note_name.title, note_path.as_posix(), make_mod_time()])
return note_path
def update_note(db: DB, note_path: Path):
"Update content of existing note"
# everything but the ID (that would be a new note)
# tags could be tricky ... probably need a separate add/update tags function
if not note_path.exists():
raise NoteError('Note not found at path {}'.format(note_path))
note = parse_note(note_path)
db.ex('''
update notes
set
title = ?,
frontmatter = ?,
body = ?,
mod_time = ?
where id = ?''',
[note.title, note.frontmatter, note.body, make_mod_time(), note.id]
)
update_note_links(db, note.id, note.links)
# Tags
# can roll up into a generalised update function?
# or good to keep tag update function simple and leave management here ... ?
tag_paths = get_all_full_tag_path(db)
new_tag_paths = []
for tag_path in note.tags:
check_valid_tag_path(tag_path)
if tag_path in tag_paths:
tag_id = get_tag_path_id(db, tag_path)
else:
tag_id = add_new_tag_path(db, tag_path)
if tag_id is None:
raise NoteError('Failed to add new tag ({})'.format(tag_path))
new_tag_paths.append(tag_id)
# add_note_tag(db, note.id, tag_id)
update_note_tags(db, note.id, new_tag_paths)
# remove from staging
db.ex('delete from staged_notes where id = ?', [note.id])
def add_old_note(db, note_path: Path):
note = parse_note(note_path)
if not is_note_id_unique(db, note.id):
raise NoteError('old note id {} is not unique (note_path: {})'.format(
note.id, note_path))
db.ex('insert into notes(id, title) values(?, ?)', [note.id, note.title])
update_note(db, note_path)
# BIG ISSUE Here with note_links and the foreign key constraint
# if adding notes one at a time, a link is likely to be to a note not yet added
# and can be unresolvable adding only one note at a time
# BETTER to batch add all the notes into the notes table only, then update
# keep a list of failed notes to report at the end
def add_batch_old_note(db, note_paths: list):
failed_notes = set()
for note_path in note_paths:
note = parse_note(note_path)
if not is_note_id_unique(db, note.id):
raise NoteError('old note id {} is not unique (note_path: {})'.format(
note.id, note_path))
try:
db.ex('insert into notes(id, title) values(?, ?)', [note.id, note.title])
except Exception:
failed_notes.add(note_path)
update_fails = set()
for note_path in note_paths:
if note_path not in failed_notes:
try:
update_note(db, note_path)
except Exception:
update_fails.add(note_path)
return failed_notes, update_fails
def update_all_notes(db: DB, note_dir_path: Path) -> Tuple[set, set]:
"Add or update all note_path files in note_dir_path"
note_paths = note_dir_path.glob(f'*{NOTE_EXTENSION}')
new_note_paths = []
update_note_paths = []
for note_path in note_paths:
note = parse_note(note_path)
result = db.ex('select mod_time from notes where id = ?', [note.id])
# note not in database as empty list returned
if not result:
new_note_paths.append(note_path)
else:
mod_time = float(result[0][0])
note_mod_time = get_note_mod_time(note_path)
# note file modified since database entry was last updated
if note_mod_time > mod_time:
update_note_paths.append(note_path)
# add new notes
failed, update_failed = add_batch_old_note(db, new_note_paths)
# update notes that have been modified
for note_path in update_note_paths:
try:
update_note(db, note_path)
except Exception:
update_failed.add(note_path)
return failed, update_failed
def delete_note(db: DB, note_path: Path):
"delete note from db and file"
# note_name = parse_note_name(note_path)
note = parse_note(note_path)
db.ex(
[
'delete from notes where id = ?',
'delete from note_links where parent_note_id = ?',
'delete from note_tags where note_id = ?'
],
[
[note.id],
[note.id],
[note.id]
]
)
note_path.unlink()
# >> Staging and Opening Notes
def open_note(db: DB, note_path: Path):
open_note_command = [
element.strip()
for element in
config['editor_shell_command']
.format(note_path)
.split(',')
]
_ = subprocess.call(open_note_command)
stage_note(db, note_path)
# > query notes
# >> Fuzzy id
def get_note_ids_from_fuzzy_id(db: DB, fuzzy_id: int) -> Optional[Union[list, Path]]:
note_cands = db.ex('select id, title from notes where id like ("%" || ?)', [fuzzy_id])
if not note_cands:
return
elif len(note_cands) > 1:
return note_cands
else:
note_path = ZK_PATH / Path(make_note_file_name(NoteName(*note_cands[0])))
return note_path
# >> CTEs
def id_cte(note_id: int):
"CTE for selecting notes by tail of note_id"
id_cte = f'''
id_notes(note_id) as (
select id from notes
where id like "%{note_id}"
)
'''
return dedent(id_cte)
def tag_cte(tag: str):
"CTE for select note_ids with a single tag"
tag_cte = f'''
tagged_notes(note_id) as (
select note_id from note_tags
where tag_id = (
select id from full_tag_paths where full_tag_path = "{tag}"
)
)
'''
return dedent(tag_cte)
def title_cte(phrase: str):
'''
CTE for selecting note_ids of all notes with matching FTS phrase in title
phrase formats include:
"token1 token2" (implicit AND)
"token1 + token2" (single search term ... concatenated into single)
"(token1 AND token2) OR token3" (booleans with operators in caps and parens for order)
'''
title_cte = f'''
title_notes(note_id) as (
select rowid from notes_fts
where title match "{phrase}"
)
'''
return dedent(title_cte)
def body_cte(phrase: str):
'''
CTE for selecting note_ids of all notes with matching FTS phrase in body
phrase formats include:
"token1 token2" (implicit AND)
"token1 + token2" (single search term ... concatenated into single)
"(token1 AND token2) OR token3" (booleans with operators in caps and parens for order)
'''
body_cte = f'''
body_notes(note_id) as (
select rowid from notes_fts
where body match "{phrase}"
)
'''
return dedent(body_cte)
def child_cte(note_id: int):
"CTE for all notes that are child of note_id"
child_cte = f'''
child_notes(note_id) as (
select child_note_id from note_links
where parent_note_id = "{note_id}"
)
'''
return dedent(child_cte)
def children_cte(*_):
"""all children of all previously selected notes
Is a passive follow-through CTE that simply allows for a join
"""
cte = f'''
children_notes(parent_note_id, note_id) as (
select parent_note_id, child_note_id
from note_links
)
'''
return dedent(cte)
def parents_cte(*_):
"""all children of all previously selected notes
Is a passive follow-through CTE that simply allows for a join
"""
cte = f'''
parents_notes(note_id, child_note_id) as (
select parent_note_id, child_note_id
from note_links
)
'''
return dedent(cte)
def tag_or_cte(tags: str):
"CTE for all notes with any or all of tags provided as 'a, b, c'"
tags_tuple = tuple(t.strip() for t in tags.split(','))
cte = f'''
tagged_or_notes(note_id) as (
select note_id
from note_tags
where tag_id in (
select id from full_tag_paths where full_tag_path in {tags_tuple}
)
group by note_id
)
'''
return dedent(cte)
def tag_and_cte(tags: str):
"CTE for all notes with all of the provided tags provided as 'a b c' (implicit AND)"
tags_tuple = tuple(t.strip() for t in tags.split(' '))
cte = f'''
tagged_and_notes(note_id) as (
select note_id
from note_tags
where tag_id in (
select id from full_tag_paths where full_tag_path in {tags_tuple}
)
group by note_id
having count(note_id) = {len(tags_tuple)}
)
'''
return dedent(cte)
# >> CTE keywords to functions maping
# just single characters from alphabet ... could maybe create a mapping
cte_aliases = list(string.ascii_lowercase)
cte_map = {
'id': id_cte,
'title': title_cte,