-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy path_storage.py
More file actions
1449 lines (1246 loc) · 46.4 KB
/
_storage.py
File metadata and controls
1449 lines (1246 loc) · 46.4 KB
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
import json
import logging
import sqlite3
from datetime import datetime
from datetime import timedelta
from functools import partial
from itertools import chain
from itertools import repeat
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Mapping
from typing import NamedTuple
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import TypeVar
from ._sql_utils import BaseQuery
from ._sql_utils import paginated_query
from ._sql_utils import Query
from ._sqlite_utils import DBError
from ._sqlite_utils import rowcount_exactly_one
from ._sqlite_utils import setup_db as setup_sqlite_db
from ._sqlite_utils import wrap_exceptions
from ._sqlite_utils import wrap_exceptions_iter
from ._types import EntryFilterOptions
from ._types import EntryForUpdate
from ._types import EntryUpdateIntent
from ._types import FeedFilterOptions
from ._types import FeedForUpdate
from ._types import FeedUpdateIntent
from ._types import TagFilter
from ._utils import chunks
from ._utils import exactly_one
from ._utils import join_paginated_iter
from ._utils import zero_or_one
from .exceptions import EntryMetadataNotFoundError
from .exceptions import EntryNotFoundError
from .exceptions import FeedExistsError
from .exceptions import FeedMetadataNotFoundError
from .exceptions import FeedNotFoundError
from .exceptions import MetadataNotFoundError
from .exceptions import ReaderError
from .exceptions import StorageError
from .types import Content
from .types import Enclosure
from .types import Entry
from .types import EntryCounts
from .types import EntrySortOrder
from .types import ExceptionInfo
from .types import Feed
from .types import FeedCounts
from .types import FeedSortOrder
from .types import JSONType
APPLICATION_ID = int(''.join(f'{ord(c):x}' for c in 'read'), 16)
log = logging.getLogger('reader')
_T = TypeVar('_T')
def create_db(db: sqlite3.Connection) -> None:
create_feeds(db)
create_entries(db)
create_feed_metadata(db)
create_feed_tags(db)
create_indexes(db)
def create_feeds(db: sqlite3.Connection, name: str = 'feeds') -> None:
db.execute(
f"""
CREATE TABLE {name} (
-- feed data
url TEXT PRIMARY KEY NOT NULL,
title TEXT,
link TEXT,
updated TIMESTAMP,
author TEXT,
user_title TEXT, -- except this one, which comes from reader
http_etag TEXT,
http_last_modified TEXT,
data_hash BLOB, -- derived from feed data
-- reader data
stale INTEGER NOT NULL DEFAULT 0,
updates_enabled INTEGER NOT NULL DEFAULT 1,
last_updated TIMESTAMP, -- null if the feed was never updated
added TIMESTAMP NOT NULL,
last_exception TEXT
-- NOTE: when adding new fields, check if they should be set
-- to their default value in change_feed_url()
);
"""
)
def create_entries(db: sqlite3.Connection, name: str = 'entries') -> None:
db.execute(
f"""
CREATE TABLE {name} (
-- entry data
id TEXT NOT NULL,
feed TEXT NOT NULL,
title TEXT,
link TEXT,
updated TIMESTAMP NOT NULL,
author TEXT,
published TIMESTAMP,
summary TEXT,
content TEXT,
enclosures TEXT,
original_feed TEXT, -- null if the feed was never moved
data_hash BLOB, -- derived from entry data
data_hash_changed INTEGER, -- metadata about data_hash
-- reader data
read INTEGER NOT NULL DEFAULT 0,
important INTEGER NOT NULL DEFAULT 0,
last_updated TIMESTAMP NOT NULL,
first_updated_epoch TIMESTAMP NOT NULL,
feed_order INTEGER NOT NULL,
PRIMARY KEY (id, feed),
FOREIGN KEY (feed) REFERENCES feeds(url)
ON UPDATE CASCADE
ON DELETE CASCADE
);
"""
)
def create_feed_metadata(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE feed_metadata (
feed TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (feed, key),
FOREIGN KEY (feed) REFERENCES feeds(url)
ON UPDATE CASCADE
ON DELETE CASCADE
);
"""
)
def create_feed_tags(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE feed_tags (
feed TEXT NOT NULL,
tag TEXT NOT NULL,
PRIMARY KEY (feed, tag),
FOREIGN KEY (feed) REFERENCES feeds(url)
ON UPDATE CASCADE
ON DELETE CASCADE
);
"""
)
class SchemaInfo(NamedTuple):
table_prefix: str
id_columns: Tuple[str, ...]
not_found_exc: Type[ReaderError]
metadata_not_found_exc: Type[MetadataNotFoundError]
SCHEMA_INFO = {
1: SchemaInfo('feed_', ('feed',), FeedNotFoundError, FeedMetadataNotFoundError),
2: SchemaInfo(
'entry_', ('feed', 'id'), EntryNotFoundError, EntryMetadataNotFoundError
),
}
def create_indexes(db: sqlite3.Connection) -> None:
# Speed up get_entries() queries that use apply_recent().
db.execute(
"""
CREATE INDEX entries_by_kinda_first_updated ON entries(
first_updated_epoch,
coalesce(published, updated),
feed,
last_updated,
- feed_order,
id
);
"""
)
db.execute(
"""
CREATE INDEX entries_by_kinda_published ON entries (
coalesce(published, updated),
coalesce(published, updated),
feed,
last_updated,
- feed_order,
id
);
"""
)
def setup_db(db: sqlite3.Connection, wal_enabled: Optional[bool]) -> None:
return setup_sqlite_db(
db,
create=create_db,
version=29,
migrations={
# 1-9 removed before 0.1 (last in e4769d8ba77c61ec1fe2fbe99839e1826c17ace7)
# 10-16 removed before 1.0 (last in 618f158ebc0034eefb724a55a84937d21c93c1a7)
# 17-28 removed before 2.0 (last in be9c89581ea491d0c9cc95c9d39f073168a2fd02)
},
id=APPLICATION_ID,
# Row value support was added in 3.15.
# TODO: Remove the Search.update() check once this gets bumped to >=3.18.
minimum_sqlite_version=(3, 15),
# We use the JSON1 extension for entries.content.
required_sqlite_compile_options=["ENABLE_JSON1"],
wal_enabled=wal_enabled,
)
# There are two reasons for paginating methods that return an iterator:
#
# * to avoid locking the database for too long
# (not consuming a generator should not lock the database), and
# * to avoid consuming too much memory;
#
# it is OK to take proportionally more time to get more things,
# it is not OK to have more errors.
#
# See the following for more details:
#
# https://github.com/lemon24/reader/issues/6
# https://github.com/lemon24/reader/issues/167#issuecomment-626753299
# When trying to fix "database is locked" errors or to optimize stuff,
# have a look at the lessons here first:
# https://github.com/lemon24/reader/issues/175#issuecomment-657495233
# When adding a new method, add a new test_storage.py::test_errors_locked test.
class Storage:
# recent_threshold and chunk_size are not part of the Storage interface,
# but are part of the private API of this implementation.
recent_threshold = timedelta(7)
chunk_size = 2 ** 8
@wrap_exceptions(StorageError)
def __init__(
self,
path: str,
timeout: Optional[float] = None,
wal_enabled: Optional[bool] = True,
factory: Optional[Type[sqlite3.Connection]] = None,
):
kwargs: Dict[str, Any] = {}
if timeout is not None:
kwargs['timeout'] = timeout
if factory: # pragma: no cover
kwargs['factory'] = factory
with wrap_exceptions(StorageError, "error while opening database"):
db = self.connect(path, detect_types=sqlite3.PARSE_DECLTYPES, **kwargs)
with wrap_exceptions(StorageError, "error while setting up database"):
try:
try:
self.setup_db(db, wal_enabled)
except BaseException:
db.close()
raise
except DBError as e:
message = str(e)
if 'no migration' in message:
message += "; you may have skipped some required migrations, see https://reader.readthedocs.io/en/latest/changelog.html#removed-migrations-2-0"
raise StorageError(message=message)
self.db: sqlite3.Connection = db
self.path = path
self.timeout = timeout
# TODO: these are not part of the Storage API
connect = staticmethod(sqlite3.connect)
setup_db = staticmethod(setup_db)
@wrap_exceptions(StorageError)
def close(self) -> None:
# If "PRAGMA optimize" on every close becomes too expensive, we can
# add an option to disable it, or call db.interrupt() after some time.
# TODO: Once SQLite 3.32 becomes widespread, use "PRAGMA analysis_limit"
# for the same purpose. Details:
# https://github.com/lemon24/reader/issues/143#issuecomment-663433197
try:
self.db.execute("PRAGMA optimize;")
except sqlite3.ProgrammingError as e:
# Calling close() a second time is a noop.
if "cannot operate on a closed database" in str(e).lower():
return
raise
self.db.close()
@wrap_exceptions(StorageError)
def add_feed(self, url: str, added: datetime) -> None:
with self.db:
try:
self.db.execute(
"INSERT INTO feeds (url, added) VALUES (:url, :added);",
dict(url=url, added=added),
)
except sqlite3.IntegrityError as e:
if "unique constraint failed" not in str(e).lower(): # pragma: no cover
raise
raise FeedExistsError(url)
@wrap_exceptions(StorageError)
def delete_feed(self, url: str) -> None:
with self.db:
cursor = self.db.execute(
"DELETE FROM feeds WHERE url = :url;", dict(url=url)
)
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(url))
@wrap_exceptions(StorageError)
def change_feed_url(self, old: str, new: str) -> None:
with self.db:
try:
cursor = self.db.execute(
"UPDATE feeds SET url = :new WHERE url = :old;",
dict(old=old, new=new),
)
except sqlite3.IntegrityError as e:
if "unique constraint failed" not in str(e).lower(): # pragma: no cover
raise
raise FeedExistsError(new)
else:
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(old))
# Some of the fields are not kept from the old feed; details:
# https://github.com/lemon24/reader/issues/149#issuecomment-700532183
self.db.execute(
"""
UPDATE feeds
SET
updated = NULL,
http_etag = NULL,
http_last_modified = NULL,
stale = 0,
last_updated = NULL,
last_exception = NULL
WHERE url = ?;
""",
(new,),
)
self.db.execute(
"""
UPDATE entries
SET original_feed = (
SELECT coalesce(sub.original_feed, :old)
FROM entries AS sub
WHERE entries.id = sub.id AND entries.feed = sub.feed
)
WHERE feed = :new;
""",
dict(old=old, new=new),
)
def get_feeds(
self,
filter_options: FeedFilterOptions = FeedFilterOptions(), # noqa: B008
sort: FeedSortOrder = 'title',
limit: Optional[int] = None,
starting_after: Optional[str] = None,
) -> Iterable[Feed]:
rv = join_paginated_iter(
partial(self.get_feeds_page, filter_options, sort), # type: ignore[arg-type]
self.chunk_size,
self.get_feed_last(sort, starting_after) if starting_after else None,
limit or 0,
)
yield from rv
@wrap_exceptions(StorageError)
def get_feed_last(self, sort: str, url: str) -> Tuple[Any, ...]:
# TODO: make this method private?
query = Query().FROM("feeds").WHERE("url = :url")
# TODO: kinda sorta duplicates the scrolling_window_order_by call
if sort == 'title':
query.SELECT(("kinda_title", "lower(coalesce(user_title, title))"), 'url')
elif sort == 'added':
query.SELECT("added", 'url')
else:
assert False, "shouldn't get here" # noqa: B011; # pragma: no cover
return zero_or_one(
self.db.execute(str(query), dict(url=url)), lambda: FeedNotFoundError(url)
)
@wrap_exceptions_iter(StorageError)
def get_feeds_page(
self,
filter_options: FeedFilterOptions = FeedFilterOptions(), # noqa: B008
sort: FeedSortOrder = 'title',
chunk_size: Optional[int] = None,
last: Optional[_T] = None,
) -> Iterable[Tuple[Feed, Optional[_T]]]:
query, context = make_get_feeds_query(filter_options, sort)
yield from paginated_query(
self.db, query, context, chunk_size, last, feed_factory
)
@wrap_exceptions(StorageError)
def get_feed_counts(
self,
filter_options: FeedFilterOptions = FeedFilterOptions(), # noqa: B008
) -> FeedCounts:
query = (
Query()
.SELECT(
'count(*)',
'coalesce(sum(last_exception IS NOT NULL), 0)',
'coalesce(sum(updates_enabled == 1), 0)',
)
.FROM("feeds")
)
context = apply_feed_filter_options(query, filter_options)
row = exactly_one(self.db.execute(str(query), context))
return FeedCounts(*row)
@wrap_exceptions_iter(StorageError)
def get_feeds_for_update(
self,
url: Optional[str] = None,
new: Optional[bool] = None,
enabled_only: bool = True,
) -> Iterable[FeedForUpdate]:
# Reader shouldn't care this is paginated,
# so we don't expose any pagination stuff.
def inner(
chunk_size: Optional[int], last: Optional[_T]
) -> Iterable[Tuple[FeedForUpdate, Optional[_T]]]:
query = (
Query()
.SELECT(
'url',
'updated',
'http_etag',
'http_last_modified',
'stale',
'last_updated',
('last_exception', 'last_exception IS NOT NULL'),
'data_hash',
)
.FROM("feeds")
)
context: Dict[str, object] = {}
# TODO: stale and last_exception should be bool, not int
if url:
query.WHERE("url = :url")
context.update(url=url)
if new is not None:
query.WHERE(f"last_updated is {'' if new else 'NOT'} NULL")
if enabled_only:
query.WHERE("updates_enabled")
query.scrolling_window_order_by("url")
yield from paginated_query(
self.db, query, context, chunk_size, last, FeedForUpdate._make
)
yield from join_paginated_iter(inner, self.chunk_size)
def _get_entries_for_update_n_queries(
self, entries: Sequence[Tuple[str, str]]
) -> Iterable[Optional[EntryForUpdate]]:
# We use an explicit transaction for speed
# (otherwise we get an implicit one for each query).
with self.db:
for feed_url, id in entries: # noqa: B007
context = dict(feed_url=feed_url, id=id)
row = self.db.execute(
"""
SELECT updated, data_hash, data_hash_changed
FROM entries
WHERE feed = :feed_url
AND id = :id;
""",
context,
).fetchone()
yield EntryForUpdate._make(row) if row else None
def _get_entries_for_update_one_query(
self, entries: Sequence[Tuple[str, str]]
) -> Iterable[Optional[EntryForUpdate]]:
if not entries: # pragma: no cover
return []
values_snippet = ', '.join(repeat('(?, ?)', len(entries)))
parameters = list(chain.from_iterable(entries))
rows = self.db.execute(
f"""
WITH
input(feed, id) AS (
VALUES {values_snippet}
)
SELECT
entries.id IS NOT NULL,
entries.updated,
entries.data_hash,
entries.data_hash_changed
FROM input
LEFT JOIN entries
ON (input.id, input.feed) == (entries.id, entries.feed);
""",
parameters,
)
# This can't be a generator because we need to get OperationalError
# in this function (so get_entries_for_update() below can catch it).
return (
EntryForUpdate._make(rest) if exists else None for exists, *rest in rows
)
@wrap_exceptions_iter(StorageError)
def get_entries_for_update(
self, entries: Iterable[Tuple[str, str]]
) -> Iterable[Optional[EntryForUpdate]]:
# It's acceptable for this method to not be atomic. TODO: Why?
iterables = chunks(self.chunk_size, entries) if self.chunk_size else (entries,)
for iterable in iterables:
# The reason there are two implementations for this method:
# https://github.com/lemon24/reader/issues/109
iterable = list(iterable)
try:
rv = self._get_entries_for_update_one_query(iterable)
except sqlite3.OperationalError as e:
if "too many SQL variables" not in str(e):
raise
rv = self._get_entries_for_update_n_queries(iterable)
if self.chunk_size:
rv = list(rv)
yield from rv
@wrap_exceptions(StorageError)
def set_feed_user_title(self, url: str, title: Optional[str]) -> None:
with self.db:
cursor = self.db.execute(
"UPDATE feeds SET user_title = :title WHERE url = :url;",
dict(url=url, title=title),
)
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(url))
@wrap_exceptions(StorageError)
def set_feed_updates_enabled(self, url: str, enabled: bool) -> None:
with self.db:
cursor = self.db.execute(
"UPDATE feeds SET updates_enabled = :updates_enabled WHERE url = :url;",
dict(url=url, updates_enabled=enabled),
)
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(url))
@wrap_exceptions(StorageError)
def mark_as_stale(self, url: str) -> None:
with self.db:
cursor = self.db.execute(
"UPDATE feeds SET stale = 1 WHERE url = :url;", dict(url=url)
)
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(url))
@wrap_exceptions(StorageError)
def mark_as_read_unread(self, feed_url: str, entry_id: str, read: bool) -> None:
with self.db:
cursor = self.db.execute(
"""
UPDATE entries
SET read = :read
WHERE feed = :feed_url AND id = :entry_id;
""",
dict(feed_url=feed_url, entry_id=entry_id, read=read),
)
rowcount_exactly_one(cursor, lambda: EntryNotFoundError(feed_url, entry_id))
@wrap_exceptions(StorageError)
def mark_as_important_unimportant(
self, feed_url: str, entry_id: str, important: bool
) -> None:
with self.db:
cursor = self.db.execute(
"""
UPDATE entries
SET important = :important
WHERE feed = :feed_url AND id = :entry_id;
""",
dict(feed_url=feed_url, entry_id=entry_id, important=important),
)
rowcount_exactly_one(cursor, lambda: EntryNotFoundError(feed_url, entry_id))
@wrap_exceptions(StorageError)
def update_feed(self, intent: FeedUpdateIntent) -> None:
url, last_updated, feed, http_etag, http_last_modified, last_exception = intent
if feed:
# TODO support updating feed URL
# https://github.com/lemon24/reader/issues/149
assert url == feed.url, "updating feed URL not supported"
assert last_exception is None, "last_exception must be none if feed is set"
self._update_feed_full(intent)
return
assert http_etag is None, "http_etag must be none if feed is none"
assert (
http_last_modified is None
), "http_last_modified must be none if feed is none"
if not last_exception:
assert last_updated, "last_updated must be set if last_exception is none"
self._update_feed_last_updated(url, last_updated)
else:
assert (
not last_updated
), "last_updated must not be set if last_exception is not none"
self._update_feed_last_exception(url, last_exception)
def _update_feed_full(self, intent: FeedUpdateIntent) -> None:
context = intent._asdict()
feed = context.pop('feed')
assert feed is not None
context.pop('last_exception')
context.update(feed._asdict(), data_hash=feed.hash)
with self.db:
cursor = self.db.execute(
"""
UPDATE feeds
SET
title = :title,
link = :link,
updated = :updated,
author = :author,
http_etag = :http_etag,
http_last_modified = :http_last_modified,
data_hash = :data_hash,
stale = 0,
last_updated = :last_updated,
last_exception = NULL
WHERE url = :url;
""",
context,
)
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(intent.url))
def _update_feed_last_updated(self, url: str, last_updated: datetime) -> None:
with self.db:
cursor = self.db.execute(
"""
UPDATE feeds
SET
last_updated = :last_updated,
last_exception = NULL
WHERE url = :url;
""",
dict(url=url, last_updated=last_updated),
)
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(url))
def _update_feed_last_exception(
self, url: str, last_exception: ExceptionInfo
) -> None:
with self.db:
cursor = self.db.execute(
"""
UPDATE feeds
SET
last_exception = :last_exception
WHERE url = :url;
""",
dict(url=url, last_exception=json.dumps(last_exception._asdict())),
)
rowcount_exactly_one(cursor, lambda: FeedNotFoundError(url))
def _make_add_or_update_entries_args(
self, intent: EntryUpdateIntent
) -> Mapping[str, Any]:
context = intent._asdict()
entry = context.pop('entry')
context.update(
entry._asdict(),
content=(
json.dumps([t._asdict() for t in entry.content])
if entry.content
else None
),
enclosures=(
json.dumps([t._asdict() for t in entry.enclosures])
if entry.enclosures
else None
),
data_hash=entry.hash,
data_hash_changed=context.pop('hash_changed'),
)
return context
@wrap_exceptions(StorageError)
def add_or_update_entries(self, entry_tuples: Iterable[EntryUpdateIntent]) -> None:
iterables = (
chunks(self.chunk_size, entry_tuples)
if self.chunk_size
else (entry_tuples,)
)
# It's acceptable for this to not be atomic (only some of the entries
# may be updated if we get an exception), since they will likely
# be updated on the next update (because the feed will not be marked
# as updated if there's an exception, so we get a free retry).
for iterable in iterables:
self._add_or_update_entries(iterable)
def _add_or_update_entries(self, entry_tuples: Iterable[EntryUpdateIntent]) -> None:
# We need to capture the last value for exception handling
# (it's not guaranteed all the entries belong to the same tuple).
# FIXME: In this case, is it ok to just fail other feeds too
# if we have an exception? If no, we should force the entries to
# belong to a single feed!
last_param: Mapping[str, Any] = {}
def make_params() -> Iterable[Mapping[str, Any]]:
nonlocal last_param
for last_param in map(self._make_add_or_update_entries_args, entry_tuples):
yield last_param
with self.db:
try:
self.db.executemany(
"""
INSERT OR REPLACE INTO entries (
id,
feed,
--
title,
link,
updated,
author,
published,
summary,
content,
enclosures,
read,
important,
last_updated,
first_updated_epoch,
feed_order,
original_feed,
data_hash,
data_hash_changed
) VALUES (
:id,
:feed_url,
:title,
:link,
:updated,
:author,
:published,
:summary,
:content,
:enclosures,
(
SELECT read
FROM entries
WHERE id = :id AND feed = :feed_url
),
(
SELECT important
FROM entries
WHERE id = :id AND feed = :feed_url
),
:last_updated,
coalesce(:first_updated_epoch, (
SELECT first_updated_epoch
FROM entries
WHERE id = :id AND feed = :feed_url
)),
:feed_order,
NULL, -- original_feed
:data_hash,
:data_hash_changed
);
""",
make_params(),
)
except sqlite3.IntegrityError as e:
if (
"foreign key constraint failed" not in str(e).lower()
): # pragma: no cover
raise
feed_url = last_param['feed_url']
entry_id = last_param['id']
log.debug(
"add_entry %r of feed %r: got IntegrityError",
entry_id,
feed_url,
exc_info=True,
)
raise FeedNotFoundError(feed_url)
def add_or_update_entry(self, intent: EntryUpdateIntent) -> None:
# TODO: this method is for testing convenience only, maybe delete it?
self.add_or_update_entries([intent])
def get_entries(
self,
now: datetime,
filter_options: EntryFilterOptions = EntryFilterOptions(), # noqa: B008
sort: EntrySortOrder = 'recent',
limit: Optional[int] = None,
starting_after: Optional[Tuple[str, str]] = None,
) -> Iterable[Entry]:
# TODO: deduplicate
if sort == 'recent':
rv = join_paginated_iter(
partial(self.get_entries_page, now, filter_options, sort), # type: ignore[arg-type]
self.chunk_size,
self.get_entry_last(now, sort, starting_after)
if starting_after
else None,
limit or 0,
)
elif sort == 'random':
assert not starting_after
it = self.get_entries_page(
now,
filter_options,
sort,
min(limit, self.chunk_size or limit) if limit else self.chunk_size,
)
rv = (entry for entry, _ in it)
else:
assert False, "shouldn't get here" # noqa: B011; # pragma: no cover
yield from rv
@wrap_exceptions(StorageError)
def get_entry_last(
self, now: datetime, sort: str, entry: Tuple[str, str]
) -> Tuple[Any, ...]:
# TODO: make this method private?
feed_url, entry_id = entry
query = Query().FROM("entries").WHERE("feed = :feed AND id = :id")
assert sort != 'random'
# TODO: kinda sorta duplicates the scrolling_window_order_by call
if sort == 'recent':
query.SELECT(*make_recent_last_select())
else:
assert False, "shouldn't get here" # noqa: B011; # pragma: no cover
context = dict(
feed=feed_url,
id=entry_id,
# TODO: duplicated from get_entries_page()
recent_threshold=now - self.recent_threshold,
)
return zero_or_one(
self.db.execute(str(query), context),
lambda: EntryNotFoundError(feed_url, entry_id),
)
@wrap_exceptions_iter(StorageError)
def get_entries_page(
self,
now: datetime,
filter_options: EntryFilterOptions = EntryFilterOptions(), # noqa: B008
sort: EntrySortOrder = 'recent',
chunk_size: Optional[int] = None,
last: Optional[_T] = None,
) -> Iterable[Tuple[Entry, Optional[_T]]]:
query, context = make_get_entries_query(filter_options, sort)
context.update(recent_threshold=now - self.recent_threshold)
yield from paginated_query(
self.db, query, context, chunk_size, last, entry_factory
)
@wrap_exceptions(StorageError)
def get_entry_counts(
self,
filter_options: EntryFilterOptions = EntryFilterOptions(), # noqa: B008
) -> EntryCounts:
query = (
Query()
.SELECT(
'count(*)',
'coalesce(sum(read == 1), 0)',
'coalesce(sum(important == 1), 0)',
"""
coalesce(
sum(
NOT (
json_array_length(entries.enclosures) IS NULL OR json_array_length(entries.enclosures) = 0
)
), 0
)
""",
)
.FROM("entries")
)
context = apply_entry_filter_options(query, filter_options)
row = exactly_one(self.db.execute(str(query), context))
return EntryCounts(*row)
def iter_metadata(
self,
object_id: Tuple[str, ...],
key: Optional[str] = None,
) -> Iterable[Tuple[str, JSONType]]:
yield from join_paginated_iter(
partial(self.iter_metadata_page, object_id, key),
self.chunk_size,
)
@wrap_exceptions_iter(StorageError)
def iter_metadata_page(
self,
object_id: Tuple[str, ...],
key: Optional[str] = None,
chunk_size: Optional[int] = None,
last: Optional[_T] = None,
) -> Iterable[Tuple[Tuple[str, JSONType], Optional[_T]]]:
info = SCHEMA_INFO[len(object_id)]
query = Query().SELECT("key", "value").FROM(f"{info.table_prefix}metadata")
for column in info.id_columns:
query.WHERE(f"{column} = :{column}")
context = dict(zip(info.id_columns, object_id))
if key is not None:
query.WHERE("key = :key")
context.update(key=key)
query.scrolling_window_order_by("key")
def row_factory(t: Tuple[Any, ...]) -> Tuple[str, JSONType]:
key, value, *_ = t
return key, json.loads(value)
yield from paginated_query(
self.db, query, context, chunk_size, last, row_factory
)
@wrap_exceptions(StorageError)
def set_metadata(
self, object_id: Tuple[str, ...], key: str, value: JSONType
) -> None:
info = SCHEMA_INFO[len(object_id)]
columns = info.id_columns + ('key', 'value')
query = f"""