-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
84 lines (69 loc) · 1.87 KB
/
db.py
File metadata and controls
84 lines (69 loc) · 1.87 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
from collections.abc import Collection, Iterable
from datetime import datetime
from typing import NamedTuple, NewType
import polars as pl
from polars._typing import SchemaDict
from config import DATA_DIR
OsmId = NewType('OsmId', str)
class DbItem(NamedTuple):
id: OsmId
date: datetime
query: str
link: str | None
added: bool
_PATH = DATA_DIR / 'db.parquet'
_SCHEMA: SchemaDict = {
'id': pl.Utf8,
'date': pl.Datetime,
'query': pl.Utf8,
'link': pl.Utf8,
'added': pl.Boolean,
}
def db_filter(ids: set[OsmId]) -> None:
if _PATH.is_file():
ids.difference_update(
pl.read_parquet(_PATH, columns=['id'], schema=_SCHEMA)
.get_column('id')
.to_list()
)
def db_insert(items: Iterable[DbItem]) -> None:
rows = [item._asdict() for item in items]
(
(
pl.read_parquet(_PATH, schema=_SCHEMA)
if _PATH.is_file()
else pl.DataFrame(None, _SCHEMA)
)
.vstack(pl.DataFrame(rows, _SCHEMA))
.write_parquet(
_PATH,
compression='uncompressed', # using disk compression
)
)
def db_ready_to_upload() -> list[DbItem]:
return [
DbItem(**d)
for d in (
pl.scan_parquet(_PATH, schema=_SCHEMA)
.filter(
pl.col('link').is_not_null(),
pl.col('added') == False, # noqa: E712
)
.collect()
.to_dicts()
)
]
def db_mark_added(ids: Collection[OsmId]) -> None:
(
pl.scan_parquet(_PATH, schema=_SCHEMA)
.with_columns(
added=pl.when(pl.col('id').is_in(ids))
.then(True)
.otherwise(pl.col('added')),
)
.collect()
.write_parquet(
_PATH,
compression='uncompressed', # using disk compression
)
)