zarr_sqlite
zarr-sqlite is a Python library which provides SQLiteStore, a
single-file store implementation backed by SQLite for
zarr-python. It combines Zarr's
chunked, hierarchical data model with SQLite's single-file database format,
mutability and ACID guarantees.
Why SQLiteStore?
- Single file — complete Zarr hierarchy is stored in one .zarrdb file.
- ACID transactions — writes are backed by SQLite's transactional database engine. A crash or power loss during a write cannot corrupt the entire file, at most, a single chunk may be lost. Readers can safely access the store concurrently with writers and are guaranteed to see a consistent view of the data.
- Mutable storage — arrays can be modified, overwritten, resized, appended to and deleted.
SQLiteStore is primarily intended for relatively small Zarr datasets (typically
up to a few gigabytes) where the convenience of a single file is useful for
archival, distribution, or sharing. It is not intended as an alternative to
cloud-based object storage designed for chunk-level access to multi-terabyte
datasets.
Installation
Install from PyPI using your favorite package manager, for example:
pip install zarr-sqlite
uv add zarr-sqlite
Quick start
import zarr
from zarr_sqlite import SQLiteStore
with SQLiteStore("my_zarr_file.zarrdb") as store:
root = zarr.create_group(store=store)
foo = root.create_group("foo")
bar = foo.create_group("bar")
z1 = bar.create_array(name="baz", shape=(10000, 10000), chunks=(1000, 1000), dtype="int32")
z1[:] = 42
SQLiteStore otherwise behaves identically to other stores used with zarr.
See the zarr-python user guide
for more information.
How it works
SQLiteStore implements the abstract store
interface
defined by the Zarr Core Specification, which essentially provides a key-value
storage interface. It maps this interface directly onto a SQLite table, using
string keys and binary BLOB values. Keys correspond to Zarr paths, while values
contain either array chunks or Zarr metadata items. SQLite then provides the
persistence and transactional semantics underneath the Zarr store.
Specification
The file format is described by a specification stored in this project's repository. This document should allow the implementation of SQLiteStore for other programming languages or Zarr libraries.
Status
The version of this library was incremented to v1.0 to reflect the fact that it complies with v1 of the SQLiteStore Specification. However, this is a relatively young library that has not seen a lot of real-world use yet, therefore users should expect the occasional bug, and possibly breaking API changes in future versions, if absolutely necessary.
The database format defined by the Specification is intended to provide a stable basis for interoperability between implementations.
API Reference
The SQLiteStore class implements the zarr-python Store interface.
1""" 2**zarr-sqlite** is a Python library which provides `SQLiteStore`, a 3single-file store implementation backed by SQLite for 4[zarr-python](https://zarr.readthedocs.io/en/stable/). It combines Zarr's 5chunked, hierarchical data model with SQLite's single-file database format, 6mutability 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 20up to a few gigabytes) where the convenience of a single file is useful for 21archival, distribution, or sharing. It is not intended as an alternative to 22cloud-based object storage designed for chunk-level access to multi-terabyte 23datasets. 24 25## Installation 26 27Install from PyPI using your favorite package manager, for example: 28 29``` 30pip install zarr-sqlite 31``` 32 33``` 34uv add zarr-sqlite 35``` 36 37## Quick start 38 39```python 40import zarr 41 42from zarr_sqlite import SQLiteStore 43 44with 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. 53See the [zarr-python user guide](https://zarr.readthedocs.io/en/stable/user-guide/storage.html) 54for more information. 55 56## How it works 57 58`SQLiteStore` implements the [abstract store 59interface](https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#abstract-store-interface) 60defined by the Zarr Core Specification, which essentially provides a key-value 61storage interface. It maps this interface directly onto a SQLite table, using 62string keys and binary BLOB values. Keys correspond to Zarr paths, while values 63contain either array chunks or Zarr metadata items. SQLite then provides the 64persistence and transactional semantics underneath the Zarr store. 65 66## Specification 67 68The file format is described by a [specification stored in this project's 69repository](./SPEC.md). This document should allow the implementation of 70SQLiteStore for other programming languages or Zarr libraries. 71 72## Status 73 74The version of this library was incremented to v1.0 to reflect the fact that it 75complies with v1 of the SQLiteStore Specification. However, this is a relatively 76young library that has not seen a lot of real-world use yet, therefore users 77should expect the occasional bug, and possibly breaking API changes in future 78versions, if absolutely necessary. 79 80The database format defined by the [Specification](./SPEC.md) is intended to provide 81a stable basis for interoperability between implementations. 82 83## API Reference 84 85The `SQLiteStore` class implements the [zarr-python `Store` interface](https://zarr.readthedocs.io/en/stable/api/zarr/storage.html#zarr.abc.store.Store). 86""" 87 88from .zarr_sqlite import SQLiteStore 89 90from ._version import __version__ 91 92__all__ = ["__version__", "SQLiteStore"]
53class SQLiteStore(Store): 54 """Single-file SQLite-backed store for Zarr datasets. 55 56 Parameters 57 ---------- 58 database : str or Path 59 Path to the SQLite database file, or ``:memory:`` for an in-memory 60 database. The file will be created if it does not already exist. 61 read_only : bool, optional 62 Whether the store is read-only. In-memory databases cannot be opened 63 read-only. Default: False (read-write). 64 journal_mode : str, optional 65 SQLite journaling mode. ``"WAL"`` (write-ahead log) or ``"DELETE"`` 66 are supported. If ``None``, the journaling mode will be the database's 67 previously set value, or SQLite's default for a new database. Default: WAL. 68 page_size : int, optional 69 SQLite page size in bytes. The default value of 4096 bytes has been found 70 to provide good all-around performance for approximately 1 MB chunks. 71 """ 72 73 _database: str 74 _is_open: bool 75 _open_lock: asyncio.Lock 76 _conn: Connection | None 77 _transaction_lock: asyncio.Lock 78 _journal_mode: str | None 79 _page_size: int 80 81 @property 82 @override 83 def supports_writes(self) -> bool: 84 """`True`""" 85 return True 86 87 @property 88 @override 89 def supports_deletes(self) -> bool: 90 """`True`""" 91 return True 92 93 @property 94 @override 95 def supports_listing(self) -> bool: 96 """`True`""" 97 return True 98 99 def __init__( 100 self, 101 database: str | Path, 102 *, 103 read_only: bool = False, 104 journal_mode: str | None = "WAL", 105 page_size: int = 4096, 106 ) -> None: 107 super().__init__(read_only=read_only) 108 self._database = str(database) 109 self._journal_mode = journal_mode 110 self._page_size = page_size 111 self._conn = None 112 113 self._open_lock = asyncio.Lock() 114 self._transaction_lock = asyncio.Lock() 115 116 if self.is_in_memory() and read_only: 117 raise ValueError("In-memory databases cannot be opened read-only") 118 119 # To open a database in read-only mode in python, we need to use 120 # a SQLite URI. 121 if read_only: 122 self._database = self._database_as_uri(self.database, read_only) 123 124 @property 125 def database(self) -> str: 126 """The database path or URI as a string.""" 127 return self._database 128 129 def is_in_memory(self) -> bool: 130 """Return whether the database is in-memory.""" 131 return is_in_memory_database(self._database) 132 133 @staticmethod 134 def _database_as_uri(database: str, read_only: bool) -> str: 135 """Create a sqlite-compatible database URI. 136 137 Parameters 138 ---------- 139 database : str 140 File path or sqlite-compatible URI (must have `file:` scheme). If 141 `database` is a URI, the parameters will be kept unmodified, except 142 "mode", which will always be overwritten or added based on the value 143 of `read_only`. 144 read_only : bool 145 Whether the store is read-only 146 """ 147 148 if not is_database_uri(database): 149 database = Path(database).absolute().as_uri() 150 uri_parts = urllib.parse.urlsplit(database) 151 152 query = urllib.parse.parse_qs(uri_parts.query) 153 mode = "ro" if read_only else "rwc" 154 query["mode"] = [mode] 155 156 return urllib.parse.urlunsplit( 157 urllib.parse.SplitResult( 158 scheme=uri_parts.scheme, 159 netloc="", 160 path=uri_parts.path, 161 query=urllib.parse.urlencode(query, doseq=True), 162 fragment="", 163 ) 164 ) 165 166 @override 167 async def _ensure_open(self): 168 if self._is_open: 169 return 170 171 async with self._open_lock: 172 if self._is_open: 173 return 174 await self._open() 175 176 @asynccontextmanager 177 async def _transaction(self) -> AsyncGenerator[None, None]: 178 """Context manager for write transactions. 179 180 Acquires the transaction lock to serialize write operations on the 181 single SQLite connection. Commits on success, rolls back on error. 182 """ 183 assert self._conn is not None 184 async with self._transaction_lock: 185 try: 186 yield 187 await self._conn.commit() 188 except BaseException: 189 await self._conn.rollback() 190 raise 191 192 @override 193 async def _open(self) -> None: 194 if self._is_open: 195 raise ValueError("store is already open") 196 197 self._conn = await connect( 198 self._database, 199 uri=is_database_uri(self._database), 200 autocommit=False, 201 ) 202 203 try: 204 if not self.read_only and self._journal_mode is not None: 205 await self._set_journal_mode() 206 207 # Create schema only on empty file to avoid clobbering an existing file. 208 if not self._read_only and await self._db_is_empty(): 209 async with self._transaction(): 210 await self._create_schema() 211 await self._update_timestamp() 212 213 await self._validate_schema() 214 except Exception: 215 self._conn.stop(join=True) 216 self._conn = None 217 raise 218 219 self._is_open = True 220 221 @override 222 def with_read_only(self, read_only: bool = False) -> Self: 223 if self.is_in_memory(): 224 raise ValueError("Cannot create a read-only view of an in-memory database.") 225 return type(self)(self.database, read_only=read_only) 226 227 async def _create_schema(self) -> None: 228 assert self._conn is not None 229 await self._conn.execute("PRAGMA page_size=" + str(int(self._page_size))) 230 await self._conn.execute( 231 "CREATE TABLE IF NOT EXISTS zarr_sqlitestore_metadata(" 232 "k TEXT PRIMARY KEY NOT NULL, v TEXT NOT NULL)" 233 ) 234 await self._conn.execute( 235 "CREATE TABLE IF NOT EXISTS zarr(" 236 "k TEXT PRIMARY KEY NOT NULL, v BLOB NOT NULL)" 237 ) 238 await self._conn.execute( 239 "PRAGMA application_id = " + str(int(_SQLITESTORE_APPLICATION_ID)) 240 ) 241 await self._conn.executemany( 242 "INSERT OR IGNORE INTO zarr_sqlitestore_metadata(k, v) VALUES (?, ?)", 243 [ 244 ("sqlitestore_version", _SQLITESTORE_SPEC_VERSION), 245 ("compatible_flags", ""), 246 ("incompatible_flags", ""), 247 ("created_by", _CREATED_BY), 248 ], 249 ) 250 251 async def _set_journal_mode(self): 252 assert self._conn is not None 253 if self._journal_mode is None: 254 return 255 elif self._journal_mode.upper() not in {"DELETE", "WAL"}: 256 raise ValueError(f"Invalid journal_mode: {self._journal_mode}") 257 258 # PRAGMA journal_mode cannot be changed within a transaction. 259 # Temporarily set autocommit=True to execute it outside a 260 # transaction, then restore the previous value. 261 await self._conn.set_autocommit(True) 262 try: 263 await self._conn.execute("PRAGMA journal_mode=" + self._journal_mode) 264 finally: 265 await self._conn.set_autocommit(False) 266 267 async def _update_timestamp(self) -> None: 268 assert self._conn is not None 269 270 now = datetime.now(timezone.utc).isoformat().upper() 271 if now.endswith("+00:00"): 272 now = now.removesuffix("+00:00") + "Z" 273 assert now.endswith("Z") 274 275 await self._conn.execute( 276 "INSERT INTO zarr_sqlitestore_metadata(k, v) VALUES (?, ?) " 277 "ON CONFLICT(k) DO UPDATE SET v = excluded.v", 278 ("modified_at", now), 279 ) 280 281 async def _db_is_empty(self) -> bool: 282 assert self._conn is not None 283 row = await self._conn.fetchone( 284 """ 285 SELECT EXISTS ( 286 SELECT 1 FROM sqlite_schema 287 WHERE type IN ('table', 'view', 'index', 'trigger') 288 AND name NOT LIKE 'sqlite_%' 289 ) 290 """ 291 ) 292 assert row is not None 293 return row[0] == 0 294 295 async def _validate_schema(self) -> None: 296 metadata_keys = ( 297 "sqlitestore_version", 298 "compatible_flags", 299 "incompatible_flags", 300 ) 301 302 assert self._conn is not None 303 for required_table in ("zarr", "zarr_sqlitestore_metadata"): 304 rows = await self._conn.fetchall( 305 "PRAGMA table_info(" + required_table + ")" 306 ) 307 if not rows: 308 raise ValueError( 309 f"Invalid SQLiteStore file: missing required table '{required_table}'" 310 ) 311 312 app_id_row = await self._conn.fetchone("PRAGMA application_id") 313 assert app_id_row is not None 314 app_id = app_id_row[0] 315 316 if app_id != _SQLITESTORE_APPLICATION_ID: 317 if self.read_only: 318 warnings.warn( 319 f"Unexpected application_id for SQLiteStore: {app_id:#x} " 320 f"(expected {_SQLITESTORE_APPLICATION_ID:#x}). " 321 "This may not be a valid Zarr SQLiteStore file. Attempting to open it anyway.", 322 stacklevel=2, 323 ) 324 else: 325 # For writable files, we don't want to make modifications to a non-sqlitestore 326 # file that may have been opened by error, so refuse to open it. 327 raise ValueError( 328 f"Invalid SQLiteStore file: " 329 f"Unexpected application_id for SQLiteStore {app_id:#x} " 330 f"(expected {_SQLITESTORE_APPLICATION_ID:#x})." 331 ) 332 333 metadata_rows = await self._conn.fetchall( 334 "SELECT k, v FROM zarr_sqlitestore_metadata WHERE k IN (?, ?, ?)", 335 metadata_keys, 336 ) 337 338 metadata: dict[str, str] = ( 339 {k: v for k, v in metadata_rows} if metadata_rows else {} 340 ) 341 for k in metadata_keys: 342 if k not in metadata: 343 raise ValueError( 344 f"Invalid SQLiteStore file: missing required metadata entry '{k}'" 345 ) 346 347 version_str = metadata["sqlitestore_version"] 348 try: 349 version = [int(n) for n in version_str.strip().split(".")] 350 except ValueError: 351 raise ValueError(f"Invalid sqlitestore_version string: '{version_str}'") 352 if len(version) != 2: 353 raise ValueError(f"Invalid sqlitestore_version string: '{version_str}'") 354 if version[0] > 1: 355 raise ValueError(f"Unsupported sqlitestore_version: {version_str}") 356 357 incompat_flags = [ 358 f.strip() 359 for f in metadata["incompatible_flags"].split(",") 360 if len(f.strip()) > 0 361 ] 362 if len(incompat_flags) > 0: 363 raise ValueError(f"SQLiteStore flag '{incompat_flags[0]}' is not supported") 364 365 @override 366 def close(self) -> None: 367 """Immediately close the store and the SQLite connection.""" 368 if self._conn is not None: 369 self._conn.stop(join=True) 370 self._conn = None 371 self._is_open = False 372 373 @staticmethod 374 def _get_text_boundaries(prefix: str) -> tuple[str, str]: 375 """Compute a pair of (lower bound, upper bound) strings. 376 377 These strings are used to achieve efficient prefix search with an SQL 378 clause like "(...) WHERE k < :lower_bound AND k > :upper_bound". 379 380 The upper bound string is obtained by replacing the trailing slash (/) 381 character in a prefix with a zero (0) character, which is the next 382 character in lexicographical order (in ASCII and Unicode). 383 384 We do not use GLOB or LIKE in prefix searches because they have many 385 issues in SQLite. For example, LIKE does not support case-sensitive 386 matching (required for zarr keys), and GLOB does not support escaping 387 the special glob characters (*, [, ] and ?). 388 389 IMPORTANT: this does not work for the empty prefix "", which is considered 390 valid. 391 """ 392 assert prefix != "" 393 394 is_valid = not (prefix.startswith("/") or "//" in prefix) 395 if not is_valid: 396 raise ValueError(f"Invalid prefix '{prefix}'") 397 if prefix != "" and not prefix.endswith("/"): 398 prefix += "/" 399 400 upper = prefix[:-1] + "0" 401 return (prefix, upper) 402 403 @override 404 async def is_empty(self, prefix: str) -> bool: 405 await self._ensure_open() 406 assert self._conn is not None 407 408 params: Sequence[str] = () 409 if prefix == "": 410 sql = "SELECT EXISTS(SELECT 1 FROM zarr LIMIT 1)" 411 else: 412 params = self._get_text_boundaries(prefix) 413 sql = "SELECT EXISTS(SELECT 1 FROM zarr WHERE k > ? AND k < ? LIMIT 1)" 414 415 row = await self._conn.fetchone(sql, params) 416 return row is not None and row[0] == 0 417 418 @override 419 async def clear(self) -> None: 420 await self.delete_dir("") 421 422 @override 423 def __str__(self) -> str: 424 return repr(self) 425 426 @override 427 def __repr__(self) -> str: 428 return f"SQLiteStore('{self._database}')" 429 430 @override 431 def __eq__(self, other: object) -> bool: 432 if not isinstance(other, type(self)): 433 return False 434 435 if self.is_in_memory() or other.is_in_memory(): 436 return False 437 438 return self.database == other.database 439 440 @override 441 async def get( 442 self, 443 key: str, 444 prototype: BufferPrototype, 445 byte_range: ByteRequest | None = None, 446 ) -> Buffer | None: 447 _validate_key(key) 448 await self._ensure_open() 449 assert self._conn is not None 450 451 row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,)) 452 453 if row is None: 454 return None 455 data = row[0] 456 if not isinstance(data, bytes): 457 return None 458 459 if byte_range is not None: 460 blob_len = len(data) 461 match byte_range: 462 case OffsetByteRequest(offset=o): 463 start = min(o, blob_len) 464 data = data[start:] 465 case RangeByteRequest(start=s, end=e): 466 start = max(0, s) 467 end_clamped = min(blob_len, max(0, e)) 468 data = data[start:end_clamped] 469 case SuffixByteRequest(suffix=s): 470 start = max(0, blob_len - s) 471 data = data[start:] 472 case _: 473 raise ValueError(f"Unsupported byte range type: {type(byte_range)}") 474 475 return prototype.buffer.from_bytes(data) 476 477 @override 478 async def get_partial_values( 479 self, 480 prototype: BufferPrototype, 481 key_ranges: Iterable[tuple[str, ByteRequest | None]], 482 ) -> list[Buffer | None]: 483 return await asyncio.gather( 484 *[self.get(key, prototype, byte_range) for key, byte_range in key_ranges] 485 ) 486 487 @override 488 async def exists(self, key: str) -> bool: 489 _validate_key(key) 490 await self._ensure_open() 491 assert self._conn is not None 492 row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,)) 493 return row is not None 494 495 @override 496 async def set(self, key: str, value: Buffer) -> None: 497 """Store a (key, value) pair. 498 499 If the key already exists, its value is replaced. 500 501 Parameters 502 ---------- 503 key : str 504 The key to store under. 505 value : Buffer 506 The value to store. 507 """ 508 self._check_writable() 509 _validate_key(key) 510 await self._ensure_open() 511 assert self._conn is not None 512 async with self._transaction(): 513 await self._conn.execute( 514 "INSERT INTO zarr(k, v) VALUES (?, ?)" 515 "ON CONFLICT(k) DO UPDATE SET v = excluded.v", 516 (key, value.to_bytes()), 517 ) 518 519 @override 520 async def set_if_not_exists(self, key: str, value: Buffer) -> None: 521 self._check_writable() 522 _validate_key(key) 523 await self._ensure_open() 524 assert self._conn is not None 525 async with self._transaction(): 526 await self._conn.execute( 527 "INSERT OR IGNORE INTO zarr (k, v) VALUES (?, ?)", 528 (key, value.to_bytes()), 529 ) 530 531 @override 532 async def delete(self, key: str) -> None: 533 self._check_writable() 534 await self._ensure_open() 535 assert self._conn is not None 536 async with self._transaction(): 537 await self._conn.execute("DELETE FROM zarr WHERE k = ?", (key,)) 538 539 @override 540 async def list(self) -> AsyncIterator[str]: 541 await self._ensure_open() 542 assert self._conn is not None 543 async for row in self._conn.fetch_iter("SELECT k FROM zarr"): 544 yield str(row[0]) 545 546 @override 547 async def list_prefix(self, prefix: str) -> AsyncIterator[str]: 548 await self._ensure_open() 549 assert self._conn is not None 550 params: Sequence[str] = () 551 if prefix == "": 552 sql = "SELECT k FROM zarr" 553 else: 554 params = self._get_text_boundaries(prefix) 555 sql = "SELECT k FROM zarr WHERE k > ? AND k < ?" 556 async for row in self._conn.fetch_iter(sql, params): 557 yield str(row[0]) 558 559 @override 560 async def list_dir(self, prefix: str) -> AsyncIterator[str]: 561 # Even though prefix will be normalized in list_prefix(), this is 562 # required for the removeprefix(prefix) call used below. 563 if prefix != "" and not prefix[-1] == "/": 564 prefix += "/" 565 566 # _ensure_open is called in list_prefix() 567 seen: set[str] = set() 568 async for full_key in self.list_prefix(prefix): 569 rel_key = full_key.removeprefix(prefix) 570 parts = rel_key.split("/") 571 k = parts[0] 572 if len(parts) > 1: 573 k = k + "/" 574 if k not in seen: 575 seen.add(k) 576 yield k 577 578 @override 579 async def delete_dir(self, prefix: str) -> None: 580 self._check_writable() 581 await self._ensure_open() 582 583 async with self._transaction(): 584 assert self._conn is not None 585 # Check if key exists 586 row = await self._conn.fetchone( 587 "SELECT v FROM zarr WHERE k = ?", (prefix.rstrip("/"),) 588 ) 589 if row is not None: 590 raise ValueError( 591 f"Cannot delete directory {prefix} as it is a key in the store." 592 ) 593 594 params: Sequence[str] = () 595 if prefix == "": 596 sql = "DELETE FROM zarr" 597 else: 598 params = self._get_text_boundaries(prefix) 599 sql = "DELETE FROM zarr WHERE k > ? AND k < ?" 600 await self._conn.execute(sql, params) 601 602 @override 603 async def getsize(self, key: str) -> int: 604 _validate_key(key) 605 await self._ensure_open() 606 assert self._conn is not None 607 row = await self._conn.fetchone( 608 "SELECT LENGTH(v) FROM zarr WHERE k = ?", (key,) 609 ) 610 if row is None: 611 raise FileNotFoundError(key) 612 return int(row[0]) 613 614 @override 615 async def getsize_prefix(self, prefix: str) -> int: 616 await self._ensure_open() 617 assert self._conn is not None 618 params: Sequence[str] = () 619 if prefix == "": 620 sql = "SELECT SUM(LENGTH(v)) FROM zarr" 621 else: 622 params = self._get_text_boundaries(prefix) 623 sql = "SELECT SUM(LENGTH(v)) FROM zarr WHERE k > ? AND k < ?" 624 size_row = await self._conn.fetchone(sql, params) 625 if size_row is None or size_row[0] is None: 626 return 0 627 return int(size_row[0]) 628 629 def __del__(self): 630 if self._conn is not None: 631 self._conn.stop()
Single-file SQLite-backed store for Zarr datasets.
Parameters
- database (str or Path):
Path to the SQLite database file, or
:memory:for an in-memory database. The file will be created if it does not already exist. - read_only (bool, optional): Whether the store is read-only. In-memory databases cannot be opened read-only. Default: False (read-write).
- journal_mode (str, optional):
SQLite journaling mode.
"WAL"(write-ahead log) or"DELETE"are supported. IfNone, the journaling mode will be the database's previously set value, or SQLite's default for a new database. Default: WAL. - page_size (int, optional): SQLite page size in bytes. The default value of 4096 bytes has been found to provide good all-around performance for approximately 1 MB chunks.
99 def __init__( 100 self, 101 database: str | Path, 102 *, 103 read_only: bool = False, 104 journal_mode: str | None = "WAL", 105 page_size: int = 4096, 106 ) -> None: 107 super().__init__(read_only=read_only) 108 self._database = str(database) 109 self._journal_mode = journal_mode 110 self._page_size = page_size 111 self._conn = None 112 113 self._open_lock = asyncio.Lock() 114 self._transaction_lock = asyncio.Lock() 115 116 if self.is_in_memory() and read_only: 117 raise ValueError("In-memory databases cannot be opened read-only") 118 119 # To open a database in read-only mode in python, we need to use 120 # a SQLite URI. 121 if read_only: 122 self._database = self._database_as_uri(self.database, read_only)
124 @property 125 def database(self) -> str: 126 """The database path or URI as a string.""" 127 return self._database
The database path or URI as a string.
129 def is_in_memory(self) -> bool: 130 """Return whether the database is in-memory.""" 131 return is_in_memory_database(self._database)
Return whether the database is in-memory.
221 @override 222 def with_read_only(self, read_only: bool = False) -> Self: 223 if self.is_in_memory(): 224 raise ValueError("Cannot create a read-only view of an in-memory database.") 225 return type(self)(self.database, read_only=read_only)
Return a new store with a new read_only setting.
The new store points to the same location with the specified new read_only state. The returned Store is not automatically opened, and this store is not automatically closed.
Parameters
- read_only: If True, the store will be created in read-only mode. Defaults to False.
Returns
- A new store of the same type with the new read only attribute.
365 @override 366 def close(self) -> None: 367 """Immediately close the store and the SQLite connection.""" 368 if self._conn is not None: 369 self._conn.stop(join=True) 370 self._conn = None 371 self._is_open = False
Immediately close the store and the SQLite connection.
403 @override 404 async def is_empty(self, prefix: str) -> bool: 405 await self._ensure_open() 406 assert self._conn is not None 407 408 params: Sequence[str] = () 409 if prefix == "": 410 sql = "SELECT EXISTS(SELECT 1 FROM zarr LIMIT 1)" 411 else: 412 params = self._get_text_boundaries(prefix) 413 sql = "SELECT EXISTS(SELECT 1 FROM zarr WHERE k > ? AND k < ? LIMIT 1)" 414 415 row = await self._conn.fetchone(sql, params) 416 return row is not None and row[0] == 0
Check if the directory is empty.
Parameters
- prefix (str): Prefix of keys to check.
Returns
- bool: True if the store is empty, False otherwise.
Clear the store.
Remove all keys and values from the store.
440 @override 441 async def get( 442 self, 443 key: str, 444 prototype: BufferPrototype, 445 byte_range: ByteRequest | None = None, 446 ) -> Buffer | None: 447 _validate_key(key) 448 await self._ensure_open() 449 assert self._conn is not None 450 451 row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,)) 452 453 if row is None: 454 return None 455 data = row[0] 456 if not isinstance(data, bytes): 457 return None 458 459 if byte_range is not None: 460 blob_len = len(data) 461 match byte_range: 462 case OffsetByteRequest(offset=o): 463 start = min(o, blob_len) 464 data = data[start:] 465 case RangeByteRequest(start=s, end=e): 466 start = max(0, s) 467 end_clamped = min(blob_len, max(0, e)) 468 data = data[start:end_clamped] 469 case SuffixByteRequest(suffix=s): 470 start = max(0, blob_len - s) 471 data = data[start:] 472 case _: 473 raise ValueError(f"Unsupported byte range type: {type(byte_range)}") 474 475 return prototype.buffer.from_bytes(data)
Retrieve the value associated with a given key.
Parameters
key (str):
prototype (BufferPrototype): The prototype of the output buffer. Stores may support a default buffer prototype.
- byte_range (ByteRequest, optional):
ByteRequest may be one of the following. If not provided, all data associated with the key is retrieved.
- RangeByteRequest(int, int): Request a specific range of bytes in the form (start, end). The end is exclusive. If the given range is zero-length or starts after the end of the object, an error will be returned. Additionally, if the range ends after the end of the object, the entire remainder of the object will be returned. Otherwise, the exact requested range will be returned.
- OffsetByteRequest(int): Request all bytes starting from a given byte offset. This is equivalent to bytes={int}- as an HTTP header.
- SuffixByteRequest(int): Request the last int bytes. Note that here, int is the size of the request, not the byte offset. This is equivalent to bytes=-{int} as an HTTP header.
Returns
- Buffer
477 @override 478 async def get_partial_values( 479 self, 480 prototype: BufferPrototype, 481 key_ranges: Iterable[tuple[str, ByteRequest | None]], 482 ) -> list[Buffer | None]: 483 return await asyncio.gather( 484 *[self.get(key, prototype, byte_range) for key, byte_range in key_ranges] 485 )
Retrieve possibly partial values from given key_ranges.
Parameters
- prototype (BufferPrototype): The prototype of the output buffer. Stores may support a default buffer prototype.
- key_ranges (Iterable[tuple[str, tuple[int | None, int | None]]]): Ordered set of key, range pairs, a key may occur multiple times with different ranges
Returns
- list of values, in the order of the key_ranges, may contain null/none for missing keys
487 @override 488 async def exists(self, key: str) -> bool: 489 _validate_key(key) 490 await self._ensure_open() 491 assert self._conn is not None 492 row = await self._conn.fetchone("SELECT v FROM zarr WHERE k = ?", (key,)) 493 return row is not None
Check if a key exists in the store.
Parameters
- key (str):
Returns
- bool
495 @override 496 async def set(self, key: str, value: Buffer) -> None: 497 """Store a (key, value) pair. 498 499 If the key already exists, its value is replaced. 500 501 Parameters 502 ---------- 503 key : str 504 The key to store under. 505 value : Buffer 506 The value to store. 507 """ 508 self._check_writable() 509 _validate_key(key) 510 await self._ensure_open() 511 assert self._conn is not None 512 async with self._transaction(): 513 await self._conn.execute( 514 "INSERT INTO zarr(k, v) VALUES (?, ?)" 515 "ON CONFLICT(k) DO UPDATE SET v = excluded.v", 516 (key, value.to_bytes()), 517 )
Store a (key, value) pair.
If the key already exists, its value is replaced.
Parameters
- key (str): The key to store under.
- value (Buffer): The value to store.
519 @override 520 async def set_if_not_exists(self, key: str, value: Buffer) -> None: 521 self._check_writable() 522 _validate_key(key) 523 await self._ensure_open() 524 assert self._conn is not None 525 async with self._transaction(): 526 await self._conn.execute( 527 "INSERT OR IGNORE INTO zarr (k, v) VALUES (?, ?)", 528 (key, value.to_bytes()), 529 )
Store a key to value if the key is not already present.
Parameters
key (str):
value (Buffer):
531 @override 532 async def delete(self, key: str) -> None: 533 self._check_writable() 534 await self._ensure_open() 535 assert self._conn is not None 536 async with self._transaction(): 537 await self._conn.execute("DELETE FROM zarr WHERE k = ?", (key,))
Remove a key from the store
Parameters
- key (str):
539 @override 540 async def list(self) -> AsyncIterator[str]: 541 await self._ensure_open() 542 assert self._conn is not None 543 async for row in self._conn.fetch_iter("SELECT k FROM zarr"): 544 yield str(row[0])
Retrieve all keys in the store.
Returns
- AsyncIterator[str]
546 @override 547 async def list_prefix(self, prefix: str) -> AsyncIterator[str]: 548 await self._ensure_open() 549 assert self._conn is not None 550 params: Sequence[str] = () 551 if prefix == "": 552 sql = "SELECT k FROM zarr" 553 else: 554 params = self._get_text_boundaries(prefix) 555 sql = "SELECT k FROM zarr WHERE k > ? AND k < ?" 556 async for row in self._conn.fetch_iter(sql, params): 557 yield str(row[0])
Retrieve all keys in the store that begin with a given prefix. Keys are returned relative to the root of the store.
Parameters
- prefix (str):
Returns
- AsyncIterator[str]
559 @override 560 async def list_dir(self, prefix: str) -> AsyncIterator[str]: 561 # Even though prefix will be normalized in list_prefix(), this is 562 # required for the removeprefix(prefix) call used below. 563 if prefix != "" and not prefix[-1] == "/": 564 prefix += "/" 565 566 # _ensure_open is called in list_prefix() 567 seen: set[str] = set() 568 async for full_key in self.list_prefix(prefix): 569 rel_key = full_key.removeprefix(prefix) 570 parts = rel_key.split("/") 571 k = parts[0] 572 if len(parts) > 1: 573 k = k + "/" 574 if k not in seen: 575 seen.add(k) 576 yield k
Retrieve all keys and prefixes with a given prefix and which do not contain the character “/” after the given prefix.
Parameters
- prefix (str):
Returns
- AsyncIterator[str]
578 @override 579 async def delete_dir(self, prefix: str) -> None: 580 self._check_writable() 581 await self._ensure_open() 582 583 async with self._transaction(): 584 assert self._conn is not None 585 # Check if key exists 586 row = await self._conn.fetchone( 587 "SELECT v FROM zarr WHERE k = ?", (prefix.rstrip("/"),) 588 ) 589 if row is not None: 590 raise ValueError( 591 f"Cannot delete directory {prefix} as it is a key in the store." 592 ) 593 594 params: Sequence[str] = () 595 if prefix == "": 596 sql = "DELETE FROM zarr" 597 else: 598 params = self._get_text_boundaries(prefix) 599 sql = "DELETE FROM zarr WHERE k > ? AND k < ?" 600 await self._conn.execute(sql, params)
Remove all keys and prefixes in the store that begin with a given prefix.
602 @override 603 async def getsize(self, key: str) -> int: 604 _validate_key(key) 605 await self._ensure_open() 606 assert self._conn is not None 607 row = await self._conn.fetchone( 608 "SELECT LENGTH(v) FROM zarr WHERE k = ?", (key,) 609 ) 610 if row is None: 611 raise FileNotFoundError(key) 612 return int(row[0])
Return the size, in bytes, of a value in a Store.
Parameters
- key (str):
Returns
- nbytes (int): The size of the value (in bytes).
Raises
- FileNotFoundError: When the given key does not exist in the store.
614 @override 615 async def getsize_prefix(self, prefix: str) -> int: 616 await self._ensure_open() 617 assert self._conn is not None 618 params: Sequence[str] = () 619 if prefix == "": 620 sql = "SELECT SUM(LENGTH(v)) FROM zarr" 621 else: 622 params = self._get_text_boundaries(prefix) 623 sql = "SELECT SUM(LENGTH(v)) FROM zarr WHERE k > ? AND k < ?" 624 size_row = await self._conn.fetchone(sql, params) 625 if size_row is None or size_row[0] is None: 626 return 0 627 return int(size_row[0])
Return the size, in bytes, of all values under a prefix.
Parameters
- prefix (str): The prefix of the directory to measure.
Returns
- nbytes (int): The sum of the sizes of the values in the directory (in bytes).
See Also
zarr.Array.nbytes_stored
Store.getsize
Notes
getsize_prefix is just provided as a potentially faster alternative to
listing all the keys under a prefix calling [Store.getsize][zarr.abc.store.Store.getsize] on each.
In general, prefix should be the path of an Array or Group in the Store.
Implementations may differ on the behavior when some other prefix
is provided.