zarr-sqlite 1.0.0__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.
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: zarr-sqlite
3
+ Version: 1.0.2
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
+ Project-URL: Documentation, https://auxym.github.io/zarr-sqlite-python/zarr_sqlite.html
14
+ Project-URL: Format specification, https://github.com/auxym/zarr-sqlite-python/blob/main/SPEC.md
15
+ Project-URL: Source, https://github.com/auxym/zarr-sqlite-python
16
+ Provides-Extra: test
17
+ Description-Content-Type: text/markdown
18
+
19
+ # zarr-sqlite-python
20
+
21
+ **Store [Zarr](zarr.dev) datasets in a single SQLite database.**
22
+
23
+ [![PyPI version](https://img.shields.io/pypi/v/zarr-sqlite.svg)](https://pypi.org/project/zarr-sqlite/)
24
+
25
+ `zarr-sqlite` is a Python library which provides `SQLiteStore`, a single-file store implementation
26
+ backed by SQLite for [zarr-python](https://zarr.readthedocs.io/en/stable/). It combines Zarr's chunked, hierarchical data model with SQLite's single-file database format, mutability and ACID guarantees.
27
+
28
+ ## Why SQLiteStore?
29
+
30
+ * Single file — complete Zarr hierarchy is stored in one .zarrdb file.
31
+ * ACID transactions — writes are backed by SQLite's transactional database
32
+ engine. A crash or power loss during a write cannot corrupt the entire file,
33
+ at most, a single chunk may be lost. Readers can safely access the store
34
+ concurrently with writers and are guaranteed to see a consistent view of the
35
+ data.
36
+ * Mutable storage — arrays can be modified, overwritten, resized, appended to
37
+ and deleted.
38
+
39
+ `SQLiteStore` is primarily intended for relatively small Zarr datasets (typically
40
+ up to a few gigabytes) where the convenience of a single file is useful for
41
+ archival, distribution, or sharing. It is not intended as an alternative to
42
+ cloud-based object storage designed for chunk-level access to multi-terabyte
43
+ datasets.
44
+
45
+ ## Installation
46
+
47
+ Install from PyPI using your favorite package manager, for example:
48
+
49
+ ```
50
+ pip install zarr-sqlite
51
+ ```
52
+
53
+ ```
54
+ uv add zarr-sqlite
55
+ ```
56
+
57
+ ## Quick start
58
+
59
+ ```python
60
+ import zarr
61
+
62
+ from zarr_sqlite import SQLiteStore
63
+
64
+ with SQLiteStore("my_zarr_file.zarrdb") as store:
65
+ root = zarr.create_group(store=store)
66
+ foo = root.create_group("foo")
67
+ bar = foo.create_group("bar")
68
+ z1 = bar.create_array(name="baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="int32")
69
+ z1[:] = 42
70
+ ```
71
+
72
+ `SQLiteStore` otherwise behaves identically to other stores used with zarr.
73
+ See the [zarr-python user guide](https://zarr.readthedocs.io/en/stable/user-guide/storage.html)
74
+ for more information.
75
+
76
+ ## Documentation
77
+
78
+ There isn't much more to using `SQLiteStore` as it "just works" with
79
+ zarr-python. Full API reference can be accessed by running `uv run pdoc -d
80
+ numpy` (or `just doc` if you have [just](https://just.systems/) installed).
81
+
82
+ A copy of the API documentation for the current *main* branch is also hosted here:
83
+
84
+ **[Documentation for zarr_sqlite](https://auxym.github.io/zarr-sqlite-python)**
85
+
86
+ ## How it works
87
+
88
+ `SQLiteStore` implements the [abstract store
89
+ interface](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#abstract-store-interface)
90
+ defined by the Zarr Core Specification, which essentially provides a key-value
91
+ storage interface. It maps this interface directly onto a SQLite table, using
92
+ string keys and binary BLOB values. Keys correspond to Zarr paths, while values
93
+ contain either array chunks or Zarr metadata items. SQLite then provides the
94
+ persistence and transactional semantics underneath the Zarr store.
95
+
96
+ ## Specification
97
+
98
+ The file format is described by a [specification stored in this project's
99
+ repository](./SPEC.md). This document should allow the implementation of
100
+ SQLiteStore for other programming languages or Zarr libraries.
101
+
102
+ ## Status
103
+
104
+ The version of this library was incremented to v1.0 to reflect the fact that it
105
+ complies with v1 of the SQLiteStore Specification. However, this is a relatively
106
+ young library that has not seen a lot of real-world use yet, therefore users
107
+ should expect the occasional bug, and possibly breaking API changes in future
108
+ versions, if absolutely necessary.
109
+
110
+ The database format defined by the [Specification](./SPEC.md) is intended to provide
111
+ a stable basis for interoperability between implementations.
@@ -0,0 +1,93 @@
1
+ # zarr-sqlite-python
2
+
3
+ **Store [Zarr](zarr.dev) datasets in a single SQLite database.**
4
+
5
+ [![PyPI version](https://img.shields.io/pypi/v/zarr-sqlite.svg)](https://pypi.org/project/zarr-sqlite/)
6
+
7
+ `zarr-sqlite` is a Python library which provides `SQLiteStore`, a single-file store implementation
8
+ backed by SQLite for [zarr-python](https://zarr.readthedocs.io/en/stable/). It combines Zarr's chunked, hierarchical data model with SQLite's single-file database format, mutability and ACID guarantees.
9
+
10
+ ## Why SQLiteStore?
11
+
12
+ * Single file — complete Zarr hierarchy is stored in one .zarrdb file.
13
+ * ACID transactions — writes are backed by SQLite's transactional database
14
+ engine. A crash or power loss during a write cannot corrupt the entire file,
15
+ at most, a single chunk may be lost. Readers can safely access the store
16
+ concurrently with writers and are guaranteed to see a consistent view of the
17
+ data.
18
+ * Mutable storage — arrays can be modified, overwritten, resized, appended to
19
+ and deleted.
20
+
21
+ `SQLiteStore` is primarily intended for relatively small Zarr datasets (typically
22
+ up to a few gigabytes) where the convenience of a single file is useful for
23
+ archival, distribution, or sharing. It is not intended as an alternative to
24
+ cloud-based object storage designed for chunk-level access to multi-terabyte
25
+ datasets.
26
+
27
+ ## Installation
28
+
29
+ Install from PyPI using your favorite package manager, for example:
30
+
31
+ ```
32
+ pip install zarr-sqlite
33
+ ```
34
+
35
+ ```
36
+ uv add zarr-sqlite
37
+ ```
38
+
39
+ ## Quick start
40
+
41
+ ```python
42
+ import zarr
43
+
44
+ from zarr_sqlite import SQLiteStore
45
+
46
+ with SQLiteStore("my_zarr_file.zarrdb") as store:
47
+ root = zarr.create_group(store=store)
48
+ foo = root.create_group("foo")
49
+ bar = foo.create_group("bar")
50
+ z1 = bar.create_array(name="baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="int32")
51
+ z1[:] = 42
52
+ ```
53
+
54
+ `SQLiteStore` otherwise behaves identically to other stores used with zarr.
55
+ See the [zarr-python user guide](https://zarr.readthedocs.io/en/stable/user-guide/storage.html)
56
+ for more information.
57
+
58
+ ## Documentation
59
+
60
+ There isn't much more to using `SQLiteStore` as it "just works" with
61
+ zarr-python. Full API reference can be accessed by running `uv run pdoc -d
62
+ numpy` (or `just doc` if you have [just](https://just.systems/) installed).
63
+
64
+ A copy of the API documentation for the current *main* branch is also hosted here:
65
+
66
+ **[Documentation for zarr_sqlite](https://auxym.github.io/zarr-sqlite-python)**
67
+
68
+ ## How it works
69
+
70
+ `SQLiteStore` implements the [abstract store
71
+ interface](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#abstract-store-interface)
72
+ defined by the Zarr Core Specification, which essentially provides a key-value
73
+ storage interface. It maps this interface directly onto a SQLite table, using
74
+ string keys and binary BLOB values. Keys correspond to Zarr paths, while values
75
+ contain either array chunks or Zarr metadata items. SQLite then provides the
76
+ persistence and transactional semantics underneath the Zarr store.
77
+
78
+ ## Specification
79
+
80
+ The file format is described by a [specification stored in this project's
81
+ repository](./SPEC.md). This document should allow the implementation of
82
+ SQLiteStore for other programming languages or Zarr libraries.
83
+
84
+ ## Status
85
+
86
+ The version of this library was incremented to v1.0 to reflect the fact that it
87
+ complies with v1 of the SQLiteStore Specification. However, this is a relatively
88
+ young library that has not seen a lot of real-world use yet, therefore users
89
+ should expect the occasional bug, and possibly breaking API changes in future
90
+ versions, if absolutely necessary.
91
+
92
+ The database format defined by the [Specification](./SPEC.md) is intended to provide
93
+ a stable basis for interoperability between implementations.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "zarr-sqlite"
3
- version = "1.0.0"
3
+ version = "1.0.2"
4
4
  description = "Single-file Zarr v3 dataset store using SQLite"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -19,6 +19,11 @@ test = [
19
19
  "pytest>=8.4.1",
20
20
  ]
21
21
 
22
+ [project.urls]
23
+ Documentation = "https://auxym.github.io/zarr-sqlite-python/zarr_sqlite.html"
24
+ Source = "https://github.com/auxym/zarr-sqlite-python"
25
+ "Format specification" = "https://github.com/auxym/zarr-sqlite-python/blob/main/SPEC.md"
26
+
22
27
  [build-system]
23
28
  requires = ["uv_build>=0.8.3,<0.9.0"]
24
29
  build-backend = "uv_build"
@@ -27,6 +32,7 @@ build-backend = "uv_build"
27
32
  dev = [
28
33
  "mypy==2.3.0",
29
34
  "numpy>=2.3.2",
35
+ "pdoc>=16.0.0",
30
36
  "pytest>=8.4.1",
31
37
  "pytest-asyncio>=1.1.0",
32
38
  "pytest-benchmark>=5.2.3",
@@ -0,0 +1,91 @@
1
+ """
2
+ **zarr-sqlite** is a Python library which provides `SQLiteStore`, a
3
+ single-file store implementation backed by SQLite for
4
+ [zarr-python](https://zarr.readthedocs.io/en/stable/). It combines Zarr's
5
+ chunked, hierarchical data model with SQLite's single-file database format,
6
+ mutability and ACID guarantees.
7
+
8
+ ## Why SQLiteStore?
9
+
10
+ * Single file — complete Zarr hierarchy is stored in one .zarrdb file.
11
+ * ACID transactions — writes are backed by SQLite's transactional database
12
+ engine. A crash or power loss during a write cannot corrupt the entire file,
13
+ at most, a single chunk may be lost. Readers can safely access the store
14
+ concurrently with writers and are guaranteed to see a consistent view of the
15
+ data.
16
+ * Mutable storage — arrays can be modified, overwritten, resized, appended to
17
+ and deleted.
18
+
19
+ `SQLiteStore` is primarily intended for relatively small Zarr datasets (typically
20
+ up to a few gigabytes) where the convenience of a single file is useful for
21
+ archival, distribution, or sharing. It is not intended as an alternative to
22
+ cloud-based object storage designed for chunk-level access to multi-terabyte
23
+ datasets.
24
+
25
+ ## Installation
26
+
27
+ Install from PyPI using your favorite package manager, for example:
28
+
29
+ ```
30
+ pip install zarr-sqlite
31
+ ```
32
+
33
+ ```
34
+ uv add zarr-sqlite
35
+ ```
36
+
37
+ ## Quick start
38
+
39
+ ```python
40
+ import zarr
41
+
42
+ from zarr_sqlite import SQLiteStore
43
+
44
+ with SQLiteStore("my_zarr_file.zarrdb") as store:
45
+ root = zarr.create_group(store=store)
46
+ foo = root.create_group("foo")
47
+ bar = foo.create_group("bar")
48
+ z1 = bar.create_array(name="baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="int32")
49
+ z1[:] = 42
50
+ ```
51
+
52
+ `SQLiteStore` otherwise behaves identically to other stores used with zarr.
53
+ See the [zarr-python user guide](https://zarr.readthedocs.io/en/stable/user-guide/storage.html)
54
+ for more information.
55
+
56
+ ## How it works
57
+
58
+ `SQLiteStore` implements the [abstract store
59
+ interface](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#abstract-store-interface)
60
+ defined by the Zarr Core Specification, which essentially provides a key-value
61
+ storage interface. It maps this interface directly onto a SQLite table, using
62
+ string keys and binary BLOB values. Keys correspond to Zarr paths, while values
63
+ contain either array chunks or Zarr metadata items. SQLite then provides the
64
+ persistence and transactional semantics underneath the Zarr store.
65
+
66
+ ## Specification
67
+
68
+ The file format is described by a [specification stored in this project's
69
+ repository](./SPEC.md). This document should allow the implementation of
70
+ SQLiteStore for other programming languages or Zarr libraries.
71
+
72
+ ## Status
73
+
74
+ The version of this library was incremented to v1.0 to reflect the fact that it
75
+ complies with v1 of the SQLiteStore Specification. However, this is a relatively
76
+ young library that has not seen a lot of real-world use yet, therefore users
77
+ should expect the occasional bug, and possibly breaking API changes in future
78
+ versions, if absolutely necessary.
79
+
80
+ The database format defined by the [Specification](./SPEC.md) is intended to provide
81
+ a stable basis for interoperability between implementations.
82
+
83
+ ## API Reference
84
+
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
+ """
87
+
88
+ from ._version import __version__
89
+ from .zarr_sqlite import SQLiteStore
90
+
91
+ __all__ = ["SQLiteStore", "__version__"]
@@ -1,10 +1,14 @@
1
1
  def is_in_memory_database(database: str) -> bool:
2
2
  """Check whether a database specifier refers to an in-memory database.
3
3
 
4
- Args:
5
- database: The SQLite database specifier (path, URI, or ":memory:").
4
+ Parameters
5
+ ----------
6
+ database : str
7
+ The SQLite database specifier (path, URI, or ":memory:").
6
8
 
7
- Returns:
9
+ Returns
10
+ -------
11
+ bool
8
12
  True if the database is in-memory, False otherwise.
9
13
  """
10
14
  return database == ":memory:" or (
@@ -18,10 +22,14 @@ def is_database_uri(database: str) -> bool:
18
22
  SQLite URIs use the ``file:`` scheme, e.g. ``file:/path/to/db`` or
19
23
  ``file::memory:?mode=memory``.
20
24
 
21
- Args:
22
- database: The SQLite database specifier.
25
+ Parameters
26
+ ----------
27
+ database : str
28
+ The SQLite database specifier.
23
29
 
24
- Returns:
30
+ Returns
31
+ -------
32
+ bool
25
33
  True if the database is a URI, False otherwise.
26
34
  """
27
35
  return database.startswith("file:/")
@@ -1,4 +1,4 @@
1
- from importlib.metadata import version, PackageNotFoundError
1
+ from importlib.metadata import PackageNotFoundError, version
2
2
 
3
3
  try:
4
4
  __version__ = version("zarr_sqlite")
@@ -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, Callable, Optional
44
+ from typing import Any
45
45
  from warnings import warn
46
46
 
47
- __all__ = ["connect", "Connection"]
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[Optional[asyncio.Future], Callable[[], Any]]]
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: Optional[sqlite3.Connection] = None
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(self, join=False, join_timeout: float | None = None) -> Optional[asyncio.Future]:
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 Exception:
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._conn.execute, sql, parameters)
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
- def _fetchall():
245
- cursor = self._conn.execute(sql, parameters)
246
- return cursor.fetchall()
261
+ return await self._execute(self._fetchall, sql, parameters)
247
262
 
248
- return await self._execute(_fetchall)
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
- def _fetchone():
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
- 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
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 urllib.parse
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(
@@ -50,23 +48,23 @@ def _validate_key(key: str):
50
48
 
51
49
 
52
50
  class SQLiteStore(Store):
53
- """
54
- Store for the local file system.
51
+ """Single-file SQLite-backed store for Zarr datasets.
55
52
 
56
53
  Parameters
57
54
  ----------
58
55
  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
56
+ Path to the SQLite database file, or ``:memory:`` for an in-memory
57
+ database. The file will be created if it does not already exist.
58
+ read_only : bool, optional
59
+ Whether the store is read-only. In-memory databases cannot be opened
60
+ read-only. Default: False (read-write).
61
+ journal_mode : str, optional
62
+ SQLite journaling mode. ``"WAL"`` (write-ahead log) or ``"DELETE"``
63
+ are supported. If ``None``, the journaling mode will be the database's
64
+ previously set value, or SQLite's default for a new database. Default: WAL.
65
+ page_size : int, optional
66
+ SQLite page size in bytes. The default value of 4096 bytes has been found
67
+ to provide good all-around performance for approximately 1 MB chunks.
70
68
  """
71
69
 
72
70
  _database: str
@@ -80,16 +78,19 @@ class SQLiteStore(Store):
80
78
  @property
81
79
  @override
82
80
  def supports_writes(self) -> bool:
81
+ """`True`"""
83
82
  return True
84
83
 
85
84
  @property
86
85
  @override
87
86
  def supports_deletes(self) -> bool:
87
+ """`True`"""
88
88
  return True
89
89
 
90
90
  @property
91
91
  @override
92
92
  def supports_listing(self) -> bool:
93
+ """`True`"""
93
94
  return True
94
95
 
95
96
  def __init__(
@@ -118,10 +119,12 @@ class SQLiteStore(Store):
118
119
  self._database = self._database_as_uri(self.database, read_only)
119
120
 
120
121
  @property
121
- def database(self):
122
+ def database(self) -> str:
123
+ """The database path or URI as a string."""
122
124
  return self._database
123
125
 
124
126
  def is_in_memory(self) -> bool:
127
+ """Return whether the database is in-memory."""
125
128
  return is_in_memory_database(self._database)
126
129
 
127
130
  @staticmethod
@@ -131,9 +134,9 @@ class SQLiteStore(Store):
131
134
  Parameters
132
135
  ----------
133
136
  database : str
134
- File path or sqlite-compatible URI (must have `file:` scheme). If
137
+ File path or sqlite-compatible URI (must have `file:` scheme). If
135
138
  `database` is a URI, the parameters will be kept unmodified, except
136
- "mode", which will always be overwritten or added base on the value
139
+ "mode", which will always be overwritten or added based on the value
137
140
  of `read_only`.
138
141
  read_only : bool
139
142
  Whether the store is read-only
@@ -177,6 +180,10 @@ class SQLiteStore(Store):
177
180
  assert self._conn is not None
178
181
  async with self._transaction_lock:
179
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()
180
187
  yield
181
188
  await self._conn.commit()
182
189
  except BaseException:
@@ -249,19 +256,20 @@ class SQLiteStore(Store):
249
256
  elif self._journal_mode.upper() not in {"DELETE", "WAL"}:
250
257
  raise ValueError(f"Invalid journal_mode: {self._journal_mode}")
251
258
 
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)
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)
260
268
 
261
269
  async def _update_timestamp(self) -> None:
262
270
  assert self._conn is not None
263
271
 
264
- now = datetime.now(timezone.utc).isoformat().upper()
272
+ now = datetime.now(UTC).isoformat().upper()
265
273
  if now.endswith("+00:00"):
266
274
  now = now.removesuffix("+00:00") + "Z"
267
275
  assert now.endswith("Z")
@@ -274,15 +282,16 @@ class SQLiteStore(Store):
274
282
 
275
283
  async def _db_is_empty(self) -> bool:
276
284
  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_%'
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
+ """
283
294
  )
284
- """
285
- )
286
295
  assert row is not None
287
296
  return row[0] == 0
288
297
 
@@ -294,19 +303,27 @@ class SQLiteStore(Store):
294
303
  )
295
304
 
296
305
  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}'"
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 + ")"
304
311
  )
312
+ if not rows:
313
+ raise ValueError(
314
+ f"Invalid SQLiteStore file: missing required table '{required_table}'"
315
+ )
316
+
317
+ app_id_row = await self._conn.fetchone("PRAGMA application_id")
305
318
 
306
- app_id_row = await self._conn.fetchone("PRAGMA application_id")
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
307
325
  assert app_id_row is not None
308
326
  app_id = app_id_row[0]
309
-
310
327
  if app_id != _SQLITESTORE_APPLICATION_ID:
311
328
  if self.read_only:
312
329
  warnings.warn(
@@ -324,11 +341,7 @@ class SQLiteStore(Store):
324
341
  f"(expected {_SQLITESTORE_APPLICATION_ID:#x})."
325
342
  )
326
343
 
327
- metadata_rows = await self._conn.fetchall(
328
- "SELECT k, v FROM zarr_sqlitestore_metadata WHERE k IN (?, ?, ?)",
329
- metadata_keys,
330
- )
331
-
344
+ # Check validity of metadata
332
345
  metadata: dict[str, str] = (
333
346
  {k: v for k, v in metadata_rows} if metadata_rows else {}
334
347
  )
@@ -372,8 +385,8 @@ class SQLiteStore(Store):
372
385
  clause like "(...) WHERE k < :lower_bound AND k > :upper_bound".
373
386
 
374
387
  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).
388
+ character in a prefix with a zero (0) character, which is the next
389
+ character in lexicographical order (in ASCII and Unicode).
377
390
 
378
391
  We do not use GLOB or LIKE in prefix searches because they have many
379
392
  issues in SQLite. For example, LIKE does not support case-sensitive
@@ -406,7 +419,8 @@ class SQLiteStore(Store):
406
419
  params = self._get_text_boundaries(prefix)
407
420
  sql = "SELECT EXISTS(SELECT 1 FROM zarr WHERE k > ? AND k < ? LIMIT 1)"
408
421
 
409
- row = await self._conn.fetchone(sql, params)
422
+ async with self._transaction():
423
+ row = await self._conn.fetchone(sql, params)
410
424
  return row is not None and row[0] == 0
411
425
 
412
426
  @override
@@ -423,7 +437,6 @@ class SQLiteStore(Store):
423
437
 
424
438
  @override
425
439
  def __eq__(self, other: object) -> bool:
426
- """Equality comparison."""
427
440
  if not isinstance(other, type(self)):
428
441
  return False
429
442
 
@@ -443,7 +456,9 @@ class SQLiteStore(Store):
443
456
  await self._ensure_open()
444
457
  assert self._conn is not None
445
458
 
446
- row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
459
+ async with self._transaction():
460
+ row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
461
+ # print(f"Get '{key}'")
447
462
 
448
463
  if row is None:
449
464
  return None
@@ -484,11 +499,23 @@ class SQLiteStore(Store):
484
499
  _validate_key(key)
485
500
  await self._ensure_open()
486
501
  assert self._conn is not None
487
- row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
502
+ async with self._transaction():
503
+ row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,))
488
504
  return row is not None
489
505
 
490
506
  @override
491
507
  async def set(self, key: str, value: Buffer) -> None:
508
+ """Store a (key, value) pair.
509
+
510
+ If the key already exists, its value is replaced.
511
+
512
+ Parameters
513
+ ----------
514
+ key : str
515
+ The key to store under.
516
+ value : Buffer
517
+ The value to store.
518
+ """
492
519
  self._check_writable()
493
520
  _validate_key(key)
494
521
  await self._ensure_open()
@@ -524,8 +551,9 @@ class SQLiteStore(Store):
524
551
  async def list(self) -> AsyncIterator[str]:
525
552
  await self._ensure_open()
526
553
  assert self._conn is not None
527
- async for row in self._conn.fetch_iter("SELECT k FROM zarr"):
528
- yield str(row[0])
554
+ async with self._transaction():
555
+ async for row in self._conn.fetch_iter("SELECT k FROM zarr"):
556
+ yield str(row[0])
529
557
 
530
558
  @override
531
559
  async def list_prefix(self, prefix: str) -> AsyncIterator[str]:
@@ -537,14 +565,15 @@ class SQLiteStore(Store):
537
565
  else:
538
566
  params = self._get_text_boundaries(prefix)
539
567
  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])
568
+ async with self._transaction():
569
+ async for row in self._conn.fetch_iter(sql, params):
570
+ yield str(row[0])
542
571
 
543
572
  @override
544
573
  async def list_dir(self, prefix: str) -> AsyncIterator[str]:
545
574
  # Even though prefix will be normalized in list_prefix(), this is
546
575
  # required for the removeprefix(prefix) call used below.
547
- if prefix != "" and not prefix[-1] == "/":
576
+ if prefix != "" and prefix[-1] != "/":
548
577
  prefix += "/"
549
578
 
550
579
  # _ensure_open is called in list_prefix()
@@ -564,23 +593,25 @@ class SQLiteStore(Store):
564
593
  self._check_writable()
565
594
  await self._ensure_open()
566
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
+
567
603
  async with self._transaction():
568
604
  assert self._conn is not None
569
605
  # Check if key exists
570
606
  row = await self._conn.fetchone(
571
607
  "SELECT v FROM zarr WHERE k = ?", (prefix.rstrip("/"),)
572
608
  )
609
+
573
610
  if row is not None:
574
611
  raise ValueError(
575
612
  f"Cannot delete directory {prefix} as it is a key in the store."
576
613
  )
577
614
 
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
615
  await self._conn.execute(sql, params)
585
616
 
586
617
  @override
@@ -588,9 +619,10 @@ class SQLiteStore(Store):
588
619
  _validate_key(key)
589
620
  await self._ensure_open()
590
621
  assert self._conn is not None
591
- row = await self._conn.fetchone(
592
- "SELECT LENGTH(v) FROM zarr WHERE k = ?", (key,)
593
- )
622
+ async with self._transaction():
623
+ row = await self._conn.fetchone(
624
+ "SELECT LENGTH(v) FROM zarr WHERE k = ?", (key,)
625
+ )
594
626
  if row is None:
595
627
  raise FileNotFoundError(key)
596
628
  return int(row[0])
@@ -605,7 +637,8 @@ class SQLiteStore(Store):
605
637
  else:
606
638
  params = self._get_text_boundaries(prefix)
607
639
  sql = "SELECT SUM(LENGTH(v)) FROM zarr WHERE k > ? AND k < ?"
608
- size_row = await self._conn.fetchone(sql, params)
640
+ async with self._transaction():
641
+ size_row = await self._conn.fetchone(sql, params)
609
642
  if size_row is None or size_row[0] is None:
610
643
  return 0
611
644
  return int(size_row[0])
@@ -1,61 +0,0 @@
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.
@@ -1,46 +0,0 @@
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.
@@ -1,5 +0,0 @@
1
- from .zarr_sqlite import SQLiteStore
2
-
3
- from ._version import __version__
4
-
5
- __all__ = ["__version__", "SQLiteStore"]
File without changes