zarr-sqlite 1.0.0__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.0/LICENSE.txt +19 -0
- zarr_sqlite-1.0.0/PKG-INFO +61 -0
- zarr_sqlite-1.0.0/README.md +46 -0
- zarr_sqlite-1.0.0/pyproject.toml +41 -0
- zarr_sqlite-1.0.0/src/zarr_sqlite/__init__.py +5 -0
- zarr_sqlite-1.0.0/src/zarr_sqlite/_db_utils.py +27 -0
- zarr_sqlite-1.0.0/src/zarr_sqlite/_version.py +7 -0
- zarr_sqlite-1.0.0/src/zarr_sqlite/async_sqlite.py +311 -0
- zarr_sqlite-1.0.0/src/zarr_sqlite/py.typed +0 -0
- zarr_sqlite-1.0.0/src/zarr_sqlite/zarr_sqlite.py +615 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2025 Francis Thérien
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
4
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
5
|
+
the Software without restriction, including without limitation the rights to
|
|
6
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
7
|
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
8
|
+
subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
15
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
16
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
18
|
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
19
|
+
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zarr-sqlite
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Single-file Zarr v3 dataset store using SQLite
|
|
5
|
+
Author: Francis Thérien
|
|
6
|
+
Author-email: Francis Thérien <frtherien@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE.txt
|
|
9
|
+
Requires-Dist: zarr>=3.2.1
|
|
10
|
+
Requires-Dist: mypy>=1.17.0 ; extra == 'test'
|
|
11
|
+
Requires-Dist: pytest>=8.4.1 ; extra == 'test'
|
|
12
|
+
Requires-Python: >=3.12
|
|
13
|
+
Provides-Extra: test
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# zarr-sqlite-python
|
|
17
|
+
|
|
18
|
+
SQLite-based single-file store for [zarr](https://zarr.dev/) v3 datasets, in Python.
|
|
19
|
+
|
|
20
|
+
SQLiteStore provides a single-file storage backend for Zarr. Key advantages over alternative single-file formats (e.g., ZipStore):
|
|
21
|
+
|
|
22
|
+
- Support for key deletion, overwriting, and partial value writes.
|
|
23
|
+
- Full ACID guarantees provided by SQLite.
|
|
24
|
+
- High availability of SQLite implementations across programming languages
|
|
25
|
+
and environments.
|
|
26
|
+
|
|
27
|
+
Example usage:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import zarr
|
|
31
|
+
|
|
32
|
+
from zarr_sqlite import SQLiteStore
|
|
33
|
+
|
|
34
|
+
with SQLiteStore("my_zarr_file.zarrdb") as store:
|
|
35
|
+
root = zarr.create_group(store=store)
|
|
36
|
+
foo = root.create_group('foo')
|
|
37
|
+
bar = foo.create_group('bar')
|
|
38
|
+
z1 = bar.create_array(name='baz', shape=(10000, 10000), chunks=(1000, 1000), dtype='int32')
|
|
39
|
+
z1[:] = 42
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`SQLiteStore` otherwise behaves identically to other stores used with zarr, see
|
|
43
|
+
the [zarr user guide](https://zarr.readthedocs.io/en/stable/user-guide/storage.html)
|
|
44
|
+
for more information.
|
|
45
|
+
|
|
46
|
+
## Specification
|
|
47
|
+
|
|
48
|
+
The store format is described in the document [SPEC.md](/SPEC.md). This document
|
|
49
|
+
should allow the implementation of SQLiteStore for other programming languages
|
|
50
|
+
or Zarr libraries.
|
|
51
|
+
|
|
52
|
+
## Status
|
|
53
|
+
|
|
54
|
+
The version of this library was incremented to v1.0 to reflect the fact that it
|
|
55
|
+
complies with v1 of the SQLiteStore Specification. However, this is a relatively
|
|
56
|
+
new library that has not seen a lot of real-world use yet, therefore users should
|
|
57
|
+
expect the occasional bug, and possibly breaking API changes in future versions,
|
|
58
|
+
if absolutely necessary.
|
|
59
|
+
|
|
60
|
+
The database format however, defined by the Specification, can be expected to be
|
|
61
|
+
stable.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# zarr-sqlite-python
|
|
2
|
+
|
|
3
|
+
SQLite-based single-file store for [zarr](https://zarr.dev/) v3 datasets, in Python.
|
|
4
|
+
|
|
5
|
+
SQLiteStore provides a single-file storage backend for Zarr. Key advantages over alternative single-file formats (e.g., ZipStore):
|
|
6
|
+
|
|
7
|
+
- Support for key deletion, overwriting, and partial value writes.
|
|
8
|
+
- Full ACID guarantees provided by SQLite.
|
|
9
|
+
- High availability of SQLite implementations across programming languages
|
|
10
|
+
and environments.
|
|
11
|
+
|
|
12
|
+
Example usage:
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
import zarr
|
|
16
|
+
|
|
17
|
+
from zarr_sqlite import SQLiteStore
|
|
18
|
+
|
|
19
|
+
with SQLiteStore("my_zarr_file.zarrdb") as store:
|
|
20
|
+
root = zarr.create_group(store=store)
|
|
21
|
+
foo = root.create_group('foo')
|
|
22
|
+
bar = foo.create_group('bar')
|
|
23
|
+
z1 = bar.create_array(name='baz', shape=(10000, 10000), chunks=(1000, 1000), dtype='int32')
|
|
24
|
+
z1[:] = 42
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`SQLiteStore` otherwise behaves identically to other stores used with zarr, see
|
|
28
|
+
the [zarr user guide](https://zarr.readthedocs.io/en/stable/user-guide/storage.html)
|
|
29
|
+
for more information.
|
|
30
|
+
|
|
31
|
+
## Specification
|
|
32
|
+
|
|
33
|
+
The store format is described in the document [SPEC.md](/SPEC.md). This document
|
|
34
|
+
should allow the implementation of SQLiteStore for other programming languages
|
|
35
|
+
or Zarr libraries.
|
|
36
|
+
|
|
37
|
+
## Status
|
|
38
|
+
|
|
39
|
+
The version of this library was incremented to v1.0 to reflect the fact that it
|
|
40
|
+
complies with v1 of the SQLiteStore Specification. However, this is a relatively
|
|
41
|
+
new library that has not seen a lot of real-world use yet, therefore users should
|
|
42
|
+
expect the occasional bug, and possibly breaking API changes in future versions,
|
|
43
|
+
if absolutely necessary.
|
|
44
|
+
|
|
45
|
+
The database format however, defined by the Specification, can be expected to be
|
|
46
|
+
stable.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "zarr-sqlite"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Single-file Zarr v3 dataset store using SQLite"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Francis Thérien", email = "frtherien@gmail.com" }
|
|
8
|
+
]
|
|
9
|
+
license = "MIT"
|
|
10
|
+
license-files = ["LICENSE.txt",]
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"zarr>=3.2.1",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
test = [
|
|
18
|
+
"mypy>=1.17.0",
|
|
19
|
+
"pytest>=8.4.1",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["uv_build>=0.8.3,<0.9.0"]
|
|
24
|
+
build-backend = "uv_build"
|
|
25
|
+
|
|
26
|
+
[dependency-groups]
|
|
27
|
+
dev = [
|
|
28
|
+
"mypy==2.3.0",
|
|
29
|
+
"numpy>=2.3.2",
|
|
30
|
+
"pytest>=8.4.1",
|
|
31
|
+
"pytest-asyncio>=1.1.0",
|
|
32
|
+
"pytest-benchmark>=5.2.3",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[tool.pytest.ini_options]
|
|
36
|
+
asyncio_mode = "auto"
|
|
37
|
+
markers = [
|
|
38
|
+
"asyncio: mark a test as an asyncio coroutine",
|
|
39
|
+
]
|
|
40
|
+
python_files = ["test_*.py", "benchmark_*.py"]
|
|
41
|
+
testpaths = ["test"]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
def is_in_memory_database(database: str) -> bool:
|
|
2
|
+
"""Check whether a database specifier refers to an in-memory database.
|
|
3
|
+
|
|
4
|
+
Args:
|
|
5
|
+
database: The SQLite database specifier (path, URI, or ":memory:").
|
|
6
|
+
|
|
7
|
+
Returns:
|
|
8
|
+
True if the database is in-memory, False otherwise.
|
|
9
|
+
"""
|
|
10
|
+
return database == ":memory:" or (
|
|
11
|
+
database.startswith("file:/") and "mode=memory" in database
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def is_database_uri(database: str) -> bool:
|
|
16
|
+
"""Check whether a database specifier is a SQLite URI.
|
|
17
|
+
|
|
18
|
+
SQLite URIs use the ``file:`` scheme, e.g. ``file:/path/to/db`` or
|
|
19
|
+
``file::memory:?mode=memory``.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
database: The SQLite database specifier.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
True if the database is a URI, False otherwise.
|
|
26
|
+
"""
|
|
27
|
+
return database.startswith("file:/")
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
# This file contains code which is derived from aiosqlite v0.22.1
|
|
2
|
+
# aiosqlite is Copyright (c) 2022 Amethyst Reese
|
|
3
|
+
# Modifications are Copyright (c) 2026 Francis Thérien
|
|
4
|
+
#
|
|
5
|
+
# The work is re-distributed here under the terms of the MIT license, reproduced
|
|
6
|
+
# below.
|
|
7
|
+
|
|
8
|
+
# MIT License
|
|
9
|
+
|
|
10
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
# in the Software without restriction, including without limitation the rights
|
|
13
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
# furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
# copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
# SOFTWARE.
|
|
27
|
+
|
|
28
|
+
"""
|
|
29
|
+
Async SQLite connection proxy.
|
|
30
|
+
|
|
31
|
+
Core implementation derived from aiosqlite, simplified for use with
|
|
32
|
+
zarr-sqlite. The background-thread model is preserved: SQL is executed on a
|
|
33
|
+
dedicated thread and results are returned as raw ``sqlite3`` objects.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
import asyncio
|
|
37
|
+
import logging
|
|
38
|
+
import sqlite3
|
|
39
|
+
from collections.abc import AsyncIterator, Generator, Iterable
|
|
40
|
+
from functools import partial
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from queue import SimpleQueue
|
|
43
|
+
from threading import Thread
|
|
44
|
+
from typing import Any, Callable, Optional
|
|
45
|
+
from warnings import warn
|
|
46
|
+
|
|
47
|
+
__all__ = ["connect", "Connection"]
|
|
48
|
+
|
|
49
|
+
LOG = logging.getLogger("zarr_sqlite")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _Stop:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_STOP_RUNNING_SENTINEL = _Stop()
|
|
57
|
+
_TxQueue = SimpleQueue[tuple[Optional[asyncio.Future], Callable[[], Any]]]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def set_result(fut: asyncio.Future, result: Any) -> None:
|
|
61
|
+
"""Set the result of a future if it hasn't been set already."""
|
|
62
|
+
if not fut.done():
|
|
63
|
+
fut.set_result(result)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def set_exception(fut: asyncio.Future, e: BaseException) -> None:
|
|
67
|
+
"""Set the exception of a future if it hasn't been set already."""
|
|
68
|
+
if not fut.done():
|
|
69
|
+
fut.set_exception(e)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _connection_worker_thread(tx: _TxQueue):
|
|
73
|
+
"""
|
|
74
|
+
Execute function calls on a separate thread.
|
|
75
|
+
|
|
76
|
+
:meta private:
|
|
77
|
+
"""
|
|
78
|
+
while True:
|
|
79
|
+
# Continues running until all queue items are processed,
|
|
80
|
+
# even after connection is closed (so we can finalize all
|
|
81
|
+
# futures)
|
|
82
|
+
|
|
83
|
+
future, function = tx.get()
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
LOG.debug("executing %s", function)
|
|
87
|
+
result = function()
|
|
88
|
+
|
|
89
|
+
if future:
|
|
90
|
+
future.get_loop().call_soon_threadsafe(set_result, future, result)
|
|
91
|
+
LOG.debug("operation %s completed", function)
|
|
92
|
+
|
|
93
|
+
if result is _STOP_RUNNING_SENTINEL:
|
|
94
|
+
break
|
|
95
|
+
|
|
96
|
+
except BaseException as e: # noqa B036
|
|
97
|
+
LOG.debug("returning exception %s", e)
|
|
98
|
+
if future:
|
|
99
|
+
future.get_loop().call_soon_threadsafe(set_exception, future, e)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Connection:
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
connector: Callable[[], sqlite3.Connection],
|
|
106
|
+
) -> None:
|
|
107
|
+
self._running = True
|
|
108
|
+
self._connection: Optional[sqlite3.Connection] = None
|
|
109
|
+
self._connector = connector
|
|
110
|
+
self._tx: _TxQueue = SimpleQueue()
|
|
111
|
+
self._thread = Thread(target=_connection_worker_thread, args=(self._tx,))
|
|
112
|
+
|
|
113
|
+
def __del__(self):
|
|
114
|
+
if self._connection is None:
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
warn(
|
|
118
|
+
(
|
|
119
|
+
f"{self!r} was deleted before being closed. "
|
|
120
|
+
"Please use 'async with' or '.close()' to close the connection properly."
|
|
121
|
+
),
|
|
122
|
+
ResourceWarning,
|
|
123
|
+
stacklevel=1,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
# Don't try to be creative here, the event loop may have already been
|
|
127
|
+
# closed. Simply stop the worker thread, and let the underlying
|
|
128
|
+
# sqlite3 connection be finalized by its own __del__.
|
|
129
|
+
self.stop()
|
|
130
|
+
|
|
131
|
+
def stop(self, join=False, join_timeout: float | None = None) -> Optional[asyncio.Future]:
|
|
132
|
+
"""Stop the background thread. Prefer `async with` or `await close()`"""
|
|
133
|
+
self._running = False
|
|
134
|
+
|
|
135
|
+
def close_and_stop():
|
|
136
|
+
if self._connection is not None:
|
|
137
|
+
self._connection.close()
|
|
138
|
+
self._connection = None
|
|
139
|
+
return _STOP_RUNNING_SENTINEL
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
future = asyncio.get_running_loop().create_future()
|
|
143
|
+
except Exception:
|
|
144
|
+
future = None
|
|
145
|
+
|
|
146
|
+
self._tx.put_nowait((future, close_and_stop))
|
|
147
|
+
if join:
|
|
148
|
+
self._thread.join(timeout=join_timeout)
|
|
149
|
+
return future
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def _conn(self) -> sqlite3.Connection:
|
|
153
|
+
if self._connection is None:
|
|
154
|
+
raise ValueError("no active connection")
|
|
155
|
+
|
|
156
|
+
return self._connection
|
|
157
|
+
|
|
158
|
+
async def _execute(self, fn, *args, **kwargs):
|
|
159
|
+
"""Queue a function with the given arguments for execution."""
|
|
160
|
+
if not self._running or not self._connection:
|
|
161
|
+
raise ValueError("Connection closed")
|
|
162
|
+
|
|
163
|
+
function = partial(fn, *args, **kwargs)
|
|
164
|
+
future = asyncio.get_event_loop().create_future()
|
|
165
|
+
|
|
166
|
+
self._tx.put_nowait((future, function))
|
|
167
|
+
|
|
168
|
+
return await future
|
|
169
|
+
|
|
170
|
+
async def _connect(self) -> "Connection":
|
|
171
|
+
"""Connect to the actual sqlite database."""
|
|
172
|
+
if self._connection is None:
|
|
173
|
+
try:
|
|
174
|
+
future = asyncio.get_event_loop().create_future()
|
|
175
|
+
self._tx.put_nowait((future, self._connector))
|
|
176
|
+
self._connection = await future
|
|
177
|
+
except BaseException:
|
|
178
|
+
self.stop()
|
|
179
|
+
self._connection = None
|
|
180
|
+
raise
|
|
181
|
+
|
|
182
|
+
return self
|
|
183
|
+
|
|
184
|
+
def __await__(self) -> Generator[Any, None, "Connection"]:
|
|
185
|
+
self._thread.start()
|
|
186
|
+
return self._connect().__await__()
|
|
187
|
+
|
|
188
|
+
async def commit(self) -> None:
|
|
189
|
+
"""Commit the current transaction."""
|
|
190
|
+
await self._execute(self._conn.commit)
|
|
191
|
+
|
|
192
|
+
async def rollback(self) -> None:
|
|
193
|
+
"""Roll back the current transaction."""
|
|
194
|
+
await self._execute(self._conn.rollback)
|
|
195
|
+
|
|
196
|
+
async def close(self) -> None:
|
|
197
|
+
"""Complete queued queries/cursors and close the connection."""
|
|
198
|
+
|
|
199
|
+
if self._connection is None:
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
try:
|
|
203
|
+
await self._execute(self._conn.close)
|
|
204
|
+
except Exception:
|
|
205
|
+
LOG.info("exception occurred while closing connection")
|
|
206
|
+
raise
|
|
207
|
+
finally:
|
|
208
|
+
self._connection = None
|
|
209
|
+
future = self.stop(join=False)
|
|
210
|
+
if future:
|
|
211
|
+
await future
|
|
212
|
+
|
|
213
|
+
async def execute(self, sql: str, parameters: Iterable[Any] | None = None) -> None:
|
|
214
|
+
"""Execute a SQL statement."""
|
|
215
|
+
if parameters is None:
|
|
216
|
+
parameters = []
|
|
217
|
+
await self._execute(self._conn.execute, sql, parameters)
|
|
218
|
+
|
|
219
|
+
async def set_autocommit(self, value: bool) -> None:
|
|
220
|
+
"""Set the autocommit mode of the underlying sqlite3 connection.
|
|
221
|
+
|
|
222
|
+
When ``value`` is ``True``, each SQL statement is committed
|
|
223
|
+
immediately (autocommit mode). This is required for PRAGMA
|
|
224
|
+
statements that cannot be executed within a transaction, such
|
|
225
|
+
as ``PRAGMA journal_mode``.
|
|
226
|
+
"""
|
|
227
|
+
await self._execute(setattr, self._conn, "autocommit", value)
|
|
228
|
+
|
|
229
|
+
async def executemany(self, sql: str, parameters: Iterable[Any]) -> None:
|
|
230
|
+
"""Execute a SQL statement many times."""
|
|
231
|
+
await self._execute(self._conn.executemany, sql, parameters)
|
|
232
|
+
|
|
233
|
+
async def fetchall(
|
|
234
|
+
self, sql: str, parameters: Iterable[Any] | None = None
|
|
235
|
+
) -> list[tuple[Any, ...]]:
|
|
236
|
+
"""Execute a SQL query and return all matching rows.
|
|
237
|
+
|
|
238
|
+
Both the cursor creation and ``fetchall`` happen on the
|
|
239
|
+
worker thread in a single queued operation.
|
|
240
|
+
"""
|
|
241
|
+
if parameters is None:
|
|
242
|
+
parameters = []
|
|
243
|
+
|
|
244
|
+
def _fetchall():
|
|
245
|
+
cursor = self._conn.execute(sql, parameters)
|
|
246
|
+
return cursor.fetchall()
|
|
247
|
+
|
|
248
|
+
return await self._execute(_fetchall)
|
|
249
|
+
|
|
250
|
+
async def fetchone(
|
|
251
|
+
self, sql: str, parameters: Iterable[Any] | None = None
|
|
252
|
+
) -> tuple[Any, ...] | None:
|
|
253
|
+
"""Execute a SQL query and return the first matching row.
|
|
254
|
+
|
|
255
|
+
Returns ``None`` if no rows match. Both the cursor creation
|
|
256
|
+
and ``fetchone`` happen on the worker thread in a single
|
|
257
|
+
queued operation.
|
|
258
|
+
"""
|
|
259
|
+
if parameters is None:
|
|
260
|
+
parameters = []
|
|
261
|
+
|
|
262
|
+
def _fetchone():
|
|
263
|
+
cursor = self._conn.execute(sql, parameters)
|
|
264
|
+
return cursor.fetchone()
|
|
265
|
+
|
|
266
|
+
return await self._execute(_fetchone)
|
|
267
|
+
|
|
268
|
+
async def fetch_iter(
|
|
269
|
+
self, sql: str, parameters: Iterable[Any] | None = None
|
|
270
|
+
) -> AsyncIterator[tuple[Any, ...]]:
|
|
271
|
+
"""Asynchronously iterate over rows from a SQL query.
|
|
272
|
+
|
|
273
|
+
The cursor is created and all fetches happen on the worker
|
|
274
|
+
thread. Rows are fetched in chunks of ``_fetch_chunk_size``
|
|
275
|
+
for efficiency, with individual rows yielded to the caller.
|
|
276
|
+
The cursor is closed when the iterator is exhausted or when
|
|
277
|
+
the caller breaks out of the loop.
|
|
278
|
+
"""
|
|
279
|
+
if parameters is None:
|
|
280
|
+
parameters = []
|
|
281
|
+
|
|
282
|
+
_fetch_chunk_size: int = 20
|
|
283
|
+
cursor = await self._execute(self._conn.execute, sql, parameters)
|
|
284
|
+
try:
|
|
285
|
+
while True:
|
|
286
|
+
chunk = await self._execute(cursor.fetchmany, _fetch_chunk_size)
|
|
287
|
+
if not chunk:
|
|
288
|
+
break
|
|
289
|
+
for row in chunk:
|
|
290
|
+
yield row
|
|
291
|
+
finally:
|
|
292
|
+
await self._execute(cursor.close)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def connect(
|
|
296
|
+
database: Path | str,
|
|
297
|
+
**kwargs: Any,
|
|
298
|
+
) -> Connection:
|
|
299
|
+
"""Create and return a connection proxy to the sqlite database."""
|
|
300
|
+
|
|
301
|
+
def connector() -> sqlite3.Connection:
|
|
302
|
+
if isinstance(database, str):
|
|
303
|
+
loc = database
|
|
304
|
+
elif isinstance(database, bytes):
|
|
305
|
+
loc = database.decode("utf-8")
|
|
306
|
+
else:
|
|
307
|
+
loc = str(database)
|
|
308
|
+
|
|
309
|
+
return sqlite3.connect(loc, **kwargs)
|
|
310
|
+
|
|
311
|
+
return Connection(connector)
|
|
File without changes
|
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
from typing import override, Self, Sequence
|
|
2
|
+
from collections.abc import Iterable, AsyncIterator, AsyncGenerator
|
|
3
|
+
from contextlib import asynccontextmanager
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
import sqlite3
|
|
6
|
+
import warnings
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import asyncio
|
|
10
|
+
|
|
11
|
+
from .async_sqlite import Connection, connect
|
|
12
|
+
|
|
13
|
+
from zarr.core.buffer import BufferPrototype, Buffer
|
|
14
|
+
|
|
15
|
+
from zarr.abc.store import (
|
|
16
|
+
ByteRequest,
|
|
17
|
+
OffsetByteRequest,
|
|
18
|
+
RangeByteRequest,
|
|
19
|
+
Store,
|
|
20
|
+
SuffixByteRequest,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from ._version import __version__
|
|
24
|
+
from ._db_utils import is_database_uri, is_in_memory_database
|
|
25
|
+
|
|
26
|
+
if sqlite3.sqlite_version_info < (3, 17, 7):
|
|
27
|
+
raise ValueError(
|
|
28
|
+
f"Unsupported SQLite version {sqlite3.sqlite_version}.The minimum supported version of sqlite is 3.17.7."
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
_SQLITESTORE_SPEC_VERSION = "1.0" # spec version we adhere to
|
|
32
|
+
_SQLITESTORE_APPLICATION_ID = 0x10B50760
|
|
33
|
+
_CREATED_BY = f"zarr-sqlite-python v{__version__}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _validate_key(key: str):
|
|
37
|
+
"""Validates a key according to SQLiteStore specification
|
|
38
|
+
|
|
39
|
+
From the Zarr core spec:
|
|
40
|
+
- a key is a Unicode string, where the final character is not a `/` character.
|
|
41
|
+
|
|
42
|
+
Additional checks (not in the core spec):
|
|
43
|
+
- a key which starts with '/' is invalid, and
|
|
44
|
+
- a key that contains '//' is invalid.
|
|
45
|
+
|
|
46
|
+
The empty string is a valid key: it addresses a store's root resource as a single blob.
|
|
47
|
+
"""
|
|
48
|
+
if key.startswith("/") or key.endswith("/") or "//" in key:
|
|
49
|
+
raise ValueError(f"Invalid key '{key}'")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class SQLiteStore(Store):
|
|
53
|
+
"""
|
|
54
|
+
Store for the local file system.
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
database : str or Path
|
|
59
|
+
Directory to use as root of store.
|
|
60
|
+
read_only : bool
|
|
61
|
+
Whether the store is read-only
|
|
62
|
+
|
|
63
|
+
Attributes
|
|
64
|
+
----------
|
|
65
|
+
supports_writes
|
|
66
|
+
supports_deletes
|
|
67
|
+
supports_partial_writes
|
|
68
|
+
supports_listing
|
|
69
|
+
root
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
_database: str
|
|
73
|
+
_is_open: bool
|
|
74
|
+
_open_lock: asyncio.Lock
|
|
75
|
+
_conn: Connection | None
|
|
76
|
+
_transaction_lock: asyncio.Lock
|
|
77
|
+
_journal_mode: str | None
|
|
78
|
+
_page_size: int
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
@override
|
|
82
|
+
def supports_writes(self) -> bool:
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
@override
|
|
87
|
+
def supports_deletes(self) -> bool:
|
|
88
|
+
return True
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
@override
|
|
92
|
+
def supports_listing(self) -> bool:
|
|
93
|
+
return True
|
|
94
|
+
|
|
95
|
+
def __init__(
|
|
96
|
+
self,
|
|
97
|
+
database: str | Path,
|
|
98
|
+
*,
|
|
99
|
+
read_only: bool = False,
|
|
100
|
+
journal_mode: str | None = "WAL",
|
|
101
|
+
page_size: int = 4096,
|
|
102
|
+
) -> None:
|
|
103
|
+
super().__init__(read_only=read_only)
|
|
104
|
+
self._database = str(database)
|
|
105
|
+
self._journal_mode = journal_mode
|
|
106
|
+
self._page_size = page_size
|
|
107
|
+
self._conn = None
|
|
108
|
+
|
|
109
|
+
self._open_lock = asyncio.Lock()
|
|
110
|
+
self._transaction_lock = asyncio.Lock()
|
|
111
|
+
|
|
112
|
+
if self.is_in_memory() and read_only:
|
|
113
|
+
raise ValueError("In-memory databases cannot be opened read-only")
|
|
114
|
+
|
|
115
|
+
# To open a database in read-only mode in python, we need to use
|
|
116
|
+
# a SQLite URI.
|
|
117
|
+
if read_only:
|
|
118
|
+
self._database = self._database_as_uri(self.database, read_only)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def database(self):
|
|
122
|
+
return self._database
|
|
123
|
+
|
|
124
|
+
def is_in_memory(self) -> bool:
|
|
125
|
+
return is_in_memory_database(self._database)
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def _database_as_uri(database: str, read_only: bool) -> str:
|
|
129
|
+
"""Create a sqlite-compatible database URI.
|
|
130
|
+
|
|
131
|
+
Parameters
|
|
132
|
+
----------
|
|
133
|
+
database : str
|
|
134
|
+
File path or sqlite-compatible URI (must have `file:` scheme). If
|
|
135
|
+
`database` is a URI, the parameters will be kept unmodified, except
|
|
136
|
+
"mode", which will always be overwritten or added base on the value
|
|
137
|
+
of `read_only`.
|
|
138
|
+
read_only : bool
|
|
139
|
+
Whether the store is read-only
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
if not is_database_uri(database):
|
|
143
|
+
database = Path(database).absolute().as_uri()
|
|
144
|
+
uri_parts = urllib.parse.urlsplit(database)
|
|
145
|
+
|
|
146
|
+
query = urllib.parse.parse_qs(uri_parts.query)
|
|
147
|
+
mode = "ro" if read_only else "rwc"
|
|
148
|
+
query["mode"] = [mode]
|
|
149
|
+
|
|
150
|
+
return urllib.parse.urlunsplit(
|
|
151
|
+
urllib.parse.SplitResult(
|
|
152
|
+
scheme=uri_parts.scheme,
|
|
153
|
+
netloc="",
|
|
154
|
+
path=uri_parts.path,
|
|
155
|
+
query=urllib.parse.urlencode(query, doseq=True),
|
|
156
|
+
fragment="",
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
@override
|
|
161
|
+
async def _ensure_open(self):
|
|
162
|
+
if self._is_open:
|
|
163
|
+
return
|
|
164
|
+
|
|
165
|
+
async with self._open_lock:
|
|
166
|
+
if self._is_open:
|
|
167
|
+
return
|
|
168
|
+
await self._open()
|
|
169
|
+
|
|
170
|
+
@asynccontextmanager
|
|
171
|
+
async def _transaction(self) -> AsyncGenerator[None, None]:
|
|
172
|
+
"""Context manager for write transactions.
|
|
173
|
+
|
|
174
|
+
Acquires the transaction lock to serialize write operations on the
|
|
175
|
+
single SQLite connection. Commits on success, rolls back on error.
|
|
176
|
+
"""
|
|
177
|
+
assert self._conn is not None
|
|
178
|
+
async with self._transaction_lock:
|
|
179
|
+
try:
|
|
180
|
+
yield
|
|
181
|
+
await self._conn.commit()
|
|
182
|
+
except BaseException:
|
|
183
|
+
await self._conn.rollback()
|
|
184
|
+
raise
|
|
185
|
+
|
|
186
|
+
@override
|
|
187
|
+
async def _open(self) -> None:
|
|
188
|
+
if self._is_open:
|
|
189
|
+
raise ValueError("store is already open")
|
|
190
|
+
|
|
191
|
+
self._conn = await connect(
|
|
192
|
+
self._database,
|
|
193
|
+
uri=is_database_uri(self._database),
|
|
194
|
+
autocommit=False,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
try:
|
|
198
|
+
if not self.read_only and self._journal_mode is not None:
|
|
199
|
+
await self._set_journal_mode()
|
|
200
|
+
|
|
201
|
+
# Create schema only on empty file to avoid clobbering an existing file.
|
|
202
|
+
if not self._read_only and await self._db_is_empty():
|
|
203
|
+
async with self._transaction():
|
|
204
|
+
await self._create_schema()
|
|
205
|
+
await self._update_timestamp()
|
|
206
|
+
|
|
207
|
+
await self._validate_schema()
|
|
208
|
+
except Exception:
|
|
209
|
+
self._conn.stop(join=True)
|
|
210
|
+
self._conn = None
|
|
211
|
+
raise
|
|
212
|
+
|
|
213
|
+
self._is_open = True
|
|
214
|
+
|
|
215
|
+
@override
|
|
216
|
+
def with_read_only(self, read_only: bool = False) -> Self:
|
|
217
|
+
if self.is_in_memory():
|
|
218
|
+
raise ValueError("Cannot create a read-only view of an in-memory database.")
|
|
219
|
+
return type(self)(self.database, read_only=read_only)
|
|
220
|
+
|
|
221
|
+
async def _create_schema(self) -> None:
|
|
222
|
+
assert self._conn is not None
|
|
223
|
+
await self._conn.execute("PRAGMA page_size=" + str(int(self._page_size)))
|
|
224
|
+
await self._conn.execute(
|
|
225
|
+
"CREATE TABLE IF NOT EXISTS zarr_sqlitestore_metadata("
|
|
226
|
+
"k TEXT PRIMARY KEY NOT NULL, v TEXT NOT NULL)"
|
|
227
|
+
)
|
|
228
|
+
await self._conn.execute(
|
|
229
|
+
"CREATE TABLE IF NOT EXISTS zarr("
|
|
230
|
+
"k TEXT PRIMARY KEY NOT NULL, v BLOB NOT NULL)"
|
|
231
|
+
)
|
|
232
|
+
await self._conn.execute(
|
|
233
|
+
"PRAGMA application_id = " + str(int(_SQLITESTORE_APPLICATION_ID))
|
|
234
|
+
)
|
|
235
|
+
await self._conn.executemany(
|
|
236
|
+
"INSERT OR IGNORE INTO zarr_sqlitestore_metadata(k, v) VALUES (?, ?)",
|
|
237
|
+
[
|
|
238
|
+
("sqlitestore_version", _SQLITESTORE_SPEC_VERSION),
|
|
239
|
+
("compatible_flags", ""),
|
|
240
|
+
("incompatible_flags", ""),
|
|
241
|
+
("created_by", _CREATED_BY),
|
|
242
|
+
],
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
async def _set_journal_mode(self):
|
|
246
|
+
assert self._conn is not None
|
|
247
|
+
if self._journal_mode is None:
|
|
248
|
+
return
|
|
249
|
+
elif self._journal_mode.upper() not in {"DELETE", "WAL"}:
|
|
250
|
+
raise ValueError(f"Invalid journal_mode: {self._journal_mode}")
|
|
251
|
+
|
|
252
|
+
# PRAGMA journal_mode cannot be changed within a transaction.
|
|
253
|
+
# Temporarily set autocommit=True to execute it outside a
|
|
254
|
+
# transaction, then restore the previous value.
|
|
255
|
+
await self._conn.set_autocommit(True)
|
|
256
|
+
try:
|
|
257
|
+
await self._conn.execute("PRAGMA journal_mode=" + self._journal_mode)
|
|
258
|
+
finally:
|
|
259
|
+
await self._conn.set_autocommit(False)
|
|
260
|
+
|
|
261
|
+
async def _update_timestamp(self) -> None:
|
|
262
|
+
assert self._conn is not None
|
|
263
|
+
|
|
264
|
+
now = datetime.now(timezone.utc).isoformat().upper()
|
|
265
|
+
if now.endswith("+00:00"):
|
|
266
|
+
now = now.removesuffix("+00:00") + "Z"
|
|
267
|
+
assert now.endswith("Z")
|
|
268
|
+
|
|
269
|
+
await self._conn.execute(
|
|
270
|
+
"INSERT INTO zarr_sqlitestore_metadata(k, v) VALUES (?, ?) "
|
|
271
|
+
"ON CONFLICT(k) DO UPDATE SET v = excluded.v",
|
|
272
|
+
("modified_at", now),
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
async def _db_is_empty(self) -> bool:
|
|
276
|
+
assert self._conn is not None
|
|
277
|
+
row = await self._conn.fetchone(
|
|
278
|
+
"""
|
|
279
|
+
SELECT EXISTS (
|
|
280
|
+
SELECT 1 FROM sqlite_schema
|
|
281
|
+
WHERE type IN ('table', 'view', 'index', 'trigger')
|
|
282
|
+
AND name NOT LIKE 'sqlite_%'
|
|
283
|
+
)
|
|
284
|
+
"""
|
|
285
|
+
)
|
|
286
|
+
assert row is not None
|
|
287
|
+
return row[0] == 0
|
|
288
|
+
|
|
289
|
+
async def _validate_schema(self) -> None:
|
|
290
|
+
metadata_keys = (
|
|
291
|
+
"sqlitestore_version",
|
|
292
|
+
"compatible_flags",
|
|
293
|
+
"incompatible_flags",
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
assert self._conn is not None
|
|
297
|
+
for required_table in ("zarr", "zarr_sqlitestore_metadata"):
|
|
298
|
+
rows = await self._conn.fetchall(
|
|
299
|
+
"PRAGMA table_info(" + required_table + ")"
|
|
300
|
+
)
|
|
301
|
+
if not rows:
|
|
302
|
+
raise ValueError(
|
|
303
|
+
f"Invalid SQLiteStore file: missing required table '{required_table}'"
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
app_id_row = await self._conn.fetchone("PRAGMA application_id")
|
|
307
|
+
assert app_id_row is not None
|
|
308
|
+
app_id = app_id_row[0]
|
|
309
|
+
|
|
310
|
+
if app_id != _SQLITESTORE_APPLICATION_ID:
|
|
311
|
+
if self.read_only:
|
|
312
|
+
warnings.warn(
|
|
313
|
+
f"Unexpected application_id for SQLiteStore: {app_id:#x} "
|
|
314
|
+
f"(expected {_SQLITESTORE_APPLICATION_ID:#x}). "
|
|
315
|
+
"This may not be a valid Zarr SQLiteStore file. Attempting to open it anyway.",
|
|
316
|
+
stacklevel=2,
|
|
317
|
+
)
|
|
318
|
+
else:
|
|
319
|
+
# For writable files, we don't want to make modifications to a non-sqlitestore
|
|
320
|
+
# file that may have been opened by error, so refuse to open it.
|
|
321
|
+
raise ValueError(
|
|
322
|
+
f"Invalid SQLiteStore file: "
|
|
323
|
+
f"Unexpected application_id for SQLiteStore {app_id:#x} "
|
|
324
|
+
f"(expected {_SQLITESTORE_APPLICATION_ID:#x})."
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
metadata_rows = await self._conn.fetchall(
|
|
328
|
+
"SELECT k, v FROM zarr_sqlitestore_metadata WHERE k IN (?, ?, ?)",
|
|
329
|
+
metadata_keys,
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
metadata: dict[str, str] = (
|
|
333
|
+
{k: v for k, v in metadata_rows} if metadata_rows else {}
|
|
334
|
+
)
|
|
335
|
+
for k in metadata_keys:
|
|
336
|
+
if k not in metadata:
|
|
337
|
+
raise ValueError(
|
|
338
|
+
f"Invalid SQLiteStore file: missing required metadata entry '{k}'"
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
version_str = metadata["sqlitestore_version"]
|
|
342
|
+
try:
|
|
343
|
+
version = [int(n) for n in version_str.strip().split(".")]
|
|
344
|
+
except ValueError:
|
|
345
|
+
raise ValueError(f"Invalid sqlitestore_version string: '{version_str}'")
|
|
346
|
+
if len(version) != 2:
|
|
347
|
+
raise ValueError(f"Invalid sqlitestore_version string: '{version_str}'")
|
|
348
|
+
if version[0] > 1:
|
|
349
|
+
raise ValueError(f"Unsupported sqlitestore_version: {version_str}")
|
|
350
|
+
|
|
351
|
+
incompat_flags = [
|
|
352
|
+
f.strip()
|
|
353
|
+
for f in metadata["incompatible_flags"].split(",")
|
|
354
|
+
if len(f.strip()) > 0
|
|
355
|
+
]
|
|
356
|
+
if len(incompat_flags) > 0:
|
|
357
|
+
raise ValueError(f"SQLiteStore flag '{incompat_flags[0]}' is not supported")
|
|
358
|
+
|
|
359
|
+
@override
|
|
360
|
+
def close(self) -> None:
|
|
361
|
+
"""Immediately close the store and the SQLite connection."""
|
|
362
|
+
if self._conn is not None:
|
|
363
|
+
self._conn.stop(join=True)
|
|
364
|
+
self._conn = None
|
|
365
|
+
self._is_open = False
|
|
366
|
+
|
|
367
|
+
@staticmethod
|
|
368
|
+
def _get_text_boundaries(prefix: str) -> tuple[str, str]:
|
|
369
|
+
"""Compute a pair of (lower bound, upper bound) strings.
|
|
370
|
+
|
|
371
|
+
These strings are used to achieve efficient prefix search with an SQL
|
|
372
|
+
clause like "(...) WHERE k < :lower_bound AND k > :upper_bound".
|
|
373
|
+
|
|
374
|
+
The upper bound string is obtained by replacing the trailing slash (/)
|
|
375
|
+
character in a prefix with a zero (0) character, which is the next
|
|
376
|
+
character is lexicographical order (in ASCII and Unicode).
|
|
377
|
+
|
|
378
|
+
We do not use GLOB or LIKE in prefix searches because they have many
|
|
379
|
+
issues in SQLite. For example, LIKE does not support case-sensitive
|
|
380
|
+
matching (required for zarr keys), and GLOB does not support escaping
|
|
381
|
+
the special glob characters (*, [, ] and ?).
|
|
382
|
+
|
|
383
|
+
IMPORTANT: this does not work for the empty prefix "", which is considered
|
|
384
|
+
valid.
|
|
385
|
+
"""
|
|
386
|
+
assert prefix != ""
|
|
387
|
+
|
|
388
|
+
is_valid = not (prefix.startswith("/") or "//" in prefix)
|
|
389
|
+
if not is_valid:
|
|
390
|
+
raise ValueError(f"Invalid prefix '{prefix}'")
|
|
391
|
+
if prefix != "" and not prefix.endswith("/"):
|
|
392
|
+
prefix += "/"
|
|
393
|
+
|
|
394
|
+
upper = prefix[:-1] + "0"
|
|
395
|
+
return (prefix, upper)
|
|
396
|
+
|
|
397
|
+
@override
|
|
398
|
+
async def is_empty(self, prefix: str) -> bool:
|
|
399
|
+
await self._ensure_open()
|
|
400
|
+
assert self._conn is not None
|
|
401
|
+
|
|
402
|
+
params: Sequence[str] = ()
|
|
403
|
+
if prefix == "":
|
|
404
|
+
sql = "SELECT EXISTS(SELECT 1 FROM zarr LIMIT 1)"
|
|
405
|
+
else:
|
|
406
|
+
params = self._get_text_boundaries(prefix)
|
|
407
|
+
sql = "SELECT EXISTS(SELECT 1 FROM zarr WHERE k > ? AND k < ? LIMIT 1)"
|
|
408
|
+
|
|
409
|
+
row = await self._conn.fetchone(sql, params)
|
|
410
|
+
return row is not None and row[0] == 0
|
|
411
|
+
|
|
412
|
+
@override
|
|
413
|
+
async def clear(self) -> None:
|
|
414
|
+
await self.delete_dir("")
|
|
415
|
+
|
|
416
|
+
@override
|
|
417
|
+
def __str__(self) -> str:
|
|
418
|
+
return repr(self)
|
|
419
|
+
|
|
420
|
+
@override
|
|
421
|
+
def __repr__(self) -> str:
|
|
422
|
+
return f"SQLiteStore('{self._database}')"
|
|
423
|
+
|
|
424
|
+
@override
|
|
425
|
+
def __eq__(self, other: object) -> bool:
|
|
426
|
+
"""Equality comparison."""
|
|
427
|
+
if not isinstance(other, type(self)):
|
|
428
|
+
return False
|
|
429
|
+
|
|
430
|
+
if self.is_in_memory() or other.is_in_memory():
|
|
431
|
+
return False
|
|
432
|
+
|
|
433
|
+
return self.database == other.database
|
|
434
|
+
|
|
435
|
+
@override
|
|
436
|
+
async def get(
|
|
437
|
+
self,
|
|
438
|
+
key: str,
|
|
439
|
+
prototype: BufferPrototype,
|
|
440
|
+
byte_range: ByteRequest | None = None,
|
|
441
|
+
) -> Buffer | None:
|
|
442
|
+
_validate_key(key)
|
|
443
|
+
await self._ensure_open()
|
|
444
|
+
assert self._conn is not None
|
|
445
|
+
|
|
446
|
+
row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
|
|
447
|
+
|
|
448
|
+
if row is None:
|
|
449
|
+
return None
|
|
450
|
+
data = row[0]
|
|
451
|
+
if not isinstance(data, bytes):
|
|
452
|
+
return None
|
|
453
|
+
|
|
454
|
+
if byte_range is not None:
|
|
455
|
+
blob_len = len(data)
|
|
456
|
+
match byte_range:
|
|
457
|
+
case OffsetByteRequest(offset=o):
|
|
458
|
+
start = min(o, blob_len)
|
|
459
|
+
data = data[start:]
|
|
460
|
+
case RangeByteRequest(start=s, end=e):
|
|
461
|
+
start = max(0, s)
|
|
462
|
+
end_clamped = min(blob_len, max(0, e))
|
|
463
|
+
data = data[start:end_clamped]
|
|
464
|
+
case SuffixByteRequest(suffix=s):
|
|
465
|
+
start = max(0, blob_len - s)
|
|
466
|
+
data = data[start:]
|
|
467
|
+
case _:
|
|
468
|
+
raise ValueError(f"Unsupported byte range type: {type(byte_range)}")
|
|
469
|
+
|
|
470
|
+
return prototype.buffer.from_bytes(data)
|
|
471
|
+
|
|
472
|
+
@override
|
|
473
|
+
async def get_partial_values(
|
|
474
|
+
self,
|
|
475
|
+
prototype: BufferPrototype,
|
|
476
|
+
key_ranges: Iterable[tuple[str, ByteRequest | None]],
|
|
477
|
+
) -> list[Buffer | None]:
|
|
478
|
+
return await asyncio.gather(
|
|
479
|
+
*[self.get(key, prototype, byte_range) for key, byte_range in key_ranges]
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
@override
|
|
483
|
+
async def exists(self, key: str) -> bool:
|
|
484
|
+
_validate_key(key)
|
|
485
|
+
await self._ensure_open()
|
|
486
|
+
assert self._conn is not None
|
|
487
|
+
row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
|
|
488
|
+
return row is not None
|
|
489
|
+
|
|
490
|
+
@override
|
|
491
|
+
async def set(self, key: str, value: Buffer) -> None:
|
|
492
|
+
self._check_writable()
|
|
493
|
+
_validate_key(key)
|
|
494
|
+
await self._ensure_open()
|
|
495
|
+
assert self._conn is not None
|
|
496
|
+
async with self._transaction():
|
|
497
|
+
await self._conn.execute(
|
|
498
|
+
"INSERT INTO zarr(k, v) VALUES (?, ?)"
|
|
499
|
+
"ON CONFLICT(k) DO UPDATE SET v = excluded.v",
|
|
500
|
+
(key, value.to_bytes()),
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
@override
|
|
504
|
+
async def set_if_not_exists(self, key: str, value: Buffer) -> None:
|
|
505
|
+
self._check_writable()
|
|
506
|
+
_validate_key(key)
|
|
507
|
+
await self._ensure_open()
|
|
508
|
+
assert self._conn is not None
|
|
509
|
+
async with self._transaction():
|
|
510
|
+
await self._conn.execute(
|
|
511
|
+
"INSERT OR IGNORE INTO zarr (k, v) VALUES (?, ?)",
|
|
512
|
+
(key, value.to_bytes()),
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
@override
|
|
516
|
+
async def delete(self, key: str) -> None:
|
|
517
|
+
self._check_writable()
|
|
518
|
+
await self._ensure_open()
|
|
519
|
+
assert self._conn is not None
|
|
520
|
+
async with self._transaction():
|
|
521
|
+
await self._conn.execute("DELETE FROM zarr WHERE k = ?", (key,))
|
|
522
|
+
|
|
523
|
+
@override
|
|
524
|
+
async def list(self) -> AsyncIterator[str]:
|
|
525
|
+
await self._ensure_open()
|
|
526
|
+
assert self._conn is not None
|
|
527
|
+
async for row in self._conn.fetch_iter("SELECT k FROM zarr"):
|
|
528
|
+
yield str(row[0])
|
|
529
|
+
|
|
530
|
+
@override
|
|
531
|
+
async def list_prefix(self, prefix: str) -> AsyncIterator[str]:
|
|
532
|
+
await self._ensure_open()
|
|
533
|
+
assert self._conn is not None
|
|
534
|
+
params: Sequence[str] = ()
|
|
535
|
+
if prefix == "":
|
|
536
|
+
sql = "SELECT k FROM zarr"
|
|
537
|
+
else:
|
|
538
|
+
params = self._get_text_boundaries(prefix)
|
|
539
|
+
sql = "SELECT k FROM zarr WHERE k > ? AND k < ?"
|
|
540
|
+
async for row in self._conn.fetch_iter(sql, params):
|
|
541
|
+
yield str(row[0])
|
|
542
|
+
|
|
543
|
+
@override
|
|
544
|
+
async def list_dir(self, prefix: str) -> AsyncIterator[str]:
|
|
545
|
+
# Even though prefix will be normalized in list_prefix(), this is
|
|
546
|
+
# required for the removeprefix(prefix) call used below.
|
|
547
|
+
if prefix != "" and not prefix[-1] == "/":
|
|
548
|
+
prefix += "/"
|
|
549
|
+
|
|
550
|
+
# _ensure_open is called in list_prefix()
|
|
551
|
+
seen: set[str] = set()
|
|
552
|
+
async for full_key in self.list_prefix(prefix):
|
|
553
|
+
rel_key = full_key.removeprefix(prefix)
|
|
554
|
+
parts = rel_key.split("/")
|
|
555
|
+
k = parts[0]
|
|
556
|
+
if len(parts) > 1:
|
|
557
|
+
k = k + "/"
|
|
558
|
+
if k not in seen:
|
|
559
|
+
seen.add(k)
|
|
560
|
+
yield k
|
|
561
|
+
|
|
562
|
+
@override
|
|
563
|
+
async def delete_dir(self, prefix: str) -> None:
|
|
564
|
+
self._check_writable()
|
|
565
|
+
await self._ensure_open()
|
|
566
|
+
|
|
567
|
+
async with self._transaction():
|
|
568
|
+
assert self._conn is not None
|
|
569
|
+
# Check if key exists
|
|
570
|
+
row = await self._conn.fetchone(
|
|
571
|
+
"SELECT v FROM zarr WHERE k = ?", (prefix.rstrip("/"),)
|
|
572
|
+
)
|
|
573
|
+
if row is not None:
|
|
574
|
+
raise ValueError(
|
|
575
|
+
f"Cannot delete directory {prefix} as it is a key in the store."
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
params: Sequence[str] = ()
|
|
579
|
+
if prefix == "":
|
|
580
|
+
sql = "DELETE FROM zarr"
|
|
581
|
+
else:
|
|
582
|
+
params = self._get_text_boundaries(prefix)
|
|
583
|
+
sql = "DELETE FROM zarr WHERE k > ? AND k < ?"
|
|
584
|
+
await self._conn.execute(sql, params)
|
|
585
|
+
|
|
586
|
+
@override
|
|
587
|
+
async def getsize(self, key: str) -> int:
|
|
588
|
+
_validate_key(key)
|
|
589
|
+
await self._ensure_open()
|
|
590
|
+
assert self._conn is not None
|
|
591
|
+
row = await self._conn.fetchone(
|
|
592
|
+
"SELECT LENGTH(v) FROM zarr WHERE k = ?", (key,)
|
|
593
|
+
)
|
|
594
|
+
if row is None:
|
|
595
|
+
raise FileNotFoundError(key)
|
|
596
|
+
return int(row[0])
|
|
597
|
+
|
|
598
|
+
@override
|
|
599
|
+
async def getsize_prefix(self, prefix: str) -> int:
|
|
600
|
+
await self._ensure_open()
|
|
601
|
+
assert self._conn is not None
|
|
602
|
+
params: Sequence[str] = ()
|
|
603
|
+
if prefix == "":
|
|
604
|
+
sql = "SELECT SUM(LENGTH(v)) FROM zarr"
|
|
605
|
+
else:
|
|
606
|
+
params = self._get_text_boundaries(prefix)
|
|
607
|
+
sql = "SELECT SUM(LENGTH(v)) FROM zarr WHERE k > ? AND k < ?"
|
|
608
|
+
size_row = await self._conn.fetchone(sql, params)
|
|
609
|
+
if size_row is None or size_row[0] is None:
|
|
610
|
+
return 0
|
|
611
|
+
return int(size_row[0])
|
|
612
|
+
|
|
613
|
+
def __del__(self):
|
|
614
|
+
if self._conn is not None:
|
|
615
|
+
self._conn.stop()
|