/
store.go
1407 lines (1214 loc) · 29.6 KB
/
store.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
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
package store
// TODO:
// - all reads to be performed via Iter
// - all writes to be performed by Batch
// - kill all the direct-manipulation functions!
import (
"database/sql"
"fmt"
"sort"
//"github.com/bcampbell/arts/arts"
_ "github.com/mattn/go-sqlite3"
"os"
"regexp"
"strconv"
"strings"
"time"
)
type Logger interface {
Printf(format string, v ...interface{})
}
type ProgressFn func(expected int, completed int)
//
var defaultField string = "content"
// indexer is the interface for maintaining a fulltext index on the database
type indexer interface {
// add or update articles
index(...*Article) error
zap(...ArtID) error
search(string, string) (ArtList, error)
Close() error
}
// Store is the core representation of our data set.
// Provides base methods for querying, tagging, whatever
type Store struct {
db *sql.DB
dbug Logger
idx indexer
// lang is default language used for indexing
lang string
loc *time.Location
dbFile string
}
/* TEMP - cheesy access to db directly */
func (store *Store) DB() *sql.DB {
return store.db
}
// Open an existing database & index. Returns error if non-existant.
func Open(dbFile string, dbug Logger, defaultLang string, loc *time.Location) (*Store, error) {
_, err := os.Stat(dbFile)
if err != nil {
//if os.IsNotExist(err) { ... }
return nil, err
}
return internalNew(dbFile, dbug, defaultLang, loc, true)
}
// Create creates a new database and index. Returns an error if already existant.
func Create(dbFile string, dbug Logger, defaultLang string, loc *time.Location) (*Store, error) {
_, err := os.Stat(dbFile)
if os.IsNotExist(err) {
return internalNew(dbFile, dbug, defaultLang, loc, true)
} else {
return nil, fmt.Errorf("%s already exists", dbFile)
}
}
// DEPRECATED - use Open() or Create() instead
// defaultLang is lang used when creating a new db (or updating an older version).
// Otherwise Lang set from existing DB.
func New(dbFile string, dbug Logger, defaultLang string, loc *time.Location) (*Store, error) {
return internalNew(dbFile, dbug, defaultLang, loc, true)
}
// NewWithoutIndex opens a store without a fulltext interface
func NewWithoutIndex(dbFile string, dbug Logger, defaultLang string, loc *time.Location) (*Store, error) {
return internalNew(dbFile, dbug, defaultLang, loc, false)
}
func internalNew(dbFile string, dbug Logger, defaultLang string, loc *time.Location, useBleve bool) (*Store, error) {
store := &Store{dbug: dbug, lang: defaultLang, loc: loc, dbFile: dbFile}
var err error
//
store.db, err = sql.Open("sqlite3", dbFile)
if err != nil {
return nil, err
}
// make sure schema is current
err = store.ensureSchema()
if err != nil {
return nil, err
}
// update the lang from the db itself.
err = store.db.QueryRow(`SELECT v FROM settings WHERE n='lang'`).Scan(&store.lang)
if err != nil {
return nil, err
}
err = store.cleanDanglingData()
if err != nil {
return nil, err
}
if useBleve {
indexDir := dbFile + ".bleve"
fi, err := os.Stat(indexDir)
if os.IsNotExist(err) {
store.dbug.Printf("Create new index from scratch\n")
// new indexer
store.idx, err = newBleveIndex(store.dbug, indexDir, store.lang, loc)
if err != nil {
return nil, err
}
// index all articles
allArts, err := store.AllArts()
if err != nil {
return nil, err
}
err = store.reindex(allArts)
if err != nil {
return nil, err
}
} else {
store.dbug.Printf("Open existing index %s\n", indexDir)
// open existing indexer
if !fi.IsDir() {
return nil, fmt.Errorf("expected %s to be a directory", indexDir)
}
store.idx, err = openBleveIndex(store.dbug, indexDir, loc)
if err != nil {
return nil, fmt.Errorf("%s: %s", indexDir, err)
}
}
} else {
store.idx = &dummyIndex{}
}
//
return store, nil
}
// Filename returns the filename of the .db file underlying this store
func (store *Store) Filename() string {
return store.dbFile
}
func (store *Store) Close() {
if store.db != nil {
//store.dbug.Printf("Close sqlite db\n")
store.db.Close()
store.db = nil
}
if store.idx != nil {
err := store.idx.Close()
if err != nil {
store.dbug.Printf("ERROR closing index: %s\n", err)
}
store.idx = nil
}
}
func (store *Store) TotalArts() int {
var cnt int
var err error
err = store.db.QueryRow(`SELECT COUNT(*) FROM article`).Scan(&cnt)
if err != nil {
store.dbug.Printf("TotalArts() failed: %s\n", err)
return 0
}
return cnt
}
// tidy up some potentially-dangling data (due to faulty delete mechanism!)
func (store *Store) cleanDanglingData() error {
db := store.db
// clean up article_author table
result, err := db.Exec("DELETE FROM article_author WHERE article_id NOT IN (SELECT id FROM article)")
if err != nil {
return err
}
var n int64
n, err = result.RowsAffected()
if err != nil {
return err
}
if n > 0 {
store.dbug.Printf("WARNING: cleaned up %d dangling author entries\n", n)
}
// clean up article_link table
result, err = db.Exec("DELETE FROM article_link WHERE article_id NOT IN (SELECT id FROM article)")
if err != nil {
return err
}
n, err = result.RowsAffected()
if err != nil {
return err
}
if n > 0 {
store.dbug.Printf("WARNING: cleaned up %d dangling article_link entries\n", n)
}
// clean up article_keyword table
result, err = db.Exec("DELETE FROM article_keyword WHERE article_id NOT IN (SELECT id FROM article)")
if err != nil {
return err
}
n, err = result.RowsAffected()
if err != nil {
return err
}
if n > 0 {
store.dbug.Printf("WARNING: cleaned up %d dangling article_keyword entries\n", n)
}
return nil
}
// read in articles from DB
/*
func (store *Store) readAllArts() (ArtList, error) {
db := store.db
tab := map[ArtID]*Article{}
// now grab all the articles!
rows, err := db.Query("SELECT id,canonical_url,headline,content,published,updated,pub,section,retweet_count,favourite_count FROM article")
if err != nil {
return nil, err
}
for rows.Next() {
a := &Article{}
err = rows.Scan(&a.ID, &a.CanonicalURL, &a.Headline, &a.Content, &a.Published, &a.Updated, &a.Pub, &a.Section, &a.Retweets, &a.Favourites)
if err != nil {
return nil, err
}
tab[a.ID] = a
}
err = rows.Err()
if err != nil {
return nil, err
}
// URLs
rows, err = db.Query("SELECT article_id,url FROM article_url")
if err != nil {
return nil, err
}
for rows.Next() {
var artID ArtID
var u string
err = rows.Scan(&artID, &u)
if err != nil {
return nil, err
}
art := tab[artID]
art.URLs = append(art.URLs, u)
}
err = rows.Err()
if err != nil {
return nil, err
}
// Keywords
rows, err = db.Query("SELECT article_id,name,url FROM article_keyword")
if err != nil {
return nil, err
}
for rows.Next() {
var artID ArtID
// TODO: restore use of full Keyword struct
var name string
var u string
err = rows.Scan(&artID, &name, &u)
if err != nil {
return nil, err
}
art := tab[artID]
art.Keywords = append(art.Keywords, name)
}
err = rows.Err()
if err != nil {
return nil, err
}
// Links
rows, err = db.Query("SELECT article_id,url FROM article_link")
if err != nil {
return nil, err
}
for rows.Next() {
var artID ArtID
var link string
err = rows.Scan(&artID, &link)
if err != nil {
return nil, err
}
art := tab[artID]
art.Links = append(art.Links, link)
}
err = rows.Err()
if err != nil {
return nil, err
}
// tags
rows, err = db.Query("SELECT article_id,tag FROM article_tag")
if err != nil {
return nil, err
}
for rows.Next() {
var artID ArtID
var tag string
err = rows.Scan(&artID, &tag)
if err != nil {
return nil, err
}
art := tab[artID]
art.Tags = append(art.Tags, tag)
}
err = rows.Err()
if err != nil {
return nil, err
}
// authors
danglingAuthorCnt := 0
rows, err = db.Query("SELECT article_id,name FROM article_author")
if err != nil {
return nil, err
}
for rows.Next() {
var artID ArtID
var name string
err = rows.Scan(&artID, &name)
if err != nil {
return nil, err
}
art, got := tab[artID]
if got {
art.Authors = append(art.Authors, Author{Name: name})
} else {
danglingAuthorCnt++
}
}
err = rows.Err()
if err != nil {
return nil, err
}
if danglingAuthorCnt > 0 {
store.dbug.Printf("WARNING: database has %d dangling authors from deleted articles.\n", danglingAuthorCnt)
store.dbug.Printf("not a big deal, but db can be repaired manually via sql:\n")
store.dbug.Printf(" DELETE FROM article_author WHERE article_id NOT IN (SELECT id FROM article);\n")
}
// all done
out := ArtList{}
for _, art := range tab {
// evil hack (TODO: less evil, please)
art.Byline = art.BylineString()
out = append(out, art.ID)
}
return out, nil
}
*/
// standin - return IDs of all articles
func (store *Store) AllArts() (ArtList, error) {
rows, err := store.db.Query("SELECT id FROM article")
if err != nil {
return nil, err
}
out := make(ArtList, 0, 2000)
for rows.Next() {
var artID ArtID
err = rows.Scan(&artID)
if err != nil {
return nil, err
}
out = append(out, artID)
}
err = rows.Err()
if err != nil {
return nil, err
}
return out, nil
}
// search performs a search and returns the results
// XYZZY: add sort criteria
func (store *Store) Search(queryString string) (ArtList, error) {
// cheesy-ass hackery
if queryString == "" {
return store.AllArts()
}
out, err := store.idx.search(queryString, "")
if err != nil {
store.dbug.Printf("Search(%s) error: %s\n", queryString, err)
return nil, err
}
//store.dbug.Printf("Search(%s): %d matches\n", queryString, len(out))
return out, nil
}
func fileNameFromQuery(q string) string {
colon := regexp.MustCompile(`:\s*`)
spc := regexp.MustCompile(`\s+`)
chars := regexp.MustCompile(`[^-\w]`)
f := q
f = colon.ReplaceAllString(f, "-")
f = spc.ReplaceAllString(f, "_")
f = chars.ReplaceAllString(f, "")
return f
}
func (store *Store) AddTags(arts ArtList, tags []string) (ArtList, error) {
if store.db == nil {
return ArtList{}, nil
}
begun := time.Now()
// apply to db
tx, err := store.db.Begin()
if err != nil {
return nil, err
}
affected := ArtList{}
for _, tag := range tags {
newlyTagged, err := store.addTag(tx, arts, tag)
if err != nil {
tx.Rollback()
return nil, err
}
affected = affected.Union(newlyTagged)
}
err = tx.Commit()
if err != nil {
return nil, err
}
elapsedDB := time.Now().Sub(begun)
begun = time.Now()
// now apply to belve index
// a bit cumbersome, but bleve has no way to update select fields?
err = store.reindex(affected)
if err != nil {
return nil, err
}
elapsedBleve := time.Now().Sub(begun)
store.dbug.Printf("add tags %q: affected %d articles (%s db, %s bleve)\n", tags, len(affected), elapsedDB, elapsedBleve)
return affected, nil
}
func (store *Store) reindex(arts ArtList) error {
start := 0
for start < len(arts) {
n := 200
end := start + n
if end > len(arts) {
end = len(arts)
}
//store.dbug.Printf("chunk %d:%d (of %d)\n", start, end, len(arts))
chunk := arts[start:end]
start = end
fullArts, err := store.Fetch(chunk...)
if err != nil {
return err
}
err = store.idx.index(fullArts...)
if err != nil {
return err
}
}
return nil
}
func (store *Store) addTag(tx *sql.Tx, arts ArtList, tag string) (ArtList, error) {
tag = strings.ToLower(tag)
// find any article which already have the tag
gotRows, err := store.db.Query(`SELECT article_id FROM article_tag WHERE tag=? AND article_id IN (`+arts.StringList()+`)`, tag)
if err != nil {
return nil, err
}
got := ArtList{}
for gotRows.Next() {
var id ArtID
err = gotRows.Scan(&id)
if err != nil {
return nil, err
}
got = append(got, id)
}
// tag the ones that need it
affected := arts.Subtract(got)
insStmt, err := tx.Prepare("INSERT INTO article_tag(article_id,tag) VALUES(?,?)")
if err != nil {
return nil, err
}
defer insStmt.Close()
for _, artID := range affected {
_, err = insStmt.Exec(artID, tag)
if err != nil {
return nil, err
}
}
return affected, nil
}
func (store *Store) RemoveTags(arts ArtList, tags []string) (ArtList, error) {
if store.db == nil {
return ArtList{}, nil
}
// apply to db
tx, err := store.db.Begin()
if err != nil {
return nil, err
}
affected := ArtList{}
for _, tag := range tags {
newly, err := store.removeTag(tx, arts, tag)
if err != nil {
tx.Rollback()
return nil, err
}
store.dbug.Printf("removed '%s' tag from %d articles\n", tag, len(newly))
affected = affected.Union(newly)
}
err = tx.Commit()
if err != nil {
return nil, err
}
// now apply to belve index
// a bit cumbersome, but bleve has no way to update select fields?
err = store.reindex(affected)
if err != nil {
return nil, err
}
return affected, nil
}
func (store *Store) removeTag(tx *sql.Tx, arts ArtList, tag string) (ArtList, error) {
tag = strings.ToLower(tag)
// find which articles need the tag removed
rows, err := store.db.Query(`SELECT article_id FROM article_tag WHERE tag=? AND article_id IN (`+idList(arts)+`)`, tag)
if err != nil {
return nil, err
}
got := ArtList{}
for rows.Next() {
var id ArtID
err = rows.Scan(&id)
if err != nil {
return nil, err
}
got = append(got, id)
}
_, err = store.db.Exec(`DELETE FROM article_tag WHERE tag=? AND article_id IN (`+idList(got)+`)`, tag)
if err != nil {
return nil, err
}
return got, nil
}
// Delete articles from the store (and index)
// if progress is non-nil, it'll be called at regularish intervals
func (store *Store) Delete(arts ArtList, progress ProgressFn) error {
// delete from bleve index
begun := time.Now()
store.dbug.Printf("delete from index\n")
err := store.idx.zap(arts...)
if err != nil {
return err
}
elapsedBleve := time.Now().Sub(begun)
// now delete from db
store.dbug.Printf("delete from db\n")
begun = time.Now()
tx, err := store.db.Begin()
if err != nil {
return err
}
affected, err := store.doDelete(tx, arts, progress)
if err != nil {
store.dbug.Printf("error, rolling back\n")
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return err
}
elapsedDB := time.Now().Sub(begun)
store.dbug.Printf("Delete affected %d articles (%s in db, %s in bleve)\n", affected, elapsedDB, elapsedBleve)
return nil
}
func (store *Store) doDelete(tx *sql.Tx, arts ArtList, progress ProgressFn) (int64, error) {
var affected int64 = 0
// TODO: maybe use "on delete cascade" to let the db handle the details...
// (requires an sqlite pragma to enable foreign keys)
delTagsStmt, err := tx.Prepare("DELETE FROM article_tag WHERE article_id=?")
if err != nil {
return 0, err
}
defer delTagsStmt.Close()
delURLsStmt, err := tx.Prepare("DELETE FROM article_url WHERE article_id=?")
if err != nil {
return 0, err
}
defer delURLsStmt.Close()
delAuthorsStmt, err := tx.Prepare("DELETE FROM article_author WHERE article_id=?")
if err != nil {
return 0, err
}
defer delAuthorsStmt.Close()
delKeywordsStmt, err := tx.Prepare("DELETE FROM article_keyword WHERE article_id=?")
if err != nil {
return 0, err
}
defer delKeywordsStmt.Close()
delLinksStmt, err := tx.Prepare("DELETE FROM article_link WHERE article_id=?")
if err != nil {
return 0, err
}
defer delLinksStmt.Close()
delArtStmt, err := tx.Prepare("DELETE FROM article WHERE id=?")
if err != nil {
return 0, err
}
defer delArtStmt.Close()
for idx, artID := range arts {
_, err = delTagsStmt.Exec(artID)
if err != nil {
return 0, err
}
_, err = delURLsStmt.Exec(artID)
if err != nil {
return 0, err
}
_, err = delLinksStmt.Exec(artID)
if err != nil {
return 0, err
}
_, err = delKeywordsStmt.Exec(artID)
if err != nil {
return 0, err
}
_, err = delAuthorsStmt.Exec(artID)
if err != nil {
return 0, err
}
r, err := delArtStmt.Exec(artID)
if err != nil {
return 0, err
}
// check we actually deleted something...
foo, err := r.RowsAffected()
if err != nil {
return 0, err
}
affected += foo
if progress != nil {
progress(len(arts), idx)
}
}
return affected, nil
}
func (store *Store) FindArt(urls []string) (ArtID, error) {
placeholders := make([]string, len(urls))
params := make([]interface{}, len(urls))
for i, _ := range urls {
placeholders[i] = "?"
params[i] = urls[i]
}
foo := fmt.Sprintf(`SELECT article_id FROM article_url WHERE url IN(%s)`, strings.Join(placeholders, ","))
var artID ArtID
err := store.db.QueryRow(foo, params...).Scan(&artID)
if err == sql.ErrNoRows {
return 0, nil // article not found
} else if err != nil {
return 0, err
} else {
return artID, nil
}
}
func (store *Store) Stash(arts []*Article) error {
tx, err := store.db.Begin()
if err != nil {
return err
}
for _, art := range arts {
if art.ID != 0 {
panic("article id already set")
}
err = store.doStash(tx, art)
if err != nil {
break
}
}
if err == nil {
// update the index
err = store.idx.index(arts...)
}
if err == nil {
err = tx.Commit()
} else {
err2 := tx.Rollback()
if err2 != nil {
err = err2
}
}
return err
}
func (store *Store) doStash(tx *sql.Tx, art *Article) error {
var result sql.Result
result, err := tx.Exec(`INSERT INTO article(canonical_url, headline, content,published,updated,pub,section,retweet_count,favourite_count)
values(?,?,?,?,?,?,?,?,?)`,
art.CanonicalURL,
art.Headline,
art.Content,
art.Published,
art.Updated,
art.Pub,
art.Section,
art.Retweets,
art.Favourites)
if err != nil {
return err
}
if artID, err := result.LastInsertId(); err == nil {
art.ID = ArtID(artID)
} else {
return err
}
// add urls
urlStmt, err := tx.Prepare("INSERT INTO article_url(article_id,url) VALUES(?,?)")
if err != nil {
return err
}
defer urlStmt.Close()
for _, u := range art.URLs {
_, err = urlStmt.Exec(art.ID, u)
if err != nil {
return err
}
}
// add tags
tagStmt, err := tx.Prepare("INSERT INTO article_tag(article_id,tag) VALUES(?,?)")
if err != nil {
return err
}
defer tagStmt.Close()
for _, tag := range art.Tags {
_, err = tagStmt.Exec(art.ID, tag)
if err != nil {
return err
}
}
// add authors (TODO: other author fields)
authorStmt, err := tx.Prepare("INSERT INTO article_author(article_id,name) VALUES(?,?)")
if err != nil {
return err
}
defer authorStmt.Close()
for _, author := range art.Authors {
_, err = authorStmt.Exec(art.ID, author.Name)
if err != nil {
return err
}
}
// add keywords
kwStmt, err := tx.Prepare("INSERT INTO article_keyword(article_id,name,url) VALUES(?,?,?)")
if err != nil {
return err
}
defer kwStmt.Close()
for _, kw := range art.Keywords {
// TODO: restore use of full keyword struct
_, err = kwStmt.Exec(art.ID, kw, "")
if err != nil {
return err
}
}
// add resolved links
linkStmt, err := tx.Prepare("INSERT INTO article_link(article_id,url) VALUES(?,?)")
if err != nil {
return err
}
defer linkStmt.Close()
for _, link := range art.Links {
_, err = linkStmt.Exec(art.ID, link)
if err != nil {
return err
}
}
// add similar articles
simStmt, err := tx.Prepare("INSERT INTO similar(article_id, other_id, score) VALUES(?, ?, ?)")
if err != nil {
return err
}
defer simStmt.Close()
for _, match := range art.Similar {
_, err = tagStmt.Exec(art.ID, match.ID, match.Score)
if err != nil {
return err
}
}
return nil
}
// HACK - update all the links for the given articles
func (store *Store) UpdateLinks(arts ArtList) error {
/* XYZZY */
return nil
/*
tx, err := store.db.Begin()
if err != nil {
return err
}
delStmt, err := tx.Prepare("DELETE FROM article_link WHERE article_id=?")
if err != nil {
return err
}
defer delStmt.Close()
insStmt, err := tx.Prepare("INSERT INTO article_link(article_id,url) VALUES(?,?)")
if err != nil {
return err
}
defer insStmt.Close()
for _, art := range arts {
// zap old links
_, err = delStmt.Exec(art.ID)
if err != nil {
return err
}
// add new links
for _, link := range art.Links {
_, err = insStmt.Exec(art.ID, link)
if err != nil {
return err
}
}
}
err = tx.Commit()
if err != nil {
return err
}
return nil
*/
}
func idList(ids []ArtID) string {
frags := make([]string, len(ids))
for idx, id := range ids {
frags[idx] = strconv.Itoa(int(id))
}
return strings.Join(frags, ",")
}
func (store *Store) Fetch(artIDs ...ArtID) ([]*Article, error) {
if len(artIDs) > 0 {
return store.doFetch(artIDs)
}
return []*Article{}, nil
}
func (store *Store) FetchAll() ([]*Article, error) {
return store.doFetch(ArtList{})
}
// read in articles from DB. Empty list means fetch _all_ arts :-)
func (store *Store) doFetch(artIDs ArtList) ([]*Article, error) {
db := store.db
tab := map[ArtID]*Article{}
var where string
if len(artIDs) > 0 {
where = " WHERE id IN (" + idList(artIDs) + ")"
}
// now grab all the articles!
rows, err := db.Query(`SELECT id,canonical_url,headline,content,published,updated,pub,section,retweet_count,favourite_count FROM article` + where)
if err != nil {
return nil, err
}
for rows.Next() {
a := &Article{}
err = rows.Scan(&a.ID, &a.CanonicalURL, &a.Headline, &a.Content, &a.Published, &a.Updated, &a.Pub, &a.Section, &a.Retweets, &a.Favourites)
if err != nil {
return nil, err
}
tab[a.ID] = a
}
err = rows.Err()
if err != nil {
return nil, err
}
if len(artIDs) > 0 {
// all auxillary tables indexed by article_id