-
Notifications
You must be signed in to change notification settings - Fork 114
/
note_dao.go
901 lines (764 loc) · 22.1 KB
/
note_dao.go
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
package sqlite
import (
"database/sql"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"github.com/mickael-menu/zk/internal/core"
"github.com/mickael-menu/zk/internal/util"
"github.com/mickael-menu/zk/internal/util/errors"
"github.com/mickael-menu/zk/internal/util/fts5"
"github.com/mickael-menu/zk/internal/util/opt"
"github.com/mickael-menu/zk/internal/util/paths"
strutil "github.com/mickael-menu/zk/internal/util/strings"
)
// NoteDAO persists notes in the SQLite database.
type NoteDAO struct {
tx Transaction
logger util.Logger
// Prepared SQL statements
indexedStmt *LazyStmt
addStmt *LazyStmt
updateStmt *LazyStmt
removeStmt *LazyStmt
findIdByPathStmt *LazyStmt
findIdsByPathRegexStmt *LazyStmt
findByIdStmt *LazyStmt
}
// NewNoteDAO creates a new instance of a DAO working on the given database
// transaction.
func NewNoteDAO(tx Transaction, logger util.Logger) *NoteDAO {
return &NoteDAO{
tx: tx,
logger: logger,
// Get file info about all indexed notes.
indexedStmt: tx.PrepareLazy(`
SELECT path, modified from notes
ORDER BY sortable_path ASC
`),
// Add a new note to the index.
addStmt: tx.PrepareLazy(`
INSERT INTO notes (path, sortable_path, title, lead, body, raw_content, word_count, metadata, checksum, created, modified)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`),
// Update the content of a note.
updateStmt: tx.PrepareLazy(`
UPDATE notes
SET title = ?, lead = ?, body = ?, raw_content = ?, word_count = ?, metadata = ?, checksum = ?, modified = ?
WHERE path = ?
`),
// Remove a note.
removeStmt: tx.PrepareLazy(`
DELETE FROM notes
WHERE id = ?
`),
// Find a note ID from its exact path.
findIdByPathStmt: tx.PrepareLazy(`
SELECT id FROM notes
WHERE path = ?
`),
// Find note IDs from a regex matching their path.
findIdsByPathRegexStmt: tx.PrepareLazy(`
SELECT id FROM notes
WHERE path REGEXP ?
-- To find the best match possible, we sort by path length.
-- See https://github.com/mickael-menu/zk/issues/23
ORDER BY LENGTH(path) ASC
`),
// Find a note from its ID.
findByIdStmt: tx.PrepareLazy(`
SELECT id, path, title, lead, body, raw_content, word_count, created, modified, metadata, checksum, tags, lead AS snippet
FROM notes_with_metadata
WHERE id = ?
`),
}
}
// Indexed returns file info of all indexed notes.
func (d *NoteDAO) Indexed() (<-chan paths.Metadata, error) {
rows, err := d.indexedStmt.Query()
if err != nil {
return nil, err
}
c := make(chan paths.Metadata)
go func() {
defer close(c)
defer rows.Close()
var (
path string
modified time.Time
)
for rows.Next() {
err := rows.Scan(&path, &modified)
if err != nil {
d.logger.Err(err)
}
c <- paths.Metadata{
Path: path,
Modified: modified,
}
}
err = rows.Err()
if err != nil {
d.logger.Err(err)
}
}()
return c, nil
}
// Add inserts a new note to the index.
func (d *NoteDAO) Add(note core.Note) (core.NoteID, error) {
// For sortable_path, we replace in path / by the shortest non printable
// character available to make it sortable. Without this, sorting by the
// path would be a lexicographical sort instead of being the same order
// returned by filepath.Walk.
// \x01 is used instead of \x00, because SQLite treats \x00 as and end of
// string.
sortablePath := strings.ReplaceAll(note.Path, "/", "\x01")
metadata := d.metadataToJSON(note)
res, err := d.addStmt.Exec(
note.Path, sortablePath, note.Title, note.Lead, note.Body,
note.RawContent, note.WordCount, metadata, note.Checksum, note.Created,
note.Modified,
)
if err != nil {
return 0, err
}
lastId, err := res.LastInsertId()
if err != nil {
return 0, err
}
return core.NoteID(lastId), err
}
// Update modifies an existing note.
func (d *NoteDAO) Update(note core.Note) (core.NoteID, error) {
id, err := d.FindIdByPath(note.Path)
if err != nil {
return 0, err
}
if !id.IsValid() {
return 0, errors.New("note not found in the index")
}
metadata := d.metadataToJSON(note)
_, err = d.updateStmt.Exec(
note.Title, note.Lead, note.Body, note.RawContent, note.WordCount,
metadata, note.Checksum, note.Modified, note.Path,
)
return id, err
}
func (d *NoteDAO) metadataToJSON(note core.Note) string {
json, err := json.Marshal(note.Metadata)
if err != nil {
// Failure to serialize the metadata to JSON should not prevent the
// note from being saved.
d.logger.Err(errors.Wrapf(err, "cannot serialize note metadata to JSON: %s", note.Path))
return "{}"
}
return string(json)
}
// Remove deletes the note with the given path from the index.
func (d *NoteDAO) Remove(path string) error {
id, err := d.FindIdByPath(path)
if err != nil {
return err
}
if !id.IsValid() {
return errors.New("note not found in the index")
}
_, err = d.removeStmt.Exec(id)
return err
}
func (d *NoteDAO) FindIdByPath(path string) (core.NoteID, error) {
row, err := d.findIdByPathStmt.QueryRow(path)
if err != nil {
return core.NoteID(0), err
}
return idForRow(row)
}
func idForRow(row *sql.Row) (core.NoteID, error) {
var id sql.NullInt64
err := row.Scan(&id)
switch {
case err == sql.ErrNoRows:
return 0, nil
case err != nil:
return 0, err
default:
return core.NoteID(id.Int64), nil
}
}
func (d *NoteDAO) findIdsByPathRegex(regex string) ([]core.NoteID, error) {
ids := []core.NoteID{}
rows, err := d.findIdsByPathRegexStmt.Query(regex)
if err != nil {
return ids, err
}
defer rows.Close()
for rows.Next() {
var id sql.NullInt64
err := rows.Scan(&id)
if err != nil {
return ids, err
}
ids = append(ids, core.NoteID(id.Int64))
}
return ids, nil
}
func (d *NoteDAO) findIdWithStmt(stmt *LazyStmt, args ...interface{}) (core.NoteID, error) {
row, err := stmt.QueryRow(args...)
if err != nil {
return core.NoteID(0), err
}
var id sql.NullInt64
err = row.Scan(&id)
switch {
case err == sql.ErrNoRows:
return 0, nil
case err != nil:
return 0, err
default:
return core.NoteID(id.Int64), nil
}
}
func (d *NoteDAO) FindIdByHref(href string, allowPartialHref bool) (core.NoteID, error) {
ids, err := d.FindIdsByHref(href, allowPartialHref)
if len(ids) == 0 || err != nil {
return 0, err
}
return ids[0], nil
}
func (d *NoteDAO) findIdsByHrefs(hrefs []string, allowPartialHrefs bool) ([]core.NoteID, error) {
ids := make([]core.NoteID, 0)
for _, href := range hrefs {
cids, err := d.FindIdsByHref(href, allowPartialHrefs)
if err != nil {
return ids, err
}
ids = append(ids, cids...)
}
return ids, nil
}
// FIXME: This logic is duplicated in NoteIndex.linkMatchesPath(). Maybe there's a way to share it using a custom SQLite function?
func (d *NoteDAO) FindIdsByHref(href string, allowPartialHref bool) ([]core.NoteID, error) {
// Remove any anchor at the end of the HREF, since it's most likely
// matching a sub-section in the note.
href = strings.SplitN(href, "#", 2)[0]
href = regexp.QuoteMeta(href)
if allowPartialHref {
ids, err := d.findIdsByPathRegex("^(.*/)?[^/]*" + href + "[^/]*$")
if len(ids) > 0 || err != nil {
return ids, err
}
ids, err = d.findIdsByPathRegex(".*" + href + ".*")
if len(ids) > 0 || err != nil {
return ids, err
}
}
ids, err := d.findIdsByPathRegex("^(?:" + href + "[^/]*|" + href + "/.+)$")
if len(ids) > 0 || err != nil {
return ids, err
}
return []core.NoteID{}, nil
}
func (d *NoteDAO) FindMinimal(opts core.NoteFindOpts) ([]core.MinimalNote, error) {
notes := make([]core.MinimalNote, 0)
opts, err := d.expandMentionsIntoMatch(opts)
if err != nil {
return notes, err
}
rows, err := d.findRows(opts, noteSelectionMinimal)
if err != nil {
return notes, err
}
defer rows.Close()
for rows.Next() {
note, err := d.scanMinimalNote(rows)
if err != nil {
d.logger.Err(err)
continue
}
if note != nil {
notes = append(notes, *note)
}
}
return notes, nil
}
// Find returns all the notes matching the given criteria.
func (d *NoteDAO) Find(opts core.NoteFindOpts) ([]core.ContextualNote, error) {
notes := make([]core.ContextualNote, 0)
opts, err := d.expandMentionsIntoMatch(opts)
if err != nil {
return notes, err
}
rows, err := d.findRows(opts, noteSelectionFull)
if err != nil {
return notes, err
}
defer rows.Close()
for rows.Next() {
note, err := d.scanNote(rows)
if err != nil {
d.logger.Err(err)
continue
}
if note != nil {
notes = append(notes, *note)
}
}
return notes, nil
}
// parseListFromNullString splits a 0-separated string.
func parseListFromNullString(str sql.NullString) []string {
list := []string{}
if str.Valid && str.String != "" {
list = strings.Split(str.String, "\x01")
list = strutil.RemoveDuplicates(list)
list = strutil.RemoveBlank(list)
}
return list
}
// expandMentionsIntoMatch finds the titles associated with the notes in opts.Mention to
// expand them into the opts.Match predicate.
func (d *NoteDAO) expandMentionsIntoMatch(opts core.NoteFindOpts) (core.NoteFindOpts, error) {
if opts.Mention == nil {
return opts, nil
}
if opts.MatchStrategy != core.MatchStrategyFts {
return opts, fmt.Errorf("--mention can only be used with --match-strategy=fts")
}
// Find the IDs for the mentioned paths.
ids, err := d.findIdsByHrefs(opts.Mention, true /* allowPartialHrefs */)
if err != nil {
return opts, err
}
if len(ids) == 0 {
return opts, fmt.Errorf("could not find notes at: " + strings.Join(opts.Mention, ", "))
}
// Exclude the mentioned notes from the results.
opts = opts.ExcludingIDs(ids)
// Find their titles.
titlesQuery := "SELECT title, metadata FROM notes WHERE id IN (" + joinNoteIDs(ids, ",") + ")"
rows, err := d.tx.Query(titlesQuery)
if err != nil {
return opts, err
}
defer rows.Close()
mentionQueries := []string{}
for rows.Next() {
var title, metadataJSON string
err := rows.Scan(&title, &metadataJSON)
if err != nil {
return opts, err
}
mentionQueries = append(mentionQueries, buildMentionQuery(title, metadataJSON))
}
if len(mentionQueries) == 0 {
return opts, nil
}
// Expand the mention queries in the match predicate.
match := opts.Match.String()
match += " " + strings.Join(mentionQueries, " OR ")
opts.Match = opt.NewString(match)
return opts, nil
}
// noteSelection represents the amount of column selected with findRows.
type noteSelection int
const (
noteSelectionID noteSelection = iota + 1
noteSelectionMinimal
noteSelectionFull
)
func (d *NoteDAO) findRows(opts core.NoteFindOpts, selection noteSelection) (*sql.Rows, error) {
snippetCol := `n.lead`
joinClauses := []string{}
whereExprs := []string{}
additionalOrderTerms := []string{}
args := []interface{}{}
groupBy := ""
transitiveClosure := false
maxDistance := 0
setupLinkFilter := func(hrefs []string, direction int, negate, recursive bool) error {
ids, err := d.findIdsByHrefs(hrefs, true /* allowPartialHrefs */)
if err != nil {
return err
}
if len(ids) == 0 {
return fmt.Errorf("could not find notes at: " + strings.Join(hrefs, ", "))
}
idsList := "(" + joinNoteIDs(ids, ",") + ")"
linksSrc := "links"
if recursive {
transitiveClosure = true
linksSrc = "transitive_closure"
}
if !negate {
if direction != 0 {
snippetCol = "GROUP_CONCAT(REPLACE(l.snippet, l.title, '<zk:match>' || l.title || '</zk:match>'), '\x01')"
}
joinOns := make([]string, 0)
if direction <= 0 {
joinOns = append(joinOns, fmt.Sprintf(
"(n.id = l.target_id AND l.source_id IN %s)", idsList,
))
}
if direction >= 0 {
joinOns = append(joinOns, fmt.Sprintf(
"(n.id = l.source_id AND l.target_id IN %s)", idsList,
))
}
joinClauses = append(joinClauses, fmt.Sprintf(
"LEFT JOIN %s l ON %s",
linksSrc,
strings.Join(joinOns, " OR "),
))
groupBy = "GROUP BY n.id"
}
idExpr := "n.id"
if negate {
idExpr += " NOT"
}
idSelects := make([]string, 0)
if direction <= 0 {
idSelects = append(idSelects, fmt.Sprintf(
" SELECT target_id FROM %s WHERE target_id IS NOT NULL AND source_id IN %s",
linksSrc, idsList,
))
}
if direction >= 0 {
idSelects = append(idSelects, fmt.Sprintf(
" SELECT source_id FROM %s WHERE target_id IS NOT NULL AND target_id IN %s",
linksSrc, idsList,
))
}
idExpr += " IN (\n" + strings.Join(idSelects, "\n UNION\n") + "\n)"
whereExprs = append(whereExprs, idExpr)
return nil
}
if !opts.Match.IsNull() {
switch opts.MatchStrategy {
case core.MatchStrategyExact:
whereExprs = append(whereExprs, `n.raw_content LIKE '%' || ? || '%' ESCAPE '\'`)
args = append(args, escapeLikeTerm(opts.Match.String(), '\\'))
case core.MatchStrategyFts:
snippetCol = `snippet(fts_match.notes_fts, 2, '<zk:match>', '</zk:match>', '…', 20)`
joinClauses = append(joinClauses, "JOIN notes_fts fts_match ON n.id = fts_match.rowid")
additionalOrderTerms = append(additionalOrderTerms, `bm25(fts_match.notes_fts, 1000.0, 500.0, 1.0)`)
whereExprs = append(whereExprs, "fts_match.notes_fts MATCH ?")
args = append(args, fts5.ConvertQuery(opts.Match.String()))
case core.MatchStrategyRe:
whereExprs = append(whereExprs, "n.raw_content REGEXP ?")
args = append(args, opts.Match.String())
break
}
}
if opts.IncludeHrefs != nil {
ids, err := d.findIdsByHrefs(opts.IncludeHrefs, opts.AllowPartialHrefs)
if err != nil {
return nil, err
}
opts = opts.IncludingIDs(ids)
}
if opts.ExcludeHrefs != nil {
ids, err := d.findIdsByHrefs(opts.ExcludeHrefs, opts.AllowPartialHrefs)
if err != nil {
return nil, err
}
opts = opts.ExcludingIDs(ids)
}
if opts.Tags != nil {
separatorRegex := regexp.MustCompile(`(\ OR\ )|\|`)
for _, tagsArg := range opts.Tags {
tags := separatorRegex.Split(tagsArg, -1)
negate := false
globs := make([]string, 0)
for _, tag := range tags {
tag = strings.TrimSpace(tag)
if strings.HasPrefix(tag, "-") {
negate = true
tag = strings.TrimPrefix(tag, "-")
} else if strings.HasPrefix(tag, "NOT") {
negate = true
tag = strings.TrimPrefix(tag, "NOT")
}
tag = strings.TrimSpace(tag)
if len(tag) == 0 {
continue
}
globs = append(globs, "t.name GLOB ?")
args = append(args, tag)
}
if len(globs) == 0 {
continue
}
if negate && len(globs) > 1 {
return nil, fmt.Errorf("cannot negate a tag in a OR group: %s", tagsArg)
}
expr := "n.id"
if negate {
expr += " NOT"
}
expr += fmt.Sprintf(` IN (
SELECT note_id FROM notes_collections
WHERE collection_id IN (SELECT id FROM collections t WHERE kind = '%s' AND (%s))
)`,
core.CollectionKindTag,
strings.Join(globs, " OR "),
)
whereExprs = append(whereExprs, expr)
}
}
if opts.MentionedBy != nil {
ids, err := d.findIdsByHrefs(opts.MentionedBy, true /* allowPartialHrefs */)
if err != nil {
return nil, err
}
if len(ids) == 0 {
return nil, fmt.Errorf("could not find notes at: " + strings.Join(opts.MentionedBy, ", "))
}
// Exclude the mentioning notes from the results.
opts = opts.ExcludingIDs(ids)
snippetCol = `snippet(nsrc.notes_fts, 2, '<zk:match>', '</zk:match>', '…', 20)`
joinClauses = append(joinClauses, "JOIN notes_fts nsrc ON nsrc.rowid IN ("+joinNoteIDs(ids, ",")+") AND nsrc.notes_fts MATCH mention_query(n.title, n.metadata)")
}
if opts.LinkedBy != nil {
filter := opts.LinkedBy
maxDistance = filter.MaxDistance
err := setupLinkFilter(filter.Hrefs, -1, filter.Negate, filter.Recursive)
if err != nil {
return nil, err
}
}
if opts.LinkTo != nil {
filter := opts.LinkTo
maxDistance = filter.MaxDistance
err := setupLinkFilter(filter.Hrefs, 1, filter.Negate, filter.Recursive)
if err != nil {
return nil, err
}
}
if opts.Related != nil {
maxDistance = 2
err := setupLinkFilter(opts.Related, 0, false, true)
if err != nil {
return nil, err
}
groupBy += " HAVING MIN(l.distance) = 2"
}
if opts.Orphan {
whereExprs = append(whereExprs, `n.id NOT IN (
SELECT target_id FROM links WHERE target_id IS NOT NULL
)`)
}
if opts.CreatedStart != nil {
whereExprs = append(whereExprs, "created >= ?")
args = append(args, opts.CreatedStart)
}
if opts.CreatedEnd != nil {
whereExprs = append(whereExprs, "created < ?")
args = append(args, opts.CreatedEnd)
}
if opts.ModifiedStart != nil {
whereExprs = append(whereExprs, "modified >= ?")
args = append(args, opts.ModifiedStart)
}
if opts.ModifiedEnd != nil {
whereExprs = append(whereExprs, "modified < ?")
args = append(args, opts.ModifiedEnd)
}
if opts.IncludeIDs != nil {
whereExprs = append(whereExprs, "n.id IN ("+joinNoteIDs(opts.IncludeIDs, ",")+")")
}
if opts.ExcludeIDs != nil {
whereExprs = append(whereExprs, "n.id NOT IN ("+joinNoteIDs(opts.ExcludeIDs, ",")+")")
}
orderTerms := []string{}
for _, sorter := range opts.Sorters {
orderTerms = append(orderTerms, orderTerm(sorter))
}
orderTerms = append(orderTerms, additionalOrderTerms...)
orderTerms = append(orderTerms, `n.title ASC`)
query := ""
// Credit to https://inviqa.com/blog/storing-graphs-database-sql-meets-social-network
if transitiveClosure {
orderTerms = append([]string{"l.distance"}, orderTerms...)
query += `WITH RECURSIVE transitive_closure(source_id, target_id, title, snippet, distance, path) AS (
SELECT source_id, target_id, title, snippet,
1 AS distance,
'.' || source_id || '.' || target_id || '.' AS path
FROM links
UNION ALL
SELECT tc.source_id, l.target_id, l.title, l.snippet,
tc.distance + 1,
tc.path || l.target_id || '.' AS path
FROM links AS l
JOIN transitive_closure AS tc
ON l.source_id = tc.target_id
WHERE tc.path NOT LIKE '%.' || l.target_id || '.%'`
if maxDistance != 0 {
query += fmt.Sprintf(" AND tc.distance < %d", maxDistance)
}
// Guard against infinite loops by limiting the number of recursions.
query += "\n LIMIT 100000"
query += "\n)\n"
}
query += "SELECT n.id"
if selection != noteSelectionID {
query += ", n.path, n.title, n.metadata"
if selection != noteSelectionMinimal {
query += fmt.Sprintf(", n.lead, n.body, n.raw_content, n.word_count, n.created, n.modified, n.checksum, n.tags, %s AS snippet", snippetCol)
}
}
query += "\nFROM notes_with_metadata n\n"
for _, clause := range joinClauses {
query += clause + "\n"
}
if len(whereExprs) > 0 {
query += "WHERE " + strings.Join(whereExprs, "\nAND ") + "\n"
}
if groupBy != "" {
query += groupBy + "\n"
}
query += "ORDER BY " + strings.Join(orderTerms, ", ") + "\n"
if opts.Limit > 0 {
query += fmt.Sprintf("LIMIT %d\n", opts.Limit)
}
// d.logger.Println(query)
// d.logger.Println(args)
return d.tx.Query(query, args...)
}
func (d *NoteDAO) scanNoteID(row RowScanner) (core.NoteID, error) {
var id int
err := row.Scan(&id)
switch {
case err == sql.ErrNoRows:
return 0, nil
case err != nil:
return 0, err
default:
return core.NoteID(id), nil
}
}
func (d *NoteDAO) scanMinimalNote(row RowScanner) (*core.MinimalNote, error) {
var (
id int
path, title, metadataJSON string
)
err := row.Scan(&id, &path, &title, &metadataJSON)
switch {
case err == sql.ErrNoRows:
return nil, nil
case err != nil:
return nil, err
default:
metadata, err := unmarshalMetadata(metadataJSON)
if err != nil {
d.logger.Err(errors.Wrap(err, path))
}
return &core.MinimalNote{
ID: core.NoteID(id),
Path: path,
Title: title,
Metadata: metadata,
}, nil
}
}
func (d *NoteDAO) scanNote(row RowScanner) (*core.ContextualNote, error) {
var (
id, wordCount int
title, lead, body, rawContent string
snippets, tags sql.NullString
path, metadataJSON, checksum string
created, modified time.Time
)
err := row.Scan(
&id, &path, &title, &metadataJSON, &lead, &body, &rawContent,
&wordCount, &created, &modified, &checksum, &tags, &snippets,
)
switch {
case err == sql.ErrNoRows:
return nil, nil
case err != nil:
return nil, err
default:
metadata, err := unmarshalMetadata(metadataJSON)
if err != nil {
d.logger.Err(errors.Wrap(err, path))
}
return &core.ContextualNote{
Snippets: parseListFromNullString(snippets),
Note: core.Note{
ID: core.NoteID(id),
Path: path,
Title: title,
Lead: lead,
Body: body,
RawContent: rawContent,
WordCount: wordCount,
Links: []core.Link{},
Tags: parseListFromNullString(tags),
Metadata: metadata,
Created: created,
Modified: modified,
Checksum: checksum,
},
}, nil
}
}
func orderTerm(sorter core.NoteSorter) string {
order := " ASC"
if !sorter.Ascending {
order = " DESC"
}
switch sorter.Field {
case core.NoteSortCreated:
return "n.created" + order
case core.NoteSortModified:
return "n.modified" + order
case core.NoteSortPath:
return "n.path" + order
case core.NoteSortRandom:
return "RANDOM()"
case core.NoteSortTitle:
return "n.title" + order
case core.NoteSortWordCount:
return "n.word_count" + order
default:
panic(fmt.Sprintf("%v: unknown core.NoteSortField", sorter.Field))
}
}
// buildMentionQuery creates an FTS5 predicate to match the given note's title
// (or aliases from the metadata) in the content of another note.
//
// It is exposed as a custom SQLite function as `mention_query()`.
func buildMentionQuery(title, metadataJSON string) string {
titles := []string{}
appendTitle := func(t string) {
t = strings.TrimSpace(t)
if t != "" {
// Remove double quotes in the title to avoid tripping the FTS5 parser.
titles = append(titles, `"`+strings.ReplaceAll(t, `"`, "")+`"`)
}
}
appendTitle(title)
// Support `aliases` key in the YAML frontmatter, like Obsidian:
// https://publish.obsidian.md/help/How+to/Add+aliases+to+note
metadata, err := unmarshalMetadata(metadataJSON)
if err == nil {
if aliases, ok := metadata["aliases"]; ok {
switch aliases := aliases.(type) {
case []interface{}:
for _, alias := range aliases {
appendTitle(fmt.Sprint(alias))
}
case string:
appendTitle(aliases)
}
}
}
if len(titles) == 0 {
// Return an arbitrary search term otherwise MATCH will find every note.
// Not proud of this hack but it does the job.
return "8b80252291ee418289cfc9968eb2961c"
}
return "(" + strings.Join(titles, " OR ") + ")"
}