dsqlite 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dsqlite/__init__.py +24 -0
- dsqlite/_bucket.py +227 -0
- dsqlite/_local.py +255 -0
- dsqlite/_sql.py +389 -0
- dsqlite/_sync.py +384 -0
- dsqlite/_types.py +151 -0
- dsqlite/_uuid.py +30 -0
- dsqlite/py.typed +0 -0
- dsqlite-0.1.0.dist-info/METADATA +205 -0
- dsqlite-0.1.0.dist-info/RECORD +12 -0
- dsqlite-0.1.0.dist-info/WHEEL +4 -0
- dsqlite-0.1.0.dist-info/licenses/LICENSE +21 -0
dsqlite/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""dsqlite: row-level last-write-wins sync of a local SQLite database through an S3 bucket."""
|
|
2
|
+
|
|
3
|
+
from ._bucket import FormatError, ReplicaIdConflictError
|
|
4
|
+
from ._sync import Sync
|
|
5
|
+
from ._types import Change, DSQLiteError, HistoryError, SchemaMismatchError, Stamp, Stored, SyncResult, SyncStatus, TableError, Trigger, Usage
|
|
6
|
+
from ._uuid import uuid7
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Change",
|
|
10
|
+
"DSQLiteError",
|
|
11
|
+
"FormatError",
|
|
12
|
+
"HistoryError",
|
|
13
|
+
"ReplicaIdConflictError",
|
|
14
|
+
"SchemaMismatchError",
|
|
15
|
+
"Stamp",
|
|
16
|
+
"Stored",
|
|
17
|
+
"Sync",
|
|
18
|
+
"SyncResult",
|
|
19
|
+
"SyncStatus",
|
|
20
|
+
"TableError",
|
|
21
|
+
"Trigger",
|
|
22
|
+
"Usage",
|
|
23
|
+
"uuid7",
|
|
24
|
+
]
|
dsqlite/_bucket.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The bucket: object layout, the wire format, and write-once puts.
|
|
3
|
+
|
|
4
|
+
<name>/replicas/<replica id>.json.gz one per replica, so peers can find each other
|
|
5
|
+
<name>/changes/<replica id>/<first seq>.json.gz one per push, named by the seq of its first change
|
|
6
|
+
<name>/snapshots/<time ns>-<replica id>.json.gz full state, for starting a new replica
|
|
7
|
+
|
|
8
|
+
Every object is written once and never changed or deleted.
|
|
9
|
+
|
|
10
|
+
An object is gzipped JSON: ``format`` (FORMAT), ``kind`` ("replica", "changes" or "snapshot"), ``replica`` (the
|
|
11
|
+
replica that wrote it) and what the kind needs. A change in it is the dict of to_wire().
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import gzip
|
|
15
|
+
import json
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from awsimple import S3Access, S3ObjectAlreadyExists, S3RequestTier
|
|
21
|
+
|
|
22
|
+
from ._types import Change, DSQLiteError, Stamp, Stored, Usage
|
|
23
|
+
|
|
24
|
+
FORMAT = 1
|
|
25
|
+
SUFFIX = ".json.gz"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ReplicaIdConflictError(DSQLiteError):
|
|
29
|
+
"""
|
|
30
|
+
The bucket already holds a different object under this replica's id. Two databases are using one replica id,
|
|
31
|
+
which happens when a database file is copied: call Sync.new_replica_id() on the copy.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class FormatError(DSQLiteError):
|
|
36
|
+
"""A bucket object was written by a newer dsqlite than this one."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# the wire format
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def dump(payload: dict[str, Any]) -> bytes:
|
|
43
|
+
"""The bytes of a bucket object. The same payload always gives the same bytes, so a repeated push writes the same object."""
|
|
44
|
+
return gzip.compress(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode(), mtime=0)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def load(data: bytes) -> dict[str, Any]:
|
|
48
|
+
"""The payload of a bucket object. Raises FormatError if a newer dsqlite wrote it."""
|
|
49
|
+
payload: dict[str, Any] = json.loads(gzip.decompress(data))
|
|
50
|
+
if payload["format"] > FORMAT:
|
|
51
|
+
raise FormatError(f"object format {payload['format']} is newer than this dsqlite understands ({FORMAT})")
|
|
52
|
+
return payload
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _encode(value: Any) -> Any:
|
|
56
|
+
"""The JSON form of a row value. Python writes and reads a JSON number exactly, so only what JSON lacks is wrapped."""
|
|
57
|
+
if isinstance(value, bytes):
|
|
58
|
+
return {"$blob": value.hex()}
|
|
59
|
+
if isinstance(value, float) and value in (float("inf"), float("-inf")):
|
|
60
|
+
return {"$real": "inf" if value > 0 else "-inf"}
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _decode(value: Any) -> Any:
|
|
65
|
+
"""The row value of its JSON form (see _encode())."""
|
|
66
|
+
if isinstance(value, dict):
|
|
67
|
+
return bytes.fromhex(value["$blob"]) if "$blob" in value else float(value["$real"])
|
|
68
|
+
return value
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def to_wire(change: Change) -> dict[str, Any]:
|
|
72
|
+
"""A change as it is in a bucket object: table, key, op, the stamp's wall_ms, counter and replica, and the row image."""
|
|
73
|
+
row = None if change.row is None else {column: _encode(value) for column, value in change.row.items()}
|
|
74
|
+
return {"t": change.table, "k": change.key, "o": change.op, "w": change.stamp.wall_ms, "c": change.stamp.counter, "r": change.stamp.replica, "i": row}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def from_wire(wire: dict[str, Any]) -> Change:
|
|
78
|
+
"""The change of its wire form (see to_wire())."""
|
|
79
|
+
row = None if wire["i"] is None else {column: _decode(value) for column, value in wire["i"].items()}
|
|
80
|
+
return Change(table=wire["t"], key=wire["k"], op=wire["o"], stamp=Stamp(wire["w"], wire["c"], wire["r"]), row=row)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _payload(kind: str, replica: str, changes: list[Change] | None = None, **fields: Any) -> dict[str, Any]:
|
|
84
|
+
"""The payload of an object of a kind, written by a replica, with its changes (if it has any) in wire form."""
|
|
85
|
+
payload: dict[str, Any] = {"format": FORMAT, "kind": kind, "replica": replica, **fields}
|
|
86
|
+
if changes is not None:
|
|
87
|
+
payload["changes"] = [to_wire(change) for change in changes]
|
|
88
|
+
return payload
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _changes(payload: dict[str, Any]) -> list[Change]:
|
|
92
|
+
"""The changes of a "changes" or "snapshot" payload."""
|
|
93
|
+
return [from_wire(wire) for wire in payload["changes"]]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class Bucket:
|
|
97
|
+
"""
|
|
98
|
+
One database's objects in an S3 bucket.
|
|
99
|
+
|
|
100
|
+
:param bucket: the S3 bucket
|
|
101
|
+
:param name: the name of the database in the bucket, which starts the key of each of its objects
|
|
102
|
+
:param aws: keyword arguments for awsimple's S3Access (profile, credentials, region)
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, bucket: str, name: str, aws: dict[str, Any]) -> None:
|
|
106
|
+
if not name or "/" in name:
|
|
107
|
+
raise ValueError(f"name must be non-empty and contain no '/', got {name!r}")
|
|
108
|
+
self._bucket = bucket
|
|
109
|
+
self._name = name
|
|
110
|
+
self._aws = aws
|
|
111
|
+
self._thread = threading.local() # awsimple wants one S3Access per thread
|
|
112
|
+
self._lock = threading.Lock() # guards what usage() reads, which every thread adds to
|
|
113
|
+
self._accesses: list[S3Access] = [] # the S3Access of every thread, each of which counts its requests
|
|
114
|
+
self._uploaded_bytes = 0
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def s3(self) -> S3Access:
|
|
118
|
+
"""This thread's S3Access."""
|
|
119
|
+
try:
|
|
120
|
+
s3: S3Access = self._thread.s3
|
|
121
|
+
except AttributeError:
|
|
122
|
+
s3 = self._thread.s3 = S3Access(self._bucket, **self._aws)
|
|
123
|
+
with self._lock:
|
|
124
|
+
self._accesses.append(s3)
|
|
125
|
+
return s3
|
|
126
|
+
|
|
127
|
+
# keys
|
|
128
|
+
|
|
129
|
+
def _prefix(self, kind: str) -> str:
|
|
130
|
+
"""The start of the keys of this database's objects of a kind: "replicas", "changes" or "snapshots"."""
|
|
131
|
+
return f"{self._name}/{kind}/"
|
|
132
|
+
|
|
133
|
+
def _changes_key(self, replica: str, seq: int) -> str:
|
|
134
|
+
"""The key of the change object of a replica that starts with a seq. The seq is zero-padded, so the keys list in seq order."""
|
|
135
|
+
return f"{self._prefix('changes')}{replica}/{seq:020d}{SUFFIX}"
|
|
136
|
+
|
|
137
|
+
# reading and writing objects
|
|
138
|
+
|
|
139
|
+
def _get(self, key: str) -> dict[str, Any]:
|
|
140
|
+
"""The payload of an object."""
|
|
141
|
+
return load(self.s3.read_bytes(key))
|
|
142
|
+
|
|
143
|
+
def _put_once(self, key: str, payload: dict[str, Any]) -> None:
|
|
144
|
+
"""Write an object that must not exist yet, or must already hold exactly this payload (a repeated push)."""
|
|
145
|
+
data = dump(payload)
|
|
146
|
+
try:
|
|
147
|
+
self.s3.write_bytes(data, key, overwrite=False)
|
|
148
|
+
except S3ObjectAlreadyExists:
|
|
149
|
+
if self._get(key) != load(data):
|
|
150
|
+
raise ReplicaIdConflictError(f"s3://{self._bucket}/{key} already exists with different content") from None
|
|
151
|
+
with self._lock:
|
|
152
|
+
self._uploaded_bytes += len(data) # sent in either case
|
|
153
|
+
|
|
154
|
+
# replicas
|
|
155
|
+
|
|
156
|
+
def register(self, replica: str) -> None:
|
|
157
|
+
"""Record a replica in the bucket, which is how the others find its changes."""
|
|
158
|
+
self._put_once(f"{self._prefix('replicas')}{replica}{SUFFIX}", _payload("replica", replica))
|
|
159
|
+
|
|
160
|
+
def replicas(self) -> list[str]:
|
|
161
|
+
"""The ids of the replicas that have registered."""
|
|
162
|
+
prefix = self._prefix("replicas")
|
|
163
|
+
return [key.removeprefix(prefix).removesuffix(SUFFIX) for key in self.s3.keys(prefix)]
|
|
164
|
+
|
|
165
|
+
# changes
|
|
166
|
+
|
|
167
|
+
def put_changes(self, replica: str, first_seq: int, last_seq: int, changes: list[Change]) -> str:
|
|
168
|
+
"""Write one push: a replica's changes of a seq range. Returns the object's key."""
|
|
169
|
+
# Named by the first seq: two databases wrongly sharing a replica id both continue from the same seq, so
|
|
170
|
+
# the second to push meets the first one's object and the conflict is detected.
|
|
171
|
+
key = self._changes_key(replica, first_seq)
|
|
172
|
+
self._put_once(key, _payload("changes", replica, changes, first_seq=first_seq, last_seq=last_seq))
|
|
173
|
+
return key
|
|
174
|
+
|
|
175
|
+
def changes_after(self, replica: str, last_seq: int) -> list[str]:
|
|
176
|
+
"""The keys of a replica's change objects that start after a seq, in order."""
|
|
177
|
+
keys: list[str] = self.s3.keys(f"{self._prefix('changes')}{replica}/", start_after=self._changes_key(replica, last_seq))
|
|
178
|
+
return keys
|
|
179
|
+
|
|
180
|
+
def get_changes(self, key: str) -> tuple[list[Change], int]:
|
|
181
|
+
"""The changes of a change object, and the seq of its last one."""
|
|
182
|
+
payload = self._get(key)
|
|
183
|
+
return _changes(payload), int(payload["last_seq"])
|
|
184
|
+
|
|
185
|
+
# snapshots
|
|
186
|
+
|
|
187
|
+
def put_snapshot(self, replica: str, changes: list[Change], positions: dict[str, int]) -> str:
|
|
188
|
+
"""
|
|
189
|
+
Write a snapshot: the current state of every row as changes, and the position in each replica's changes that
|
|
190
|
+
the state includes. Returns the object's key, which starts with the time so that the newest lists last.
|
|
191
|
+
"""
|
|
192
|
+
key = f"{self._prefix('snapshots')}{time.time_ns():020d}-{replica}{SUFFIX}"
|
|
193
|
+
self._put_once(key, _payload("snapshot", replica, changes, positions=positions))
|
|
194
|
+
return key
|
|
195
|
+
|
|
196
|
+
def latest_snapshot(self) -> tuple[list[Change], dict[str, int]] | None:
|
|
197
|
+
"""The changes and positions of the newest snapshot (see put_snapshot()), or None if there is no snapshot."""
|
|
198
|
+
keys = self.s3.keys(self._prefix("snapshots"))
|
|
199
|
+
if not keys:
|
|
200
|
+
return None
|
|
201
|
+
payload = self._get(keys[-1])
|
|
202
|
+
return _changes(payload), {str(replica): int(seq) for replica, seq in payload["positions"].items()}
|
|
203
|
+
|
|
204
|
+
# usage
|
|
205
|
+
|
|
206
|
+
def stored(self) -> Stored:
|
|
207
|
+
"""What this database holds in the bucket (see Stored). It lists the database's objects: a request per 1000 of them."""
|
|
208
|
+
objects = self.s3.list_objects(f"{self._name}/")
|
|
209
|
+
return Stored(objects=len(objects), size=sum(listed.size for listed in objects.values()))
|
|
210
|
+
|
|
211
|
+
def usage(self) -> Usage:
|
|
212
|
+
"""What every thread has used of S3 through this Bucket (see Usage)."""
|
|
213
|
+
with self._lock:
|
|
214
|
+
accesses = list(self._accesses)
|
|
215
|
+
uploaded_bytes = self._uploaded_bytes
|
|
216
|
+
tiers = {S3RequestTier.tier1: 0, S3RequestTier.tier2: 0, S3RequestTier.free: 0}
|
|
217
|
+
for s3 in accesses:
|
|
218
|
+
for (tier, _storage_class), count in s3.usage.get_tier_counts().items():
|
|
219
|
+
tiers[tier] += count
|
|
220
|
+
return Usage(
|
|
221
|
+
uploads=sum(s3.usage.get_request_count("PutObject") for s3 in accesses),
|
|
222
|
+
uploaded_bytes=uploaded_bytes,
|
|
223
|
+
downloads=sum(s3.usage.get_request_count("GetObject") for s3 in accesses),
|
|
224
|
+
downloaded_bytes=sum(s3.usage.get_download_size() for s3 in accesses),
|
|
225
|
+
tier1_requests=tiers[S3RequestTier.tier1],
|
|
226
|
+
tier2_requests=tiers[S3RequestTier.tier2],
|
|
227
|
+
)
|
dsqlite/_local.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The local half of dsqlite: change capture, history, and applying remote changes. Nothing here touches the network.
|
|
3
|
+
|
|
4
|
+
Rows are read by index, so the application's Database may use the default row factory or sqlite3.Row.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from dataclasses import astuple
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from msqlite import Database, Transaction
|
|
12
|
+
|
|
13
|
+
from ._sql import CHANGE_COLUMNS, MIGRATIONS, ROW_COLUMNS, SEQ, STAMP, STAMP_COLUMNS, Table, check_database, install, quote_identifier, read_table, remove_unsynced, same_stamp, stamp_columns
|
|
14
|
+
from ._types import Change, HistoryError, SchemaMismatchError, Stamp, TableError, key_of, values_of
|
|
15
|
+
|
|
16
|
+
# Conditions on dsqlite_change (alias c), for Local._read():
|
|
17
|
+
_CURRENT = f"EXISTS (SELECT 1 FROM dsqlite_row AS r WHERE r.tbl = c.tbl AND r.key = c.key AND {same_stamp('r', 'c')})" # the change is the current state of its row
|
|
18
|
+
_HAS_STAMP = " AND ".join(f"c.{column} = ?" for column in STAMP) # the change has the stamp given as parameters
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _replica(tx: Transaction) -> str:
|
|
22
|
+
"""This database's replica id."""
|
|
23
|
+
return str(tx.execute("SELECT replica FROM dsqlite_state").fetchone()[0])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _peer_positions(tx: Transaction) -> dict[str, int]:
|
|
27
|
+
"""Per peer replica, the last seq of its changes that has been applied here."""
|
|
28
|
+
return {str(row[0]): int(row[1]) for row in tx.execute("SELECT replica, last_seq FROM dsqlite_peer").fetchall()}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Local:
|
|
32
|
+
"""
|
|
33
|
+
dsqlite's tables and triggers in one local database.
|
|
34
|
+
|
|
35
|
+
Creating one brings dsqlite's own schema up to date, installs the change-capture triggers of the synced tables,
|
|
36
|
+
records whatever was written to them while no triggers were there, and removes the triggers of tables that are
|
|
37
|
+
not synced any more.
|
|
38
|
+
|
|
39
|
+
:param db: the application's database
|
|
40
|
+
:param tables: the names of the tables to sync
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, db: Database, tables: Sequence[str]) -> None:
|
|
44
|
+
if not tables:
|
|
45
|
+
raise TableError("no tables to sync")
|
|
46
|
+
self.db = db
|
|
47
|
+
db.migrate(MIGRATIONS, name="dsqlite")
|
|
48
|
+
with db.write() as tx:
|
|
49
|
+
check_database(tx)
|
|
50
|
+
self.tables = {name: read_table(tx, name) for name in tables}
|
|
51
|
+
for table in self.tables.values():
|
|
52
|
+
install(tx, table)
|
|
53
|
+
remove_unsynced(tx, self.tables)
|
|
54
|
+
self.replica = _replica(tx)
|
|
55
|
+
|
|
56
|
+
def _table(self, name: str) -> Table:
|
|
57
|
+
"""A synced table, by name."""
|
|
58
|
+
try:
|
|
59
|
+
return self.tables[name]
|
|
60
|
+
except KeyError:
|
|
61
|
+
raise TableError(f'table "{name}" is not synced') from None
|
|
62
|
+
|
|
63
|
+
def key(self, table_name: str, pk: Any) -> str:
|
|
64
|
+
"""The key of a row, from its primary key value, or a tuple of values for a composite primary key."""
|
|
65
|
+
table = self._table(table_name)
|
|
66
|
+
values = tuple(pk) if isinstance(pk, (tuple, list)) else (pk,)
|
|
67
|
+
if len(values) != len(table.pk):
|
|
68
|
+
raise TableError(f'the primary key of "{table.name}" has {len(table.pk)} column(s), got {len(values)} value(s)')
|
|
69
|
+
return key_of(values)
|
|
70
|
+
|
|
71
|
+
def _read(self, tx: Transaction, where: str, parameters: tuple[Any, ...] = (), tables: Sequence[Table] | None = None) -> list[Change]:
|
|
72
|
+
"""
|
|
73
|
+
The recorded changes that match a condition on dsqlite_change (alias c), with their row images, in seq order.
|
|
74
|
+
``tables`` limits them to those tables; the default is every synced table.
|
|
75
|
+
"""
|
|
76
|
+
found: list[tuple[int, Change]] = []
|
|
77
|
+
for table in self.tables.values() if tables is None else tables:
|
|
78
|
+
rows = tx.execute(
|
|
79
|
+
f"SELECT c.seq, c.key, c.op, {stamp_columns('c')}, c.origin, {table.column_list('i')} "
|
|
80
|
+
f"FROM dsqlite_change AS c LEFT JOIN {table.shadow} AS i ON i.{SEQ} = c.seq WHERE c.tbl = ? AND {where}",
|
|
81
|
+
(table.name, *parameters),
|
|
82
|
+
).fetchall()
|
|
83
|
+
for row in rows:
|
|
84
|
+
image = dict(zip(table.columns, row[7:], strict=True)) if row[2] == "put" else None
|
|
85
|
+
found.append((row[0], Change(table=table.name, key=row[1], op=row[2], stamp=Stamp(row[3], row[4], row[5]), row=image, origin=row[6])))
|
|
86
|
+
return [change for _seq, change in sorted(found, key=lambda item: item[0])]
|
|
87
|
+
|
|
88
|
+
# history
|
|
89
|
+
|
|
90
|
+
def history(self, table_name: str, pk: Any) -> list[Change]:
|
|
91
|
+
"""Every recorded write of one row, oldest first."""
|
|
92
|
+
key = self.key(table_name, pk)
|
|
93
|
+
with self.db.read() as tx:
|
|
94
|
+
return sorted(self._read(tx, "c.key = ?", (key,), [self._table(table_name)]), key=lambda change: change.stamp)
|
|
95
|
+
|
|
96
|
+
def restore(self, table_name: str, pk: Any, stamp: Stamp) -> None:
|
|
97
|
+
"""
|
|
98
|
+
Write the state a row had at ``stamp`` back to the table. This is an ordinary local write, so it gets a new
|
|
99
|
+
stamp and syncs like any other.
|
|
100
|
+
"""
|
|
101
|
+
table = self._table(table_name)
|
|
102
|
+
key = self.key(table_name, pk)
|
|
103
|
+
with self.db.write() as tx:
|
|
104
|
+
found = self._read(tx, f"c.key = ? AND {_HAS_STAMP}", (key, *astuple(stamp)), [table])
|
|
105
|
+
if not found:
|
|
106
|
+
raise HistoryError(f'no write of "{table.name}" {values_of(key)} with {stamp}')
|
|
107
|
+
self._write(tx, table, found[0])
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def _check(table: Table, change: Change) -> None:
|
|
111
|
+
"""Raise SchemaMismatchError if the change's row does not have exactly the table's columns."""
|
|
112
|
+
if change.row is not None and set(change.row) != set(table.columns):
|
|
113
|
+
raise SchemaMismatchError(f'table "{table.name}" has columns {sorted(table.columns)} here, the change has {sorted(change.row)}')
|
|
114
|
+
|
|
115
|
+
def _write(self, tx: Transaction, table: Table, change: Change) -> None:
|
|
116
|
+
"""Put or delete the change's row in its table."""
|
|
117
|
+
if change.row is None:
|
|
118
|
+
tx.execute(table.delete_sql(), values_of(change.key))
|
|
119
|
+
else:
|
|
120
|
+
self._check(table, change)
|
|
121
|
+
tx.execute(table.put_sql(), tuple(change.row[column] for column in table.columns))
|
|
122
|
+
|
|
123
|
+
# push
|
|
124
|
+
|
|
125
|
+
def start_push(self) -> tuple[int, int] | None:
|
|
126
|
+
"""
|
|
127
|
+
The seq range of local changes to push next, or None if there are none. The range is recorded before it is
|
|
128
|
+
returned, so a push interrupted by a crash is repeated with exactly the same range.
|
|
129
|
+
"""
|
|
130
|
+
with self.db.write() as tx:
|
|
131
|
+
pushed_seq, pending_first, pending_last = tx.execute("SELECT pushed_seq, pending_first, pending_last FROM dsqlite_state").fetchone()
|
|
132
|
+
if pending_first is not None:
|
|
133
|
+
return int(pending_first), int(pending_last)
|
|
134
|
+
first, last = tx.execute("SELECT MIN(seq), MAX(seq) FROM dsqlite_change WHERE origin = 'local' AND seq > ?", (pushed_seq,)).fetchone()
|
|
135
|
+
if first is None:
|
|
136
|
+
return None
|
|
137
|
+
tx.execute("UPDATE dsqlite_state SET pending_first = ?, pending_last = ?", (first, last))
|
|
138
|
+
return int(first), int(last)
|
|
139
|
+
|
|
140
|
+
def local_changes(self, first: int, last: int) -> list[Change]:
|
|
141
|
+
"""The local changes in a seq range, in order. Writers are serialized, so a committed range holds only whole transactions."""
|
|
142
|
+
with self.db.read() as tx:
|
|
143
|
+
return self._read(tx, "c.origin = 'local' AND c.seq BETWEEN ? AND ?", (first, last))
|
|
144
|
+
|
|
145
|
+
def finish_push(self, last: int, uploaded: bool = True) -> None:
|
|
146
|
+
"""
|
|
147
|
+
Record that the range started by start_push(), which ends at ``last``, is done. ``uploaded`` says that it is
|
|
148
|
+
in the bucket as a change object, which counts towards the next snapshot; a range that holds no changes of
|
|
149
|
+
the synced tables is done without one.
|
|
150
|
+
"""
|
|
151
|
+
with self.db.write() as tx:
|
|
152
|
+
tx.execute(
|
|
153
|
+
"UPDATE dsqlite_state SET pushed_seq = ?, pending_first = NULL, pending_last = NULL, objects_since_snapshot = objects_since_snapshot + ?",
|
|
154
|
+
(last, int(uploaded)),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# pull
|
|
158
|
+
|
|
159
|
+
def peer_positions(self) -> dict[str, int]:
|
|
160
|
+
"""Per peer replica, the last seq of its changes that has been applied here."""
|
|
161
|
+
with self.db.read() as tx:
|
|
162
|
+
return _peer_positions(tx)
|
|
163
|
+
|
|
164
|
+
def apply(self, changes: Sequence[Change], positions: dict[str, int], objects: int = 0) -> tuple[int, int]:
|
|
165
|
+
"""
|
|
166
|
+
Apply remote changes in one transaction and advance the peer positions with them. A change is written to its
|
|
167
|
+
table only if its stamp is greater than the row's current one; every change is recorded in the history.
|
|
168
|
+
``objects`` is how many change objects the changes are, which count towards the next snapshot.
|
|
169
|
+
Returns (changes that won, changes that were superseded).
|
|
170
|
+
|
|
171
|
+
Raises SchemaMismatchError, leaving the database untouched, if a change does not fit the local schema.
|
|
172
|
+
"""
|
|
173
|
+
applied = superseded = 0
|
|
174
|
+
with self.db.write() as tx:
|
|
175
|
+
tx.execute("UPDATE dsqlite_state SET applying = 1") # rolled back with everything else if this fails
|
|
176
|
+
newest = Stamp(0, 0, "")
|
|
177
|
+
for change in changes:
|
|
178
|
+
if change.table not in self.tables:
|
|
179
|
+
raise SchemaMismatchError(f'table "{change.table}" is not synced here')
|
|
180
|
+
table = self.tables[change.table]
|
|
181
|
+
self._check(table, change)
|
|
182
|
+
stamp = change.stamp
|
|
183
|
+
newest = max(newest, stamp)
|
|
184
|
+
recorded = tx.execute(
|
|
185
|
+
f"INSERT OR IGNORE INTO dsqlite_change ({CHANGE_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, 'remote')",
|
|
186
|
+
(table.name, change.key, change.op, *astuple(stamp)),
|
|
187
|
+
)
|
|
188
|
+
if recorded.rowcount == 1 and change.row is not None: # not already in the history
|
|
189
|
+
tx.execute(table.image_sql(), (recorded.lastrowid, *(change.row[column] for column in table.columns)))
|
|
190
|
+
current = tx.execute(f"SELECT {STAMP_COLUMNS} FROM dsqlite_row WHERE tbl = ? AND key = ?", (table.name, change.key)).fetchone()
|
|
191
|
+
if current is not None and stamp <= Stamp(*current):
|
|
192
|
+
superseded += 1
|
|
193
|
+
continue
|
|
194
|
+
self._write(tx, table, change)
|
|
195
|
+
tx.execute(
|
|
196
|
+
f"INSERT OR REPLACE INTO dsqlite_row ({ROW_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?)",
|
|
197
|
+
(table.name, change.key, *astuple(stamp), int(change.op == "delete")),
|
|
198
|
+
)
|
|
199
|
+
applied += 1
|
|
200
|
+
# The next local write must get a stamp greater than everything seen.
|
|
201
|
+
tx.execute("UPDATE dsqlite_state SET wall_ms = ?1, counter = ?2 WHERE (wall_ms, counter) < (?1, ?2)", (newest.wall_ms, newest.counter))
|
|
202
|
+
for replica, last_seq in positions.items():
|
|
203
|
+
tx.execute("INSERT INTO dsqlite_peer (replica, last_seq) VALUES (?1, ?2) ON CONFLICT (replica) DO UPDATE SET last_seq = MAX(last_seq, ?2)", (replica, last_seq))
|
|
204
|
+
tx.execute("UPDATE dsqlite_state SET applying = 0, objects_since_snapshot = objects_since_snapshot + ?", (objects,))
|
|
205
|
+
return applied, superseded
|
|
206
|
+
|
|
207
|
+
# bookkeeping
|
|
208
|
+
|
|
209
|
+
def has_unpushed(self) -> bool:
|
|
210
|
+
"""True if there are local changes that no push has started for."""
|
|
211
|
+
with self.db.read() as tx:
|
|
212
|
+
return bool(tx.execute("SELECT EXISTS (SELECT 1 FROM dsqlite_change WHERE origin = 'local' AND seq > (SELECT pushed_seq FROM dsqlite_state))").fetchone()[0])
|
|
213
|
+
|
|
214
|
+
def flag(self, name: str) -> bool:
|
|
215
|
+
"""The ``registered`` or ``bootstrapped`` flag."""
|
|
216
|
+
with self.db.read() as tx:
|
|
217
|
+
return bool(tx.execute(f"SELECT {quote_identifier(name)} FROM dsqlite_state").fetchone()[0])
|
|
218
|
+
|
|
219
|
+
def set_flag(self, name: str) -> None:
|
|
220
|
+
"""Set the ``registered`` or ``bootstrapped`` flag, which then stays set."""
|
|
221
|
+
with self.db.write() as tx:
|
|
222
|
+
tx.execute(f"UPDATE dsqlite_state SET {quote_identifier(name)} = 1")
|
|
223
|
+
|
|
224
|
+
def new_replica_id(self) -> str:
|
|
225
|
+
"""
|
|
226
|
+
Give this database a new replica id, for a database file that was copied from another replica. Everything it
|
|
227
|
+
has recorded locally is pushed again under the new id, which is harmless because applying is idempotent.
|
|
228
|
+
"""
|
|
229
|
+
with self.db.write() as tx:
|
|
230
|
+
tx.execute("UPDATE dsqlite_state SET replica = lower(hex(randomblob(16))), registered = 0, pushed_seq = 0, pending_first = NULL, pending_last = NULL")
|
|
231
|
+
self.replica = _replica(tx)
|
|
232
|
+
return self.replica
|
|
233
|
+
|
|
234
|
+
# snapshot
|
|
235
|
+
|
|
236
|
+
def snapshot(self) -> tuple[list[Change], dict[str, int]]:
|
|
237
|
+
"""
|
|
238
|
+
A consistent view of every synced row's current state (including tombstones), with the position in each
|
|
239
|
+
replica's changes that the view includes (this replica's own being what it has pushed).
|
|
240
|
+
"""
|
|
241
|
+
with self.db.read() as tx:
|
|
242
|
+
changes = self._read(tx, _CURRENT)
|
|
243
|
+
positions = _peer_positions(tx)
|
|
244
|
+
positions[self.replica] = int(tx.execute("SELECT pushed_seq FROM dsqlite_state").fetchone()[0])
|
|
245
|
+
return changes, positions
|
|
246
|
+
|
|
247
|
+
def objects_since_snapshot(self) -> int:
|
|
248
|
+
"""How many change objects this replica has pushed or pulled since it last uploaded a snapshot, in any process."""
|
|
249
|
+
with self.db.read() as tx:
|
|
250
|
+
return int(tx.execute("SELECT objects_since_snapshot FROM dsqlite_state").fetchone()[0])
|
|
251
|
+
|
|
252
|
+
def snapshot_uploaded(self) -> None:
|
|
253
|
+
"""Start counting change objects towards the next snapshot again."""
|
|
254
|
+
with self.db.write() as tx:
|
|
255
|
+
tx.execute("UPDATE dsqlite_state SET objects_since_snapshot = 0")
|