zarr-sqlite 1.0.1__tar.gz → 1.0.2__tar.gz
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.
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/PKG-INFO +1 -1
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/pyproject.toml +1 -1
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/src/zarr_sqlite/__init__.py +3 -4
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/src/zarr_sqlite/_version.py +1 -1
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/src/zarr_sqlite/async_sqlite.py +33 -17
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/src/zarr_sqlite/zarr_sqlite.py +78 -60
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/LICENSE.txt +0 -0
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/README.md +0 -0
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/src/zarr_sqlite/_db_utils.py +0 -0
- {zarr_sqlite-1.0.1 → zarr_sqlite-1.0.2}/src/zarr_sqlite/py.typed +0 -0
|
@@ -13,7 +13,7 @@ mutability and ACID guarantees.
|
|
|
13
13
|
at most, a single chunk may be lost. Readers can safely access the store
|
|
14
14
|
concurrently with writers and are guaranteed to see a consistent view of the
|
|
15
15
|
data.
|
|
16
|
-
* Mutable storage — arrays can be modified, overwritten, resized, appended to
|
|
16
|
+
* Mutable storage — arrays can be modified, overwritten, resized, appended to
|
|
17
17
|
and deleted.
|
|
18
18
|
|
|
19
19
|
`SQLiteStore` is primarily intended for relatively small Zarr datasets (typically
|
|
@@ -85,8 +85,7 @@ a stable basis for interoperability between implementations.
|
|
|
85
85
|
The `SQLiteStore` class implements the [zarr-python `Store` interface](https://zarr.readthedocs.io/en/stable/api/zarr/storage.html#zarr.abc.store.Store).
|
|
86
86
|
"""
|
|
87
87
|
|
|
88
|
-
from .zarr_sqlite import SQLiteStore
|
|
89
|
-
|
|
90
88
|
from ._version import __version__
|
|
89
|
+
from .zarr_sqlite import SQLiteStore
|
|
91
90
|
|
|
92
|
-
__all__ = ["
|
|
91
|
+
__all__ = ["SQLiteStore", "__version__"]
|
|
@@ -36,15 +36,15 @@ dedicated thread and results are returned as raw ``sqlite3`` objects.
|
|
|
36
36
|
import asyncio
|
|
37
37
|
import logging
|
|
38
38
|
import sqlite3
|
|
39
|
-
from collections.abc import AsyncIterator, Generator, Iterable
|
|
39
|
+
from collections.abc import AsyncIterator, Callable, Generator, Iterable
|
|
40
40
|
from functools import partial
|
|
41
41
|
from pathlib import Path
|
|
42
42
|
from queue import SimpleQueue
|
|
43
43
|
from threading import Thread
|
|
44
|
-
from typing import Any
|
|
44
|
+
from typing import Any
|
|
45
45
|
from warnings import warn
|
|
46
46
|
|
|
47
|
-
__all__ = ["
|
|
47
|
+
__all__ = ["Connection", "connect"]
|
|
48
48
|
|
|
49
49
|
LOG = logging.getLogger("zarr_sqlite")
|
|
50
50
|
|
|
@@ -54,7 +54,7 @@ class _Stop:
|
|
|
54
54
|
|
|
55
55
|
|
|
56
56
|
_STOP_RUNNING_SENTINEL = _Stop()
|
|
57
|
-
_TxQueue = SimpleQueue[tuple[
|
|
57
|
+
_TxQueue = SimpleQueue[tuple[asyncio.Future | None, Callable[[], Any]]]
|
|
58
58
|
|
|
59
59
|
|
|
60
60
|
def set_result(fut: asyncio.Future, result: Any) -> None:
|
|
@@ -105,7 +105,7 @@ class Connection:
|
|
|
105
105
|
connector: Callable[[], sqlite3.Connection],
|
|
106
106
|
) -> None:
|
|
107
107
|
self._running = True
|
|
108
|
-
self._connection:
|
|
108
|
+
self._connection: sqlite3.Connection | None = None
|
|
109
109
|
self._connector = connector
|
|
110
110
|
self._tx: _TxQueue = SimpleQueue()
|
|
111
111
|
self._thread = Thread(target=_connection_worker_thread, args=(self._tx,))
|
|
@@ -128,7 +128,9 @@ class Connection:
|
|
|
128
128
|
# sqlite3 connection be finalized by its own __del__.
|
|
129
129
|
self.stop()
|
|
130
130
|
|
|
131
|
-
def stop(
|
|
131
|
+
def stop(
|
|
132
|
+
self, join=False, join_timeout: float | None = None
|
|
133
|
+
) -> asyncio.Future | None:
|
|
132
134
|
"""Stop the background thread. Prefer `async with` or `await close()`"""
|
|
133
135
|
self._running = False
|
|
134
136
|
|
|
@@ -140,7 +142,7 @@ class Connection:
|
|
|
140
142
|
|
|
141
143
|
try:
|
|
142
144
|
future = asyncio.get_running_loop().create_future()
|
|
143
|
-
except
|
|
145
|
+
except RuntimeError:
|
|
144
146
|
future = None
|
|
145
147
|
|
|
146
148
|
self._tx.put_nowait((future, close_and_stop))
|
|
@@ -210,11 +212,19 @@ class Connection:
|
|
|
210
212
|
if future:
|
|
211
213
|
await future
|
|
212
214
|
|
|
215
|
+
def _execute_and_close(self, sql, params) -> None:
|
|
216
|
+
cur = self._conn.execute(sql, params)
|
|
217
|
+
|
|
218
|
+
# We need to close in cursor on the same thread that owns the
|
|
219
|
+
# connection. Otherwise I've had weird issues like journal_mode being
|
|
220
|
+
# reverted to previous setting after an attempt to change it.
|
|
221
|
+
cur.close()
|
|
222
|
+
|
|
213
223
|
async def execute(self, sql: str, parameters: Iterable[Any] | None = None) -> None:
|
|
214
224
|
"""Execute a SQL statement."""
|
|
215
225
|
if parameters is None:
|
|
216
226
|
parameters = []
|
|
217
|
-
await self._execute(self.
|
|
227
|
+
await self._execute(self._execute_and_close, sql, parameters)
|
|
218
228
|
|
|
219
229
|
async def set_autocommit(self, value: bool) -> None:
|
|
220
230
|
"""Set the autocommit mode of the underlying sqlite3 connection.
|
|
@@ -230,6 +240,13 @@ class Connection:
|
|
|
230
240
|
"""Execute a SQL statement many times."""
|
|
231
241
|
await self._execute(self._conn.executemany, sql, parameters)
|
|
232
242
|
|
|
243
|
+
def _fetchall(self, sql, params):
|
|
244
|
+
cursor = self._conn.execute(sql, params)
|
|
245
|
+
try:
|
|
246
|
+
return cursor.fetchall()
|
|
247
|
+
finally:
|
|
248
|
+
cursor.close()
|
|
249
|
+
|
|
233
250
|
async def fetchall(
|
|
234
251
|
self, sql: str, parameters: Iterable[Any] | None = None
|
|
235
252
|
) -> list[tuple[Any, ...]]:
|
|
@@ -241,11 +258,14 @@ class Connection:
|
|
|
241
258
|
if parameters is None:
|
|
242
259
|
parameters = []
|
|
243
260
|
|
|
244
|
-
|
|
245
|
-
cursor = self._conn.execute(sql, parameters)
|
|
246
|
-
return cursor.fetchall()
|
|
261
|
+
return await self._execute(self._fetchall, sql, parameters)
|
|
247
262
|
|
|
248
|
-
|
|
263
|
+
def _fetchone(self, sql, params):
|
|
264
|
+
cursor = self._conn.execute(sql, params)
|
|
265
|
+
try:
|
|
266
|
+
return cursor.fetchone()
|
|
267
|
+
finally:
|
|
268
|
+
cursor.close()
|
|
249
269
|
|
|
250
270
|
async def fetchone(
|
|
251
271
|
self, sql: str, parameters: Iterable[Any] | None = None
|
|
@@ -259,11 +279,7 @@ class Connection:
|
|
|
259
279
|
if parameters is None:
|
|
260
280
|
parameters = []
|
|
261
281
|
|
|
262
|
-
|
|
263
|
-
cursor = self._conn.execute(sql, parameters)
|
|
264
|
-
return cursor.fetchone()
|
|
265
|
-
|
|
266
|
-
return await self._execute(_fetchone)
|
|
282
|
+
return await self._execute(self._fetchone, sql, parameters)
|
|
267
283
|
|
|
268
284
|
async def fetch_iter(
|
|
269
285
|
self, sql: str, parameters: Iterable[Any] | None = None
|
|
@@ -1,16 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
from collections.abc import Iterable, AsyncIterator, AsyncGenerator
|
|
3
|
-
from contextlib import asynccontextmanager
|
|
4
|
-
from datetime import datetime, timezone
|
|
1
|
+
import asyncio
|
|
5
2
|
import sqlite3
|
|
3
|
+
import urllib.parse
|
|
6
4
|
import warnings
|
|
5
|
+
from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Sequence
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from datetime import UTC, datetime
|
|
7
8
|
from pathlib import Path
|
|
8
|
-
import
|
|
9
|
-
import asyncio
|
|
10
|
-
|
|
11
|
-
from .async_sqlite import Connection, connect
|
|
12
|
-
|
|
13
|
-
from zarr.core.buffer import BufferPrototype, Buffer
|
|
9
|
+
from typing import Self, override
|
|
14
10
|
|
|
15
11
|
from zarr.abc.store import (
|
|
16
12
|
ByteRequest,
|
|
@@ -19,9 +15,11 @@ from zarr.abc.store import (
|
|
|
19
15
|
Store,
|
|
20
16
|
SuffixByteRequest,
|
|
21
17
|
)
|
|
18
|
+
from zarr.core.buffer import Buffer, BufferPrototype
|
|
22
19
|
|
|
23
|
-
from ._version import __version__
|
|
24
20
|
from ._db_utils import is_database_uri, is_in_memory_database
|
|
21
|
+
from ._version import __version__
|
|
22
|
+
from .async_sqlite import Connection, connect
|
|
25
23
|
|
|
26
24
|
if sqlite3.sqlite_version_info < (3, 17, 7):
|
|
27
25
|
raise ValueError(
|
|
@@ -182,6 +180,10 @@ class SQLiteStore(Store):
|
|
|
182
180
|
assert self._conn is not None
|
|
183
181
|
async with self._transaction_lock:
|
|
184
182
|
try:
|
|
183
|
+
# Call rollback() to ensure we begin a fresh transaction.
|
|
184
|
+
# In particular, this is helpful for "read" queries (SELECT) to
|
|
185
|
+
# ensure that they will get fresh data.
|
|
186
|
+
await self._conn.rollback()
|
|
185
187
|
yield
|
|
186
188
|
await self._conn.commit()
|
|
187
189
|
except BaseException:
|
|
@@ -254,19 +256,20 @@ class SQLiteStore(Store):
|
|
|
254
256
|
elif self._journal_mode.upper() not in {"DELETE", "WAL"}:
|
|
255
257
|
raise ValueError(f"Invalid journal_mode: {self._journal_mode}")
|
|
256
258
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
259
|
+
async with self._transaction_lock:
|
|
260
|
+
# PRAGMA journal_mode cannot be changed within a transaction.
|
|
261
|
+
# Temporarily set autocommit=True to execute it outside a
|
|
262
|
+
# transaction, then restore the previous value.
|
|
263
|
+
await self._conn.set_autocommit(True)
|
|
264
|
+
try:
|
|
265
|
+
await self._conn.execute("PRAGMA journal_mode=" + self._journal_mode)
|
|
266
|
+
finally:
|
|
267
|
+
await self._conn.set_autocommit(False)
|
|
265
268
|
|
|
266
269
|
async def _update_timestamp(self) -> None:
|
|
267
270
|
assert self._conn is not None
|
|
268
271
|
|
|
269
|
-
now = datetime.now(
|
|
272
|
+
now = datetime.now(UTC).isoformat().upper()
|
|
270
273
|
if now.endswith("+00:00"):
|
|
271
274
|
now = now.removesuffix("+00:00") + "Z"
|
|
272
275
|
assert now.endswith("Z")
|
|
@@ -279,15 +282,16 @@ class SQLiteStore(Store):
|
|
|
279
282
|
|
|
280
283
|
async def _db_is_empty(self) -> bool:
|
|
281
284
|
assert self._conn is not None
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
SELECT
|
|
286
|
-
|
|
287
|
-
|
|
285
|
+
async with self._transaction():
|
|
286
|
+
row = await self._conn.fetchone(
|
|
287
|
+
"""
|
|
288
|
+
SELECT EXISTS (
|
|
289
|
+
SELECT 1 FROM sqlite_schema
|
|
290
|
+
WHERE type IN ('table', 'view', 'index', 'trigger')
|
|
291
|
+
AND name NOT LIKE 'sqlite_%'
|
|
292
|
+
)
|
|
293
|
+
"""
|
|
288
294
|
)
|
|
289
|
-
"""
|
|
290
|
-
)
|
|
291
295
|
assert row is not None
|
|
292
296
|
return row[0] == 0
|
|
293
297
|
|
|
@@ -299,19 +303,27 @@ class SQLiteStore(Store):
|
|
|
299
303
|
)
|
|
300
304
|
|
|
301
305
|
assert self._conn is not None
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
raise ValueError(
|
|
308
|
-
f"Invalid SQLiteStore file: missing required table '{required_table}'"
|
|
306
|
+
async with self._transaction():
|
|
307
|
+
# Check for presence of required tables
|
|
308
|
+
for required_table in ("zarr", "zarr_sqlitestore_metadata"):
|
|
309
|
+
rows = await self._conn.fetchall(
|
|
310
|
+
"PRAGMA table_info(" + required_table + ")"
|
|
309
311
|
)
|
|
312
|
+
if not rows:
|
|
313
|
+
raise ValueError(
|
|
314
|
+
f"Invalid SQLiteStore file: missing required table '{required_table}'"
|
|
315
|
+
)
|
|
310
316
|
|
|
311
|
-
|
|
317
|
+
app_id_row = await self._conn.fetchone("PRAGMA application_id")
|
|
318
|
+
|
|
319
|
+
metadata_rows = await self._conn.fetchall(
|
|
320
|
+
"SELECT k, v FROM zarr_sqlitestore_metadata WHERE k IN (?, ?, ?)",
|
|
321
|
+
metadata_keys,
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
# Check application ID value
|
|
312
325
|
assert app_id_row is not None
|
|
313
326
|
app_id = app_id_row[0]
|
|
314
|
-
|
|
315
327
|
if app_id != _SQLITESTORE_APPLICATION_ID:
|
|
316
328
|
if self.read_only:
|
|
317
329
|
warnings.warn(
|
|
@@ -329,11 +341,7 @@ class SQLiteStore(Store):
|
|
|
329
341
|
f"(expected {_SQLITESTORE_APPLICATION_ID:#x})."
|
|
330
342
|
)
|
|
331
343
|
|
|
332
|
-
|
|
333
|
-
"SELECT k, v FROM zarr_sqlitestore_metadata WHERE k IN (?, ?, ?)",
|
|
334
|
-
metadata_keys,
|
|
335
|
-
)
|
|
336
|
-
|
|
344
|
+
# Check validity of metadata
|
|
337
345
|
metadata: dict[str, str] = (
|
|
338
346
|
{k: v for k, v in metadata_rows} if metadata_rows else {}
|
|
339
347
|
)
|
|
@@ -411,7 +419,8 @@ class SQLiteStore(Store):
|
|
|
411
419
|
params = self._get_text_boundaries(prefix)
|
|
412
420
|
sql = "SELECT EXISTS(SELECT 1 FROM zarr WHERE k > ? AND k < ? LIMIT 1)"
|
|
413
421
|
|
|
414
|
-
|
|
422
|
+
async with self._transaction():
|
|
423
|
+
row = await self._conn.fetchone(sql, params)
|
|
415
424
|
return row is not None and row[0] == 0
|
|
416
425
|
|
|
417
426
|
@override
|
|
@@ -447,7 +456,9 @@ class SQLiteStore(Store):
|
|
|
447
456
|
await self._ensure_open()
|
|
448
457
|
assert self._conn is not None
|
|
449
458
|
|
|
450
|
-
|
|
459
|
+
async with self._transaction():
|
|
460
|
+
row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
|
|
461
|
+
# print(f"Get '{key}'")
|
|
451
462
|
|
|
452
463
|
if row is None:
|
|
453
464
|
return None
|
|
@@ -488,7 +499,8 @@ class SQLiteStore(Store):
|
|
|
488
499
|
_validate_key(key)
|
|
489
500
|
await self._ensure_open()
|
|
490
501
|
assert self._conn is not None
|
|
491
|
-
|
|
502
|
+
async with self._transaction():
|
|
503
|
+
row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
|
|
492
504
|
return row is not None
|
|
493
505
|
|
|
494
506
|
@override
|
|
@@ -539,8 +551,9 @@ class SQLiteStore(Store):
|
|
|
539
551
|
async def list(self) -> AsyncIterator[str]:
|
|
540
552
|
await self._ensure_open()
|
|
541
553
|
assert self._conn is not None
|
|
542
|
-
async
|
|
543
|
-
|
|
554
|
+
async with self._transaction():
|
|
555
|
+
async for row in self._conn.fetch_iter("SELECT k FROM zarr"):
|
|
556
|
+
yield str(row[0])
|
|
544
557
|
|
|
545
558
|
@override
|
|
546
559
|
async def list_prefix(self, prefix: str) -> AsyncIterator[str]:
|
|
@@ -552,14 +565,15 @@ class SQLiteStore(Store):
|
|
|
552
565
|
else:
|
|
553
566
|
params = self._get_text_boundaries(prefix)
|
|
554
567
|
sql = "SELECT k FROM zarr WHERE k > ? AND k < ?"
|
|
555
|
-
async
|
|
556
|
-
|
|
568
|
+
async with self._transaction():
|
|
569
|
+
async for row in self._conn.fetch_iter(sql, params):
|
|
570
|
+
yield str(row[0])
|
|
557
571
|
|
|
558
572
|
@override
|
|
559
573
|
async def list_dir(self, prefix: str) -> AsyncIterator[str]:
|
|
560
574
|
# Even though prefix will be normalized in list_prefix(), this is
|
|
561
575
|
# required for the removeprefix(prefix) call used below.
|
|
562
|
-
if prefix != "" and
|
|
576
|
+
if prefix != "" and prefix[-1] != "/":
|
|
563
577
|
prefix += "/"
|
|
564
578
|
|
|
565
579
|
# _ensure_open is called in list_prefix()
|
|
@@ -579,23 +593,25 @@ class SQLiteStore(Store):
|
|
|
579
593
|
self._check_writable()
|
|
580
594
|
await self._ensure_open()
|
|
581
595
|
|
|
596
|
+
params: Sequence[str] = ()
|
|
597
|
+
if prefix == "":
|
|
598
|
+
sql = "DELETE FROM zarr"
|
|
599
|
+
else:
|
|
600
|
+
params = self._get_text_boundaries(prefix)
|
|
601
|
+
sql = "DELETE FROM zarr WHERE k > ? AND k < ?"
|
|
602
|
+
|
|
582
603
|
async with self._transaction():
|
|
583
604
|
assert self._conn is not None
|
|
584
605
|
# Check if key exists
|
|
585
606
|
row = await self._conn.fetchone(
|
|
586
607
|
"SELECT v FROM zarr WHERE k = ?", (prefix.rstrip("/"),)
|
|
587
608
|
)
|
|
609
|
+
|
|
588
610
|
if row is not None:
|
|
589
611
|
raise ValueError(
|
|
590
612
|
f"Cannot delete directory {prefix} as it is a key in the store."
|
|
591
613
|
)
|
|
592
614
|
|
|
593
|
-
params: Sequence[str] = ()
|
|
594
|
-
if prefix == "":
|
|
595
|
-
sql = "DELETE FROM zarr"
|
|
596
|
-
else:
|
|
597
|
-
params = self._get_text_boundaries(prefix)
|
|
598
|
-
sql = "DELETE FROM zarr WHERE k > ? AND k < ?"
|
|
599
615
|
await self._conn.execute(sql, params)
|
|
600
616
|
|
|
601
617
|
@override
|
|
@@ -603,9 +619,10 @@ class SQLiteStore(Store):
|
|
|
603
619
|
_validate_key(key)
|
|
604
620
|
await self._ensure_open()
|
|
605
621
|
assert self._conn is not None
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
622
|
+
async with self._transaction():
|
|
623
|
+
row = await self._conn.fetchone(
|
|
624
|
+
"SELECT LENGTH(v) FROM zarr WHERE k = ?", (key,)
|
|
625
|
+
)
|
|
609
626
|
if row is None:
|
|
610
627
|
raise FileNotFoundError(key)
|
|
611
628
|
return int(row[0])
|
|
@@ -620,7 +637,8 @@ class SQLiteStore(Store):
|
|
|
620
637
|
else:
|
|
621
638
|
params = self._get_text_boundaries(prefix)
|
|
622
639
|
sql = "SELECT SUM(LENGTH(v)) FROM zarr WHERE k > ? AND k < ?"
|
|
623
|
-
|
|
640
|
+
async with self._transaction():
|
|
641
|
+
size_row = await self._conn.fetchone(sql, params)
|
|
624
642
|
if size_row is None or size_row[0] is None:
|
|
625
643
|
return 0
|
|
626
644
|
return int(size_row[0])
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|