diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d325c98..7c0cd5e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,7 +1,9 @@ name: Tests on: - workflow_dispatch: # Manual trigger only to save CI minutes + workflow_dispatch: + pull_request: + branches: [main] jobs: test: @@ -12,8 +14,8 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macos-latest] # macos-latest is now Apple Silicon - python-version: ["3.10"] # Test only Python 3.10 (most common) + os: [ubuntu-latest, macos-15-intel, macos-15] # linux x86_64, mac intel, mac arm + python-version: ["3.10"] steps: - uses: actions/checkout@v5 @@ -29,14 +31,21 @@ jobs: sudo apt-get update sudo apt-get install -y gcc g++ make cmake + - name: Cache RocksDB dependencies + id: deps-cache + uses: actions/cache@v4 + with: + path: /tmp/rdbpy_deps + key: rdbpy-deps-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-rocksdb-*.sh', 'scripts/rocksdb-cstdint.patch') }} + - name: Build RocksDB dependencies (Linux) - if: runner.os == 'Linux' + if: runner.os == 'Linux' && steps.deps-cache.outputs.cache-hit != 'true' run: | export RDBPY_DEP_DIR=/tmp/rdbpy_deps bash scripts/build-rocksdb-linux.sh - name: Build RocksDB dependencies (macOS) - if: runner.os == 'macOS' + if: runner.os == 'macOS' && steps.deps-cache.outputs.cache-hit != 'true' run: | export RDBPY_DEP_DIR=/tmp/rdbpy_deps bash scripts/build-rocksdb-macos.sh diff --git a/README.md b/README.md index 62839bb..cb10a5a 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,125 @@ # rdbpy -Python bindings for RocksDB with Cython - **batteries included!** +Python bindings for RocksDB 6.29.5, written in Cython. Small surface, every +read path takes a snapshot, every blocking call releases the GIL, every +RocksDB status maps to a typed exception. -**No RocksDB installation required** - everything is bundled in the wheel for Linux and macOS (Intel + Apple Silicon). - -## Installation +**No RocksDB installation required**: wheels bundle RocksDB and the +compression libraries for Linux and macOS (Intel + Apple Silicon). ```bash pip install rdbpython ``` -That's it! No need to install RocksDB or any compression libraries manually. - ## Usage ```python import rdbpy -# Open database -options = rdbpy.Options(create_if_missing=True) -db = rdbpy.DB('/path/to/db', options) +db = rdbpy.DB("/path/to/db", rdbpy.Options(create_if_missing=True, compression="lz4")) +db.put(b"k1", b"v1") +db.get(b"k1") # b"v1"; None when missing +db.multi_get([b"k1", b"k2"]) +db.delete(b"k1") + +batch = rdbpy.WriteBatch() +batch.put(b"a", b"1") +batch.delete(b"b") +db.write(batch) + +# snapshots: a point-in-time view accepted by every read +with db.snapshot() as snap: + db.put(b"a", b"2") + db.get(b"a", snapshot=snap) # b"1" + list(db.iterator(snapshot=snap)) # rows as of the snapshot + +# iterators: bounds, prefix, direction, keys only, batched rows +for key, value in db.iterator(lower=b"a", upper=b"m"): + ... +for key in db.iterator(prefix=b"user:", reverse=True, keys_only=True): + ... +it = db.iterator() +while rows := it.next_batch(1000): # one native loop per batch, not per row + ... +it.seek(b"m"); it.valid(); it.key(); it.value(); it.next(); it.seek_for_prev(b"m") + +db.close() +``` -# Put/Get -db.put(b'key', b'value') -value = db.get(b'key') +### Transactions -# Iterate -it = db.iterkeys() -it.seek_to_first() -while it.valid(): - print(it.key()) - it.next() +```python +db = rdbpy.TransactionDB(path, rdbpy.Options(create_if_missing=True), lock_timeout_ms=1000) + +txn = db.begin(set_snapshot=True, deadlock_detect=True) +txn.get(b"a") # reads at the txn snapshot, merges own writes +txn.get_for_update(b"a") # locks the row; Busy if it changed after the snapshot +txn.put(b"a", b"1") # locks the row; TimedOut after lock_timeout_ms +txn.delete(b"b") +for k, v in txn.iterator(prefix=b"a"): + ... +txn.commit() # or txn.rollback(); both end the transaction + +odb = rdbpy.OptimisticTransactionDB(path) +txn = odb.begin() +txn.get_for_update(b"n") # tracked read: commit fails with Busy if it changes +txn.put(b"n", b"1") +txn.commit() ``` +Pessimistic (`TransactionDB`): `put`, `delete`, `get_for_update` take row locks +and raise `TimedOut` when the wait exceeds `lock_timeout_ms` (per DB or per +`begin`), `Deadlock` when `deadlock_detect=True` finds a cycle, `Busy` when a +key changed after the transaction's snapshot. Optimistic +(`OptimisticTransactionDB`): no locks, `commit()` raises `Busy` when a written +or tracked key changed. It keeps memtable history by default +(`max_write_buffer_size_to_maintain=0` becomes `-1`), so a commit after a flush +does not fail with `TryAgain`. `get_for_update(validate=False)` reads latest and +skips the check; combining it with `snapshot=` raises `ValueError`. + +### Errors + +All exceptions derive from `rdbpy.RocksDBError` (`.code`, `.subcode`, +`.message`). Transaction outcomes: `Busy`, `Deadlock` (a `Busy`), `TimedOut`, +`TryAgain`, `Expired`, `LockLimit`. Others: `Corruption`, `RocksIOError`, +`InvalidArgument`, `NotSupported`, `Incomplete`, `Aborted`, ... A missing key +is `None`, never an exception. + ## Lifetimes and threads -Iterators, snapshots and transactions point into native state owned by their parent: +Iterators, snapshots and transactions point into native state owned by their +parent: + +- `Transaction.commit()` / `rollback()` end the transaction and invalidate + every iterator and snapshot view created from it. A failed commit is rolled + back. +- `DB.close()` invalidates every iterator and snapshot of the DB and rolls + back any transaction still open. +- Using an invalidated object raises `RuntimeError`. Dropping one is safe, in + any order, including when gc frees it. -- `Transaction.commit()`, `rollback()`, `close()` and a successful `rollback_to_save_point()` invalidate every iterator created from that transaction. So does `TransactionDB.begin_transaction(reuse=txn)`. -- `DB.close()` / `TransactionDB.close()` invalidate every iterator and snapshot of the DB and roll back any transaction that is still open. -- Using an invalidated iterator, or a DB after `close()`, raises `RuntimeError`. Dropping an invalidated object is safe, in any order, including when gc frees it. +Threads: rdbpy does no locking of its own and releases the GIL inside RocksDB +calls, so several threads can read and write the same DB concurrently (RocksDB +is thread safe). Child objects are different: -Threads: a transaction and its iterators belong to one thread and must not be shared between threads. rdbpy does no locking of its own and releases the GIL inside RocksDB calls, so ending a transaction, or closing a DB, while another thread is still inside a call on it or on its iterators is undefined behaviour and can crash. Close a DB only after every thread is done with it. A finalizer (a generator's `finally`, `__del__`) that ends a transaction runs on whichever thread triggers gc, so it counts as using the transaction from that thread. gc merely freeing objects on another thread is safe. +- `Snapshot`, `Iterator`, `Transaction` and `WriteBatch` are used by one thread + at a time. Do not close, release, commit or roll back one from a thread while + another thread is using it: that is a use after free. +- `DB.close()` raises `RuntimeError` while another thread is inside a call on + the DB, so stop the workers before closing. ## Development ```bash -# Setup -make install - -# Build -make build - -# Test -make test +uv venv && uv pip install -e . pytest # needs RDBPY_DEP_DIR, see below +RDBPY_DEP_DIR=~/opt/rocksdb-6.29.5 python setup.py build_ext --inplace +pytest tests ``` +`RDBPY_DEP_DIR` points at a prefix with RocksDB 6.29.5 and the compression +libraries (`scripts/build-rocksdb-linux.sh` / `-macos.sh` build one). The +extension is linked with an rpath to `$RDBPY_DEP_DIR/lib`. + ## License Apache-2.0 diff --git a/bench/benchmark_raw.py b/bench/benchmark_raw.py index 176495f..78c7aed 100644 --- a/bench/benchmark_raw.py +++ b/bench/benchmark_raw.py @@ -1,61 +1,43 @@ -"""Benchmark raw rdbpy CPython bindings. - -Tests common KV store operations directly on rdbpy: -- put (set) -- get -- exists (get != None) -- iterator scan - -Usage: - python examples/benchmark_rdbpy_raw.py [--num-keys N] [--value-size S] +"""Raw rdbpy throughput: txn put/get, scans (per row and batched), batch write, +direct get. Run: python bench/benchmark_raw.py --num-keys 100000 """ -from __future__ import annotations - import argparse import shutil import time +from collections.abc import Callable from pathlib import Path -from typing import TYPE_CHECKING import rdbpy -if TYPE_CHECKING: - from collections.abc import Callable - - def format_ops_per_sec(ops: int, elapsed: float) -> str: - """Format operations per second.""" - if elapsed == 0: + if elapsed <= 0: return "inf" - return f"{ops / elapsed:,.0f}" + rate = ops / elapsed + if rate >= 1_000_000: + return f"{rate / 1_000_000:.2f}M" + if rate >= 1_000: + return f"{rate / 1_000:.1f}K" + return f"{rate:.0f}" + +def benchmark(func: Callable[[], int]) -> tuple[float, int]: + t0 = time.perf_counter() + ops = func() + return time.perf_counter() - t0, ops -def benchmark(_name: str, func: Callable[[], int], iterations: int = 1) -> tuple[float, int]: - """Run a benchmark and return elapsed time and operation count.""" - total_ops = 0 - start = time.perf_counter() - for _ in range(iterations): - total_ops += func() - elapsed = time.perf_counter() - start - return elapsed, total_ops + +def report(name: str, elapsed: float, ops: int) -> None: + print(f"{name:<18}{elapsed:8.3f}s | {format_ops_per_sec(ops, elapsed):>10} ops/s") def run_benchmarks(num_keys: int, value_size: int, db_path: Path) -> None: - """Run all benchmarks.""" - # Clean up any existing db if db_path.exists(): shutil.rmtree(db_path) db_path.mkdir(parents=True, exist_ok=True) - # Create options - options = rdbpy.Options(create_if_missing=True) - - # Open database (path, options) - db = rdbpy.TransactionDB(str(db_path), options) - - # Prepare test data + db = rdbpy.TransactionDB(str(db_path), rdbpy.Options(create_if_missing=True)) keys = [f"key:{i:08d}".encode() for i in range(num_keys)] value = b"x" * value_size @@ -63,98 +45,70 @@ def run_benchmarks(num_keys: int, value_size: int, db_path: Path) -> None: print(f"Keys: {num_keys:,}, Value size: {value_size} bytes") print("-" * 60) - # ========================================================================= - # PUT benchmark (sequential writes in transaction) - # ========================================================================= def bench_put() -> int: - txn = db.begin_transaction() + txn = db.begin() for key in keys: txn.put(key, value) txn.commit() return len(keys) - elapsed, ops = benchmark("put", bench_put) - print(f"put (txn): {elapsed:.3f}s | {format_ops_per_sec(ops, elapsed):>12} ops/s") + report("put (txn)", *benchmark(bench_put)) - # ========================================================================= - # GET benchmark (sequential reads in transaction) - # ========================================================================= def bench_get() -> int: - txn = db.begin_transaction() + txn = db.begin() for key in keys: - _ = txn.get(key) + txn.get(key) txn.rollback() return len(keys) - elapsed, ops = benchmark("get", bench_get) - print(f"get (txn): {elapsed:.3f}s | {format_ops_per_sec(ops, elapsed):>12} ops/s") + report("get (txn)", *benchmark(bench_get)) - # ========================================================================= - # EXISTS benchmark (check if key exists) - # ========================================================================= - def bench_exists() -> int: - txn = db.begin_transaction() + def bench_get_for_update() -> int: + txn = db.begin() for key in keys: - _ = txn.get(key) is not None + txn.get_for_update(key) txn.rollback() return len(keys) - elapsed, ops = benchmark("exists", bench_exists) - print(f"exists (txn): {elapsed:.3f}s | {format_ops_per_sec(ops, elapsed):>12} ops/s") + report("get_for_update", *benchmark(bench_get_for_update)) - # ========================================================================= - # ITERATOR KEYS benchmark (scan all keys) - # ========================================================================= def bench_iter_keys() -> int: - txn = db.begin_transaction() - it = txn.iterkeys() - it.seek_to_first() - count = 0 - while True: - try: - _ = it.get() - count += 1 - it.skip() - except (ValueError, IndexError): - break + txn = db.begin() + n = sum(1 for _ in txn.iterator(keys_only=True)) txn.rollback() - return count + return n - elapsed, ops = benchmark("iter_keys", bench_iter_keys) - print(f"iter keys: {elapsed:.3f}s | {format_ops_per_sec(ops, elapsed):>12} ops/s") + report("iter keys", *benchmark(bench_iter_keys)) - # ========================================================================= - # ITERATOR ITEMS benchmark (scan all key-value pairs) - # ========================================================================= def bench_iter_items() -> int: - txn = db.begin_transaction() - it = txn.iteritems() - it.seek_to_first() - count = 0 + n = sum(1 for _ in db.iterator()) + return n + + report("iter items", *benchmark(bench_iter_items)) + + def bench_iter_batched() -> int: + it = db.iterator() + n = 0 while True: - try: - _ = it.get() - count += 1 - it.skip() - except (ValueError, IndexError): + rows = it.next_batch(1000) + if not rows: break - txn.rollback() - return count + n += len(rows) + return n - elapsed, ops = benchmark("iter_items", bench_iter_items) - print(f"iter items: {elapsed:.3f}s | {format_ops_per_sec(ops, elapsed):>12} ops/s") + report("iter next_batch", *benchmark(bench_iter_batched)) - # ========================================================================= - # BATCH WRITE benchmark (using WriteBatch) - # ========================================================================= - # First delete all keys so we can test batch insert - txn = db.begin_transaction() - for key in keys: - try: - txn.delete_single(key) - except Exception as e: - print(e) + def bench_snapshot_get() -> int: + with db.snapshot() as snap: + for key in keys: + db.get(key, snapshot=snap) + return len(keys) + + report("get (snapshot)", *benchmark(bench_snapshot_get)) + txn = db.begin() + for key in keys: + txn.delete(key) txn.commit() def bench_batch_put() -> int: @@ -164,40 +118,36 @@ def bench_batch_put() -> int: db.write(batch) return len(keys) - elapsed, ops = benchmark("batch_put", bench_batch_put) - print(f"batch put: {elapsed:.3f}s | {format_ops_per_sec(ops, elapsed):>12} ops/s") + report("batch put", *benchmark(bench_batch_put)) - # ========================================================================= - # Direct DB GET benchmark (no transaction overhead) - # ========================================================================= def bench_direct_get() -> int: for key in keys: - _ = db.get(key) + db.get(key) return len(keys) - elapsed, ops = benchmark("direct_get", bench_direct_get) - print(f"get (direct): {elapsed:.3f}s | {format_ops_per_sec(ops, elapsed):>12} ops/s") + report("get (direct)", *benchmark(bench_direct_get)) - print("-" * 60) + def bench_commits() -> int: + n = min(num_keys, 10_000) + for key in keys[:n]: + txn = db.begin() + txn.put(key, value) + txn.commit() + return n + + report("commit (1 put)", *benchmark(bench_commits)) - # Cleanup + print("-" * 60) db.close() shutil.rmtree(db_path) def main() -> None: - """Main entry point.""" parser = argparse.ArgumentParser(description="Benchmark raw rdbpy bindings") - parser.add_argument("--num-keys", type=int, default=100_000, help="Number of keys to test") - parser.add_argument("--value-size", type=int, default=100, help="Size of values in bytes") - parser.add_argument( - "--db-path", - type=Path, - default=Path(".bench_rdbpy_raw"), - help="Database path", - ) + parser.add_argument("--num-keys", type=int, default=100_000) + parser.add_argument("--value-size", type=int, default=100) + parser.add_argument("--db-path", type=Path, default=Path(".bench_rdbpy_raw")) args = parser.parse_args() - run_benchmarks(args.num_keys, args.value_size, args.db_path) diff --git a/pyproject.toml b/pyproject.toml index eeab921..acb8732 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta" # ============================================================================ [project] name = "rdbpython" -version = "0.2.7" +version = "0.3.0" description = "Python bindings for RocksDB with Cython" readme = "README.md" license = "Apache-2.0" diff --git a/scripts/build-rocksdb-linux.sh b/scripts/build-rocksdb-linux.sh index eb42e3a..825c1e4 100755 --- a/scripts/build-rocksdb-linux.sh +++ b/scripts/build-rocksdb-linux.sh @@ -46,8 +46,11 @@ fi # Compiler flags export CFLAGS="-fPIC -O3" export CXXFLAGS="-fPIC -O3" -export LDFLAGS="-Wl,-rpath,'\$ORIGIN'" export PREFIX="$RDBPY_DEP_DIR" +# Only librocksdb needs an rpath (its compression libs sit next to it). It goes +# through make, which expands `$O`, so `$$` keeps a literal $ORIGIN; the quotes +# stop the shell. A global LDFLAGS used to end up as the runpath "RIGIN". +ROCKSDB_LDFLAGS="-Wl,-rpath,'\$\$ORIGIN'" # ============================================================================== # Build zlib @@ -162,7 +165,7 @@ make static_lib shared_lib -j$(nproc) \ DISABLE_WARNING_AS_ERROR=1 \ DEBUG_LEVEL=0 \ EXTRA_CXXFLAGS="$CXXFLAGS -include cstdint" \ - EXTRA_LDFLAGS="$LDFLAGS" + EXTRA_LDFLAGS="$ROCKSDB_LDFLAGS" # Install cp librocksdb.a "$PREFIX/lib/" diff --git a/src/rdbpy/__init__.py b/src/rdbpy/__init__.py index f80f781..e5fdbc7 100644 --- a/src/rdbpy/__init__.py +++ b/src/rdbpy/__init__.py @@ -1 +1,69 @@ -from .lib_rocksdb import * +"""rdbpy: Python bindings for RocksDB 6.29.5.""" + +from rdbpy._core import ( + DB, + Iterator, + OptimisticTransactionDB, + Options, + Snapshot, + Transaction, + TransactionDB, + WriteBatch, + destroy_db, + next_prefix, + rocksdb_version, +) +from rdbpy.errors import ( + Aborted, + Busy, + ColumnFamilyDropped, + CompactionTooLarge, + Corruption, + Deadlock, + Expired, + Incomplete, + InvalidArgument, + LockLimit, + MergeInProgress, + NotFound, + NotSupported, + RocksDBError, + RocksIOError, + ShutdownInProgress, + TimedOut, + TryAgain, +) + +__version__ = "0.3.0" + +__all__ = [ + "DB", + "TransactionDB", + "OptimisticTransactionDB", + "Transaction", + "Snapshot", + "Iterator", + "WriteBatch", + "Options", + "destroy_db", + "next_prefix", + "rocksdb_version", + "RocksDBError", + "NotFound", + "Corruption", + "NotSupported", + "InvalidArgument", + "RocksIOError", + "MergeInProgress", + "Incomplete", + "ShutdownInProgress", + "TimedOut", + "Aborted", + "LockLimit", + "Busy", + "Deadlock", + "Expired", + "TryAgain", + "CompactionTooLarge", + "ColumnFamilyDropped", +] diff --git a/src/rdbpy/_core.pyi b/src/rdbpy/_core.pyi new file mode 100644 index 0000000..4e6bb11 --- /dev/null +++ b/src/rdbpy/_core.pyi @@ -0,0 +1,331 @@ +"""Type stubs for rdbpy._core.""" + +from collections.abc import Iterable +from os import PathLike +from typing import Literal + +StrPath = str | bytes | PathLike[str] | PathLike[bytes] +Compression = Literal["none", "snappy", "zlib", "bz2", "lz4", "lz4hc", "zstd"] +CompactionStyle = Literal["level", "universal", "fifo"] + +def next_prefix(prefix: bytes) -> bytes | None: ... +def destroy_db(path: StrPath, options: Options | None = None) -> None: ... +def rocksdb_version() -> str: ... + +class Options: + def __init__( + self, + *, + create_if_missing: bool = ..., + error_if_exists: bool = ..., + paranoid_checks: bool = ..., + max_open_files: int = ..., + use_fsync: bool = ..., + wal_dir: StrPath = ..., + db_log_dir: StrPath = ..., + max_background_jobs: int = ..., + max_log_file_size: int = ..., + keep_log_file_num: int = ..., + max_total_wal_size: int = ..., + db_write_buffer_size: int = ..., + allow_mmap_reads: bool = ..., + allow_mmap_writes: bool = ..., + use_direct_reads: bool = ..., + use_direct_io_for_flush_and_compaction: bool = ..., + bytes_per_sync: int = ..., + wal_bytes_per_sync: int = ..., + allow_concurrent_memtable_write: bool = ..., + manual_wal_flush: bool = ..., + avoid_unnecessary_blocking_io: bool = ..., + atomic_flush: bool = ..., + wal_ttl_seconds: int = ..., + wal_size_limit_mb: int = ..., + write_buffer_size: int = ..., + max_write_buffer_number: int = ..., + min_write_buffer_number_to_merge: int = ..., + max_write_buffer_size_to_maintain: int = ..., + compression: Compression | int = ..., + bottommost_compression: Compression | int = ..., + num_levels: int = ..., + level0_file_num_compaction_trigger: int = ..., + level0_slowdown_writes_trigger: int = ..., + level0_stop_writes_trigger: int = ..., + target_file_size_base: int = ..., + target_file_size_multiplier: int = ..., + max_bytes_for_level_base: int = ..., + max_bytes_for_level_multiplier: float = ..., + level_compaction_dynamic_level_bytes: bool = ..., + disable_auto_compactions: bool = ..., + compaction_style: CompactionStyle = ..., + max_compaction_bytes: int = ..., + optimize_filters_for_hits: bool = ..., + memtable_prefix_bloom_size_ratio: float = ..., + prefix_extractor_len: int = ..., + block_cache_size: int | None = ..., + block_size: int = ..., + block_restart_interval: int = ..., + bloom_bits_per_key: float = ..., + cache_index_and_filter_blocks: bool = ..., + pin_l0_filter_and_index_blocks_in_cache: bool = ..., + pin_top_level_index_and_filter: bool = ..., + partition_filters: bool = ..., + whole_key_filtering: bool = ..., + format_version: int = ..., + optimize_filters_for_memory: bool = ..., + ) -> None: ... + create_if_missing: bool + error_if_exists: bool + paranoid_checks: bool + max_open_files: int + use_fsync: bool + wal_dir: str + db_log_dir: str + max_background_jobs: int + max_log_file_size: int + keep_log_file_num: int + max_total_wal_size: int + db_write_buffer_size: int + allow_mmap_reads: bool + allow_mmap_writes: bool + use_direct_reads: bool + use_direct_io_for_flush_and_compaction: bool + bytes_per_sync: int + wal_bytes_per_sync: int + allow_concurrent_memtable_write: bool + manual_wal_flush: bool + avoid_unnecessary_blocking_io: bool + atomic_flush: bool + wal_ttl_seconds: int + wal_size_limit_mb: int + write_buffer_size: int + max_write_buffer_number: int + min_write_buffer_number_to_merge: int + max_write_buffer_size_to_maintain: int + compression: str + bottommost_compression: str + num_levels: int + level0_file_num_compaction_trigger: int + level0_slowdown_writes_trigger: int + level0_stop_writes_trigger: int + target_file_size_base: int + target_file_size_multiplier: int + max_bytes_for_level_base: int + max_bytes_for_level_multiplier: float + level_compaction_dynamic_level_bytes: bool + disable_auto_compactions: bool + compaction_style: str + max_compaction_bytes: int + optimize_filters_for_hits: bool + memtable_prefix_bloom_size_ratio: float + prefix_extractor_len: int + block_cache_size: int | None + block_size: int + block_restart_interval: int + bloom_bits_per_key: float + cache_index_and_filter_blocks: bool + pin_l0_filter_and_index_blocks_in_cache: bool + pin_top_level_index_and_filter: bool + partition_filters: bool + whole_key_filtering: bool + format_version: int + optimize_filters_for_memory: bool + +class WriteBatch: + """Batched writes applied atomically by DB.write(). + + One thread at a time: do not close, release or end it from one thread + while another thread is using it. + """ + + def put(self, key: bytes, value: bytes) -> None: ... + def delete(self, key: bytes) -> None: ... + def single_delete(self, key: bytes) -> None: ... + def clear(self) -> None: ... + def count(self) -> int: ... + def __len__(self) -> int: ... + +class Snapshot: + """Point-in-time read view; release() frees it, DB.close() invalidates it. + + One thread at a time: do not close, release or end it from one thread + while another thread is using it. + """ + + def release(self) -> None: ... + @property + def released(self) -> bool: ... + @property + def sequence(self) -> int: ... + def __enter__(self) -> Snapshot: ... + def __exit__(self, *exc: object) -> bool: ... + +class Iterator: + """Cursor over a DB or transaction; invalidated when its parent ends. + + One thread at a time: do not close, release or end it from one thread + while another thread is using it. + """ + + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def __enter__(self) -> Iterator: ... + def __exit__(self, *exc: object) -> bool: ... + def seek(self, key: bytes) -> None: ... + def seek_for_prev(self, key: bytes) -> None: ... + def seek_to_first(self) -> None: ... + def seek_to_last(self) -> None: ... + def valid(self) -> bool: ... + def key(self) -> bytes: ... + def value(self) -> bytes: ... + def item(self) -> tuple[bytes, bytes]: ... + def next(self) -> None: ... + def prev(self) -> None: ... + def status(self) -> None: ... + def __iter__(self) -> Iterator: ... + def __next__(self) -> bytes | tuple[bytes, bytes]: ... + def next_batch(self, n: int = 1000) -> list[bytes] | list[tuple[bytes, bytes]]: ... + +class DB: + path: str + options: Options + def __init__( + self, + path: StrPath, + options: Options | None = None, + *, + read_only: bool = False, + secondary_path: StrPath | None = None, + ) -> None: ... + def close(self) -> None: + """Close the DB, invalidating its iterators and snapshots and rolling back + open transactions. Raises RuntimeError while another thread is inside a + call on this DB.""" + @property + def closed(self) -> bool: ... + def __enter__(self) -> DB: ... + def __exit__(self, *exc: object) -> bool: ... + def get(self, key: bytes, *, snapshot: Snapshot | None = None) -> bytes | None: ... + def multi_get( + self, keys: Iterable[bytes], *, snapshot: Snapshot | None = None + ) -> list[bytes | None]: ... + def snapshot(self) -> Snapshot: ... + def iterator( + self, + *, + snapshot: Snapshot | None = None, + lower: bytes | None = None, + upper: bytes | None = None, + prefix: bytes | None = None, + reverse: bool = False, + keys_only: bool = False, + fill_cache: bool = True, + ) -> Iterator: ... + @property + def latest_sequence_number(self) -> int: ... + def get_property(self, name: str | bytes) -> str | None: ... + def put(self, key: bytes, value: bytes, *, sync: bool = False, disable_wal: bool = False) -> None: ... + def delete(self, key: bytes, *, sync: bool = False, disable_wal: bool = False) -> None: ... + def write(self, batch: WriteBatch, *, sync: bool = False, disable_wal: bool = False) -> None: ... + def flush(self, *, wait: bool = True) -> None: ... + def flush_wal(self, *, sync: bool = False) -> None: ... + def compact_range(self, begin: bytes | None = None, end: bytes | None = None) -> None: ... + def try_catch_up_with_primary(self) -> None: ... + +class Transaction: + """A transaction from TransactionDB.begin() or OptimisticTransactionDB.begin(). + + One thread at a time: do not close, release or end it from one thread + while another thread is using it. + commit()/rollback() also invalidate its iterators and snapshot views. + """ + + optimistic: bool + @property + def active(self) -> bool: ... + @property + def committed(self) -> bool: ... + @property + def id(self) -> int: ... + @property + def num_keys(self) -> int: ... + def __enter__(self) -> Transaction: ... + def __exit__(self, *exc: object) -> bool: ... + def set_snapshot(self) -> None: ... + def clear_snapshot(self) -> None: ... + @property + def snapshot(self) -> Snapshot | None: ... + def get(self, key: bytes, *, snapshot: Snapshot | None = None) -> bytes | None: ... + def get_for_update( + self, + key: bytes, + *, + exclusive: bool = True, + snapshot: Snapshot | None = None, + validate: bool = True, + ) -> bytes | None: + """Read and lock (pessimistic) or track (optimistic) the key. + + validate=False reads latest and skips the conflict check; passing + snapshot= with it raises ValueError. + """ + def iterator( + self, + *, + snapshot: Snapshot | None = None, + lower: bytes | None = None, + upper: bytes | None = None, + prefix: bytes | None = None, + reverse: bool = False, + keys_only: bool = False, + fill_cache: bool = True, + ) -> Iterator: ... + def put(self, key: bytes, value: bytes) -> None: ... + def delete(self, key: bytes) -> None: ... + def single_delete(self, key: bytes) -> None: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + +class TransactionDB(DB): + def __init__( + self, + path: StrPath, + options: Options | None = None, + *, + lock_timeout_ms: int = 1000, + default_lock_timeout_ms: int = 1000, + max_num_locks: int = -1, + num_stripes: int = 16, + max_num_deadlocks: int = 5, + ) -> None: ... + def begin( + self, + *, + set_snapshot: bool = False, + sync: bool = False, + disable_wal: bool = False, + lock_timeout_ms: int | None = None, + deadlock_detect: bool = False, + deadlock_detect_depth: int | None = None, + expiration_ms: int | None = None, + ) -> Transaction: ... + +class OptimisticTransactionDB(DB): + """Optimistic transactions: no locks, conflicts surface at commit as Busy. + + When options leave max_write_buffer_size_to_maintain at 0, memtable history + of max_write_buffer_number * write_buffer_size is kept so commits after a + flush still validate instead of raising TryAgain. + """ + + def __init__( + self, + path: StrPath, + options: Options | None = None, + *, + validate_policy: Literal["parallel", "serial"] = "parallel", + occ_lock_buckets: int | None = None, + ) -> None: ... + def begin( + self, *, set_snapshot: bool = False, sync: bool = False, disable_wal: bool = False + ) -> Transaction: ... diff --git a/src/rdbpy/_core.pyx b/src/rdbpy/_core.pyx new file mode 100644 index 0000000..8289791 --- /dev/null +++ b/src/rdbpy/_core.pyx @@ -0,0 +1,1664 @@ +# distutils: language = c++ +# cython: language_level=3 +"""rdbpy core: a small Cython binding over RocksDB 6.29.5. + +Shape: DB / TransactionDB / OptimisticTransactionDB, Transaction, Snapshot, +Iterator, WriteBatch, Options. Every read path takes a snapshot, every +blocking RocksDB call runs without the GIL, every non-ok status becomes a +typed exception (see rdbpy.errors). + +Lifetime rules (iterators, snapshots, transactions point into native state +owned by their parent): a parent records each live child's address in a set +(an int, no reference cycle) and frees the children's native state before +its own. A child drops its entry when it is freed. Children are no_gc_clear +so they can still reach the parent in __dealloc__. Registries are walked +with set.pop() so no gc can run between taking an entry and freeing it. +""" +import cython +import os + +from cpython.bytes cimport PyBytes_AS_STRING, PyBytes_GET_SIZE, PyBytes_FromStringAndSize +from libc.stddef cimport size_t +from libc.stdint cimport int64_t, uint32_t, uint64_t +from libcpp cimport bool as cpp_bool +from libcpp.string cimport string +from libcpp.vector cimport vector + +cimport rdbpy._rocksdb as r + +from rdbpy import errors + + +# ---------------------------------------------------------------------------- +# helpers +# ---------------------------------------------------------------------------- + +cdef inline size_t _addr(object ob): + return ob + + +cdef inline r.Slice _slice(bytes b): + return r.Slice(PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b)) + + +cdef inline bytes _bytes(const r.Slice& s): + return PyBytes_FromStringAndSize(s.data(), s.size()) + + +cdef inline string _path(object path) except *: + return os.fsencode(path) + + +cdef inline int _check(const r.Status& st) except -1: + if st.ok(): + return 0 + raise errors.error_for( + r.status_code(st), r.status_subcode(st), st.ToString().decode("utf-8", "replace") + ) + + +cdef inline cpp_bool _is_not_found(const r.Status& st) nogil: + return r.status_code(st) == 1 + + +# In-flight native calls per DB. Taken with the GIL held around every +# `with nogil` block that touches the DB or its children, so close() can +# refuse instead of freeing state another thread is still inside. +cdef inline void _busy(DB db) noexcept: + db._inflight += 1 + + +cdef inline void _idle(DB db) noexcept: + db._inflight -= 1 + + +_COMPRESSION = { + "none": r.kNoCompression, + "snappy": r.kSnappyCompression, + "zlib": r.kZlibCompression, + "bz2": r.kBZip2Compression, + "lz4": r.kLZ4Compression, + "lz4hc": r.kLZ4HCCompression, + "zstd": r.kZSTD, +} +_COMPRESSION_NAMES = {v: k for k, v in _COMPRESSION.items()} + +_COMPACTION = { + "level": r.kCompactionStyleLevel, + "universal": r.kCompactionStyleUniversal, + "fifo": r.kCompactionStyleFIFO, +} +_COMPACTION_NAMES = {v: k for k, v in _COMPACTION.items()} + + +def next_prefix(bytes prefix not None): + """Smallest byte string greater than every string starting with `prefix`, + or None when there is none (prefix empty or all 0xff).""" + cdef bytearray b = bytearray(prefix) + cdef Py_ssize_t n = len(b) + while n > 0 and b[n - 1] == 0xFF: + n -= 1 + if n == 0: + return None + del b[n:] + b[n - 1] += 1 + return bytes(b) + + +# ---------------------------------------------------------------------------- +# Options +# ---------------------------------------------------------------------------- + +cdef class Options: + """DB options plus the block-based table options virtuals tunes. + + All fields are keyword arguments and read/write properties. Table-level + fields (block_cache_size, block_size, bloom_bits_per_key, ...) build one + BlockBasedTableFactory when the DB opens. + """ + cdef r.Options opts + cdef r.BlockBasedTableOptions bbto + cdef bint bbto_set + cdef double _bloom_bits + cdef object _block_cache_size + cdef size_t _prefix_len + + def __cinit__(self): + self.bbto_set = False + self._bloom_bits = 0.0 + self._block_cache_size = None + self._prefix_len = 0 + + def __init__(self, **kwargs): + for name, value in kwargs.items(): + if not hasattr(type(self), name): + raise TypeError("unknown option %r" % name) + setattr(self, name, value) + + cdef void _finalize(self) except *: + if self.bbto_set: + r.opts_set_table_factory(self.opts, self.bbto) + + # --- DBOptions --- + @property + def create_if_missing(self): return self.opts.create_if_missing + @create_if_missing.setter + def create_if_missing(self, bint v): self.opts.create_if_missing = v + + @property + def error_if_exists(self): return self.opts.error_if_exists + @error_if_exists.setter + def error_if_exists(self, bint v): self.opts.error_if_exists = v + + @property + def paranoid_checks(self): return self.opts.paranoid_checks + @paranoid_checks.setter + def paranoid_checks(self, bint v): self.opts.paranoid_checks = v + + @property + def max_open_files(self): return self.opts.max_open_files + @max_open_files.setter + def max_open_files(self, int v): self.opts.max_open_files = v + + @property + def use_fsync(self): return self.opts.use_fsync + @use_fsync.setter + def use_fsync(self, bint v): self.opts.use_fsync = v + + @property + def wal_dir(self): return os.fsdecode(self.opts.wal_dir) + @wal_dir.setter + def wal_dir(self, v): self.opts.wal_dir = _path(v) + + @property + def db_log_dir(self): return os.fsdecode(self.opts.db_log_dir) + @db_log_dir.setter + def db_log_dir(self, v): self.opts.db_log_dir = _path(v) + + @property + def max_background_jobs(self): return self.opts.max_background_jobs + @max_background_jobs.setter + def max_background_jobs(self, int v): self.opts.max_background_jobs = v + + @property + def max_log_file_size(self): return self.opts.max_log_file_size + @max_log_file_size.setter + def max_log_file_size(self, size_t v): self.opts.max_log_file_size = v + + @property + def keep_log_file_num(self): return self.opts.keep_log_file_num + @keep_log_file_num.setter + def keep_log_file_num(self, size_t v): self.opts.keep_log_file_num = v + + @property + def max_total_wal_size(self): return self.opts.max_total_wal_size + @max_total_wal_size.setter + def max_total_wal_size(self, uint64_t v): self.opts.max_total_wal_size = v + + @property + def db_write_buffer_size(self): return self.opts.db_write_buffer_size + @db_write_buffer_size.setter + def db_write_buffer_size(self, size_t v): self.opts.db_write_buffer_size = v + + @property + def allow_mmap_reads(self): return self.opts.allow_mmap_reads + @allow_mmap_reads.setter + def allow_mmap_reads(self, bint v): self.opts.allow_mmap_reads = v + + @property + def allow_mmap_writes(self): return self.opts.allow_mmap_writes + @allow_mmap_writes.setter + def allow_mmap_writes(self, bint v): self.opts.allow_mmap_writes = v + + @property + def use_direct_reads(self): return self.opts.use_direct_reads + @use_direct_reads.setter + def use_direct_reads(self, bint v): self.opts.use_direct_reads = v + + @property + def use_direct_io_for_flush_and_compaction(self): return self.opts.use_direct_io_for_flush_and_compaction + @use_direct_io_for_flush_and_compaction.setter + def use_direct_io_for_flush_and_compaction(self, bint v): self.opts.use_direct_io_for_flush_and_compaction = v + + @property + def bytes_per_sync(self): return self.opts.bytes_per_sync + @bytes_per_sync.setter + def bytes_per_sync(self, uint64_t v): self.opts.bytes_per_sync = v + + @property + def wal_bytes_per_sync(self): return self.opts.wal_bytes_per_sync + @wal_bytes_per_sync.setter + def wal_bytes_per_sync(self, uint64_t v): self.opts.wal_bytes_per_sync = v + + @property + def allow_concurrent_memtable_write(self): return self.opts.allow_concurrent_memtable_write + @allow_concurrent_memtable_write.setter + def allow_concurrent_memtable_write(self, bint v): self.opts.allow_concurrent_memtable_write = v + + @property + def manual_wal_flush(self): return self.opts.manual_wal_flush + @manual_wal_flush.setter + def manual_wal_flush(self, bint v): self.opts.manual_wal_flush = v + + @property + def avoid_unnecessary_blocking_io(self): return self.opts.avoid_unnecessary_blocking_io + @avoid_unnecessary_blocking_io.setter + def avoid_unnecessary_blocking_io(self, bint v): self.opts.avoid_unnecessary_blocking_io = v + + @property + def atomic_flush(self): return self.opts.atomic_flush + @atomic_flush.setter + def atomic_flush(self, bint v): self.opts.atomic_flush = v + + @property + def wal_ttl_seconds(self): return self.opts.WAL_ttl_seconds + @wal_ttl_seconds.setter + def wal_ttl_seconds(self, uint64_t v): self.opts.WAL_ttl_seconds = v + + @property + def wal_size_limit_mb(self): return self.opts.WAL_size_limit_MB + @wal_size_limit_mb.setter + def wal_size_limit_mb(self, uint64_t v): self.opts.WAL_size_limit_MB = v + + # --- ColumnFamilyOptions --- + @property + def write_buffer_size(self): return self.opts.write_buffer_size + @write_buffer_size.setter + def write_buffer_size(self, size_t v): self.opts.write_buffer_size = v + + @property + def max_write_buffer_number(self): return self.opts.max_write_buffer_number + @max_write_buffer_number.setter + def max_write_buffer_number(self, int v): self.opts.max_write_buffer_number = v + + @property + def min_write_buffer_number_to_merge(self): return self.opts.min_write_buffer_number_to_merge + @min_write_buffer_number_to_merge.setter + def min_write_buffer_number_to_merge(self, int v): self.opts.min_write_buffer_number_to_merge = v + + @property + def max_write_buffer_size_to_maintain(self): return self.opts.max_write_buffer_size_to_maintain + @max_write_buffer_size_to_maintain.setter + def max_write_buffer_size_to_maintain(self, int64_t v): self.opts.max_write_buffer_size_to_maintain = v + + @property + def compression(self): return _COMPRESSION_NAMES.get(self.opts.compression, "unknown") + @compression.setter + def compression(self, v): + self.opts.compression = _compression_value(v) + + @property + def bottommost_compression(self): return _COMPRESSION_NAMES.get(self.opts.bottommost_compression, "unknown") + @bottommost_compression.setter + def bottommost_compression(self, v): + self.opts.bottommost_compression = _compression_value(v) + + @property + def num_levels(self): return self.opts.num_levels + @num_levels.setter + def num_levels(self, int v): self.opts.num_levels = v + + @property + def level0_file_num_compaction_trigger(self): return self.opts.level0_file_num_compaction_trigger + @level0_file_num_compaction_trigger.setter + def level0_file_num_compaction_trigger(self, int v): self.opts.level0_file_num_compaction_trigger = v + + @property + def level0_slowdown_writes_trigger(self): return self.opts.level0_slowdown_writes_trigger + @level0_slowdown_writes_trigger.setter + def level0_slowdown_writes_trigger(self, int v): self.opts.level0_slowdown_writes_trigger = v + + @property + def level0_stop_writes_trigger(self): return self.opts.level0_stop_writes_trigger + @level0_stop_writes_trigger.setter + def level0_stop_writes_trigger(self, int v): self.opts.level0_stop_writes_trigger = v + + @property + def target_file_size_base(self): return self.opts.target_file_size_base + @target_file_size_base.setter + def target_file_size_base(self, uint64_t v): self.opts.target_file_size_base = v + + @property + def target_file_size_multiplier(self): return self.opts.target_file_size_multiplier + @target_file_size_multiplier.setter + def target_file_size_multiplier(self, int v): self.opts.target_file_size_multiplier = v + + @property + def max_bytes_for_level_base(self): return self.opts.max_bytes_for_level_base + @max_bytes_for_level_base.setter + def max_bytes_for_level_base(self, uint64_t v): self.opts.max_bytes_for_level_base = v + + @property + def max_bytes_for_level_multiplier(self): return self.opts.max_bytes_for_level_multiplier + @max_bytes_for_level_multiplier.setter + def max_bytes_for_level_multiplier(self, double v): self.opts.max_bytes_for_level_multiplier = v + + @property + def level_compaction_dynamic_level_bytes(self): return self.opts.level_compaction_dynamic_level_bytes + @level_compaction_dynamic_level_bytes.setter + def level_compaction_dynamic_level_bytes(self, bint v): self.opts.level_compaction_dynamic_level_bytes = v + + @property + def disable_auto_compactions(self): return self.opts.disable_auto_compactions + @disable_auto_compactions.setter + def disable_auto_compactions(self, bint v): self.opts.disable_auto_compactions = v + + @property + def compaction_style(self): return _COMPACTION_NAMES.get(self.opts.compaction_style, "unknown") + @compaction_style.setter + def compaction_style(self, v): + if v not in _COMPACTION: + raise ValueError("compaction_style must be one of %s" % sorted(_COMPACTION)) + self.opts.compaction_style = (_COMPACTION[v]) + + @property + def max_compaction_bytes(self): return self.opts.max_compaction_bytes + @max_compaction_bytes.setter + def max_compaction_bytes(self, uint64_t v): self.opts.max_compaction_bytes = v + + @property + def optimize_filters_for_hits(self): return self.opts.optimize_filters_for_hits + @optimize_filters_for_hits.setter + def optimize_filters_for_hits(self, bint v): self.opts.optimize_filters_for_hits = v + + @property + def memtable_prefix_bloom_size_ratio(self): return self.opts.memtable_prefix_bloom_size_ratio + @memtable_prefix_bloom_size_ratio.setter + def memtable_prefix_bloom_size_ratio(self, double v): self.opts.memtable_prefix_bloom_size_ratio = v + + @property + def prefix_extractor_len(self): + """Fixed-length prefix extractor (0 = none). Iterators always seek in + total order, so this only feeds prefix bloom filters.""" + return self._prefix_len + @prefix_extractor_len.setter + def prefix_extractor_len(self, size_t v): + self._prefix_len = v + r.opts_set_prefix_extractor(self.opts, v) + + # --- BlockBasedTableOptions --- + @property + def block_cache_size(self): + """LRU block cache capacity in bytes. None = rocksdb default (8MB).""" + return self._block_cache_size + @block_cache_size.setter + def block_cache_size(self, v): + self._block_cache_size = v + self.bbto_set = True + if v is None: + self.bbto.no_block_cache = False + r.bbto_set_cache(self.bbto, 8 << 20) + elif int(v) <= 0: + self.bbto.no_block_cache = True + else: + self.bbto.no_block_cache = False + r.bbto_set_cache(self.bbto, int(v)) + + @property + def block_size(self): return self.bbto.block_size + @block_size.setter + def block_size(self, size_t v): + self.bbto_set = True + self.bbto.block_size = v + + @property + def block_restart_interval(self): return self.bbto.block_restart_interval + @block_restart_interval.setter + def block_restart_interval(self, int v): + self.bbto_set = True + self.bbto.block_restart_interval = v + + @property + def bloom_bits_per_key(self): return self._bloom_bits + @bloom_bits_per_key.setter + def bloom_bits_per_key(self, double v): + self.bbto_set = True + self._bloom_bits = v + r.bbto_set_bloom(self.bbto, v) + + @property + def cache_index_and_filter_blocks(self): return self.bbto.cache_index_and_filter_blocks + @cache_index_and_filter_blocks.setter + def cache_index_and_filter_blocks(self, bint v): + self.bbto_set = True + self.bbto.cache_index_and_filter_blocks = v + + @property + def pin_l0_filter_and_index_blocks_in_cache(self): return self.bbto.pin_l0_filter_and_index_blocks_in_cache + @pin_l0_filter_and_index_blocks_in_cache.setter + def pin_l0_filter_and_index_blocks_in_cache(self, bint v): + self.bbto_set = True + self.bbto.pin_l0_filter_and_index_blocks_in_cache = v + + @property + def pin_top_level_index_and_filter(self): return self.bbto.pin_top_level_index_and_filter + @pin_top_level_index_and_filter.setter + def pin_top_level_index_and_filter(self, bint v): + self.bbto_set = True + self.bbto.pin_top_level_index_and_filter = v + + @property + def partition_filters(self): return self.bbto.partition_filters + @partition_filters.setter + def partition_filters(self, bint v): + self.bbto_set = True + self.bbto.partition_filters = v + + @property + def whole_key_filtering(self): return self.bbto.whole_key_filtering + @whole_key_filtering.setter + def whole_key_filtering(self, bint v): + self.bbto_set = True + self.bbto.whole_key_filtering = v + + @property + def format_version(self): return self.bbto.format_version + @format_version.setter + def format_version(self, uint32_t v): + self.bbto_set = True + self.bbto.format_version = v + + @property + def optimize_filters_for_memory(self): return self.bbto.optimize_filters_for_memory + @optimize_filters_for_memory.setter + def optimize_filters_for_memory(self, bint v): + self.bbto_set = True + self.bbto.optimize_filters_for_memory = v + + +cdef int _compression_value(v) except -1: + if isinstance(v, str): + if v not in _COMPRESSION: + raise ValueError("compression must be one of %s" % sorted(_COMPRESSION)) + return _COMPRESSION[v] + return v + + +# ---------------------------------------------------------------------------- +# WriteBatch +# ---------------------------------------------------------------------------- + +cdef class WriteBatch: + """Atomic group of puts and deletes, applied with DB.write().""" + cdef r.WriteBatch* batch + + def __cinit__(self): + self.batch = new r.WriteBatch() + + def __dealloc__(self): + if self.batch != NULL: + del self.batch + self.batch = NULL + + def put(self, bytes key not None, bytes value not None): + self.batch.Put(_slice(key), _slice(value)) + + def delete(self, bytes key not None): + self.batch.Delete(_slice(key)) + + def single_delete(self, bytes key not None): + self.batch.SingleDelete(_slice(key)) + + def clear(self): + self.batch.Clear() + + def count(self): + return self.batch.Count() + + def __len__(self): + return self.batch.Count() + + +# ---------------------------------------------------------------------------- +# Snapshot +# ---------------------------------------------------------------------------- + +@cython.no_gc_clear +cdef class Snapshot: + """A point-in-time view. Pass as `snapshot=` to any read. + + From DB.snapshot(): owned, release() (or the context manager, or gc) frees + it. From Transaction.snapshot: a view on the transaction's own snapshot, + valid until the transaction ends or changes snapshot. + """ + cdef const r.Snapshot* ptr + cdef DB db + cdef set registry + cdef bint owned + + def __cinit__(self, *args, **kwargs): + self.ptr = NULL + self.registry = None + self.owned = False + + def __dealloc__(self): + self._release() + + cdef void _release(self): + cdef const r.Snapshot* p = self.ptr + if p == NULL: + return + self.ptr = NULL + if self.registry is not None: + self.registry.discard(_addr(self)) + if self.owned and self.db is not None and self.db.db != NULL: + _busy(self.db) + with nogil: + self.db.db.ReleaseSnapshot(p) + _idle(self.db) + + cdef void _invalidate(self): + # Called by the owner that is about to free the native snapshot. + self.ptr = NULL + + cdef const r.Snapshot* _ptr(self, DB db) except NULL: + if self.ptr == NULL: + raise RuntimeError("snapshot has been released") + if self.db is not db: + raise ValueError("snapshot belongs to another DB") + return self.ptr + + def release(self): + """Free the native snapshot (no-op for transaction-owned views).""" + self._release() + + @property + def released(self): + return self.ptr == NULL + + @property + def sequence(self): + if self.ptr == NULL: + raise RuntimeError("snapshot has been released") + return self.ptr.GetSequenceNumber() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self._release() + return False + + +cdef inline const r.Snapshot* _snap_ptr(object snapshot, DB db) except? NULL: + if snapshot is None: + return NULL + if not isinstance(snapshot, Snapshot): + raise TypeError("snapshot must be a Snapshot or None") + return (snapshot)._ptr(db) + + +# ---------------------------------------------------------------------------- +# Iterator +# ---------------------------------------------------------------------------- + +@cython.no_gc_clear +cdef class Iterator: + """Cursor over a DB or Transaction. + + Raw cursor methods: seek, seek_for_prev, seek_to_first, seek_to_last, + valid, key, value, item, next, prev. Convenience: iteration (`for k, v in + it`, or keys when keys_only) and next_batch(n), both walk in the direction + given by `reverse` and position themselves on first use. + + Bounds (lower inclusive, upper exclusive) and prefix are passed to RocksDB + and also enforced here: a transaction iterator's own pending writes are + not bounded by RocksDB 6.29, so seeks are clamped into the window and a + key outside it reads as invalid. + """ + cdef r.Iterator* it + cdef r.ReadOptions ro + cdef r.Slice lower_s + cdef r.Slice upper_s + cdef bytes lower + cdef bytes upper + cdef bint has_lower + cdef bint has_upper + cdef DB db + cdef set registry + cdef bint reverse + cdef bint keys_only + cdef bint positioned + + def __cinit__(self, *args, **kwargs): + self.it = NULL + self.registry = None + self.positioned = False + self.has_lower = False + self.has_upper = False + + def __dealloc__(self): + self._free() + + cdef void _free(self): + cdef r.Iterator* p = self.it + if p == NULL: + return + self.it = NULL + if self.registry is not None: + self.registry.discard(_addr(self)) + # An iterator's destructor may drop the last SuperVersion ref and + # purge obsolete files, so it runs without the GIL. + with nogil: + del p + + cdef void _invalidate(self): + # Called by the parent, which already popped us from its registry. + cdef r.Iterator* p = self.it + if p == NULL: + return + self.it = NULL + with nogil: + del p + + cdef void _setup(self, DB db, set registry, const r.Snapshot* snap, lower, upper, prefix, + bint reverse, bint keys_only, bint fill_cache) except *: + if prefix is not None: + if lower is not None or upper is not None: + raise ValueError("prefix cannot be combined with lower/upper") + lower = prefix + upper = next_prefix(prefix) + self.db = db + self.registry = registry + self.reverse = reverse + self.keys_only = keys_only + self.ro.snapshot = snap + self.ro.fill_cache = fill_cache + self.ro.total_order_seek = True + if lower is not None: + self.lower = lower + self.lower_s = _slice(self.lower) + self.ro.iterate_lower_bound = &self.lower_s + self.has_lower = True + if upper is not None: + self.upper = upper + self.upper_s = _slice(self.upper) + self.ro.iterate_upper_bound = &self.upper_s + self.has_upper = True + + cdef inline int _check(self) except -1: + if self.it == NULL or self.db.db == NULL: + raise RuntimeError("iterator is closed or its parent has ended") + return 0 + + cdef inline int _status(self) except -1: + cdef r.Status st + _busy(self.db) + try: + with nogil: + st = self.it.status() + finally: + _idle(self.db) + return _check(st) + + # --- window-aware native moves (no GIL) --- + cdef inline cpp_bool _valid(self) noexcept nogil: + if not self.it.Valid(): + return False + if self.has_upper and self.it.key().compare(self.upper_s) >= 0: + return False + if self.has_lower and self.it.key().compare(self.lower_s) < 0: + return False + return True + + cdef inline void _seek(self, const r.Slice& k) noexcept nogil: + if self.has_lower and k.compare(self.lower_s) < 0: + self.it.Seek(self.lower_s) + else: + self.it.Seek(k) + + cdef inline void _seek_first(self) noexcept nogil: + if self.has_lower: + self.it.Seek(self.lower_s) + else: + self.it.SeekToFirst() + + cdef inline void _seek_last(self) noexcept nogil: + if self.has_upper: + self.it.SeekForPrev(self.upper_s) + while self.it.Valid() and self.it.key().compare(self.upper_s) >= 0: + self.it.Prev() + else: + self.it.SeekToLast() + + cdef inline void _seek_for_prev(self, const r.Slice& k) noexcept nogil: + if self.has_upper and k.compare(self.upper_s) >= 0: + self._seek_last() + else: + self.it.SeekForPrev(k) + + def close(self): + self._free() + + @property + def closed(self): + return self.it == NULL + + def __enter__(self): + return self + + def __exit__(self, *exc): + self._free() + return False + + # --- raw cursor --- + def seek(self, bytes key not None): + self._check() + cdef r.Slice k = _slice(key) + _busy(self.db) + try: + with nogil: + self._seek(k) + finally: + _idle(self.db) + self.positioned = True + return self._status() + + def seek_for_prev(self, bytes key not None): + self._check() + cdef r.Slice k = _slice(key) + _busy(self.db) + try: + with nogil: + self._seek_for_prev(k) + finally: + _idle(self.db) + self.positioned = True + return self._status() + + def seek_to_first(self): + self._check() + _busy(self.db) + try: + with nogil: + self._seek_first() + finally: + _idle(self.db) + self.positioned = True + return self._status() + + def seek_to_last(self): + self._check() + _busy(self.db) + try: + with nogil: + self._seek_last() + finally: + _idle(self.db) + self.positioned = True + return self._status() + + def valid(self): + self._check() + return self._valid() + + def key(self): + self._check() + if not self._valid(): + raise RuntimeError("iterator is not valid") + return _bytes(self.it.key()) + + def value(self): + self._check() + if not self._valid(): + raise RuntimeError("iterator is not valid") + return _bytes(self.it.value()) + + def item(self): + self._check() + if not self._valid(): + raise RuntimeError("iterator is not valid") + return (_bytes(self.it.key()), _bytes(self.it.value())) + + def next(self): + self._check() + _busy(self.db) + try: + with nogil: + self.it.Next() + finally: + _idle(self.db) + return self._status() + + def prev(self): + self._check() + _busy(self.db) + try: + with nogil: + self.it.Prev() + finally: + _idle(self.db) + return self._status() + + def status(self): + """Raise the iterator's pending error, if any.""" + self._check() + return self._status() + + # --- directional iteration --- + cdef inline void _ensure_positioned(self) noexcept nogil: + if not self.positioned: + if self.reverse: + self._seek_last() + else: + self._seek_first() + self.positioned = True + + def __iter__(self): + return self + + def __next__(self): + self._check() + cdef object out + _busy(self.db) + try: + with nogil: + self._ensure_positioned() + finally: + _idle(self.db) + if not self._valid(): + self._status() + raise StopIteration + if self.keys_only: + out = _bytes(self.it.key()) + else: + out = (_bytes(self.it.key()), _bytes(self.it.value())) + _busy(self.db) + try: + with nogil: + if self.reverse: + self.it.Prev() + else: + self.it.Next() + finally: + _idle(self.db) + return out + + def next_batch(self, Py_ssize_t n=1000): + """Up to n rows from the current position in the iteration direction, + as a list of keys (keys_only) or (key, value) tuples. The native loop + runs without the GIL; Python objects are built afterwards. An empty + list means the end.""" + self._check() + if n <= 0: + raise ValueError("n must be positive") + cdef vector[string] ks + cdef vector[string] vs + cdef Py_ssize_t left = n + cdef bint keys_only = self.keys_only + cdef bint reverse = self.reverse + cdef r.Iterator* it = self.it + _busy(self.db) + try: + with nogil: + self._ensure_positioned() + ks.reserve(n) + if not keys_only: + vs.reserve(n) + while left > 0 and self._valid(): + ks.push_back(it.key().ToString()) + if not keys_only: + vs.push_back(it.value().ToString()) + if reverse: + it.Prev() + else: + it.Next() + left -= 1 + finally: + _idle(self.db) + if ks.empty(): + self._status() + return [] + cdef size_t i, count = ks.size() + cdef list out = [None] * count + if keys_only: + for i in range(count): + out[i] = PyBytes_FromStringAndSize(ks[i].data(), ks[i].size()) + else: + for i in range(count): + out[i] = ( + PyBytes_FromStringAndSize(ks[i].data(), ks[i].size()), + PyBytes_FromStringAndSize(vs[i].data(), vs[i].size()), + ) + return out + + +cdef void _invalidate_iterators(set registry): + cdef Iterator it + if registry is None: + return + while registry: + it = registry.pop() + it._invalidate() + + +cdef void _release_snapshots(set registry, r.DB* db): + # DB close: owned snapshots must be released before the DB is deleted, + # rocksdb does not free them itself. + cdef Snapshot snap + cdef const r.Snapshot* p + if registry is None: + return + while registry: + snap = registry.pop() + p = snap.ptr + snap._invalidate() + if p != NULL and snap.owned: + with nogil: + db.ReleaseSnapshot(p) + + +cdef void _invalidate_snapshots(set registry): + cdef Snapshot snap + if registry is None: + return + while registry: + snap = registry.pop() + snap._invalidate() + + +# ---------------------------------------------------------------------------- +# DB +# ---------------------------------------------------------------------------- + +@cython.no_gc_clear +cdef class DB: + """A plain RocksDB handle. + + DB(path, options=None, *, read_only=False, secondary_path=None) + + read_only opens with OpenForReadOnly; secondary_path opens as a secondary + instance that follows a primary (call try_catch_up_with_primary()). + """ + cdef r.DB* db + cdef set _iters + cdef set _snaps + cdef set _txns + cdef int _inflight + cdef readonly str path + cdef readonly Options options + + def __cinit__(self, *args, **kwargs): + self.db = NULL + self._iters = set() + self._snaps = set() + self._txns = set() + self._inflight = 0 + + def __init__(self, path, Options options=None, *, bint read_only=False, secondary_path=None): + cdef r.DB* db = NULL + cdef r.Status st + cdef string name = _path(path) + cdef string secondary + if options is None: + options = Options(create_if_missing=True) + options._finalize() + self.path = os.fsdecode(path) + self.options = options + if secondary_path is not None: + secondary = _path(secondary_path) + with nogil: + st = r.DB_OpenAsSecondary(options.opts, name, secondary, &db) + elif read_only: + with nogil: + st = r.DB_OpenForReadOnly(options.opts, name, &db, False) + else: + with nogil: + st = r.DB_Open(options.opts, name, &db) + _check(st) + self.db = db + + def __dealloc__(self): + self._close() + + cdef void _close(self): + cdef r.DB* p + cdef Transaction txn + if self.db == NULL: + return + # Detach first: from here every call on the DB or its children raises, + # even while the steps below release the GIL. + p = self.db + self.db = NULL + _invalidate_iterators(self._iters) + _release_snapshots(self._snaps, p) + while self._txns: + txn = self._txns.pop() + txn._end(True) + with nogil: + del p + + cdef inline int _check(self) except -1: + if self.db == NULL: + raise RuntimeError("DB is closed") + return 0 + + def close(self): + """Free every iterator, snapshot and transaction, then the DB. + + Raises RuntimeError while another thread is inside a call on this DB + or one of its children (freeing it then would be a use after free). + """ + if self._inflight: + raise RuntimeError("DB is in use by another thread") + self._close() + + @property + def closed(self): + return self.db == NULL + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + return False + + def __repr__(self): + return "<%s %r%s>" % (type(self).__name__, self.path, " closed" if self.db == NULL else "") + + # --- reads --- + def get(self, bytes key not None, *, snapshot=None): + """Value for key at `snapshot` (or latest), None if missing.""" + self._check() + cdef r.ReadOptions ro + cdef r.Slice k = _slice(key) + cdef string value + cdef r.Status st + ro.snapshot = _snap_ptr(snapshot, self) + _busy(self) + try: + with nogil: + st = r.db_get(self.db, ro, k, &value) + finally: + _idle(self) + if _is_not_found(st): + return None + _check(st) + return PyBytes_FromStringAndSize(value.data(), value.size()) + + def multi_get(self, keys, *, snapshot=None): + """Values for keys (list, None for missing) at `snapshot` or latest.""" + # Materialise first: iterating `keys` may run Python code (and let + # another thread close the DB), so the closed check comes after. + cdef list key_list = [k for k in keys] + self._check() + cdef r.ReadOptions ro + cdef vector[r.Slice] ks + cdef vector[string] vs + cdef vector[r.Status] sts + cdef size_t i, n = len(key_list) + ro.snapshot = _snap_ptr(snapshot, self) + ks.reserve(n) + for k in key_list: + if not isinstance(k, bytes): + raise TypeError("keys must be bytes") + ks.push_back(_slice(k)) + _busy(self) + try: + with nogil: + sts = self.db.MultiGet(ro, ks, &vs) + finally: + _idle(self) + cdef list out = [None] * n + for i in range(n): + if _is_not_found(sts[i]): + continue + _check(sts[i]) + out[i] = PyBytes_FromStringAndSize(vs[i].data(), vs[i].size()) + return out + + def snapshot(self): + """Take a snapshot of the current state (release it when done).""" + self._check() + cdef Snapshot snap = Snapshot.__new__(Snapshot) + cdef const r.Snapshot* p + _busy(self) + try: + with nogil: + p = self.db.GetSnapshot() + finally: + _idle(self) + snap.ptr = p + snap.db = self + snap.owned = True + snap.registry = self._snaps + self._snaps.add(_addr(snap)) + return snap + + def iterator(self, *, snapshot=None, lower=None, upper=None, prefix=None, + bint reverse=False, bint keys_only=False, bint fill_cache=True): + """Cursor over [lower, upper) or `prefix`, at `snapshot` or latest.""" + self._check() + cdef Iterator it = Iterator.__new__(Iterator) + cdef r.Iterator* p + it._setup(self, self._iters, _snap_ptr(snapshot, self), lower, upper, prefix, + reverse, keys_only, fill_cache) + _busy(self) + try: + with nogil: + p = self.db.NewIterator(it.ro) + finally: + _idle(self) + it.it = p + self._iters.add(_addr(it)) + return it + + @property + def latest_sequence_number(self): + self._check() + return self.db.GetLatestSequenceNumber() + + def get_property(self, name): + """A rocksdb.* property string, or None if unknown.""" + self._check() + cdef bytes b = name.encode() if isinstance(name, str) else name + cdef string out + if not self.db.GetProperty(_slice(b), &out): + return None + return out.decode("utf-8", "replace") + + # --- writes --- + def put(self, bytes key not None, bytes value not None, *, bint sync=False, bint disable_wal=False): + self._check() + cdef r.WriteOptions wo + cdef r.Slice k = _slice(key) + cdef r.Slice v = _slice(value) + cdef r.Status st + wo.sync = sync + wo.disableWAL = disable_wal + _busy(self) + try: + with nogil: + st = self.db.Put(wo, k, v) + finally: + _idle(self) + _check(st) + + def delete(self, bytes key not None, *, bint sync=False, bint disable_wal=False): + self._check() + cdef r.WriteOptions wo + cdef r.Slice k = _slice(key) + cdef r.Status st + wo.sync = sync + wo.disableWAL = disable_wal + _busy(self) + try: + with nogil: + st = self.db.Delete(wo, k) + finally: + _idle(self) + _check(st) + + def write(self, WriteBatch batch not None, *, bint sync=False, bint disable_wal=False): + """Apply a WriteBatch atomically.""" + self._check() + cdef r.WriteOptions wo + cdef r.Status st + wo.sync = sync + wo.disableWAL = disable_wal + _busy(self) + try: + with nogil: + st = self.db.Write(wo, batch.batch) + finally: + _idle(self) + _check(st) + + # --- maintenance --- + def flush(self, *, bint wait=True): + self._check() + cdef r.FlushOptions fo + cdef r.Status st + fo.wait = wait + _busy(self) + try: + with nogil: + st = self.db.Flush(fo) + finally: + _idle(self) + _check(st) + + def flush_wal(self, *, bint sync=False): + self._check() + cdef r.Status st + _busy(self) + try: + with nogil: + st = self.db.FlushWAL(sync) + finally: + _idle(self) + _check(st) + + def compact_range(self, bytes begin=None, bytes end=None): + self._check() + cdef r.CompactRangeOptions co + cdef r.Slice b, e + cdef const r.Slice* bp = NULL + cdef const r.Slice* ep = NULL + cdef r.Status st + if begin is not None: + b = _slice(begin) + bp = &b + if end is not None: + e = _slice(end) + ep = &e + _busy(self) + try: + with nogil: + st = self.db.CompactRange(co, bp, ep) + finally: + _idle(self) + _check(st) + + def try_catch_up_with_primary(self): + """Secondary instances: pull the primary's latest state.""" + self._check() + cdef r.Status st + _busy(self) + try: + with nogil: + st = self.db.TryCatchUpWithPrimary() + finally: + _idle(self) + _check(st) + + +# ---------------------------------------------------------------------------- +# Transactions +# ---------------------------------------------------------------------------- + +@cython.no_gc_clear +cdef class Transaction: + """A transaction from TransactionDB.begin() or OptimisticTransactionDB.begin(). + + Reads default to the transaction's own snapshot when one is set (begin + with set_snapshot=True, or set_snapshot()), and merge the transaction's + pending writes. commit() and rollback() end it; a failed commit is rolled + back. Use as a context manager to roll back on exceptions. + """ + cdef r.Transaction* txn + cdef DB db + cdef set _iters + cdef set _snaps + cdef readonly bint optimistic + cdef bint _committed + + def __cinit__(self, *args, **kwargs): + self.txn = NULL + self._iters = set() + self._snaps = set() + self._committed = False + + def __dealloc__(self): + self._end(True) + + cdef void _end(self, bint rollback): + # Free native state; rollback first when asked. Never raises. + cdef r.Transaction* p = self.txn + cdef r.Status st + cdef DB db = self.db + if p == NULL: + return + _invalidate_iterators(self._iters) + _invalidate_snapshots(self._snaps) + self.txn = NULL + if self.db is not None and self.db._txns is not None: + self.db._txns.discard(_addr(self)) + if db is not None: + _busy(db) + with nogil: + if rollback: + st = p.Rollback() + del p + if db is not None: + _idle(db) + + cdef inline int _check(self) except -1: + if self.txn == NULL: + raise RuntimeError("transaction has ended") + if self.db.db == NULL: + raise RuntimeError("DB is closed") + return 0 + + cdef const r.Snapshot* _read_snapshot(self, object snapshot) except? NULL: + if snapshot is None: + return self.txn.GetSnapshot() + return _snap_ptr(snapshot, self.db) + + @property + def active(self): + return self.txn != NULL + + @property + def committed(self): + return self._committed + + @property + def id(self): + self._check() + return self.txn.GetID() + + @property + def num_keys(self): + self._check() + return self.txn.GetNumKeys() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self._end(True) + return False + + # --- snapshot --- + def set_snapshot(self): + """Pin reads and conflict checks to the current state.""" + self._check() + _invalidate_snapshots(self._snaps) + _busy(self.db) + try: + with nogil: + self.txn.SetSnapshot() + finally: + _idle(self.db) + + def clear_snapshot(self): + self._check() + _invalidate_snapshots(self._snaps) + _busy(self.db) + try: + with nogil: + self.txn.ClearSnapshot() + finally: + _idle(self.db) + + @property + def snapshot(self): + """The transaction's own snapshot (a view, not owned), or None.""" + self._check() + cdef const r.Snapshot* p = self.txn.GetSnapshot() + if p == NULL: + return None + cdef Snapshot snap = Snapshot.__new__(Snapshot) + snap.ptr = p + snap.db = self.db + snap.owned = False + snap.registry = self._snaps + self._snaps.add(_addr(snap)) + return snap + + # --- reads --- + def get(self, bytes key not None, *, snapshot=None): + """Read, merging own writes. snapshot: None = the txn snapshot if set.""" + self._check() + cdef r.ReadOptions ro + cdef r.Slice k = _slice(key) + cdef string value + cdef r.Status st + ro.snapshot = self._read_snapshot(snapshot) + _busy(self.db) + try: + with nogil: + st = r.txn_get(self.txn, ro, k, &value) + finally: + _idle(self.db) + if _is_not_found(st): + return None + _check(st) + return PyBytes_FromStringAndSize(value.data(), value.size()) + + def get_for_update(self, bytes key not None, *, bint exclusive=True, snapshot=None, + bint validate=True): + """Read and lock (pessimistic) or track (optimistic) the key. + + Conflict checks use the transaction's own snapshot: with one set and + validate=True, raises Busy when the key changed after it (pessimistic) + or fails the commit (optimistic). An explicit `snapshot=` only picks + what is read. Lock waits raise TimedOut, cycles Deadlock. + validate=False reads latest and skips the check; passing `snapshot=` + with it raises ValueError. + """ + self._check() + cdef r.ReadOptions ro + cdef r.Slice k = _slice(key) + cdef string value + cdef r.Status st + if not validate and snapshot is not None: + raise ValueError("snapshot cannot be combined with validate=False") + ro.snapshot = self._read_snapshot(snapshot) if validate else NULL + _busy(self.db) + try: + with nogil: + st = r.txn_get_for_update(self.txn, ro, k, &value, exclusive, validate) + finally: + _idle(self.db) + if _is_not_found(st): + return None + _check(st) + return PyBytes_FromStringAndSize(value.data(), value.size()) + + def iterator(self, *, snapshot=None, lower=None, upper=None, prefix=None, + bint reverse=False, bint keys_only=False, bint fill_cache=True): + """Cursor merging own writes; snapshot defaults to the txn's.""" + self._check() + cdef Iterator it = Iterator.__new__(Iterator) + cdef r.Iterator* p + it._setup(self.db, self._iters, self._read_snapshot(snapshot), lower, upper, prefix, + reverse, keys_only, fill_cache) + _busy(self.db) + try: + with nogil: + p = r.txn_iterator(self.txn, it.ro) + finally: + _idle(self.db) + it.it = p + self._iters.add(_addr(it)) + return it + + # --- writes --- + def put(self, bytes key not None, bytes value not None): + """Buffer a put; on a pessimistic DB this takes the key lock now.""" + self._check() + cdef r.Slice k = _slice(key) + cdef r.Slice v = _slice(value) + cdef r.Status st + _busy(self.db) + try: + with nogil: + st = self.txn.Put(k, v) + finally: + _idle(self.db) + _check(st) + + def delete(self, bytes key not None): + self._check() + cdef r.Slice k = _slice(key) + cdef r.Status st + _busy(self.db) + try: + with nogil: + st = self.txn.Delete(k) + finally: + _idle(self.db) + _check(st) + + def single_delete(self, bytes key not None): + self._check() + cdef r.Slice k = _slice(key) + cdef r.Status st + _busy(self.db) + try: + with nogil: + st = self.txn.SingleDelete(k) + finally: + _idle(self.db) + _check(st) + + # --- end --- + def commit(self): + """Commit and end. Raises Busy/TryAgain/Expired... and rolls back on failure.""" + self._check() + cdef r.Transaction* p = self.txn + cdef r.Status st + _invalidate_iterators(self._iters) + _invalidate_snapshots(self._snaps) + _busy(self.db) + try: + with nogil: + st = p.Commit() + finally: + _idle(self.db) + if st.ok(): + self._committed = True + self._end(False) + return + self._end(True) + _check(st) + + def rollback(self): + """Discard pending writes, release locks, end.""" + if self.txn == NULL: + return + self._end(True) + + +cdef Transaction _wrap_txn(DB db, r.Transaction* p, bint optimistic): + cdef Transaction txn = Transaction.__new__(Transaction) + txn.txn = p + txn.db = db + txn.optimistic = optimistic + db._txns.add(_addr(txn)) + return txn + + +cdef class TransactionDB(DB): + """Pessimistic transactions: writes and get_for_update take row locks. + + TransactionDB(path, options=None, *, lock_timeout_ms=1000, + default_lock_timeout_ms=1000, max_num_locks=-1, + num_stripes=16, max_num_deadlocks=5) + + lock_timeout_ms: per-lock wait for transactions (negative = no timeout). + default_lock_timeout_ms: the same for plain db.put/delete/write. + """ + + def __init__(self, path, Options options=None, *, int64_t lock_timeout_ms=1000, + int64_t default_lock_timeout_ms=1000, int64_t max_num_locks=-1, + size_t num_stripes=16, uint32_t max_num_deadlocks=5): + cdef r.TransactionDB* db = NULL + cdef r.TransactionDBOptions tdo + cdef r.Status st + cdef string name = _path(path) + if options is None: + options = Options(create_if_missing=True) + options._finalize() + self.path = os.fsdecode(path) + self.options = options + tdo.transaction_lock_timeout = lock_timeout_ms + tdo.default_lock_timeout = default_lock_timeout_ms + tdo.max_num_locks = max_num_locks + tdo.num_stripes = num_stripes + tdo.max_num_deadlocks = max_num_deadlocks + with nogil: + st = r.TransactionDB_Open(options.opts, tdo, name, &db) + _check(st) + self.db = db + + def begin(self, *, bint set_snapshot=False, bint sync=False, bint disable_wal=False, + lock_timeout_ms=None, bint deadlock_detect=False, deadlock_detect_depth=None, + expiration_ms=None): + """Start a transaction. + + lock_timeout_ms overrides the DB default for this transaction (0 = + fail at once, negative = DB default). deadlock_detect makes lock waits + raise Deadlock instead of timing out when they form a cycle. + """ + self._check() + cdef r.WriteOptions wo + cdef r.TransactionOptions to + cdef r.Transaction* p + wo.sync = sync + wo.disableWAL = disable_wal + to.set_snapshot = set_snapshot + to.deadlock_detect = deadlock_detect + if lock_timeout_ms is not None: + to.lock_timeout = lock_timeout_ms + if deadlock_detect_depth is not None: + to.deadlock_detect_depth = deadlock_detect_depth + if expiration_ms is not None: + to.expiration = expiration_ms + _busy(self) + try: + with nogil: + p = (self.db).BeginTransaction(wo, to) + finally: + _idle(self) + return _wrap_txn(self, p, False) + + +cdef class OptimisticTransactionDB(DB): + """Optimistic transactions: no locks, conflicts surface at commit as Busy. + + OptimisticTransactionDB(path, options=None, *, validate_policy="parallel", + occ_lock_buckets=None) + """ + + def __init__(self, path, Options options=None, *, validate_policy="parallel", + occ_lock_buckets=None): + cdef r.OptimisticTransactionDB* db = NULL + cdef r.OptimisticTransactionDBOptions occ + cdef r.Status st + cdef string name = _path(path) + if options is None: + options = Options(create_if_missing=True) + options._finalize() + self.path = os.fsdecode(path) + self.options = options + if validate_policy == "parallel": + occ.validate_policy = r.kValidateParallel + elif validate_policy == "serial": + occ.validate_policy = r.kValidateSerial + else: + raise ValueError("validate_policy must be 'parallel' or 'serial'") + if occ_lock_buckets is not None: + occ.occ_lock_buckets = occ_lock_buckets + with nogil: + st = r.open_optimistic(options.opts, occ, name, &db) + _check(st) + self.db = db + + def begin(self, *, bint set_snapshot=False, bint sync=False, bint disable_wal=False): + self._check() + cdef r.WriteOptions wo + cdef r.OptimisticTransactionOptions to + cdef r.Transaction* p + wo.sync = sync + wo.disableWAL = disable_wal + to.set_snapshot = set_snapshot + _busy(self) + try: + with nogil: + p = (self.db).BeginTransaction(wo, to) + finally: + _idle(self) + return _wrap_txn(self, p, True) + + +# ---------------------------------------------------------------------------- +# module functions +# ---------------------------------------------------------------------------- + +def destroy_db(path, Options options=None): + """Delete a database directory's contents (the DB must be closed).""" + cdef string name = _path(path) + cdef r.Status st + if options is None: + options = Options() + with nogil: + st = r.DestroyDB(name, options.opts) + _check(st) + + +def rocksdb_version(): + return "6.29.5" diff --git a/src/rdbpy/_rocksdb.pxd b/src/rdbpy/_rocksdb.pxd new file mode 100644 index 0000000..3d4a358 --- /dev/null +++ b/src/rdbpy/_rocksdb.pxd @@ -0,0 +1,380 @@ +# Declarations of the RocksDB 6.29.5 C++ surface rdbpy uses. Nothing else. +from libc.stddef cimport size_t +from libc.stdint cimport int64_t, uint32_t, uint64_t +from libcpp cimport bool as cpp_bool +from libcpp.string cimport string +from libcpp.vector cimport vector + + +cdef extern from "" namespace "std": + cdef cppclass shared_ptr[T]: + shared_ptr() except+ nogil + shared_ptr(T*) except+ nogil + void reset() except+ nogil + void reset(T*) except+ nogil + T* get() except+ nogil + + +cdef extern from "rocksdb/slice.h" namespace "rocksdb": + cdef cppclass Slice: + Slice() nogil + Slice(const char*, size_t) nogil + Slice(const string&) nogil + const char* data() nogil + size_t size() nogil + int compare(const Slice&) nogil + string ToString() nogil + + +cdef extern from "rocksdb/status.h" namespace "rocksdb": + cdef cppclass Status: + Status() nogil + cpp_bool ok() nogil + string ToString() except+ nogil + + +cdef extern from "rocksdb/snapshot.h" namespace "rocksdb": + cdef cppclass Snapshot: + uint64_t GetSequenceNumber() nogil + + +cdef extern from "rocksdb/cache.h" namespace "rocksdb": + cdef cppclass Cache: + pass + shared_ptr[Cache] NewLRUCache(size_t capacity) except+ nogil + + +cdef extern from "rocksdb/filter_policy.h" namespace "rocksdb": + cdef cppclass FilterPolicy: + pass + const FilterPolicy* NewBloomFilterPolicy(double bits_per_key, cpp_bool use_block_based_builder) except+ nogil + + +cdef extern from "rocksdb/slice_transform.h" namespace "rocksdb": + cdef cppclass SliceTransform: + pass + const SliceTransform* NewFixedPrefixTransform(size_t prefix_len) except+ nogil + + +cdef extern from "rocksdb/table.h" namespace "rocksdb": + cdef cppclass TableFactory: + pass + + cdef cppclass BlockBasedTableOptions: + BlockBasedTableOptions() except+ nogil + cpp_bool no_block_cache + size_t block_size + int block_restart_interval + cpp_bool cache_index_and_filter_blocks + cpp_bool pin_l0_filter_and_index_blocks_in_cache + cpp_bool pin_top_level_index_and_filter + cpp_bool partition_filters + cpp_bool whole_key_filtering + uint32_t format_version + cpp_bool optimize_filters_for_memory + + TableFactory* NewBlockBasedTableFactory(const BlockBasedTableOptions&) except+ nogil + + +cdef extern from "rocksdb/options.h" namespace "rocksdb": + ctypedef enum CompressionType: + kNoCompression + kSnappyCompression + kZlibCompression + kBZip2Compression + kLZ4Compression + kLZ4HCCompression + kZSTD + + ctypedef enum CompactionStyle: + kCompactionStyleLevel + kCompactionStyleUniversal + kCompactionStyleFIFO + + cdef cppclass Options: + Options() except+ nogil + # DBOptions + cpp_bool create_if_missing + cpp_bool error_if_exists + cpp_bool paranoid_checks + int max_open_files + cpp_bool use_fsync + string db_log_dir + string wal_dir + int max_background_jobs + size_t max_log_file_size + size_t keep_log_file_num + uint64_t max_total_wal_size + size_t db_write_buffer_size + cpp_bool allow_mmap_reads + cpp_bool allow_mmap_writes + cpp_bool use_direct_reads + cpp_bool use_direct_io_for_flush_and_compaction + uint64_t bytes_per_sync + uint64_t wal_bytes_per_sync + cpp_bool allow_concurrent_memtable_write + cpp_bool manual_wal_flush + cpp_bool avoid_unnecessary_blocking_io + cpp_bool atomic_flush + uint64_t WAL_ttl_seconds + uint64_t WAL_size_limit_MB + # ColumnFamilyOptions + size_t write_buffer_size + int max_write_buffer_number + int min_write_buffer_number_to_merge + int64_t max_write_buffer_size_to_maintain + CompressionType compression + CompressionType bottommost_compression + int num_levels + int level0_file_num_compaction_trigger + int level0_slowdown_writes_trigger + int level0_stop_writes_trigger + uint64_t target_file_size_base + int target_file_size_multiplier + uint64_t max_bytes_for_level_base + double max_bytes_for_level_multiplier + cpp_bool level_compaction_dynamic_level_bytes + cpp_bool disable_auto_compactions + CompactionStyle compaction_style + uint64_t max_compaction_bytes + cpp_bool optimize_filters_for_hits + double memtable_prefix_bloom_size_ratio + + cdef cppclass WriteOptions: + WriteOptions() except+ nogil + cpp_bool sync + cpp_bool disableWAL + cpp_bool no_slowdown + + cdef cppclass ReadOptions: + ReadOptions() except+ nogil + const Snapshot* snapshot + const Slice* iterate_lower_bound + const Slice* iterate_upper_bound + cpp_bool verify_checksums + cpp_bool fill_cache + cpp_bool total_order_seek + cpp_bool prefix_same_as_start + + cdef cppclass FlushOptions: + FlushOptions() except+ nogil + cpp_bool wait + + cdef cppclass CompactRangeOptions: + CompactRangeOptions() except+ nogil + + +cdef extern from "rocksdb/iterator.h" namespace "rocksdb": + cdef cppclass Iterator: + cpp_bool Valid() except+ nogil + void SeekToFirst() except+ nogil + void SeekToLast() except+ nogil + void Seek(const Slice&) except+ nogil + void SeekForPrev(const Slice&) except+ nogil + void Next() except+ nogil + void Prev() except+ nogil + Slice key() except+ nogil + Slice value() except+ nogil + Status status() except+ nogil + + +cdef extern from "rocksdb/write_batch.h" namespace "rocksdb": + cdef cppclass WriteBatch: + WriteBatch() except+ nogil + void Put(const Slice&, const Slice&) except+ nogil + void Delete(const Slice&, ) except+ nogil + void SingleDelete(const Slice&) except+ nogil + void Clear() except+ nogil + int Count() except+ nogil + + +cdef extern from "rocksdb/db.h" namespace "rocksdb": + cdef cppclass DB: + Status Put(const WriteOptions&, const Slice&, const Slice&) except+ nogil + Status Delete(const WriteOptions&, const Slice&) except+ nogil + Status SingleDelete(const WriteOptions&, const Slice&) except+ nogil + Status Write(const WriteOptions&, WriteBatch*) except+ nogil + Status Get(const ReadOptions&, const Slice&, string*) except+ nogil + vector[Status] MultiGet(const ReadOptions&, const vector[Slice]&, vector[string]*) except+ nogil + Iterator* NewIterator(const ReadOptions&) except+ nogil + const Snapshot* GetSnapshot() except+ nogil + void ReleaseSnapshot(const Snapshot*) except+ nogil + uint64_t GetLatestSequenceNumber() except+ nogil + cpp_bool GetProperty(const Slice&, string*) except+ nogil + Status Flush(const FlushOptions&) except+ nogil + Status FlushWAL(cpp_bool sync) except+ nogil + Status CompactRange(const CompactRangeOptions&, const Slice*, const Slice*) except+ nogil + Status TryCatchUpWithPrimary() except+ nogil + Status Close() except+ nogil + + Status DB_Open "rocksdb::DB::Open"(const Options&, const string&, DB**) except+ nogil + Status DB_OpenForReadOnly "rocksdb::DB::OpenForReadOnly"( + const Options&, const string&, DB**, cpp_bool error_if_wal_file_exists) except+ nogil + Status DB_OpenAsSecondary "rocksdb::DB::OpenAsSecondary"( + const Options&, const string&, const string&, DB**) except+ nogil + Status DestroyDB(const string&, const Options&) except+ nogil + + +cdef extern from "rocksdb/utilities/transaction.h" namespace "rocksdb": + cdef cppclass Transaction: + Status Commit() except+ nogil + Status Rollback() except+ nogil + void SetSnapshot() except+ nogil + const Snapshot* GetSnapshot() except+ nogil + void ClearSnapshot() except+ nogil + uint64_t GetID() except+ nogil + Status Put(const Slice&, const Slice&) except+ nogil + Status Delete(const Slice&) except+ nogil + Status SingleDelete(const Slice&) except+ nogil + Status Get(const ReadOptions&, const Slice&, string*) except+ nogil + Status GetForUpdate(const ReadOptions&, const Slice&, string*, cpp_bool exclusive, cpp_bool do_validate) except+ nogil + Iterator* GetIterator(const ReadOptions&) except+ nogil + uint64_t GetNumKeys() except+ nogil + + +cdef extern from "rocksdb/utilities/transaction_db.h" namespace "rocksdb": + cdef cppclass TransactionDBOptions: + TransactionDBOptions() except+ nogil + int64_t max_num_locks + uint32_t max_num_deadlocks + size_t num_stripes + int64_t transaction_lock_timeout + int64_t default_lock_timeout + + cdef cppclass TransactionOptions: + TransactionOptions() except+ nogil + cpp_bool set_snapshot + cpp_bool deadlock_detect + int64_t lock_timeout + int64_t expiration + int64_t deadlock_detect_depth + size_t max_write_batch_size + + cdef cppclass TransactionDB(DB): + Transaction* BeginTransaction(const WriteOptions&, const TransactionOptions&) except+ nogil + + Status TransactionDB_Open "rocksdb::TransactionDB::Open"( + const Options&, const TransactionDBOptions&, const string&, TransactionDB**) except+ nogil + + +cdef extern from "rocksdb/utilities/optimistic_transaction_db.h" namespace "rocksdb": + ctypedef enum OccValidationPolicy: + kValidateSerial "rocksdb::OccValidationPolicy::kValidateSerial" + kValidateParallel "rocksdb::OccValidationPolicy::kValidateParallel" + + cdef cppclass OptimisticTransactionOptions: + OptimisticTransactionOptions() except+ nogil + cpp_bool set_snapshot + + cdef cppclass OptimisticTransactionDBOptions: + OptimisticTransactionDBOptions() except+ nogil + OccValidationPolicy validate_policy + uint32_t occ_lock_buckets + + cdef cppclass OptimisticTransactionDB(DB): + Transaction* BeginTransaction(const WriteOptions&, const OptimisticTransactionOptions&) except+ nogil + + +# Small C++ helpers: status code access and overload disambiguation. +cdef extern from *: + """ + #include + #include + #include "rocksdb/db.h" + #include "rocksdb/status.h" + #include "rocksdb/utilities/transaction.h" + #include "rocksdb/utilities/transaction_db.h" + #include "rocksdb/utilities/optimistic_transaction_db.h" + #include "rocksdb/table.h" + #include "rocksdb/filter_policy.h" + #include "rocksdb/slice_transform.h" + #include "rocksdb/cache.h" + + namespace rdbpy { + + static inline int status_code(const rocksdb::Status& s) { return (int)s.code(); } + static inline int status_subcode(const rocksdb::Status& s) { return (int)s.subcode(); } + + static inline rocksdb::Status txn_get(rocksdb::Transaction* txn, + const rocksdb::ReadOptions& ro, + const rocksdb::Slice& key, + std::string* value) { + return txn->Get(ro, key, value); + } + + static inline rocksdb::Status txn_get_for_update(rocksdb::Transaction* txn, + const rocksdb::ReadOptions& ro, + const rocksdb::Slice& key, + std::string* value, + bool exclusive, + bool do_validate) { + return txn->GetForUpdate(ro, key, value, exclusive, do_validate); + } + + static inline rocksdb::Iterator* txn_iterator(rocksdb::Transaction* txn, + const rocksdb::ReadOptions& ro) { + return txn->GetIterator(ro); + } + + static inline rocksdb::Status db_get(rocksdb::DB* db, + const rocksdb::ReadOptions& ro, + const rocksdb::Slice& key, + std::string* value) { + return db->Get(ro, key, value); + } + + static inline rocksdb::Status open_optimistic(const rocksdb::Options& opts, + const rocksdb::OptimisticTransactionDBOptions& occ, + const std::string& name, + rocksdb::OptimisticTransactionDB** out) { + std::vector cfs; + rocksdb::ColumnFamilyOptions cfo(opts); + // Optimistic commits validate against memtable history. With none kept, + // a commit after a flush fails with TryAgain. Unset (both 0) means keep + // max_write_buffer_number * write_buffer_size, as RocksDB itself does. + if (cfo.max_write_buffer_size_to_maintain == 0 && + cfo.max_write_buffer_number_to_maintain == 0) { + cfo.max_write_buffer_size_to_maintain = -1; + } + cfs.emplace_back(rocksdb::kDefaultColumnFamilyName, cfo); + std::vector handles; + rocksdb::Status s = rocksdb::OptimisticTransactionDB::Open( + rocksdb::DBOptions(opts), occ, name, cfs, &handles, out); + if (s.ok()) { + // Handles returned by Open belong to the caller; the DB keeps its own + // default handle, so these can go right away. + for (auto* h : handles) delete h; + } + return s; + } + + static inline void bbto_set_bloom(rocksdb::BlockBasedTableOptions& t, double bits) { + if (bits > 0) t.filter_policy.reset(rocksdb::NewBloomFilterPolicy(bits, false)); + else t.filter_policy.reset(); + } + static inline void bbto_set_cache(rocksdb::BlockBasedTableOptions& t, size_t bytes) { + t.block_cache = rocksdb::NewLRUCache(bytes); + } + static inline void opts_set_table_factory(rocksdb::Options& o, const rocksdb::BlockBasedTableOptions& t) { + o.table_factory.reset(rocksdb::NewBlockBasedTableFactory(t)); + } + static inline void opts_set_prefix_extractor(rocksdb::Options& o, size_t n) { + if (n > 0) o.prefix_extractor.reset(rocksdb::NewFixedPrefixTransform(n)); + else o.prefix_extractor.reset(); + } + + } // namespace rdbpy + """ + int status_code "rdbpy::status_code"(const Status&) nogil + int status_subcode "rdbpy::status_subcode"(const Status&) nogil + Status txn_get "rdbpy::txn_get"(Transaction*, const ReadOptions&, const Slice&, string*) except+ nogil + Status txn_get_for_update "rdbpy::txn_get_for_update"( + Transaction*, const ReadOptions&, const Slice&, string*, cpp_bool, cpp_bool) except+ nogil + Iterator* txn_iterator "rdbpy::txn_iterator"(Transaction*, const ReadOptions&) except+ nogil + Status db_get "rdbpy::db_get"(DB*, const ReadOptions&, const Slice&, string*) except+ nogil + Status open_optimistic "rdbpy::open_optimistic"( + const Options&, const OptimisticTransactionDBOptions&, const string&, OptimisticTransactionDB**) except+ nogil + void bbto_set_bloom "rdbpy::bbto_set_bloom"(BlockBasedTableOptions&, double) except+ nogil + void bbto_set_cache "rdbpy::bbto_set_cache"(BlockBasedTableOptions&, size_t) except+ nogil + void opts_set_table_factory "rdbpy::opts_set_table_factory"(Options&, const BlockBasedTableOptions&) except+ nogil + void opts_set_prefix_extractor "rdbpy::opts_set_prefix_extractor"(Options&, size_t) except+ nogil diff --git a/src/rdbpy/backup.pxd b/src/rdbpy/backup.pxd deleted file mode 100644 index 7db30f7..0000000 --- a/src/rdbpy/backup.pxd +++ /dev/null @@ -1,35 +0,0 @@ -from libcpp cimport bool as cpp_bool -from libcpp.string cimport string -from libcpp.vector cimport vector -from libc.stdint cimport uint32_t -from libc.stdint cimport int64_t -from libc.stdint cimport uint64_t - -from rdbpy.status cimport Status -from rdbpy.db cimport DB -from rdbpy.env cimport Env - -cdef extern from "rocksdb/utilities/backup_engine.h" namespace "rocksdb": - ctypedef uint32_t BackupID - - cdef cppclass BackupEngineOptions: - BackupEngineOptions(const string& backup_dir) - - cdef struct BackupInfo: - BackupID backup_id - int64_t timestamp - uint64_t size - - cdef cppclass BackupEngine: - Status CreateNewBackup(DB*, cpp_bool) nogil except+ - Status PurgeOldBackups(uint32_t) nogil except+ - Status DeleteBackup(BackupID) nogil except+ - void StopBackup() nogil except+ - void GetBackupInfo(vector[BackupInfo]*) nogil except+ - Status RestoreDBFromBackup(BackupID, string&, string&) nogil except+ - Status RestoreDBFromLatestBackup(string&, string&) nogil except+ - - cdef Status BackupEngine_Open "rocksdb::BackupEngine::Open"( - Env*, - BackupEngineOptions&, - BackupEngine**) diff --git a/src/rdbpy/cache.pxd b/src/rdbpy/cache.pxd deleted file mode 100644 index e68291f..0000000 --- a/src/rdbpy/cache.pxd +++ /dev/null @@ -1,8 +0,0 @@ -from rdbpy.std_memory cimport shared_ptr - -cdef extern from "rocksdb/cache.h" namespace "rocksdb": - cdef cppclass Cache: - pass - - cdef extern shared_ptr[Cache] NewLRUCache(size_t) - cdef extern shared_ptr[Cache] NewLRUCache(size_t, int) diff --git a/src/rdbpy/comparator.pxd b/src/rdbpy/comparator.pxd deleted file mode 100644 index c7b9358..0000000 --- a/src/rdbpy/comparator.pxd +++ /dev/null @@ -1,23 +0,0 @@ -from libcpp.string cimport string -from rdbpy.slice_ cimport Slice -from rdbpy.logger cimport Logger -from rdbpy.std_memory cimport shared_ptr - -cdef extern from "rocksdb/comparator.h" namespace "rocksdb": - cdef cppclass Comparator: - const char* Name() - int Compare(const Slice&, const Slice&) const - - cdef extern const Comparator* BytewiseComparator() nogil except + - -ctypedef int (*compare_func)( - void*, - Logger*, - string&, - const Slice&, - const Slice&) - -cdef extern from "rdb_include/comparator_wrapper.hpp" namespace "py_rocks": - cdef cppclass ComparatorWrapper: - ComparatorWrapper(string, void*, compare_func) nogil except + - void set_info_log(shared_ptr[Logger]) nogil except+ diff --git a/src/rdbpy/db.pxd b/src/rdbpy/db.pxd deleted file mode 100644 index 4c0568e..0000000 --- a/src/rdbpy/db.pxd +++ /dev/null @@ -1,230 +0,0 @@ -cimport rdbpy.options as options -from libc.stdint cimport uint64_t, uint32_t -from rdbpy.status cimport Status -from libcpp cimport bool as cpp_bool -from libcpp.string cimport string -from libcpp.vector cimport vector -from rdbpy.slice_ cimport Slice -from rdbpy.snapshot cimport Snapshot -from rdbpy.iterator cimport Iterator - -cdef extern from "rocksdb/write_batch.h" namespace "rocksdb": - cdef cppclass WriteBatch: - WriteBatch() nogil except+ - WriteBatch(string) nogil except+ - void Put(const Slice&, const Slice&) nogil except+ - void Put(ColumnFamilyHandle*, const Slice&, const Slice&) nogil except+ - void Merge(const Slice&, const Slice&) nogil except+ - void Merge(ColumnFamilyHandle*, const Slice&, const Slice&) nogil except+ - void Delete(const Slice&) nogil except+ - void Delete(ColumnFamilyHandle*, const Slice&) nogil except+ - void DeleteRange(const Slice&, const Slice&) nogil except+ - void DeleteRange(ColumnFamilyHandle*, const Slice&, const Slice&) nogil except+ - void PutLogData(const Slice&) nogil except+ - void Clear() nogil except+ - const string& Data() nogil except+ - int Count() nogil except+ - -cdef extern from "rdb_include/write_batch_iter_helper.hpp" namespace "py_rocks": - cdef enum BatchItemOp "RecordItemsHandler::Optype": - BatchItemOpPut "py_rocks::RecordItemsHandler::Optype::PutRecord" - BatchItemOpMerge "py_rocks::RecordItemsHandler::Optype::MergeRecord" - BatchItemOpDelte "py_rocks::RecordItemsHandler::Optype::DeleteRecord" - - cdef cppclass BatchItem "py_rocks::RecordItemsHandler::BatchItem": - BatchItemOp op - uint32_t column_family_id - Slice key - Slice value - - Status get_batch_items(WriteBatch* batch, vector[BatchItem]* items) - - -cdef extern from "rocksdb/db.h" namespace "rocksdb": - ctypedef uint64_t SequenceNumber - string kDefaultColumnFamilyName - - cdef struct LiveFileMetaData: - string name - int level - uint64_t size - string smallestkey - string largestkey - SequenceNumber smallest_seqno - SequenceNumber largest_seqno - - cdef cppclass Range: - Range(const Slice&, const Slice&) - - cdef cppclass DB: - Status Put( - const options.WriteOptions&, - ColumnFamilyHandle*, - const Slice&, - const Slice&) nogil except+ - - Status Delete( - const options.WriteOptions&, - ColumnFamilyHandle*, - const Slice&) nogil except+ - - Status DeleteRange( - const options.WriteOptions&, - ColumnFamilyHandle*, - const Slice&, - const Slice&) nogil except+ - - Status Merge( - const options.WriteOptions&, - ColumnFamilyHandle*, - const Slice&, - const Slice&) nogil except+ - - Status Write( - const options.WriteOptions&, - WriteBatch*) nogil except+ - - Status Get( - const options.ReadOptions&, - ColumnFamilyHandle*, - const Slice&, - string*) nogil except+ - - vector[Status] MultiGet( - const options.ReadOptions&, - const vector[ColumnFamilyHandle*]&, - const vector[Slice]&, - vector[string]*) nogil except+ - - cpp_bool KeyMayExist( - const options.ReadOptions&, - ColumnFamilyHandle*, - Slice&, - string*, - cpp_bool*) nogil except+ - - cpp_bool KeyMayExist( - const options.ReadOptions&, - ColumnFamilyHandle*, - Slice&, - string*) nogil except+ - - Iterator* NewIterator( - const options.ReadOptions&, - ColumnFamilyHandle*) nogil except+ - - Status NewIterators( - const options.ReadOptions&, - vector[ColumnFamilyHandle*]&, - vector[Iterator*]*) nogil except+ - - const Snapshot* GetSnapshot() nogil except+ - - void ReleaseSnapshot(const Snapshot*) nogil except+ - - cpp_bool GetProperty( - ColumnFamilyHandle*, - const Slice&, - string*) nogil except+ - - void GetApproximateSizes( - ColumnFamilyHandle*, - const Range* - int, - uint64_t*) nogil except+ - - Status CompactRange( - const options.CompactRangeOptions&, - ColumnFamilyHandle*, - const Slice*, - const Slice*) nogil except+ - - Status CreateColumnFamily( - const options.ColumnFamilyOptions&, - const string&, - ColumnFamilyHandle**) nogil except+ - - Status DropColumnFamily( - ColumnFamilyHandle*) nogil except+ - - int NumberLevels(ColumnFamilyHandle*) nogil except+ - int MaxMemCompactionLevel(ColumnFamilyHandle*) nogil except+ - int Level0StopWriteTrigger(ColumnFamilyHandle*) nogil except+ - const string& GetName() nogil except+ - const options.Options& GetOptions(ColumnFamilyHandle*) nogil except+ - Status Flush(const options.FlushOptions&, ColumnFamilyHandle*) nogil except+ - Status FlushWAL(cpp_bool sync) nogil except+ - Status DisableFileDeletions() nogil except+ - Status EnableFileDeletions() nogil except+ - - Status TryCatchUpWithPrimary() nogil except+ - - # TODO: Status GetSortedWalFiles(VectorLogPtr& files) - # TODO: SequenceNumber GetLatestSequenceNumber() - # TODO: Status GetUpdatesSince( - # SequenceNumber seq_number, - # unique_ptr[TransactionLogIterator]*) - - Status DeleteFile(string) nogil except+ - void GetLiveFilesMetaData(vector[LiveFileMetaData]*) nogil except+ - ColumnFamilyHandle* DefaultColumnFamily() - - - cdef Status DB_Open "rocksdb::DB::Open"( - const options.Options&, - const string&, - DB**) nogil except+ - - cdef Status DB_Open_ColumnFamilies "rocksdb::DB::Open"( - const options.Options&, - const string&, - const vector[ColumnFamilyDescriptor]&, - vector[ColumnFamilyHandle*]*, - DB**) nogil except+ - - cdef Status DB_OpenForReadOnly "rocksdb::DB::OpenForReadOnly"( - const options.Options&, - const string&, - DB**, - cpp_bool) nogil except+ - - cdef Status DB_OpenForReadOnly_ColumnFamilies "rocksdb::DB::OpenForReadOnly"( - const options.Options&, - const string&, - const vector[ColumnFamilyDescriptor]&, - vector[ColumnFamilyHandle*]*, - DB**, - cpp_bool) nogil except+ - - cdef Status DB_OpenAsSecondary "rocksdb::DB::OpenAsSecondary"( - const options.Options&, - const string&, - const string&, - DB**) nogil except+ - - cdef Status DB_OpenAsSecondary_ColumnFamilies "rocksdb::DB::OpenAsSecondary"( - const options.Options&, - const string&, - const string&, - const vector[ColumnFamilyDescriptor]&, - vector[ColumnFamilyHandle*]*, - DB**) nogil except+ - - cdef Status RepairDB(const string& dbname, const options.Options&) - - cdef Status ListColumnFamilies "rocksdb::DB::ListColumnFamilies" ( - const options.Options&, - const string&, - vector[string]*) nogil except+ - - cdef cppclass ColumnFamilyHandle: - const string& GetName() nogil except+ - int GetID() nogil except+ - - cdef cppclass ColumnFamilyDescriptor: - ColumnFamilyDescriptor() nogil except+ - ColumnFamilyDescriptor( - const string&, - const options.ColumnFamilyOptions&) nogil except+ - string name - options.ColumnFamilyOptions options diff --git a/src/rdbpy/env.pxd b/src/rdbpy/env.pxd deleted file mode 100644 index 5996094..0000000 --- a/src/rdbpy/env.pxd +++ /dev/null @@ -1,5 +0,0 @@ -cdef extern from "rocksdb/env.h" namespace "rocksdb": - cdef cppclass Env: - Env() - - cdef Env* Env_Default "rocksdb::Env::Default"() diff --git a/src/rdbpy/errors.py b/src/rdbpy/errors.py index c62e14e..0b74074 100644 --- a/src/rdbpy/errors.py +++ b/src/rdbpy/errors.py @@ -1,26 +1,150 @@ -class NotFound(Exception): +"""Exception classes mapped from rocksdb::Status. + +One base class, one subclass per status code. Transaction conflicts are +distinct classes so callers can decide what to retry: Busy, TryAgain, +TimedOut (lock wait), Deadlock (a Busy with the deadlock subcode), +LockLimit and Expired. +""" + + +class RocksDBError(Exception): + """Base class. `code` and `subcode` are the raw rocksdb::Status values.""" + + code: int = 0 + subcode: int = 0 + + def __init__(self, message: str = "", code: int = 0, subcode: int = 0) -> None: + super().__init__(message) + self.code = code + self.subcode = subcode + + @property + def message(self) -> str: + return str(self.args[0]) if self.args else "" + + +class NotFound(RocksDBError): + """Key missing. Reads return None instead; raised only by other paths.""" + + +class Corruption(RocksDBError): + pass + + +class NotSupported(RocksDBError): + pass + + +class InvalidArgument(RocksDBError): + pass + + +class RocksIOError(RocksDBError): pass -class Corruption(Exception): +class MergeInProgress(RocksDBError): pass -class NotSupported(Exception): +class Incomplete(RocksDBError): pass -class InvalidArgument(Exception): +class ShutdownInProgress(RocksDBError): pass -class RocksIOError(Exception): +class TimedOut(RocksDBError): + """A lock (or mutex) wait exceeded its timeout.""" + + +class Aborted(RocksDBError): pass -class MergeInProgress(Exception): +class LockLimit(RocksDBError): + """TransactionDBOptions.max_num_locks reached (rocksdb reports it as Busy + or Aborted depending on the path, so it stands on its own).""" + + +class Busy(RocksDBError): + """Write conflict: the key changed after the transaction's snapshot, or + an optimistic commit failed validation.""" + + +class Deadlock(Busy): + """Lock wait would form a cycle (needs deadlock_detect=True).""" + + +class Expired(RocksDBError): + """Transaction expiration reached before commit.""" + + +class TryAgain(RocksDBError): + """Memtable history too short to validate; retry (see + max_write_buffer_size_to_maintain).""" + + +class CompactionTooLarge(RocksDBError): pass -class Incomplete(Exception): +class ColumnFamilyDropped(RocksDBError): pass + + +# rocksdb::Status::Code -> class +_BY_CODE = { + 1: NotFound, + 2: Corruption, + 3: NotSupported, + 4: InvalidArgument, + 5: RocksIOError, + 6: MergeInProgress, + 7: Incomplete, + 8: ShutdownInProgress, + 9: TimedOut, + 10: Aborted, + 11: Busy, + 12: Expired, + 13: TryAgain, + 14: CompactionTooLarge, + 15: ColumnFamilyDropped, +} + +_SUBCODE_LOCK_LIMIT = 3 +_SUBCODE_DEADLOCK = 5 + + +def error_for(code: int, subcode: int, message: str) -> RocksDBError: + """Build the exception for a non-ok status.""" + cls = _BY_CODE.get(code, RocksDBError) + if code == 11 and subcode == _SUBCODE_DEADLOCK: + cls = Deadlock + elif code in (10, 11) and subcode == _SUBCODE_LOCK_LIMIT: + cls = LockLimit + return cls(message, code, subcode) + + +__all__ = [ + "RocksDBError", + "NotFound", + "Corruption", + "NotSupported", + "InvalidArgument", + "RocksIOError", + "MergeInProgress", + "Incomplete", + "ShutdownInProgress", + "TimedOut", + "Aborted", + "LockLimit", + "Busy", + "Deadlock", + "Expired", + "TryAgain", + "CompactionTooLarge", + "ColumnFamilyDropped", + "error_for", +] diff --git a/src/rdbpy/filter_policy.pxd b/src/rdbpy/filter_policy.pxd deleted file mode 100644 index dbb7f5f..0000000 --- a/src/rdbpy/filter_policy.pxd +++ /dev/null @@ -1,39 +0,0 @@ -from libcpp cimport bool as cpp_bool -from libcpp.string cimport string -from libc.string cimport const_char -from rdbpy.slice_ cimport Slice -from rdbpy.std_memory cimport shared_ptr -from rdbpy.logger cimport Logger - -cdef extern from "rocksdb/filter_policy.h" namespace "rocksdb": - cdef cppclass FilterPolicy: - void CreateFilter(const Slice*, int, string*) nogil except+ - cpp_bool KeyMayMatch(const Slice&, const Slice&) nogil except+ - const_char* Name() nogil except+ - - cdef extern const FilterPolicy* NewBloomFilterPolicy(int) nogil except+ - -ctypedef void (*create_filter_func)( - void*, - Logger*, - string&, - const Slice*, - int, - string*) - -ctypedef cpp_bool (*key_may_match_func)( - void*, - Logger*, - string&, - const Slice&, - const Slice&) - -cdef extern from "rdb_include/filter_policy_wrapper.hpp" namespace "py_rocks": - cdef cppclass FilterPolicyWrapper: - FilterPolicyWrapper( - string, - void*, - create_filter_func, - key_may_match_func) nogil except+ - - void set_info_log(shared_ptr[Logger]) nogil except+ diff --git a/src/rdbpy/include/rdb_include/comparator_wrapper.hpp b/src/rdbpy/include/rdb_include/comparator_wrapper.hpp deleted file mode 100644 index 4af4704..0000000 --- a/src/rdbpy/include/rdb_include/comparator_wrapper.hpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "rocksdb/comparator.h" -#include "rocksdb/env.h" -#include - -using std::string; -using rocksdb::Comparator; -using rocksdb::Slice; -using rocksdb::Logger; - -namespace py_rocks { - class ComparatorWrapper: public Comparator { - public: - typedef int (*compare_func)( - void*, - Logger*, - string&, - const Slice&, - const Slice&); - - ComparatorWrapper( - string name, - void* compare_context, - compare_func compare_callback): - name(name), - compare_context(compare_context), - compare_callback(compare_callback) - {} - - virtual int Compare(const Slice& a, const Slice& b) const { - string error_msg; - int val; - - val = this->compare_callback( - this->compare_context, - this->info_log.get(), - error_msg, - a, - b); - - if (error_msg.size()) { - throw std::runtime_error(error_msg.c_str()); - } - return val; - } - - virtual const char* Name() const { - return this->name.c_str(); - } - - virtual void FindShortestSeparator(string*, const Slice&) const {} - virtual void FindShortSuccessor(string*) const {} - - void set_info_log(std::shared_ptr info_log) { - this->info_log = info_log; - } - - private: - string name; - void* compare_context; - compare_func compare_callback; - std::shared_ptr info_log; - }; -} diff --git a/src/rdbpy/include/rdb_include/filter_policy_wrapper.hpp b/src/rdbpy/include/rdb_include/filter_policy_wrapper.hpp deleted file mode 100644 index f6e8bef..0000000 --- a/src/rdbpy/include/rdb_include/filter_policy_wrapper.hpp +++ /dev/null @@ -1,89 +0,0 @@ -#include "rocksdb/filter_policy.h" -#include "rocksdb/env.h" -#include - -using std::string; -using rocksdb::FilterPolicy; -using rocksdb::Slice; -using rocksdb::Logger; - -namespace py_rocks { - class FilterPolicyWrapper: public FilterPolicy { - public: - typedef void (*create_filter_func)( - void* ctx, - Logger*, - string&, - const Slice* keys, - int n, - string* dst); - - typedef bool (*key_may_match_func)( - void* ctx, - Logger*, - string&, - const Slice& key, - const Slice& filter); - - FilterPolicyWrapper( - string name, - void* ctx, - create_filter_func create_filter_callback, - key_may_match_func key_may_match_callback): - name(name), - ctx(ctx), - create_filter_callback(create_filter_callback), - key_may_match_callback(key_may_match_callback) - {} - - virtual void - CreateFilter(const Slice* keys, int n, std::string* dst) const { - string error_msg; - - this->create_filter_callback( - this->ctx, - this->info_log.get(), - error_msg, - keys, - n, - dst); - - if (error_msg.size()) { - throw std::runtime_error(error_msg.c_str()); - } - } - - virtual bool - KeyMayMatch(const Slice& key, const Slice& filter) const { - string error_msg; - bool val; - - val = this->key_may_match_callback( - this->ctx, - this->info_log.get(), - error_msg, - key, - filter); - - if (error_msg.size()) { - throw std::runtime_error(error_msg.c_str()); - } - return val; - } - - virtual const char* Name() const { - return this->name.c_str(); - } - - void set_info_log(std::shared_ptr info_log) { - this->info_log = info_log; - } - - private: - string name; - void* ctx; - create_filter_func create_filter_callback; - key_may_match_func key_may_match_callback; - std::shared_ptr info_log; - }; -} diff --git a/src/rdbpy/include/rdb_include/memtable_factories.hpp b/src/rdbpy/include/rdb_include/memtable_factories.hpp deleted file mode 100644 index a0855be..0000000 --- a/src/rdbpy/include/rdb_include/memtable_factories.hpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "rocksdb/memtablerep.h" - -using rocksdb::MemTableRepFactory; -using rocksdb::VectorRepFactory; -using rocksdb::SkipListFactory; - -namespace py_rocks { - MemTableRepFactory* NewVectorRepFactory(size_t count = 0) { - return new VectorRepFactory(count); - } - - MemTableRepFactory* NewSkipListFactory() { - return new SkipListFactory(); - } -} diff --git a/src/rdbpy/include/rdb_include/merge_operator_wrapper.hpp b/src/rdbpy/include/rdb_include/merge_operator_wrapper.hpp deleted file mode 100644 index cd997d6..0000000 --- a/src/rdbpy/include/rdb_include/merge_operator_wrapper.hpp +++ /dev/null @@ -1,132 +0,0 @@ -#include "rocksdb/merge_operator.h" - -using std::string; -using std::deque; -using rocksdb::Slice; -using rocksdb::Logger; -using rocksdb::MergeOperator; -using rocksdb::AssociativeMergeOperator; - -namespace py_rocks { - class AssociativeMergeOperatorWrapper: public AssociativeMergeOperator { - public: - typedef bool (*merge_func)( - void*, - const Slice& key, - const Slice* existing_value, - const Slice& value, - std::string* new_value, - Logger* logger); - - - AssociativeMergeOperatorWrapper( - string name, - void* merge_context, - merge_func merge_callback): - name(name), - merge_context(merge_context), - merge_callback(merge_callback) - {} - - virtual bool Merge( - const Slice& key, - const Slice* existing_value, - const Slice& value, - std::string* new_value, - Logger* logger) const - { - return this->merge_callback( - this->merge_context, - key, - existing_value, - value, - new_value, - logger); - } - - virtual const char* Name() const { - return this->name.c_str(); - } - - private: - string name; - void* merge_context; - merge_func merge_callback; - }; - - class MergeOperatorWrapper: public MergeOperator { - public: - typedef bool (*full_merge_func)( - void* ctx, - const Slice& key, - const Slice* existing_value, - const deque& operand_list, - string* new_value, - Logger* logger); - - typedef bool (*partial_merge_func)( - void* ctx, - const Slice& key, - const Slice& left_op, - const Slice& right_op, - string* new_value, - Logger* logger); - - MergeOperatorWrapper( - string name, - void* full_merge_context, - void* partial_merge_context, - full_merge_func full_merge_callback, - partial_merge_func partial_merge_callback): - name(name), - full_merge_context(full_merge_context), - partial_merge_context(partial_merge_context), - full_merge_callback(full_merge_callback), - partial_merge_callback(partial_merge_callback) - {} - - virtual bool FullMerge( - const Slice& key, - const Slice* existing_value, - const deque& operand_list, - string* new_value, - Logger* logger) const - { - return this->full_merge_callback( - this->full_merge_context, - key, - existing_value, - operand_list, - new_value, - logger); - } - - virtual bool PartialMerge ( - const Slice& key, - const Slice& left_operand, - const Slice& right_operand, - string* new_value, - Logger* logger) const - { - return this->partial_merge_callback( - this->partial_merge_context, - key, - left_operand, - right_operand, - new_value, - logger); - } - - virtual const char* Name() const { - return this->name.c_str(); - } - - private: - string name; - void* full_merge_context; - void* partial_merge_context; - full_merge_func full_merge_callback; - partial_merge_func partial_merge_callback; - - }; -} diff --git a/src/rdbpy/include/rdb_include/slice_transform_wrapper.hpp b/src/rdbpy/include/rdb_include/slice_transform_wrapper.hpp deleted file mode 100644 index b8c5c28..0000000 --- a/src/rdbpy/include/rdb_include/slice_transform_wrapper.hpp +++ /dev/null @@ -1,109 +0,0 @@ -#include -#include "rocksdb/slice_transform.h" -#include "rocksdb/env.h" -#include - -using std::string; -using rocksdb::SliceTransform; -using rocksdb::Slice; -using rocksdb::Logger; - -namespace py_rocks { - class SliceTransformWrapper: public SliceTransform { - public: - typedef Slice (*transform_func)( - void*, - Logger*, - string&, - const Slice&); - - typedef bool (*in_domain_func)( - void*, - Logger*, - string&, - const Slice&); - - typedef bool (*in_range_func)( - void*, - Logger*, - string&, - const Slice&); - - SliceTransformWrapper( - string name, - void* ctx, - transform_func transfrom_callback, - in_domain_func in_domain_callback, - in_range_func in_range_callback): - name(name), - ctx(ctx), - transfrom_callback(transfrom_callback), - in_domain_callback(in_domain_callback), - in_range_callback(in_range_callback) - {} - - virtual const char* Name() const { - return this->name.c_str(); - } - - virtual Slice Transform(const Slice& src) const { - string error_msg; - Slice val; - - val = this->transfrom_callback( - this->ctx, - this->info_log.get(), - error_msg, - src); - - if (error_msg.size()) { - throw std::runtime_error(error_msg.c_str()); - } - return val; - } - - virtual bool InDomain(const Slice& src) const { - string error_msg; - bool val; - - val = this->in_domain_callback( - this->ctx, - this->info_log.get(), - error_msg, - src); - - if (error_msg.size()) { - throw std::runtime_error(error_msg.c_str()); - } - return val; - } - - virtual bool InRange(const Slice& dst) const { - string error_msg; - bool val; - - val = this->in_range_callback( - this->ctx, - this->info_log.get(), - error_msg, - dst); - - if (error_msg.size()) { - throw std::runtime_error(error_msg.c_str()); - } - return val; - } - - void set_info_log(std::shared_ptr info_log) { - this->info_log = info_log; - } - - private: - string name; - void* ctx; - transform_func transfrom_callback; - in_domain_func in_domain_callback; - in_range_func in_range_callback; - std::shared_ptr info_log; - }; -} diff --git a/src/rdbpy/include/rdb_include/utils.hpp b/src/rdbpy/include/rdb_include/utils.hpp deleted file mode 100644 index 43d2093..0000000 --- a/src/rdbpy/include/rdb_include/utils.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#include - -namespace py_rocks { - template - const T* vector_data(std::vector& v) { - return v.data(); - } -} diff --git a/src/rdbpy/include/rdb_include/write_batch_iter_helper.hpp b/src/rdbpy/include/rdb_include/write_batch_iter_helper.hpp deleted file mode 100644 index ff71d09..0000000 --- a/src/rdbpy/include/rdb_include/write_batch_iter_helper.hpp +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once - -#include -#include "rocksdb/write_batch.h" - -namespace py_rocks { - -class RecordItemsHandler: public rocksdb::WriteBatch::Handler { - public: - enum Optype {PutRecord, MergeRecord, DeleteRecord}; - - class BatchItem { - public: - BatchItem( - const Optype& op, - uint32_t column_family_id, - const rocksdb::Slice& key, - const rocksdb::Slice& value): - op(op), - column_family_id(column_family_id), - key(key), - value(value) - {} - - const Optype op; - uint32_t column_family_id; - const rocksdb::Slice key; - const rocksdb::Slice value; - }; - - typedef std::vector BatchItems; - - public: - /* Items is filled during iteration. */ - RecordItemsHandler(BatchItems* items): items(items) {} - - virtual rocksdb::Status PutCF( - uint32_t column_family_id, const Slice& key, const Slice& value) { - this->items->emplace_back(PutRecord, column_family_id, key, value); - return rocksdb::Status::OK(); - } - - virtual rocksdb::Status MergeCF( - uint32_t column_family_id, const Slice& key, const Slice& value) { - this->items->emplace_back(MergeRecord, column_family_id, key, value); - return rocksdb::Status::OK(); - } - - virtual rocksdb::Status DeleteCF( - uint32_t column_family_id, const Slice& key) { - this->items->emplace_back(DeleteRecord, column_family_id, key, rocksdb::Slice()); - return rocksdb::Status::OK(); - } - - private: - BatchItems* items; -}; - -rocksdb::Status -get_batch_items(const rocksdb::WriteBatch* batch, RecordItemsHandler::BatchItems* items) { - RecordItemsHandler handler(items); - return batch->Iterate(&handler); -} - -} diff --git a/src/rdbpy/interfaces.py b/src/rdbpy/interfaces.py deleted file mode 100644 index 10a6972..0000000 --- a/src/rdbpy/interfaces.py +++ /dev/null @@ -1,77 +0,0 @@ -from abc import ABCMeta, abstractmethod - - -class Comparator: - __metaclass__ = ABCMeta - - @abstractmethod - def compare(self, a, b): - pass - - @abstractmethod - def name(self): - pass - - -class AssociativeMergeOperator: - __metaclass__ = ABCMeta - - @abstractmethod - def merge(self, key, existing_value, value): - pass - - @abstractmethod - def name(self): - pass - - -class MergeOperator: - __metaclass__ = ABCMeta - - @abstractmethod - def full_merge(self, key, existing_value, operand_list): - pass - - @abstractmethod - def partial_merge(self, key, left_operand, right_operand): - pass - - @abstractmethod - def name(self): - pass - - -class FilterPolicy: - __metaclass__ = ABCMeta - - @abstractmethod - def name(self): - pass - - @abstractmethod - def create_filter(self, keys): - pass - - @abstractmethod - def key_may_match(self, key, filter_): - pass - - -class SliceTransform: - __metaclass__ = ABCMeta - - @abstractmethod - def name(self): - pass - - @abstractmethod - def transform(self, src): - pass - - @abstractmethod - def in_domain(self, src): - pass - - @abstractmethod - def in_range(self, dst): - pass diff --git a/src/rdbpy/iterator.pxd b/src/rdbpy/iterator.pxd deleted file mode 100644 index 96877c7..0000000 --- a/src/rdbpy/iterator.pxd +++ /dev/null @@ -1,16 +0,0 @@ -from libcpp cimport bool as cpp_bool -from rdbpy.slice_ cimport Slice -from rdbpy.status cimport Status - -cdef extern from "rocksdb/iterator.h" namespace "rocksdb": - cdef cppclass Iterator: - cpp_bool Valid() nogil except+ - void SeekToFirst() nogil except+ - void SeekToLast() nogil except+ - void Seek(const Slice&) nogil except+ - void Next() nogil except+ - void Prev() nogil except+ - void SeekForPrev(const Slice&) nogil except+ - Slice key() nogil except+ - Slice value() nogil except+ - Status status() nogil except+ diff --git a/src/rdbpy/lib_rocksdb.pxd b/src/rdbpy/lib_rocksdb.pxd deleted file mode 100644 index b26eb49..0000000 --- a/src/rdbpy/lib_rocksdb.pxd +++ /dev/null @@ -1,784 +0,0 @@ -# distutils: language = c++ - -import cython -from libcpp.string cimport string -from libcpp.deque cimport deque -from libcpp.vector cimport vector -from cpython cimport bool as py_bool -from libcpp cimport bool as cpp_bool -from libc.stdint cimport uint32_t -from cython.operator cimport dereference as deref -from cpython.bytes cimport PyBytes_AsString -from cpython.bytes cimport PyBytes_Size -from cpython.bytes cimport PyBytes_FromString -from cpython.bytes cimport PyBytes_FromStringAndSize -from cpython.unicode cimport PyUnicode_Decode - -from rdbpy.std_memory cimport shared_ptr -cimport rdbpy.options as options -cimport rdbpy.merge_operator as merge_operator -cimport rdbpy.filter_policy as filter_policy -cimport rdbpy.comparator as comparator -cimport rdbpy.slice_transform as slice_transform -cimport rdbpy.cache as cache -cimport rdbpy.logger as logger -cimport rdbpy.snapshot as snapshot -cimport rdbpy.db as db -cimport rdbpy.iterator as iterator -cimport rdbpy.backup as backup -cimport rdbpy.env as env -cimport rdbpy.transaction as transaction -cimport rdbpy.table_factory as table_factory -cimport rdbpy.memtablerep as memtablerep -cimport rdbpy.universal_compaction as universal_compaction - -# Enums are the only exception for direct imports -# Their name als already unique enough -from rdbpy.universal_compaction cimport kCompactionStopStyleSimilarSize -from rdbpy.universal_compaction cimport kCompactionStopStyleTotalSize - -from rdbpy.options cimport FlushOptions -from rdbpy.options cimport kCompactionStyleLevel -from rdbpy.options cimport kCompactionStyleUniversal -from rdbpy.options cimport kCompactionStyleFIFO -from rdbpy.options cimport kCompactionStyleNone - -from rdbpy.slice_ cimport Slice -from rdbpy.status cimport Status - -ctypedef const filter_policy.FilterPolicy ConstFilterPolicy - -cdef extern from "rdb_include/utils.hpp" namespace "py_rocks": - cdef const Slice* vector_data(vector[Slice]&) - -cdef extern from "Python.h": - void PyEval_InitThreads() - -cdef check_status(const Status& st) - -cdef string bytes_to_string(path) except * - -cdef string_to_bytes(string ob) - -cdef Slice bytes_to_slice(ob) except * - -cdef slice_to_bytes(Slice sl) - -cdef string path_to_string(object path) except * - -cdef object string_to_path(string path) - -cdef class PyComparator(object): - cdef object get_ob(self) - - cdef const comparator.Comparator* get_comparator(self) - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log) - -cdef class PyGenericComparator(PyComparator): - cdef comparator.ComparatorWrapper* comparator_ptr - cdef object ob - # def __cinit__(self, object ob) - # def __dealloc__(self) - cdef object get_ob(self) - cdef const comparator.Comparator* get_comparator(self) - cdef set_info_log(self, shared_ptr[logger.Logger] info_log) - -cdef class PyBytewiseComparator(PyComparator): - cdef const comparator.Comparator* comparator_ptr - # def __cinit__(self) - cpdef name(self) - cpdef compare(self, a, b) - cdef object get_ob(self) - cdef const comparator.Comparator* get_comparator(self) - - -cdef int compare_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& a, - const Slice& b) with gil - -# BytewiseComparator = PyBytewiseComparator -######################################### - - - -## Here comes the stuff for the filter policy -cdef class PyFilterPolicy(object): - cdef object get_ob(self) - cdef shared_ptr[ConstFilterPolicy] get_policy(self) - cdef set_info_log(self, shared_ptr[logger.Logger] info_log) - -cdef class PyGenericFilterPolicy(PyFilterPolicy): - cdef shared_ptr[filter_policy.FilterPolicyWrapper] policy - cdef object ob - # def __cinit__(self, object ob) - cdef object get_ob(self) - cdef shared_ptr[ConstFilterPolicy] get_policy(self) - cdef set_info_log(self, shared_ptr[logger.Logger] info_log) - - -cdef void create_filter_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice* keys, - int n, - string* dst) with gil - -cdef cpp_bool key_may_match_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& key, - const Slice& filt) with gil - -cdef class PyBloomFilterPolicy(PyFilterPolicy): - cdef shared_ptr[ConstFilterPolicy] policy - # def __cinit__(self, int bits_per_key) - cpdef name(self) - cpdef create_filter(self, keys) - cpdef key_may_match(self, key, filter_) - cdef object get_ob(self) - cdef shared_ptr[ConstFilterPolicy] get_policy(self) - -# BloomFilterPolicy = PyBloomFilterPolicy -# ############################################# - - - -## Here comes the stuff for the merge operator -cdef class PyMergeOperator(object): - cdef shared_ptr[merge_operator.MergeOperator] merge_op - cdef object ob - # def __cinit__(self, object ob) - cdef object get_ob(self) - cdef shared_ptr[merge_operator.MergeOperator] get_operator(self) - -cdef cpp_bool merge_callback( - void* ctx, - const Slice& key, - const Slice* existing_value, - const Slice& value, - string* new_value, - logger.Logger* log) with gil - -cdef cpp_bool full_merge_callback( - void* ctx, - const Slice& key, - const Slice* existing_value, - const deque[string]& op_list, - string* new_value, - logger.Logger* log) with gil - -cdef cpp_bool partial_merge_callback( - void* ctx, - const Slice& key, - const Slice& left_op, - const Slice& right_op, - string* new_value, - logger.Logger* log) with gil - -cdef class PyCache(object): - cdef shared_ptr[cache.Cache] get_cache(self) - -cdef class PyLRUCache(PyCache): - cdef shared_ptr[cache.Cache] cache_ob - # def __cinit__(self, capacity, shard_bits = *) - cdef shared_ptr[cache.Cache] get_cache(self) - -LRUCache = PyLRUCache -############################### - -### Here comes the stuff for SliceTransform -cdef class PySliceTransform(object): - cdef shared_ptr[slice_transform.SliceTransform] transfomer - cdef object ob - # def __cinit__(self, object ob) - cdef object get_ob(self) - cdef shared_ptr[slice_transform.SliceTransform] get_transformer(self) - cdef set_info_log(self, shared_ptr[logger.Logger] info_log) - - -cdef Slice slice_transform_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& src) with gil - -cdef cpp_bool slice_in_domain_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& src) with gil - -cdef cpp_bool slice_in_range_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& src) with gil - -## Here are the TableFactories -cdef class PyTableFactory(object): - cdef shared_ptr[table_factory.TableFactory] factory - cdef shared_ptr[table_factory.TableFactory] get_table_factory(self) - cdef set_info_log(self, shared_ptr[logger.Logger] info_log) - -cdef class BlockBasedTableFactory(PyTableFactory): - cdef PyFilterPolicy py_filter_policy - # def __init__(self, - # index_type='binary_search', - # py_bool hash_index_allow_collision=True, - # checksum='crc32', - # PyCache block_cache = *, - # PyCache block_cache_compressed = *, - # filter_policy = *, - # no_block_cache=False, - # block_size = *, - # block_size_deviation = *, - # block_restart_interval = *, - # whole_key_filtering = *) - cdef set_info_log(self, shared_ptr[logger.Logger] info_log) - -cdef class PlainTableFactory(PyTableFactory): - pass - # def __init__( - # self, - # user_key_len=0, - # bloom_bits_per_key=10, - # hash_table_ratio=0.75, - # index_sparseness=10, - # huge_page_tlb_size=0, - # encoding_type='plain', - # py_bool full_scan_mode=False) -############################################# - -### Here are the MemtableFactories -cdef class PyMemtableFactory(object): - cdef shared_ptr[memtablerep.MemTableRepFactory] factory - cdef shared_ptr[memtablerep.MemTableRepFactory] get_memtable_factory(self) - -cdef class SkipListMemtableFactory(PyMemtableFactory): - pass - # def __init__(self) - -cdef class VectorMemtableFactory(PyMemtableFactory): - pass - # def __init__(self, count=0) - -cdef class HashSkipListMemtableFactory(PyMemtableFactory): - pass - # def __init__( - # self, - # bucket_count=1000000, - # skiplist_height=4, - # skiplist_branching_factor=4) - -cdef class HashLinkListMemtableFactory(PyMemtableFactory): - pass - # def __init__(self, bucket_count=50000) -################################## - - -cdef class CompressionType(object): - pass - # no_compression = u'no_compression' - # snappy_compression = u'snappy_compression' - # zlib_compression = u'zlib_compression' - # bzip2_compression = u'bzip2_compression' - # lz4_compression = u'lz4_compression' - # lz4hc_compression = u'lz4hc_compression' - # xpress_compression = u'xpress_compression' - # zstd_compression = u'zstd_compression' - # zstdnotfinal_compression = u'zstdnotfinal_compression' - # disable_compression = u'disable_compression' - -cdef class CompactionPri(object): - pass - # by_compensated_size = u'by_compensated_size' - # oldest_largest_seq_first = u'oldest_largest_seq_first' - # oldest_smallest_seq_first = u'oldest_smallest_seq_first' - # min_overlapping_ratio = u'min_overlapping_ratio' - -cdef class _ColumnFamilyHandle: - """ This is an internal class that we will weakref for safety """ - cdef db.ColumnFamilyHandle* handle - cdef object __weakref__ - cdef object weak_handle - # def __cinit__(self) - # def __dealloc__(self) - @staticmethod - cdef from_handle_ptr(db.ColumnFamilyHandle* handle) - # @property - # def name(self) - # @property - # def id(self) - # @property - # def weakref(self) - -cdef class ColumnFamilyHandle: - """ This represents a ColumnFamilyHandle """ - cdef object _ref - cdef readonly bytes name - cdef readonly int id - # def __cinit__(self, weakhandle) - # def __init__(self, *) - @staticmethod - cdef object from_wrapper(_ColumnFamilyHandle real_handle) - # @property - # cpdef is_valid(self) - # def __repr__(self) - cdef db.ColumnFamilyHandle* get_handle(self) except NULL - # def __eq__(self, other) - # def __lt__(self, other) - # Since @total_ordering isn't a thing for cython - # def __ne__(self, other) - # def __gt__(self, other) - # def __le__(self, other) - # def __ge__(self, other) - # def __hash__(self) - -cdef class ColumnFamilyOptions(object): - cdef options.ColumnFamilyOptions* copts - cdef PyComparator py_comparator - cdef PyMergeOperator py_merge_operator - cdef PySliceTransform py_prefix_extractor - cdef PyTableFactory py_table_factory - cdef PyMemtableFactory py_memtable_factory - - # Used to protect sharing of Options with many DB-objects - cdef cpp_bool in_use - # def __cinit__(self) - # def __dealloc__(self) - # def __init__(self, **kwargs) - # property write_buffer_size: - # def __get__(self) - # def __set__(self, value) - # property max_write_buffer_number: - # def __get__(self) - # def __set__(self, value) - # property min_write_buffer_number_to_merge: - # def __get__(self) - # def __set__(self, value) - # property compression_opts: - # def __get__(self) - # def __set__(self, dict value) - # property compaction_pri: - # def __get__(self) - # def __set__(self, value) - # property compression: - # def __get__(self) - # def __set__(self, value) - # property max_compaction_bytes: - # def __get__(self) - # def __set__(self, value) - # property num_levels: - # def __get__(self) - # def __set__(self, value) - # property level0_file_num_compaction_trigger: - # def __get__(self) - # def __set__(self, value) - # property level0_slowdown_writes_trigger: - # def __get__(self) - # def __set__(self, value) - # property level0_stop_writes_trigger: - # def __get__(self) - # def __set__(self, value) - # property max_mem_compaction_level: - # def __get__(self) - # def __set__(self, value) - # property target_file_size_base: - # def __get__(self) - # def __set__(self, value) - # property target_file_size_multiplier: - # def __get__(self) - # def __set__(self, value) - # property max_bytes_for_level_base: - # def __get__(self) - # def __set__(self, value) - # property max_bytes_for_level_multiplier: - # def __get__(self) - # def __set__(self, value) - # property max_bytes_for_level_multiplier_additional: - # def __get__(self) - # def __set__(self, value) - # property arena_block_size: - # def __get__(self) - # def __set__(self, value) - # property disable_auto_compactions: - # def __get__(self) - # def __set__(self, value) - # # FIXME: remove to util/options_helper.h - # # property allow_os_buffer: - # # def __get__(self): - # # return self.copts.allow_os_buffer - # # def __set__(self, value): - # # self.copts.allow_os_buffer = value - # property compaction_style: - # def __get__(self) - # def __set__(self, str value) - # property compaction_options_universal: - # def __get__(self) - # def __set__(self, dict value) - # # Deprecate - # # property filter_deletes: - # # def __get__(self): - # # return self.copts.filter_deletes - # # def __set__(self, value): - # # self.copts.filter_deletes = value - # property max_sequential_skip_in_iterations: - # def __get__(self) - # def __set__(self, value) - # property inplace_update_support: - # def __get__(self) - # def __set__(self, value) - # property table_factory: - # def __get__(self) - # def __set__(self, PyTableFactory value) - # property memtable_factory: - # def __get__(self) - # def __set__(self, PyMemtableFactory value) - # property inplace_update_num_locks: - # def __get__(self) - # def __set__(self, value) - # property comparator: - # def __get__(self) - # def __set__(self, value) - # property merge_operator: - # def __get__(self) - # def __set__(self, value) - # property prefix_extractor: - # def __get__(self) - # def __set__(self, value) - -cdef class Options(ColumnFamilyOptions): - cdef options.Options* opts - cdef PyCache py_row_cache - # def __cinit__(self) - # def __dealloc__(self) - # def __init__(self, **kwargs) -# property create_if_missing: -# def __get__(self) -# def __set__(self, value) -# property error_if_exists: -# def __get__(self) -# def __set__(self, value) -# property paranoid_checks: -# def __get__(self) -# def __set__(self, value) -# property max_open_files: -# def __get__(self) -# def __set__(self, value) -# property use_fsync: -# def __get__(self) -# def __set__(self, value) -# property db_log_dir: -# def __get__(self) -# def __set__(self, value) -# property wal_dir: -# def __get__(self) -# def __set__(self, value) -# property delete_obsolete_files_period_micros: -# def __get__(self) -# def __set__(self, value) -# property max_background_compactions: -# def __get__(self) -# def __set__(self, value) -# property max_background_flushes: -# def __get__(self) -# def __set__(self, value) -# property max_log_file_size: -# def __get__(self) -# def __set__(self, value) -# property db_write_buffer_size: -# def __get__(self) -# def __set__(self, value) -# property log_file_time_to_roll: -# def __get__(self) -# def __set__(self, value) -# property keep_log_file_num: -# def __get__(self) -# def __set__(self, value) -# property max_manifest_file_size: -# def __get__(self) -# def __set__(self, value) -# property table_cache_numshardbits: -# def __get__(self) -# def __set__(self, value) -# property wal_ttl_seconds: -# def __get__(self) -# def __set__(self, value) -# property wal_size_limit_mb: -# def __get__(self) -# def __set__(self, value) -# property manifest_preallocation_size: -# def __get__(self) -# def __set__(self, value) -# property enable_write_thread_adaptive_yield: -# def __get__(self) -# def __set__(self, value) -# property allow_concurrent_memtable_write: -# def __get__(self) -# def __set__(self, value) -# property allow_mmap_reads: -# def __get__(self) -# def __set__(self, value) -# property allow_mmap_writes: -# def __get__(self) -# def __set__(self, value) -# property is_fd_close_on_exec: -# def __get__(self) -# def __set__(self, value) -# property stats_dump_period_sec: -# def __get__(self) -# def __set__(self, value) -# property advise_random_on_open: -# def __get__(self) -# def __set__(self, value) -# # TODO: need to remove -Wconversion to make this work -# # property access_hint_on_compaction_start: -# # def __get__(sel -# # def __set__(self, AccessHint valu -# property use_adaptive_mutex: -# def __get__(self) -# def __set__(self, value) -# property bytes_per_sync: -# def __get__(self) -# def __set__(self, value) -# property row_cache: -# def __get__(self) -# def __set__(self, value) -# # cpp_bool skip_checking_sst_file_sizes_on_db_open -# property skip_checking_sst_file_sizes_on_db_open: -# def __get__(self) -# def __set__(self, value) -# # cpp_bool skip_stats_update_on_db_open -# property skip_stats_update_on_db_open: -# def __get__(self) -# def __set__(self, value) - -# Forward declaration -# cdef class Snapshot - -# cdef class KeysIterator -# cdef class ValuesIterator -# cdef class ItemsIterator -# cdef class ReversedIterator - -cdef class TransactionDBOptions(object): - cdef transaction.TransactionDBOptions* opts - cdef bint in_use - -cdef class TransactionOptions(object): - cdef transaction.TransactionOptions* opts - -# # Forward declaration -# cdef class WriteBatchIterator - -cdef class WriteBatch(object): - cdef db.WriteBatch* batch - - # def __cinit__(self, data = *) - # def __dealloc__(self) - cpdef void put(self, bytes key, bytes value, ColumnFamilyHandle column_family = *) - cpdef void merge(self, bytes key, bytes value, ColumnFamilyHandle column_family = *) - cpdef void delete_single(self, bytes key, ColumnFamilyHandle column_family = *) - cpdef void delete_range(self, bytes begin_key, bytes end_key, ColumnFamilyHandle column_family = *) - cpdef void clear(self) - cpdef data(self) - cpdef int count(self) - # def __iter__(self) - -cdef class WriteBatchIterator(object): - # Need a reference to the WriteBatch. - # The BatchItems are only pointers to the memory in WriteBatch. - cdef WriteBatch batch - cdef vector[db.BatchItem] items - cdef size_t pos - # def __init__(self, WriteBatch batch) - # def __iter__(self) - # def __next__(self) - -cdef class IDB(object): - cpdef void put(self, bytes key, bytes value, cpp_bool sync = *, cpp_bool disable_wal = *, ColumnFamilyHandle column_family = *) - cpdef void delete_single(self, bytes key, cpp_bool sync = *, cpp_bool disable_wal = *, ColumnFamilyHandle column_family = *) - cpdef void delete_range(self, bytes begin_key, bytes end_key, cpp_bool sync = *, cpp_bool disable_wal = *, ColumnFamilyHandle column_family = *) - cpdef void flush(self) - cpdef void flush_wal(self, cpp_bool sync = *) - cpdef void merge(self, bytes key, bytes value, cpp_bool sync = *, cpp_bool disable_wal = *, ColumnFamilyHandle column_family = *) - cpdef void write(self, WriteBatch batch, cpp_bool sync = *, cpp_bool disable_wal = *) - cpdef get(self, bytes key, ColumnFamilyHandle column_family = *) - cpdef multi_get(self, keys) - cpdef key_may_exist(self, bytes key, cpp_bool fetch = *, ColumnFamilyHandle column_family = *) - cpdef Iterator iterkeys(self, ColumnFamilyHandle column_family = *) - cpdef Iterator itervalues(self, ColumnFamilyHandle column_family = *) - cpdef Iterator iteritems(self, ColumnFamilyHandle column_family = *) - -@cython.no_gc_clear -cdef class DB(IDB): - cdef Options opts - cdef db.DB* db - cdef list cf_handles - cdef list cf_options - cdef set _iterators - cdef set _snapshots - # Used by TransactionDB, declared here so it is still set when - # DB.__dealloc__ calls TransactionDB.close() after TransactionDB's own - # fields were cleared. - cdef set _transactions - cdef int _check_open(self) except -1 - # def __cinit__(self, db_name, Options opts, dict column_families = *, read_only=False) - # def __dealloc__(self) - cpdef void close(self) - # @property - # cpdef column_families(self) - cpdef get_column_family(self, bytes name) - cpdef iterskeys(self, column_families) - cpdef itersvalues(self, column_families) - cpdef itersitems(self, column_families) - cpdef snapshot(self) - cpdef get_property(self, prop, ColumnFamilyHandle column_family = *) - cpdef try_catch_up_with_primary(self) - cpdef get_live_files_metadata(self) - cpdef void compact_range( - self, - bytes begin = *, - bytes end = *, - cpp_bool change_level = *, - int target_level = *, - str bottommost_level_compaction = *, - ColumnFamilyHandle column_family = * - ) - # @staticmethod - # def __parse_read_opts( - # verify_checksums = *, - # fill_cache = *, - # snapshot = *, - # read_tier = *) - cdef options.ReadOptions build_read_opts(self, dict py_opts) - # property options: - # def __get__(self) - cpdef create_column_family(self, bytes name, ColumnFamilyOptions copts) - cpdef void drop_column_family(self, ColumnFamilyHandle weak_handle) - -cpdef repair_db(db_name, Options opts) - -cpdef list_column_families(db_name, Options opts) - -@cython.no_gc_clear -cdef class TransactionDB(DB): - cdef transaction.CppTransactionDB* txn_db - cdef TransactionDBOptions txn_opts - cpdef begin_transaction(self, TransactionOptions txn_options = *, dict write_options = *, Transaction reuse = *) - cpdef void close(self) - - -@cython.no_gc_clear -cdef class Transaction(object): - cdef transaction.Transaction* txn - cdef TransactionDB db - cdef bint closed - cdef set _iterators - - cdef void _release(self) - - cdef void _ensure_open(self) - cpdef void close(self) - cpdef void commit(self) - cpdef void rollback(self) - cpdef void prepare(self) - cpdef void set_snapshot(self) - cpdef void clear_snapshot(self) - cpdef snapshot(self) - cpdef void save_point(self) - cpdef void rollback_to_save_point(self) - cpdef void pop_save_point(self) - cpdef set_name(self, name) - cpdef get_name(self) - cpdef get_id(self) - cpdef void put(self, bytes key, bytes value, ColumnFamilyHandle column_family = *, cpp_bool assume_tracked = *) - cpdef void merge(self, bytes key, bytes value, ColumnFamilyHandle column_family = *, cpp_bool assume_tracked = *) - cpdef void delete_single(self, bytes key, ColumnFamilyHandle column_family = *, cpp_bool assume_tracked = *) - cpdef get(self, bytes key, ColumnFamilyHandle column_family = *) - cpdef multi_get(self, keys) - cpdef Iterator iterkeys(self, ColumnFamilyHandle column_family = *) - cpdef Iterator itervalues(self, ColumnFamilyHandle column_family = *) - cpdef Iterator iteritems(self, ColumnFamilyHandle column_family = *) - cpdef void disable_indexing(self) - cpdef void enable_indexing(self) - - -@cython.no_gc_clear -cdef class Snapshot(object): - cdef const snapshot.Snapshot* ptr - cdef DB db - - # def __cinit__(self, DB db) - # def __dealloc__(self) - - -cdef class Iterator: - cdef object _current_value - - cpdef object next(self) - cpdef object get(self) - cpdef void skip(self) - cpdef void skip_back(self) - - -@cython.no_gc_clear -cdef class BaseIterator(Iterator): - cdef iterator.Iterator* ptr - cdef DB db - cdef ColumnFamilyHandle handle - cdef object owner - - cdef int _check_valid(self) except -1 - cdef void _invalidate(self) - - # def __cinit__(self, DB db, ColumnFamilyHandle handle = None) - # def __dealloc__(self) - # def __iter__(self) - # def __next__(self) - # def __reversed__(self) - cpdef void seek_to_first(self) - cpdef void seek_to_last(self) - cpdef void seek(self, bytes key) - cpdef void seek_for_prev(self, bytes key) - cdef object get_ob(self) - -cdef class KeysIterator(BaseIterator): - cdef object get_ob(self) - -cdef class ValuesIterator(BaseIterator): - cdef object get_ob(self) - -cdef class ItemsIterator(BaseIterator): - cdef object get_ob(self) - -cdef class ReversedIterator(Iterator): - cdef BaseIterator it - - # def __cinit__(self, BaseIterator it) - cpdef void seek_to_first(self) - cpdef void seek_to_last(self) - cpdef void seek(self, bytes key) - cpdef void seek_for_prev(self, bytes key) - # def __iter__(self) - # def __reversed__(self) - # def __next__(self) - -cdef class BackupEngine(object): - cdef backup.BackupEngine* engine - - # def __cinit__(self, backup_dir)s - # def __dealloc__(self) - cpdef create_backup(self, DB db, flush_before_backup = *) - cpdef restore_backup(self, backup_id, db_dir, wal_dir) - cpdef restore_latest_backup(self, db_dir, wal_dir) - cpdef stop_backup(self) - cpdef purge_old_backups(self, num_backups_to_keep) - cpdef delete_backup(self, backup_id) - cpdef get_backup_info(self) diff --git a/src/rdbpy/lib_rocksdb.pyi b/src/rdbpy/lib_rocksdb.pyi deleted file mode 100644 index fc58e11..0000000 --- a/src/rdbpy/lib_rocksdb.pyi +++ /dev/null @@ -1,1465 +0,0 @@ -# import cython -# from libcpp.string cimport string -# from libcpp.deque cimport deque -# from libcpp.vector cimport vector -# from cpython cimport bool as py_bool -# from libcpp cimport bool as cpp_bool -# from libc.stdint cimport uint32_t -# from cython.operator cimport dereference as deref -# from cpython.bytes cimport PyBytes_AsString -# from cpython.bytes cimport PyBytes_Size -# from cpython.bytes cimport PyBytes_FromString -# from cpython.bytes cimport PyBytes_FromStringAndSize -# from cpython.unicode cimport PyUnicode_Decode - -# from std_memory cimport shared_ptr -# cimport options -# cimport merge_operator -# cimport filter_policy -# cimport comparator -# cimport slice_transform -# cimport cache -# cimport logger -# cimport snapshot -# cimport db -# cimport iterator -# cimport backup -# cimport env -# cimport table_factory -# cimport memtablerep -# cimport universal_compaction - -# # Enums are the only exception for direct imports -# # Their name als already unique enough -# from universal_compaction cimport kCompactionStopStyleSimilarSize -# from universal_compaction cimport kCompactionStopStyleTotalSize - -# from options cimport kCompactionStyleLevel -# from options cimport kCompactionStyleUniversal -# from options cimport kCompactionStyleFIFO -# from options cimport kCompactionStyleNone - -# from slice_ cimport Slice -# from status cimport Status - -# import sys -# from interfaces import MergeOperator as IMergeOperator -# from interfaces import AssociativeMergeOperator as IAssociativeMergeOperator -# from interfaces import FilterPolicy as IFilterPolicy -# from interfaces import Comparator as IComparator -# from interfaces import SliceTransform as ISliceTransform -# import traceback -# import errors -# import weakref - -# ctypedef const filter_policy.FilterPolicy ConstFilterPolicy - -# cdef extern from "cpp/utils.hpp" namespace "py_rocks": -# cdef const Slice* vector_data(vector[Slice]&) - -# # Prepare python for threaded usage. -# # Python callbacks (merge, comparator) -# # could be executed in a rocksdb background thread (eg. compaction). -# cdef extern from "Python.h": -# void PyEval_InitThreads() -# PyEval_InitThreads() - -# ## Here comes the stuff to wrap the status to exception -# cdef check_status(const Status& st): -# if st.ok(): -# return - -# if st.IsNotFound(): -# raise errors.NotFound(st.ToString()) - -# if st.IsCorruption(): -# raise errors.Corruption(st.ToString()) - -# if st.IsNotSupported(): -# raise errors.NotSupported(st.ToString()) - -# if st.IsInvalidArgument(): -# raise errors.InvalidArgument(st.ToString()) - -# if st.IsIOError(): -# raise errors.RocksIOError(st.ToString()) - -# if st.IsMergeInProgress(): -# raise errors.MergeInProgress(st.ToString()) - -# if st.IsIncomplete(): -# raise errors.Incomplete(st.ToString()) - -# raise Exception("Unknown error: %s" % st.ToString()) -# ###################################################### - -# cdef string bytes_to_string(path) except *: -# return string(PyBytes_AsString(path), PyBytes_Size(path)) - -# cdef string_to_bytes(string ob): -# return PyBytes_FromStringAndSize(ob.c_str(), ob.size()) - -# cdef Slice bytes_to_slice(ob) except *: -# return Slice(PyBytes_AsString(ob), PyBytes_Size(ob)) - -# cdef slice_to_bytes(Slice sl): -# return PyBytes_FromStringAndSize(sl.data(), sl.size()) - -# ## only for filsystem paths -# cdef string path_to_string(object path) except *: -# if isinstance(path, bytes): -# return bytes_to_string(path) -# if isinstance(path, unicode): -# path = path.encode(sys.getfilesystemencoding()) -# return bytes_to_string(path) -# else: -# raise TypeError("Wrong type for path: %s" % path) - -# cdef object string_to_path(string path): -# fs_encoding = sys.getfilesystemencoding().encode('ascii') -# return PyUnicode_Decode(path.c_str(), path.size(), fs_encoding, "replace") - -# ## Here comes the stuff for the comparator -# @cython.internal -# cdef class PyComparator(object): -# cdef object get_ob(self): -# return None - -# cdef const comparator.Comparator* get_comparator(self): -# return NULL - -# cdef set_info_log(self, shared_ptr[logger.Logger] info_log): -# pass - -# @cython.internal -# cdef class PyGenericComparator(PyComparator): -# cdef comparator.ComparatorWrapper* comparator_ptr -# cdef object ob - -# def __cinit__(self, object ob): -# self.comparator_ptr = NULL -# if not isinstance(ob, IComparator): -# raise TypeError("%s is not of type %s" % (ob, IComparator)) - -# self.ob = ob -# self.comparator_ptr = new comparator.ComparatorWrapper( -# bytes_to_string(ob.name()), -# ob, -# compare_callback) - -# def __dealloc__(self): -# if not self.comparator_ptr == NULL: -# del self.comparator_ptr - -# cdef object get_ob(self): -# return self.ob - -# cdef const comparator.Comparator* get_comparator(self): -# return self.comparator_ptr - -# cdef set_info_log(self, shared_ptr[logger.Logger] info_log): -# self.comparator_ptr.set_info_log(info_log) - -# @cython.internal -# cdef class PyBytewiseComparator(PyComparator): -# cdef const comparator.Comparator* comparator_ptr - -# def __cinit__(self): -# self.comparator_ptr = comparator.BytewiseComparator() - -# def name(self): -# return PyBytes_FromString(self.comparator_ptr.Name()) - -# def compare(self, a, b): -# return self.comparator_ptr.Compare( -# bytes_to_slice(a), -# bytes_to_slice(b)) - -# cdef object get_ob(self): -# return self - -# cdef const comparator.Comparator* get_comparator(self): -# return self.comparator_ptr - -# cdef int compare_callback( -# void* ctx, -# logger.Logger* log, -# string& error_msg, -# const Slice& a, -# const Slice& b) with gil: - -# try: -# return (ctx).compare(slice_to_bytes(a), slice_to_bytes(b)) -# except BaseException as error: -# tb = traceback.format_exc() -# logger.Log(log, "Error in compare callback: %s", tb) -# error_msg.assign(str(error)) - -# BytewiseComparator = PyBytewiseComparator -# ######################################### - -# ## Here comes the stuff for the filter policy -# @cython.internal -# cdef class PyFilterPolicy(object): -# cdef object get_ob(self): -# return None - -# cdef shared_ptr[ConstFilterPolicy] get_policy(self): -# return shared_ptr[ConstFilterPolicy]() - -# cdef set_info_log(self, shared_ptr[logger.Logger] info_log): -# pass - -# @cython.internal -# cdef class PyGenericFilterPolicy(PyFilterPolicy): -# cdef shared_ptr[filter_policy.FilterPolicyWrapper] policy -# cdef object ob - -# def __cinit__(self, object ob): -# if not isinstance(ob, IFilterPolicy): -# raise TypeError("%s is not of type %s" % (ob, IFilterPolicy)) - -# self.ob = ob -# self.policy.reset(new filter_policy.FilterPolicyWrapper( -# bytes_to_string(ob.name()), -# ob, -# create_filter_callback, -# key_may_match_callback)) - -# cdef object get_ob(self): -# return self.ob - -# cdef shared_ptr[ConstFilterPolicy] get_policy(self): -# return (self.policy) - -# cdef set_info_log(self, shared_ptr[logger.Logger] info_log): -# self.policy.get().set_info_log(info_log) - -# cdef void create_filter_callback( -# void* ctx, -# logger.Logger* log, -# string& error_msg, -# const Slice* keys, -# int n, -# string* dst) with gil: - -# try: -# ret = (ctx).create_filter( -# [slice_to_bytes(keys[i]) for i in range(n)]) -# dst.append(bytes_to_string(ret)) -# except BaseException as error: -# tb = traceback.format_exc() -# logger.Log(log, "Error in create filter callback: %s", tb) -# error_msg.assign(str(error)) - -# cdef cpp_bool key_may_match_callback( -# void* ctx, -# logger.Logger* log, -# string& error_msg, -# const Slice& key, -# const Slice& filt) with gil: - -# try: -# return (ctx).key_may_match( -# slice_to_bytes(key), -# slice_to_bytes(filt)) -# except BaseException as error: -# tb = traceback.format_exc() -# logger.Log(log, "Error in key_mach_match callback: %s", tb) -# error_msg.assign(str(error)) - -# @cython.internal -# cdef class PyBloomFilterPolicy(PyFilterPolicy): -# cdef shared_ptr[ConstFilterPolicy] policy - -# def __cinit__(self, int bits_per_key): -# self.policy.reset(filter_policy.NewBloomFilterPolicy(bits_per_key)) - -# def name(self): -# return PyBytes_FromString(self.policy.get().Name()) - -# def create_filter(self, keys): -# cdef string dst -# cdef vector[Slice] c_keys - -# for key in keys: -# c_keys.push_back(bytes_to_slice(key)) - -# self.policy.get().CreateFilter( -# vector_data(c_keys), -# c_keys.size(), -# cython.address(dst)) - -# return string_to_bytes(dst) - -# def key_may_match(self, key, filter_): -# return self.policy.get().KeyMayMatch( -# bytes_to_slice(key), -# bytes_to_slice(filter_)) - -# cdef object get_ob(self): -# return self - -# cdef shared_ptr[ConstFilterPolicy] get_policy(self): -# return self.policy - -# BloomFilterPolicy = PyBloomFilterPolicy -# ############################################# - -# ## Here comes the stuff for the merge operator -# @cython.internal -# cdef class PyMergeOperator(object): -# cdef shared_ptr[merge_operator.MergeOperator] merge_op -# cdef object ob - -# def __cinit__(self, object ob): -# self.ob = ob -# if isinstance(ob, IAssociativeMergeOperator): -# self.merge_op.reset( -# -# new merge_operator.AssociativeMergeOperatorWrapper( -# bytes_to_string(ob.name()), -# (ob), -# merge_callback)) - -# elif isinstance(ob, IMergeOperator): -# self.merge_op.reset( -# -# new merge_operator.MergeOperatorWrapper( -# bytes_to_string(ob.name()), -# ob, -# ob, -# full_merge_callback, -# partial_merge_callback)) -# # elif isinstance(ob, str): -# # if ob == "put": -# # self.merge_op = merge_operator.MergeOperators.CreatePutOperator() -# # elif ob == "put_v1": -# # self.merge_op = merge_operator.MergeOperators.CreateDeprecatedPutOperator() -# # elif ob == "uint64add": -# # self.merge_op = merge_operator.MergeOperators.CreateUInt64AddOperator() -# # elif ob == "stringappend": -# # self.merge_op = merge_operator.MergeOperators.CreateStringAppendOperator() -# # #TODO: necessary? -# # # elif ob == "stringappendtest": -# # # self.merge_op = merge_operator.MergeOperators.CreateStringAppendTESTOperator() -# # elif ob == "max": -# # self.merge_op = merge_operator.MergeOperators.CreateMaxOperator() -# # else: -# # msg = "{0} is not the default type".format(ob) -# # raise TypeError(msg) -# else: -# msg = "%s is not of this types %s" -# msg %= (ob, (IAssociativeMergeOperator, IMergeOperator)) -# raise TypeError(msg) - -# cdef object get_ob(self): -# return self.ob - -# cdef shared_ptr[merge_operator.MergeOperator] get_operator(self): -# return self.merge_op - -# cdef cpp_bool merge_callback( -# void* ctx, -# const Slice& key, -# const Slice* existing_value, -# const Slice& value, -# string* new_value, -# logger.Logger* log) with gil: - -# if existing_value == NULL: -# py_existing_value = None -# else: -# py_existing_value = slice_to_bytes(deref(existing_value)) - -# try: -# ret = (ctx).merge( -# slice_to_bytes(key), -# py_existing_value, -# slice_to_bytes(value)) - -# if ret[0]: -# new_value.assign(bytes_to_string(ret[1])) -# return True -# return False - -# except: -# tb = traceback.format_exc() -# logger.Log(log, "Error in merge_callback: %s", tb) -# return False - -# cdef cpp_bool full_merge_callback( -# void* ctx, -# const Slice& key, -# const Slice* existing_value, -# const deque[string]& op_list, -# string* new_value, -# logger.Logger* log) with gil: - -# if existing_value == NULL: -# py_existing_value = None -# else: -# py_existing_value = slice_to_bytes(deref(existing_value)) - -# try: -# ret = (ctx).full_merge( -# slice_to_bytes(key), -# py_existing_value, -# [string_to_bytes(op_list[i]) for i in range(op_list.size())]) - -# if ret[0]: -# new_value.assign(bytes_to_string(ret[1])) -# return True -# return False - -# except: -# tb = traceback.format_exc() -# logger.Log(log, "Error in full_merge_callback: %s", tb) -# return False - -# cdef cpp_bool partial_merge_callback( -# void* ctx, -# const Slice& key, -# const Slice& left_op, -# const Slice& right_op, -# string* new_value, -# logger.Logger* log) with gil: - -# try: -# ret = (ctx).partial_merge( -# slice_to_bytes(key), -# slice_to_bytes(left_op), -# slice_to_bytes(right_op)) - -# if ret[0]: -# new_value.assign(bytes_to_string(ret[1])) -# return True -# return False - -# except: -# tb = traceback.format_exc() -# logger.Log(log, "Error in partial_merge_callback: %s", tb) -# return False -# ############################################## - -# #### Here comes the Cache stuff -# @cython.internal -# cdef class PyCache(object): -# cdef shared_ptr[cache.Cache] get_cache(self): -# return shared_ptr[cache.Cache]() - -# @cython.internal -# cdef class PyLRUCache(PyCache): -# cdef shared_ptr[cache.Cache] cache_ob - -# def __cinit__(self, capacity, shard_bits=None): -# if shard_bits is not None: -# self.cache_ob = cache.NewLRUCache(capacity, shard_bits) -# else: -# self.cache_ob = cache.NewLRUCache(capacity) - -# cdef shared_ptr[cache.Cache] get_cache(self): -# return self.cache_ob - -# LRUCache = PyLRUCache -# ############################### - -# ### Here comes the stuff for SliceTransform -# @cython.internal -# cdef class PySliceTransform(object): -# cdef shared_ptr[slice_transform.SliceTransform] transfomer -# cdef object ob - -# def __cinit__(self, object ob): -# if not isinstance(ob, ISliceTransform): -# raise TypeError("%s is not of type %s" % (ob, ISliceTransform)) - -# self.ob = ob -# self.transfomer.reset( -# -# new slice_transform.SliceTransformWrapper( -# bytes_to_string(ob.name()), -# ob, -# slice_transform_callback, -# slice_in_domain_callback, -# slice_in_range_callback)) - -# cdef object get_ob(self): -# return self.ob - -# cdef shared_ptr[slice_transform.SliceTransform] get_transformer(self): -# return self.transfomer - -# cdef set_info_log(self, shared_ptr[logger.Logger] info_log): -# cdef slice_transform.SliceTransformWrapper* ptr -# ptr = self.transfomer.get() -# ptr.set_info_log(info_log) - -# cdef Slice slice_transform_callback( -# void* ctx, -# logger.Logger* log, -# string& error_msg, -# const Slice& src) with gil: - -# cdef size_t offset -# cdef size_t size - -# try: -# ret = (ctx).transform(slice_to_bytes(src)) -# offset = ret[0] -# size = ret[1] -# if (offset + size) > src.size(): -# msg = "offset(%i) + size(%i) is bigger than slice(%i)" -# raise Exception(msg % (offset, size, src.size())) - -# return Slice(src.data() + offset, size) -# except BaseException as error: -# tb = traceback.format_exc() -# logger.Log(log, "Error in slice transfrom callback: %s", tb) -# error_msg.assign(str(error)) - -# cdef cpp_bool slice_in_domain_callback( -# void* ctx, -# logger.Logger* log, -# string& error_msg, -# const Slice& src) with gil: - -# try: -# return (ctx).in_domain(slice_to_bytes(src)) -# except BaseException as error: -# tb = traceback.format_exc() -# logger.Log(log, "Error in slice transfrom callback: %s", tb) -# error_msg.assign(str(error)) - -# cdef cpp_bool slice_in_range_callback( -# void* ctx, -# logger.Logger* log, -# string& error_msg, -# const Slice& src) with gil: - -# try: -# return (ctx).in_range(slice_to_bytes(src)) -# except BaseException as error: -# tb = traceback.format_exc() -# logger.Log(log, "Error in slice transfrom callback: %s", tb) -# error_msg.assign(str(error)) -# ########################################### - -# ## Here are the TableFactories -# @cython.internal -# cdef class PyTableFactory(object): -# cdef shared_ptr[table_factory.TableFactory] factory - -# cdef shared_ptr[table_factory.TableFactory] get_table_factory(self): -# return self.factory - -# cdef set_info_log(self, shared_ptr[logger.Logger] info_log): -# pass - -# cdef class BlockBasedTableFactory(PyTableFactory): -# cdef PyFilterPolicy py_filter_policy - -# def __init__(self, -# index_type='binary_search', -# py_bool hash_index_allow_collision=True, -# checksum='crc32', -# PyCache block_cache=None, -# PyCache block_cache_compressed=None, -# filter_policy=None, -# no_block_cache=False, -# block_size=None, -# block_size_deviation=None, -# block_restart_interval=None, -# whole_key_filtering=None): - -# cdef table_factory.BlockBasedTableOptions table_options - -# if index_type == 'binary_search': -# table_options.index_type = table_factory.kBinarySearch -# elif index_type == 'hash_search': -# table_options.index_type = table_factory.kHashSearch -# else: -# raise ValueError("Unknown index_type: %s" % index_type) - -# if hash_index_allow_collision: -# table_options.hash_index_allow_collision = True -# else: -# table_options.hash_index_allow_collision = False - -# if checksum == 'crc32': -# table_options.checksum = table_factory.kCRC32c -# elif checksum == 'xxhash': -# table_options.checksum = table_factory.kxxHash -# else: -# raise ValueError("Unknown checksum: %s" % checksum) - -# if no_block_cache: -# table_options.no_block_cache = True -# else: -# table_options.no_block_cache = False - -# # If the following options are None use the rocksdb default. -# if block_size is not None: -# table_options.block_size = block_size - -# if block_size_deviation is not None: -# table_options.block_size_deviation = block_size_deviation - -# if block_restart_interval is not None: -# table_options.block_restart_interval = block_restart_interval - -# if whole_key_filtering is not None: -# if whole_key_filtering: -# table_options.whole_key_filtering = True -# else: -# table_options.whole_key_filtering = False - -# if block_cache is not None: -# table_options.block_cache = block_cache.get_cache() - -# if block_cache_compressed is not None: -# table_options.block_cache_compressed = block_cache_compressed.get_cache() - -# # Set the filter_policy -# self.py_filter_policy = None -# if filter_policy is not None: -# if isinstance(filter_policy, PyFilterPolicy): -# if (filter_policy).get_policy().get() == NULL: -# raise Exception("Cannot set filter policy: %s" % filter_policy) -# self.py_filter_policy = filter_policy -# else: -# self.py_filter_policy = PyGenericFilterPolicy(filter_policy) - -# table_options.filter_policy = self.py_filter_policy.get_policy() - -# self.factory.reset(table_factory.NewBlockBasedTableFactory(table_options)) - -# cdef set_info_log(self, shared_ptr[logger.Logger] info_log): -# if self.py_filter_policy is not None: -# self.py_filter_policy.set_info_log(info_log) - -# cdef class PlainTableFactory(PyTableFactory): -# def __init__( -# self, -# user_key_len=0, -# bloom_bits_per_key=10, -# hash_table_ratio=0.75, -# index_sparseness=10, -# huge_page_tlb_size=0, -# encoding_type='plain', -# py_bool full_scan_mode=False): - -# cdef table_factory.PlainTableOptions table_options - -# table_options.user_key_len = user_key_len -# table_options.bloom_bits_per_key = bloom_bits_per_key -# table_options.hash_table_ratio = hash_table_ratio -# table_options.index_sparseness = index_sparseness -# table_options.huge_page_tlb_size = huge_page_tlb_size - -# if encoding_type == 'plain': -# table_options.encoding_type = table_factory.kPlain -# elif encoding_type == 'prefix': -# table_options.encoding_type = table_factory.kPrefix -# else: -# raise ValueError("Unknown encoding_type: %s" % encoding_type) - -# table_options.full_scan_mode = full_scan_mode - -# self.factory.reset( table_factory.NewPlainTableFactory(table_options)) -# ############################################# - -# ### Here are the MemtableFactories -# @cython.internal -# cdef class PyMemtableFactory(object): -# cdef shared_ptr[memtablerep.MemTableRepFactory] factory - -# cdef shared_ptr[memtablerep.MemTableRepFactory] get_memtable_factory(self): -# return self.factory - -# cdef class SkipListMemtableFactory(PyMemtableFactory): -# def __init__(self): -# self.factory.reset(memtablerep.NewSkipListFactory()) - -# cdef class VectorMemtableFactory(PyMemtableFactory): -# def __init__(self, count=0): -# self.factory.reset(memtablerep.NewVectorRepFactory(count)) - -# cdef class HashSkipListMemtableFactory(PyMemtableFactory): -# def __init__( -# self, -# bucket_count=1000000, -# skiplist_height=4, -# skiplist_branching_factor=4): - -# self.factory.reset( -# memtablerep.NewHashSkipListRepFactory( -# bucket_count, -# skiplist_height, -# skiplist_branching_factor)) - -# cdef class HashLinkListMemtableFactory(PyMemtableFactory): -# def __init__(self, bucket_count=50000): -# self.factory.reset(memtablerep.NewHashLinkListRepFactory(bucket_count)) -# ################################## - -# cdef class CompressionType(object): -# no_compression = u'no_compression' -# snappy_compression = u'snappy_compression' -# zlib_compression = u'zlib_compression' -# bzip2_compression = u'bzip2_compression' -# lz4_compression = u'lz4_compression' -# lz4hc_compression = u'lz4hc_compression' -# xpress_compression = u'xpress_compression' -# zstd_compression = u'zstd_compression' -# zstdnotfinal_compression = u'zstdnotfinal_compression' -# disable_compression = u'disable_compression' - -# cdef class CompactionPri(object): -# by_compensated_size = u'by_compensated_size' -# oldest_largest_seq_first = u'oldest_largest_seq_first' -# oldest_smallest_seq_first = u'oldest_smallest_seq_first' -# min_overlapping_ratio = u'min_overlapping_ratio' - -# @cython.internal -# cdef class _ColumnFamilyHandle: -# """ This is an internal class that we will weakref for safety """ -# cdef db.ColumnFamilyHandle* handle -# cdef object __weakref__ -# cdef object weak_handle - -# def __cinit__(self): -# self.handle = NULL - -# def __dealloc__(self): -# if not self.handle == NULL: -# del self.handle - -# @staticmethod -# cdef from_handle_ptr(db.ColumnFamilyHandle* handle): -# inst = <_ColumnFamilyHandle>_ColumnFamilyHandle.__new__(_ColumnFamilyHandle) -# inst.handle = handle -# return inst - -# @property -# def name(self): -# return self.handle.GetName() - -# @property -# def id(self): -# return self.handle.GetID() - -# @property -# def weakref(self): -# if self.weak_handle is None: -# self.weak_handle = ColumnFamilyHandle.from_wrapper(self) -# return self.weak_handle - -class ColumnFamilyHandle: - @property - def is_valid(self) -> bool: ... - def __repr__(self) -> str: ... - def __eq__(self, other) -> bool: ... - def __lt__(self, other) -> bool: ... - def __ne__(self, other): - return not self == other - - def __gt__(self, other): - return other < self - - def __le__(self, other): - return not other < self - - def __ge__(self, other): - return not self < other - - def __hash__(self) -> int: ... - -class ColumnFamilyOptions: - def __init__(self, **kwargs) -> None: - self.py_comparator = None - self.py_merge_operator = None - self.py_prefix_extractor = None - self.py_table_factory = None - self.py_memtable_factory = None - self.write_buffer_size = None - self.max_write_buffer_number = None - self.min_write_buffer_number_to_merge = None - self.compression_opts = None - self.compaction_pri = None - self.compression = None - self.max_compaction_bytes = None - self.num_levels = None - self.level0_file_num_compaction_trigger = None - self.level0_slowdown_writes_trigger = None - self.level0_stop_writes_trigger = None - self.max_mem_compaction_level = None - self.target_file_size_base = None - self.target_file_size_multiplier = None - self.max_bytes_for_level_base = None - self.max_bytes_for_level_multiplier = None - self.max_bytes_for_level_multiplier_additional = None - self.arena_block_size = None - self.disable_auto_compactions = None - self.compaction_style = None - self.compaction_options_universal = None - self.max_sequential_skip_in_iterations = None - self.inplace_update_support = None - self.table_factory = None - self.memtable_factory = None - self.inplace_update_num_locks = None - self.comparator = None - self.merge_operator = None - self.prefix_extractors = None - -class Options(ColumnFamilyOptions): - def __init__(self, **kwargs) -> None: - super().__init__() - self.create_if_missing: bool - self.error_if_exists: bool - self.paranoid_checks: bool - self.max_open_files = None - self.use_fsync: bool - self.db_log_dir = None - self.wal_dir = None - self.delete_obsolete_files_period_micros: bool - self.max_background_compactions = None - self.max_background_flushes = None - self.max_log_file_size = None - self.log_file_time_to_roll = None - self.keep_log_file_num = None - self.max_manifest_file_size = None - self.table_cache_numshardbits = None - self.wal_ttl_seconds = None - self.wal_size_limit_mb = None - self.manifest_preallocation_size = None - self.enable_write_thread_adaptive_yield = None - self.allow_concurrent_memtable_write = None - self.allow_mmap_reads = None - self.allow_mmap_writes = None - self.is_fd_close_on_exec = None - self.stats_dump_period_sec = None - self.advise_random_on_open = None - self.use_adaptive_mutex = None - self.bytes_per_sync = None - self.row_cache = None - -# # Forward declaration -# cdef class Snapshot - -# cdef class KeysIterator -# cdef class ValuesIterator -# cdef class ItemsIterator -# cdef class ReversedIterator - -# # Forward declaration -# cdef class WriteBatchIterator - -class WriteBatch: - def __init__(self, data=None) -> None: ... - def put(self, key: bytes, value: bytes): ... - def merge(self, key: bytes, value: bytes): ... - def delete(self, key: bytes): ... - def delete_range(self, key: tuple[bytes, bytes]): ... - def clear(self): ... - def data(self): ... - def count(self): ... - def __iter__(self): ... - -# @cython.internal -# cdef class WriteBatchIterator(object): -# # Need a reference to the WriteBatch. -# # The BatchItems are only pointers to the memory in WriteBatch. -# cdef WriteBatch batch -# cdef vector[db.BatchItem] items -# cdef size_t pos - -# def __init__(self, WriteBatch batch): -# cdef Status st - -# self.batch = batch -# self.pos = 0 - -# st = db.get_batch_items(batch.batch, cython.address(self.items)) -# check_status(st) - -# def __iter__(self): -# return self - -# def __next__(self): -# if self.pos == self.items.size(): -# raise StopIteration() - -# cdef str op - -# if self.items[self.pos].op == db.BatchItemOpPut: -# op = "Put" -# elif self.items[self.pos].op == db.BatchItemOpMerge: -# op = "Merge" -# elif self.items[self.pos].op == db.BatchItemOpDelte: -# op = "Delete" - -# if self.items[self.pos].column_family_id != 0: # Column Family is set -# ret = ( -# op, -# ( -# self.items[self.pos].column_family_id, -# slice_to_bytes(self.items[self.pos].key) -# ), -# slice_to_bytes(self.items[self.pos].value) -# ) -# else: -# ret = ( -# op, -# slice_to_bytes(self.items[self.pos].key), -# slice_to_bytes(self.items[self.pos].value) -# ) -# self.pos += 1 -# return ret - -from collections.abc import Iterable -from typing import Any - -class DB: - def __init__( - self, - db_name: str, - opts: Options, - column_families: dict | None = None, - read_only: bool = False, - secondary_path: str | None = None, - ) -> None: - ... - self.opts = opts - self.opts.in_use = True - - def __dealloc__(self): - self.close() - - def close(self): ... - @property - def column_families(self) -> list: ... - def get_column_family(self, name: bytes): ... - def put(self, key: bytes, value: bytes, sync: bool = False, disable_wal: bool = False): ... - def delete(self, key: bytes, sync: bool = False, disable_wal: bool = False): ... - def delete_range( - self, key: tuple[bytes, bytes], sync: bool = False, disable_wal: bool = False - ): ... - def merge(self, key: bytes, value: bytes, sync: bool = False, disable_wal: bool = False): ... - def write(self, batch: WriteBatch, sync: bool = False, disable_wal: bool = False): ... - def get(self, key: bytes, *args, **kwargs) -> bytes: ... - def multi_get(self, keys: Iterable[bytes], *args, **kwargs) -> dict[bytes, bytes]: ... - def key_may_exist( - self, key: bytes, fetch: bool = False, *args, **kwargs - ) -> tuple[bool, Any]: ... - def iterkeys( - self, column_family: ColumnFamilyHandle = None, *args, **kwargs - ) -> KeysIterator: ... - def itervalues( - self, column_family: ColumnFamilyHandle = None, *args, **kwargs - ) -> ValuesIterator: ... - def iteritems( - self, column_family: ColumnFamilyHandle = None, *args, **kwargs - ) -> ItemsIterator: ... - - # def iterskeys(self, column_families, *args, **kwargs): - # cdef vector[db.Iterator*] iters - # iters.resize(len(column_families)) - # cdef options.ReadOptions opts - # cdef db.Iterator* it_ptr - # cdef KeysIterator it - # cdef db.ColumnFamilyHandle* cf_handle - # cdef vector[db.ColumnFamilyHandle*] cf_handles - - # for column_family in column_families: - # cf_handle = (column_family).get_handle() - # cf_handles.push_back(cf_handle) - - # opts = self.build_read_opts(self.__parse_read_opts(*args, **kwargs)) - # with nogil: - # self.db.NewIterators(opts, cf_handles, &iters) - - # cf_iter = iter(column_families) - # cdef list ret = [] - # for it_ptr in iters: - # it = KeysIterator(self, next(cf_iter)) - # it.ptr = it_ptr - # ret.append(it) - # return ret - - # def itersvalues(self, column_families, *args, **kwargs): - # cdef vector[db.Iterator*] iters - # iters.resize(len(column_families)) - # cdef options.ReadOptions opts - # cdef db.Iterator* it_ptr - # cdef ValuesIterator it - # cdef db.ColumnFamilyHandle* cf_handle - # cdef vector[db.ColumnFamilyHandle*] cf_handles - - # for column_family in column_families: - # cf_handle = (column_family).get_handle() - # cf_handles.push_back(cf_handle) - - # opts = self.build_read_opts(self.__parse_read_opts(*args, **kwargs)) - # with nogil: - # self.db.NewIterators(opts, cf_handles, &iters) - - # cdef list ret = [] - # for it_ptr in iters: - # it = ValuesIterator(self) - # it.ptr = it_ptr - # ret.append(it) - # return ret - - # def iterskeys(self, column_families, *args, **kwargs): - # cdef vector[db.Iterator*] iters - # iters.resize(len(column_families)) - # cdef options.ReadOptions opts - # cdef db.Iterator* it_ptr - # cdef ItemsIterator it - # cdef db.ColumnFamilyHandle* cf_handle - # cdef vector[db.ColumnFamilyHandle*] cf_handles - - # for column_family in column_families: - # cf_handle = (column_family).get_handle() - # cf_handles.push_back(cf_handle) - - # opts = self.build_read_opts(self.__parse_read_opts(*args, **kwargs)) - # with nogil: - # self.db.NewIterators(opts, cf_handles, &iters) - - # cf_iter = iter(column_families) - # cdef list ret = [] - # for it_ptr in iters: - # it = ItemsIterator(self, next(cf_iter)) - # it.ptr = it_ptr - # ret.append(it) - # return ret - - # def snapshot(self): - # return Snapshot(self) - - def get_property(self, prop: bytes, column_family: ColumnFamilyHandle = None): ... - def get_live_files_metadata(self) -> list[dict[str, Any]]: ... - - # def compact_range(self, begin=None, end=None, ColumnFamilyHandle column_family=None, **py_options): - # cdef options.CompactRangeOptions c_options - - # c_options.change_level = py_options.get('change_level', False) - # c_options.target_level = py_options.get('target_level', -1) - - # blc = py_options.get('bottommost_level_compaction', 'if_compaction_filter') - # if blc == 'skip': - # c_options.bottommost_level_compaction = options.blc_skip - # elif blc == 'if_compaction_filter': - # c_options.bottommost_level_compaction = options.blc_is_filter - # elif blc == 'force': - # c_options.bottommost_level_compaction = options.blc_force - # else: - # raise ValueError("bottommost_level_compaction is not valid") - - # cdef Status st - # cdef Slice begin_val - # cdef Slice end_val - - # cdef Slice* begin_ptr - # cdef Slice* end_ptr - - # begin_ptr = NULL - # end_ptr = NULL - - # if begin is not None: - # begin_val = bytes_to_slice(begin) - # begin_ptr = cython.address(begin_val) - - # if end is not None: - # end_val = bytes_to_slice(end) - # end_ptr = cython.address(end_val) - - # cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - # if column_family: - # cf_handle = (column_family).get_handle() - - # st = self.db.CompactRange(c_options, cf_handle, begin_ptr, end_ptr) - # check_status(st) - - # @staticmethod - # def __parse_read_opts( - # verify_checksums=False, - # fill_cache=True, - # snapshot=None, - # read_tier="all"): - - # # TODO: Is this really effiencet ? - # return locals() - - # cdef options.ReadOptions build_read_opts(self, dict py_opts): - # cdef options.ReadOptions opts - # opts.verify_checksums = py_opts['verify_checksums'] - # opts.fill_cache = py_opts['fill_cache'] - # if py_opts['snapshot'] is not None: - # opts.snapshot = ((py_opts['snapshot'])).ptr - - # if py_opts['read_tier'] == "all": - # opts.read_tier = options.kReadAllTier - # elif py_opts['read_tier'] == 'cache': - # opts.read_tier = options.kBlockCacheTier - # else: - # raise ValueError("Invalid read_tier") - - # return opts - - # property options: - # def __get__(self): - # return self.opts - - # def create_column_family(self, bytes name, ColumnFamilyOptions copts): - # cdef db.ColumnFamilyHandle* cf_handle - # cdef Status st - # cdef string c_name = name - - # for handle in self.cf_handles: - # if handle.name == name: - # raise ValueError(f"{name} is already an existing column family") - - # if copts.in_use: - # raise Exception("ColumnFamilyOptions are in_use by another column family") - - # copts.in_use = True - # with nogil: - # st = self.db.CreateColumnFamily(deref(copts.copts), c_name, &cf_handle) - # check_status(st) - - # handle = _ColumnFamilyHandle.from_handle_ptr(cf_handle) - - # self.cf_handles.append(handle) - # self.cf_options.append(copts) - # return handle.weakref - - # def drop_column_family(self, ColumnFamilyHandle weak_handle not None): - # cdef db.ColumnFamilyHandle* cf_handle - # cdef ColumnFamilyOptions copts - # cdef Status st - - # cf_handle = weak_handle.get_handle() - - # with nogil: - # st = self.db.DropColumnFamily(cf_handle) - # check_status(st) - - # py_handle = weak_handle._ref() - # index = self.cf_handles.index(py_handle) - # copts = self.cf_options.pop(index) - # del self.cf_handles[index] - # del py_handle - # if copts: - # copts.in_use = False - -class TxnDBWritePolicy: - write_committed: str = "write_committed" - write_prepared: str = "write_prepared" - write_unprepared: str = "write_unprepared" - -class TransactionDBOptions: - max_num_locks: int - max_num_deadlocks: int - num_stripes: int - transaction_lock_timeout: int - default_lock_timeout: int - write_policy: str - rollback_merge_operands: bool - skip_concurrency_control: bool - default_write_batch_flush_threshold: int - in_use: bool - - def __init__(self, **kwargs: Any) -> None: ... - -class TransactionOptions: - set_snapshot: bool - deadlock_detect: bool - use_only_the_last_commit_time_batch_for_recovery: bool - lock_timeout: int - expiration: int - deadlock_detect_depth: int - max_write_batch_size: int - skip_concurrency_control: bool - skip_prepare: bool - write_batch_flush_threshold: int - - def __init__(self, **kwargs: Any) -> None: ... - -class TransactionDB(DB): - txn_opts: TransactionDBOptions - - def __init__( - self, - db_name: str, - opts: Options, - txn_db_opts: TransactionDBOptions | None = None, - column_families: dict | None = None, - ) -> None: ... - def begin_transaction( - self, - txn_options: TransactionOptions | None = ..., - write_options: dict[str, Any] | None = ..., - reuse: Transaction | None = ..., - ) -> Transaction: ... - def close(self) -> None: ... - -class Transaction: - closed: bool - - def close(self) -> None: ... - def commit(self) -> None: ... - def rollback(self) -> None: ... - def prepare(self) -> None: ... - def set_snapshot(self) -> None: ... - def clear_snapshot(self) -> None: ... - def snapshot(self) -> TransactionSnapshot | None: ... - def save_point(self) -> None: ... - def rollback_to_save_point(self) -> None: ... - def pop_save_point(self) -> None: ... - def set_name(self, name: str | bytes) -> None: ... - def get_name(self) -> str: ... - def get_id(self) -> int: ... - def put( - self, - key: bytes, - value: bytes, - column_family: ColumnFamilyHandle | None = None, - assume_tracked: bool = False, - ) -> None: ... - def merge( - self, - key: bytes, - value: bytes, - column_family: ColumnFamilyHandle | None = None, - assume_tracked: bool = False, - ) -> None: ... - def delete_single( - self, - key: bytes, - column_family: ColumnFamilyHandle | None = None, - assume_tracked: bool = False, - ) -> None: ... - def get(self, key: bytes, column_family: ColumnFamilyHandle | None = None) -> bytes | None: ... - def multi_get( - self, keys: Iterable[bytes | tuple[ColumnFamilyHandle, bytes]] - ) -> dict[Any, bytes | None]: ... - def iterkeys(self, column_family: ColumnFamilyHandle | None = None) -> KeysIterator: ... - def itervalues(self, column_family: ColumnFamilyHandle | None = None) -> ValuesIterator: ... - def iteritems(self, column_family: ColumnFamilyHandle | None = None) -> ItemsIterator: ... - def disable_indexing(self) -> None: ... - def enable_indexing(self) -> None: ... - -class TransactionSnapshot: - pointer: int - transaction: Transaction - - def __bool__(self) -> bool: ... - -# def repair_db(db_name, Options opts): -# cdef Status st -# cdef string db_path - -# db_path = path_to_string(db_name) -# st = db.RepairDB(db_path, deref(opts.opts)) -# check_status(st) - -# def list_column_families(db_name, Options opts): -# cdef Status st -# cdef string db_path -# cdef vector[string] column_families - -# db_path = path_to_string(db_name) -# with nogil: -# st = db.ListColumnFamilies(deref(opts.opts), db_path, &column_families) -# check_status(st) - -# return column_families - -# @cython.no_gc_clear -# @cython.internal -# cdef class Snapshot(object): -# cdef const snapshot.Snapshot* ptr -# cdef DB db - -# def __cinit__(self, DB db): -# self.db = db -# self.ptr = NULL -# with nogil: -# self.ptr = db.db.GetSnapshot() - -# def __dealloc__(self): -# if not self.ptr == NULL: -# with nogil: -# self.db.db.ReleaseSnapshot(self.ptr) - -class BaseIterator: - def __init__(self, db: DB, handle: ColumnFamilyHandle = None) -> None: ... - def __dealloc__(self): ... - def __iter__(self): - return self - - def __next__(self): ... - def get(self): ... - def __reversed__(self): ... - def seek_to_first(self): ... - def seek_to_last(self): ... - def seek(self, key: bytes): ... - def seek_for_prev(self, key): ... - def get_ob(self) -> None: - return None - -class KeysIterator(BaseIterator): - def get(self) -> bytes: ... - def __next__(self) -> bytes: ... - -class ValuesIterator(BaseIterator): - def get(self) -> bytes: ... - def __next__(self) -> bytes: ... - -class ItemsIterator(BaseIterator): - def get(self) -> tuple[bytes, bytes]: ... - def __next__(self) -> tuple[bytes, bytes]: ... - -# @cython.internal -# cdef class ReversedIterator(object): -# cdef BaseIterator it - -# def __cinit__(self, BaseIterator it): -# self.it = it - -# def seek_to_first(self): -# self.it.seek_to_first() - -# def seek_to_last(self): -# self.it.seek_to_last() - -# def seek(self, key): -# self.it.seek(key) - -# def seek_for_prev(self, key): -# self.it.seek_for_prev(key) - -# def get(self): -# return self.it.get() - -# def __iter__(self): -# return self - -# def __reversed__(self): -# return self.it - -# def __next__(self): -# if not self.it.ptr.Valid(): -# raise StopIteration() - -# cdef object ret = self.it.get_ob() -# with nogil: -# self.it.ptr.Prev() -# check_status(self.it.ptr.status()) -# return ret - -# cdef class BackupEngine(object): -# cdef backup.BackupEngine* engine - -# def __cinit__(self, backup_dir): -# cdef Status st -# cdef string c_backup_dir -# self.engine = NULL - -# c_backup_dir = path_to_string(backup_dir) -# st = backup.BackupEngine_Open( -# env.Env_Default(), -# backup.BackupEngineOptions(c_backup_dir), -# cython.address(self.engine)) - -# check_status(st) - -# def __dealloc__(self): -# if not self.engine == NULL: -# with nogil: -# del self.engine - -# def create_backup(self, DB db, flush_before_backup=False): -# cdef Status st -# cdef cpp_bool c_flush_before_backup - -# c_flush_before_backup = flush_before_backup - -# with nogil: -# st = self.engine.CreateNewBackup(db.db, c_flush_before_backup) -# check_status(st) - -# def restore_backup(self, backup_id, db_dir, wal_dir): -# cdef Status st -# cdef backup.BackupID c_backup_id -# cdef string c_db_dir -# cdef string c_wal_dir - -# c_backup_id = backup_id -# c_db_dir = path_to_string(db_dir) -# c_wal_dir = path_to_string(wal_dir) - -# with nogil: -# st = self.engine.RestoreDBFromBackup( -# c_backup_id, -# c_db_dir, -# c_wal_dir) - -# check_status(st) - -# def restore_latest_backup(self, db_dir, wal_dir): -# cdef Status st -# cdef string c_db_dir -# cdef string c_wal_dir - -# c_db_dir = path_to_string(db_dir) -# c_wal_dir = path_to_string(wal_dir) - -# with nogil: -# st = self.engine.RestoreDBFromLatestBackup(c_db_dir, c_wal_dir) - -# check_status(st) - -# def stop_backup(self): -# with nogil: -# self.engine.StopBackup() - -# def purge_old_backups(self, num_backups_to_keep): -# cdef Status st -# cdef uint32_t c_num_backups_to_keep - -# c_num_backups_to_keep = num_backups_to_keep - -# with nogil: -# st = self.engine.PurgeOldBackups(c_num_backups_to_keep) -# check_status(st) - -# def delete_backup(self, backup_id): -# cdef Status st -# cdef backup.BackupID c_backup_id - -# c_backup_id = backup_id - -# with nogil: -# st = self.engine.DeleteBackup(c_backup_id) - -# check_status(st) - -# def get_backup_info(self): -# cdef vector[backup.BackupInfo] backup_info - -# with nogil: -# self.engine.GetBackupInfo(cython.address(backup_info)) - -# ret = [] -# for ob in backup_info: -# t = {} -# t['backup_id'] = ob.backup_id -# t['timestamp'] = ob.timestamp -# t['size'] = ob.size -# ret.append(t) - -# return ret diff --git a/src/rdbpy/lib_rocksdb.pyx b/src/rdbpy/lib_rocksdb.pyx deleted file mode 100644 index 35905f0..0000000 --- a/src/rdbpy/lib_rocksdb.pyx +++ /dev/null @@ -1,3524 +0,0 @@ -# distutils: language = c++ -# distutils: language_level = 3 -import cython -from libcpp.string cimport string -from libcpp.deque cimport deque -from libcpp.vector cimport vector -from cpython cimport bool as py_bool -from libcpp cimport bool as cpp_bool -from libc.stddef cimport size_t -from libc.stdint cimport uint32_t -from cython.operator cimport dereference as deref -from cpython.bytes cimport PyBytes_AsString -from cpython.bytes cimport PyBytes_Size -from cpython.bytes cimport PyBytes_FromString -from cpython.bytes cimport PyBytes_FromStringAndSize -from cpython.unicode cimport PyUnicode_Decode - -from rdbpy.std_memory cimport shared_ptr -cimport rdbpy.options as options -cimport rdbpy.merge_operator as merge_operator -cimport rdbpy.filter_policy as filter_policy -cimport rdbpy.comparator as comparator -cimport rdbpy.slice_transform as slice_transform -cimport rdbpy.cache as cache -cimport rdbpy.logger as logger -cimport rdbpy.snapshot as snapshot -cimport rdbpy.db as db -cimport rdbpy.iterator as iterator -cimport rdbpy.backup as backup -cimport rdbpy.env as env -cimport rdbpy.transaction as transaction -cimport rdbpy.table_factory as table_factory -cimport rdbpy.memtablerep as memtablerep -cimport rdbpy.universal_compaction as universal_compaction - -# Enums are the only exception for direct imports -# Their name als already unique enough -from rdbpy.universal_compaction cimport kCompactionStopStyleSimilarSize -from rdbpy.universal_compaction cimport kCompactionStopStyleTotalSize - -from rdbpy.options cimport FlushOptions -from rdbpy.options cimport kCompactionStyleLevel -from rdbpy.options cimport kCompactionStyleUniversal -from rdbpy.options cimport kCompactionStyleFIFO -from rdbpy.options cimport kCompactionStyleNone - -from rdbpy.slice_ cimport Slice -from rdbpy.status cimport Status - -import sys -from rdbpy.interfaces import MergeOperator as IMergeOperator -from rdbpy.interfaces import AssociativeMergeOperator as IAssociativeMergeOperator -from rdbpy.interfaces import FilterPolicy as IFilterPolicy -from rdbpy.interfaces import Comparator as IComparator -from rdbpy.interfaces import SliceTransform as ISliceTransform -import traceback -import rdbpy.errors as errors -import weakref - -# pxd defines: -# ctypedef const filter_policy.FilterPolicy ConstFilterPolicy - -cdef extern from "rdb_include/utils.hpp" namespace "py_rocks": - cdef const Slice* vector_data(vector[Slice]&) - -# Prepare python for threaded usage. -# Python callbacks (merge, comparator) -# could be executed in a rocksdb background thread (eg. compaction). -cdef extern from "Python.h": - void PyEval_InitThreads() -PyEval_InitThreads() - -## Here comes the stuff to wrap the status to exception -cdef check_status(const Status& st): - if st.ok(): - return - - if st.IsNotFound(): - raise errors.NotFound(st.ToString()) - - if st.IsCorruption(): - raise errors.Corruption(st.ToString()) - - if st.IsNotSupported(): - raise errors.NotSupported(st.ToString()) - - if st.IsInvalidArgument(): - raise errors.InvalidArgument(st.ToString()) - - if st.IsIOError(): - raise errors.RocksIOError(st.ToString()) - - if st.IsMergeInProgress(): - raise errors.MergeInProgress(st.ToString()) - - if st.IsIncomplete(): - raise errors.Incomplete(st.ToString()) - - raise Exception("Unknown error: %s" % st.ToString()) -###################################################### - - -## Lifetime of native children (iterators, snapshots, transactions). -# A parent records the address of each live child in a set (an int, not a -# reference, so no cycle). Before freeing its own native state the parent -# frees the children's native state; a child drops its entry in __dealloc__. -# Children are no_gc_clear so they can still reach their parent there. -# -# Re-entrancy rules, because gc (and the finalizers it runs) can fire on any -# allocation of a gc-tracked object on CPython <= 3.11, and on any thread: -# - Registries are walked with set.pop(): it allocates nothing, so no gc can -# run mid-walk, and an entry is gone before it is used. -# - Between checking a native pointer and using it, nothing may allocate a -# gc-tracked object or call into Python; otherwise check again after. -# - Native frees on release paths keep the GIL, so no other thread can run -# between a child unregistering and its native state being freed. -cdef inline size_t _addr(object ob): - return ob - -cdef void _invalidate_iterators(set registry): - cdef BaseIterator it - if registry is None: - return - while registry: - it = registry.pop() - it._invalidate() - -cdef void _release_snapshots(DB parent): - cdef Snapshot snap - if parent._snapshots is None: - return - while parent._snapshots: - snap = parent._snapshots.pop() - if snap.ptr != NULL: - parent.db.ReleaseSnapshot(snap.ptr) - snap.ptr = NULL -###################################################### - - -cdef string bytes_to_string(path) except *: - return string(PyBytes_AsString(path), PyBytes_Size(path)) - -cdef string_to_bytes(string ob): - return PyBytes_FromStringAndSize(ob.c_str(), ob.size()) - -cdef Slice bytes_to_slice(ob) except *: - return Slice(PyBytes_AsString(ob), PyBytes_Size(ob)) - -cdef slice_to_bytes(Slice sl): - return PyBytes_FromStringAndSize(sl.data(), sl.size()) - -## only for filsystem paths -cdef string path_to_string(object path) except *: - if isinstance(path, bytes): - return bytes_to_string(path) - if isinstance(path, unicode): - path = path.encode(sys.getfilesystemencoding()) - return bytes_to_string(path) - else: - raise TypeError("Wrong type for path: %s" % path) - -cdef object string_to_path(string path): - fs_encoding = sys.getfilesystemencoding().encode('ascii') - return PyUnicode_Decode(path.c_str(), path.size(), fs_encoding, "replace") - -## Here comes the stuff for the comparator -cdef class PyComparator(object): - cdef object get_ob(self): - return None - - cdef const comparator.Comparator* get_comparator(self): - return NULL - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log): - pass - - -cdef class PyGenericComparator(PyComparator): - # pxd defines: - # cdef comparator.ComparatorWrapper* comparator_ptr - # cdef object ob - - def __cinit__(self, object ob): - self.comparator_ptr = NULL - if not isinstance(ob, IComparator): - raise TypeError("%s is not of type %s" % (ob, IComparator)) - - self.ob = ob - self.comparator_ptr = new comparator.ComparatorWrapper( - bytes_to_string(ob.name()), - ob, - compare_callback) - - def __dealloc__(self): - if not self.comparator_ptr == NULL: - del self.comparator_ptr - - cdef object get_ob(self): - return self.ob - - cdef const comparator.Comparator* get_comparator(self): - return self.comparator_ptr - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log): - self.comparator_ptr.set_info_log(info_log) - - -cdef class PyBytewiseComparator(PyComparator): - # pxd defines: - # cdef const comparator.Comparator* comparator_ptr - - def __cinit__(self): - self.comparator_ptr = comparator.BytewiseComparator() - - cpdef name(self): - return PyBytes_FromString(self.comparator_ptr.Name()) - - cpdef compare(self, a, b): - return self.comparator_ptr.Compare( - bytes_to_slice(a), - bytes_to_slice(b)) - - cdef object get_ob(self): - return self - - cdef const comparator.Comparator* get_comparator(self): - return self.comparator_ptr - - - -cdef int compare_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& a, - const Slice& b) with gil: - - try: - return (ctx).compare(slice_to_bytes(a), slice_to_bytes(b)) - except BaseException as error: - tb = traceback.format_exc() - logger.Log(log, "Error in compare callback: %s", tb) - error_msg.assign(str(error)) - -BytewiseComparator = PyBytewiseComparator -######################################### - - - -## Here comes the stuff for the filter policy -cdef class PyFilterPolicy(object): - cdef object get_ob(self): - return None - - cdef shared_ptr[ConstFilterPolicy] get_policy(self): - return shared_ptr[ConstFilterPolicy]() - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log): - pass - - -cdef class PyGenericFilterPolicy(PyFilterPolicy): - # pxd defines: - # cdef shared_ptr[filter_policy.FilterPolicyWrapper] policy - # cdef object ob - - def __cinit__(self, object ob): - if not isinstance(ob, IFilterPolicy): - raise TypeError("%s is not of type %s" % (ob, IFilterPolicy)) - - self.ob = ob - self.policy.reset(new filter_policy.FilterPolicyWrapper( - bytes_to_string(ob.name()), - ob, - create_filter_callback, - key_may_match_callback)) - - cdef object get_ob(self): - return self.ob - - cdef shared_ptr[ConstFilterPolicy] get_policy(self): - return (self.policy) - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log): - self.policy.get().set_info_log(info_log) - - -cdef void create_filter_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice* keys, - int n, - string* dst) with gil: - - try: - ret = (ctx).create_filter( - [slice_to_bytes(keys[i]) for i in range(n)]) - dst.append(bytes_to_string(ret)) - except BaseException as error: - tb = traceback.format_exc() - logger.Log(log, "Error in create filter callback: %s", tb) - error_msg.assign(str(error)) - -cdef cpp_bool key_may_match_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& key, - const Slice& filt) with gil: - - try: - return (ctx).key_may_match( - slice_to_bytes(key), - slice_to_bytes(filt)) - except BaseException as error: - tb = traceback.format_exc() - logger.Log(log, "Error in key_mach_match callback: %s", tb) - error_msg.assign(str(error)) - - -cdef class PyBloomFilterPolicy(PyFilterPolicy): - # pxd defines: - # cdef shared_ptr[ConstFilterPolicy] policy - - def __cinit__(self, int bits_per_key): - self.policy.reset(filter_policy.NewBloomFilterPolicy(bits_per_key)) - - cpdef name(self): - return PyBytes_FromString(self.policy.get().Name()) - - cpdef create_filter(self, keys): - cdef string dst - cdef vector[Slice] c_keys - - for key in keys: - c_keys.push_back(bytes_to_slice(key)) - - self.policy.get().CreateFilter( - vector_data(c_keys), - c_keys.size(), - cython.address(dst)) - - return string_to_bytes(dst) - - cpdef key_may_match(self, key, filter_): - return self.policy.get().KeyMayMatch( - bytes_to_slice(key), - bytes_to_slice(filter_)) - - cdef object get_ob(self): - return self - - cdef shared_ptr[ConstFilterPolicy] get_policy(self): - return self.policy - -BloomFilterPolicy = PyBloomFilterPolicy -############################################# - - - -## Here comes the stuff for the merge operator -cdef class PyMergeOperator(object): - # pxd defines: - # cdef shared_ptr[merge_operator.MergeOperator] merge_op - # cdef object ob - - def __cinit__(self, object ob): - self.ob = ob - if isinstance(ob, IAssociativeMergeOperator): - self.merge_op.reset( - - new merge_operator.AssociativeMergeOperatorWrapper( - bytes_to_string(ob.name()), - (ob), - merge_callback)) - - elif isinstance(ob, IMergeOperator): - self.merge_op.reset( - - new merge_operator.MergeOperatorWrapper( - bytes_to_string(ob.name()), - ob, - ob, - full_merge_callback, - partial_merge_callback)) - # elif isinstance(ob, str): - # if ob == "put": - # self.merge_op = merge_operator.MergeOperators.CreatePutOperator() - # elif ob == "put_v1": - # self.merge_op = merge_operator.MergeOperators.CreateDeprecatedPutOperator() - # elif ob == "uint64add": - # self.merge_op = merge_operator.MergeOperators.CreateUInt64AddOperator() - # elif ob == "stringappend": - # self.merge_op = merge_operator.MergeOperators.CreateStringAppendOperator() - # #TODO: necessary? - # # elif ob == "stringappendtest": - # # self.merge_op = merge_operator.MergeOperators.CreateStringAppendTESTOperator() - # elif ob == "max": - # self.merge_op = merge_operator.MergeOperators.CreateMaxOperator() - # else: - # msg = "{0} is not the default type".format(ob) - # raise TypeError(msg) - else: - msg = "%s is not of this types %s" - msg %= (ob, (IAssociativeMergeOperator, IMergeOperator)) - raise TypeError(msg) - - - cdef object get_ob(self): - return self.ob - - cdef shared_ptr[merge_operator.MergeOperator] get_operator(self): - return self.merge_op - -cdef cpp_bool merge_callback( - void* ctx, - const Slice& key, - const Slice* existing_value, - const Slice& value, - string* new_value, - logger.Logger* log) with gil: - - if existing_value == NULL: - py_existing_value = None - else: - py_existing_value = slice_to_bytes(deref(existing_value)) - - try: - ret = (ctx).merge( - slice_to_bytes(key), - py_existing_value, - slice_to_bytes(value)) - - if ret[0]: - new_value.assign(bytes_to_string(ret[1])) - return True - return False - - except: - tb = traceback.format_exc() - logger.Log(log, "Error in merge_callback: %s", tb) - return False - -cdef cpp_bool full_merge_callback( - void* ctx, - const Slice& key, - const Slice* existing_value, - const deque[string]& op_list, - string* new_value, - logger.Logger* log) with gil: - - if existing_value == NULL: - py_existing_value = None - else: - py_existing_value = slice_to_bytes(deref(existing_value)) - - try: - ret = (ctx).full_merge( - slice_to_bytes(key), - py_existing_value, - [string_to_bytes(op_list[i]) for i in range(op_list.size())]) - - if ret[0]: - new_value.assign(bytes_to_string(ret[1])) - return True - return False - - except: - tb = traceback.format_exc() - logger.Log(log, "Error in full_merge_callback: %s", tb) - return False - -cdef cpp_bool partial_merge_callback( - void* ctx, - const Slice& key, - const Slice& left_op, - const Slice& right_op, - string* new_value, - logger.Logger* log) with gil: - - try: - ret = (ctx).partial_merge( - slice_to_bytes(key), - slice_to_bytes(left_op), - slice_to_bytes(right_op)) - - if ret[0]: - new_value.assign(bytes_to_string(ret[1])) - return True - return False - - except: - tb = traceback.format_exc() - logger.Log(log, "Error in partial_merge_callback: %s", tb) - return False -############################################## - -#### Here comes the Cache stuff -cdef class PyCache(object): - cdef shared_ptr[cache.Cache] get_cache(self): - return shared_ptr[cache.Cache]() - - -cdef class PyLRUCache(PyCache): - # pxd defines: - # cdef shared_ptr[cache.Cache] cache_ob - - def __cinit__(self, capacity, shard_bits=None): - if shard_bits is not None: - self.cache_ob = cache.NewLRUCache(capacity, shard_bits) - else: - self.cache_ob = cache.NewLRUCache(capacity) - - cdef shared_ptr[cache.Cache] get_cache(self): - return self.cache_ob - -LRUCache = PyLRUCache -############################### - -### Here comes the stuff for SliceTransform -cdef class PySliceTransform(object): - # pxd defines: - # cdef shared_ptr[slice_transform.SliceTransform] transfomer - # cdef object ob - - def __cinit__(self, object ob): - if not isinstance(ob, ISliceTransform): - raise TypeError("%s is not of type %s" % (ob, ISliceTransform)) - - self.ob = ob - self.transfomer.reset( - - new slice_transform.SliceTransformWrapper( - bytes_to_string(ob.name()), - ob, - slice_transform_callback, - slice_in_domain_callback, - slice_in_range_callback)) - - cdef object get_ob(self): - return self.ob - - cdef shared_ptr[slice_transform.SliceTransform] get_transformer(self): - return self.transfomer - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log): - cdef slice_transform.SliceTransformWrapper* ptr - ptr = self.transfomer.get() - ptr.set_info_log(info_log) - - -cdef Slice slice_transform_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& src) with gil: - - cdef size_t offset - cdef size_t size - - try: - ret = (ctx).transform(slice_to_bytes(src)) - offset = ret[0] - size = ret[1] - if (offset + size) > src.size(): - msg = "offset(%i) + size(%i) is bigger than slice(%i)" - raise Exception(msg % (offset, size, src.size())) - - return Slice(src.data() + offset, size) - except BaseException as error: - tb = traceback.format_exc() - logger.Log(log, "Error in slice transfrom callback: %s", tb) - error_msg.assign(str(error)) - -cdef cpp_bool slice_in_domain_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& src) with gil: - - try: - return (ctx).in_domain(slice_to_bytes(src)) - except BaseException as error: - tb = traceback.format_exc() - logger.Log(log, "Error in slice transfrom callback: %s", tb) - error_msg.assign(str(error)) - -cdef cpp_bool slice_in_range_callback( - void* ctx, - logger.Logger* log, - string& error_msg, - const Slice& src) with gil: - - try: - return (ctx).in_range(slice_to_bytes(src)) - except BaseException as error: - tb = traceback.format_exc() - logger.Log(log, "Error in slice transfrom callback: %s", tb) - error_msg.assign(str(error)) -########################################### - - -## Here are the TableFactories -cdef class PyTableFactory(object): - # pxd defines: - # cdef shared_ptr[table_factory.TableFactory] factory - - cdef shared_ptr[table_factory.TableFactory] get_table_factory(self): - return self.factory - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log): - pass - - -cdef class BlockBasedTableFactory(PyTableFactory): - # pxd defines: - # cdef PyFilterPolicy py_filter_policy - - def __init__(self, - index_type='binary_search', - py_bool hash_index_allow_collision=True, - checksum='crc32', - PyCache block_cache=None, - PyCache block_cache_compressed=None, - filter_policy=None, - no_block_cache=False, - block_size=None, - block_size_deviation=None, - block_restart_interval=None, - whole_key_filtering=None, - cache_index_and_filter_blocks=None, - cache_index_and_filter_blocks_with_high_priority=None, - pin_l0_filter_and_index_blocks_in_cache=None, - pin_top_level_index_and_filter=None, - partition_filters=None, - metadata_block_size=None, - format_version=None, - optimize_filters_for_memory=None, - read_amp_bytes_per_bit=None): - - cdef table_factory.BlockBasedTableOptions table_options - - if index_type == 'binary_search': - table_options.index_type = table_factory.kBinarySearch - elif index_type == 'hash_search': - table_options.index_type = table_factory.kHashSearch - else: - raise ValueError("Unknown index_type: %s" % index_type) - - if hash_index_allow_collision: - table_options.hash_index_allow_collision = True - else: - table_options.hash_index_allow_collision = False - - if checksum == 'crc32': - table_options.checksum = table_factory.kCRC32c - elif checksum == 'xxhash': - table_options.checksum = table_factory.kxxHash - else: - raise ValueError("Unknown checksum: %s" % checksum) - - if no_block_cache: - table_options.no_block_cache = True - else: - table_options.no_block_cache = False - - # If the following options are None use the rocksdb default. - if block_size is not None: - table_options.block_size = block_size - - if block_size_deviation is not None: - table_options.block_size_deviation = block_size_deviation - - if block_restart_interval is not None: - table_options.block_restart_interval = block_restart_interval - - if whole_key_filtering is not None: - if whole_key_filtering: - table_options.whole_key_filtering = True - else: - table_options.whole_key_filtering = False - - if cache_index_and_filter_blocks is not None: - table_options.cache_index_and_filter_blocks = bool(cache_index_and_filter_blocks) - - if cache_index_and_filter_blocks_with_high_priority is not None: - table_options.cache_index_and_filter_blocks_with_high_priority = bool( - cache_index_and_filter_blocks_with_high_priority - ) - - if pin_l0_filter_and_index_blocks_in_cache is not None: - table_options.pin_l0_filter_and_index_blocks_in_cache = bool( - pin_l0_filter_and_index_blocks_in_cache - ) - - if pin_top_level_index_and_filter is not None: - table_options.pin_top_level_index_and_filter = bool(pin_top_level_index_and_filter) - - if partition_filters is not None: - table_options.partition_filters = bool(partition_filters) - - if metadata_block_size is not None: - table_options.metadata_block_size = metadata_block_size - - if format_version is not None: - table_options.format_version = format_version - - if optimize_filters_for_memory is not None: - table_options.optimize_filters_for_memory = bool(optimize_filters_for_memory) - - if read_amp_bytes_per_bit is not None: - table_options.read_amp_bytes_per_bit = read_amp_bytes_per_bit - - if block_cache is not None: - table_options.block_cache = block_cache.get_cache() - - if block_cache_compressed is not None: - table_options.block_cache_compressed = block_cache_compressed.get_cache() - - # Set the filter_policy - self.py_filter_policy = None - if filter_policy is not None: - if isinstance(filter_policy, PyFilterPolicy): - if (filter_policy).get_policy().get() == NULL: - raise Exception("Cannot set filter policy: %s" % filter_policy) - self.py_filter_policy = filter_policy - else: - self.py_filter_policy = PyGenericFilterPolicy(filter_policy) - - table_options.filter_policy = self.py_filter_policy.get_policy() - - self.factory.reset(table_factory.NewBlockBasedTableFactory(table_options)) - - cdef set_info_log(self, shared_ptr[logger.Logger] info_log): - if self.py_filter_policy is not None: - self.py_filter_policy.set_info_log(info_log) - - -cdef class PlainTableFactory(PyTableFactory): - def __init__( - self, - user_key_len=0, - bloom_bits_per_key=10, - hash_table_ratio=0.75, - index_sparseness=10, - huge_page_tlb_size=0, - encoding_type='plain', - py_bool full_scan_mode=False): - - cdef table_factory.PlainTableOptions table_options - - table_options.user_key_len = user_key_len - table_options.bloom_bits_per_key = bloom_bits_per_key - table_options.hash_table_ratio = hash_table_ratio - table_options.index_sparseness = index_sparseness - table_options.huge_page_tlb_size = huge_page_tlb_size - - if encoding_type == 'plain': - table_options.encoding_type = table_factory.kPlain - elif encoding_type == 'prefix': - table_options.encoding_type = table_factory.kPrefix - else: - raise ValueError("Unknown encoding_type: %s" % encoding_type) - - table_options.full_scan_mode = full_scan_mode - - self.factory.reset( table_factory.NewPlainTableFactory(table_options)) -############################################# - - -### Here are the MemtableFactories -cdef class PyMemtableFactory(object): - # pxd defines: - # cdef shared_ptr[memtablerep.MemTableRepFactory] factory - - cdef shared_ptr[memtablerep.MemTableRepFactory] get_memtable_factory(self): - return self.factory - - -cdef class SkipListMemtableFactory(PyMemtableFactory): - def __init__(self): - self.factory.reset(memtablerep.NewSkipListFactory()) - - -cdef class VectorMemtableFactory(PyMemtableFactory): - def __init__(self, count=0): - self.factory.reset(memtablerep.NewVectorRepFactory(count)) - - -cdef class HashSkipListMemtableFactory(PyMemtableFactory): - def __init__( - self, - bucket_count=1000000, - skiplist_height=4, - skiplist_branching_factor=4): - - self.factory.reset( - memtablerep.NewHashSkipListRepFactory( - bucket_count, - skiplist_height, - skiplist_branching_factor)) - - -cdef class HashLinkListMemtableFactory(PyMemtableFactory): - def __init__(self, bucket_count=50000): - self.factory.reset(memtablerep.NewHashLinkListRepFactory(bucket_count)) -################################## - - -cdef class CompressionType(object): - no_compression = u'no_compression' - snappy_compression = u'snappy_compression' - zlib_compression = u'zlib_compression' - bzip2_compression = u'bzip2_compression' - lz4_compression = u'lz4_compression' - lz4hc_compression = u'lz4hc_compression' - xpress_compression = u'xpress_compression' - zstd_compression = u'zstd_compression' - zstdnotfinal_compression = u'zstdnotfinal_compression' - disable_compression = u'disable_compression' - -cdef class CompactionPri(object): - by_compensated_size = u'by_compensated_size' - oldest_largest_seq_first = u'oldest_largest_seq_first' - oldest_smallest_seq_first = u'oldest_smallest_seq_first' - min_overlapping_ratio = u'min_overlapping_ratio' - - -cdef class TxnDBWritePolicy(object): - write_committed = u'write_committed' - write_prepared = u'write_prepared' - write_unprepared = u'write_unprepared' - - -cdef class _ColumnFamilyHandle: - """ This is an internal class that we will weakref for safety """ - # pxd defines: - # cdef db.ColumnFamilyHandle* handle - # cdef object __weakref__ - # cdef object weak_handle - - def __cinit__(self): - self.handle = NULL - - def __dealloc__(self): - if not self.handle == NULL: - del self.handle - - @staticmethod - cdef from_handle_ptr(db.ColumnFamilyHandle* handle): - inst = <_ColumnFamilyHandle>_ColumnFamilyHandle.__new__(_ColumnFamilyHandle) - inst.handle = handle - return inst - - @property - def name(self): - return self.handle.GetName() - - @property - def id(self): - return self.handle.GetID() - - @property - def weakref(self): - if self.weak_handle is None: - self.weak_handle = ColumnFamilyHandle.from_wrapper(self) - return self.weak_handle - -cdef class ColumnFamilyHandle: - """ This represents a ColumnFamilyHandle """ - # cdef object _ref - # cdef readonly bytes name - # cdef readonly int id - - def __cinit__(self, weakhandle): - self._ref = weakhandle - self.name = self._ref().name - self.id = self._ref().id - - def __init__(self, *): - raise TypeError("These can not be constructed from Python") - - @staticmethod - cdef object from_wrapper(_ColumnFamilyHandle real_handle): - return ColumnFamilyHandle.__new__(ColumnFamilyHandle, weakref.ref(real_handle)) - - @property - def is_valid(self): - return self._ref() is not None - - def __repr__(self): - valid = "valid" if self.is_valid else "invalid" - return f"" - - cdef db.ColumnFamilyHandle* get_handle(self) except NULL: - cdef _ColumnFamilyHandle real_handle = self._ref() - if real_handle is None: - raise ValueError(f"{self} is no longer a valid ColumnFamilyHandle!") - return real_handle.handle - - def __eq__(self, other): - cdef ColumnFamilyHandle fast_other - if isinstance(other, ColumnFamilyHandle): - fast_other = other - return ( - self.name == fast_other.name - and self.id == fast_other.id - and self._ref == fast_other._ref - ) - return False - - def __lt__(self, other): - cdef ColumnFamilyHandle fast_other - if isinstance(other, ColumnFamilyHandle): - return self.id < other.id - return NotImplemented - - # Since @total_ordering isn't a thing for cython - def __ne__(self, other): - return not self == other - - def __gt__(self, other): - return other < self - - def __le__(self, other): - return not other < self - - def __ge__(self, other): - return not self < other - - def __hash__(self): - # hash of a weakref matches that of its original ref'ed object - # so we use the id of our weakref object here to prevent - # a situation where we are invalid, but match a valid handle's hash - return hash((self.id, self.name, id(self._ref))) - - -cdef class ColumnFamilyOptions(object): - # pxd defines: - # cdef options.ColumnFamilyOptions* copts - # cdef PyComparator py_comparator - # cdef PyMergeOperator py_merge_operator - # cdef PySliceTransform py_prefix_extractor - # cdef PyTableFactory py_table_factory - # cdef PyMemtableFactory py_memtable_factory - # cdef cpp_bool in_use - - def __cinit__(self): - self.copts = NULL - self.copts = new options.ColumnFamilyOptions() - self.in_use = False - - def __dealloc__(self): - if not self.copts == NULL: - del self.copts - - def __init__(self, **kwargs): - self.py_comparator = BytewiseComparator() - self.py_merge_operator = None - self.py_prefix_extractor = None - self.py_table_factory = None - self.py_memtable_factory = None - - for key, value in kwargs.items(): - setattr(self, key, value) - - property write_buffer_size: - def __get__(self): - return self.copts.write_buffer_size - def __set__(self, value): - self.copts.write_buffer_size = value - - property max_write_buffer_number: - def __get__(self): - return self.copts.max_write_buffer_number - def __set__(self, value): - self.copts.max_write_buffer_number = value - - property min_write_buffer_number_to_merge: - def __get__(self): - return self.copts.min_write_buffer_number_to_merge - def __set__(self, value): - self.copts.min_write_buffer_number_to_merge = value - - property compression_opts: - def __get__(self): - cdef dict ret_ob = {} - - ret_ob['window_bits'] = self.copts.compression_opts.window_bits - ret_ob['level'] = self.copts.compression_opts.level - ret_ob['strategy'] = self.copts.compression_opts.strategy - ret_ob['max_dict_bytes'] = self.copts.compression_opts.max_dict_bytes - - return ret_ob - - def __set__(self, dict value): - cdef options.CompressionOptions* copts - copts = cython.address(self.copts.compression_opts) - # CompressionOptions(int wbits, int _lev, int _strategy, int _max_dict_bytes) - if 'window_bits' in value: - copts.window_bits = value['window_bits'] - if 'level' in value: - copts.level = value['level'] - if 'strategy' in value: - copts.strategy = value['strategy'] - if 'max_dict_bytes' in value: - copts.max_dict_bytes = value['max_dict_bytes'] - - property compaction_pri: - def __get__(self): - if self.copts.compaction_pri == options.kByCompensatedSize: - return CompactionPri.by_compensated_size - if self.copts.compaction_pri == options.kOldestLargestSeqFirst: - return CompactionPri.oldest_largest_seq_first - if self.copts.compaction_pri == options.kOldestSmallestSeqFirst: - return CompactionPri.oldest_smallest_seq_first - if self.copts.compaction_pri == options.kMinOverlappingRatio: - return CompactionPri.min_overlapping_ratio - def __set__(self, value): - if value == CompactionPri.by_compensated_size: - self.copts.compaction_pri = options.kByCompensatedSize - elif value == CompactionPri.oldest_largest_seq_first: - self.copts.compaction_pri = options.kOldestLargestSeqFirst - elif value == CompactionPri.oldest_smallest_seq_first: - self.copts.compaction_pri = options.kOldestSmallestSeqFirst - elif value == CompactionPri.min_overlapping_ratio: - self.copts.compaction_pri = options.kMinOverlappingRatio - else: - raise TypeError("Unknown compaction pri: %s" % value) - - property compression: - def __get__(self): - if self.copts.compression == options.kNoCompression: - return CompressionType.no_compression - elif self.copts.compression == options.kSnappyCompression: - return CompressionType.snappy_compression - elif self.copts.compression == options.kZlibCompression: - return CompressionType.zlib_compression - elif self.copts.compression == options.kBZip2Compression: - return CompressionType.bzip2_compression - elif self.copts.compression == options.kLZ4Compression: - return CompressionType.lz4_compression - elif self.copts.compression == options.kLZ4HCCompression: - return CompressionType.lz4hc_compression - elif self.copts.compression == options.kXpressCompression: - return CompressionType.xpress_compression - elif self.copts.compression == options.kZSTD: - return CompressionType.zstd_compression - elif self.copts.compression == options.kZSTDNotFinalCompression: - return CompressionType.zstdnotfinal_compression - elif self.copts.compression == options.kDisableCompressionOption: - return CompressionType.disable_compression - else: - raise Exception("Unknonw type: %s" % self.opts.compression) - - def __set__(self, value): - if value == CompressionType.no_compression: - self.copts.compression = options.kNoCompression - elif value == CompressionType.snappy_compression: - self.copts.compression = options.kSnappyCompression - elif value == CompressionType.zlib_compression: - self.copts.compression = options.kZlibCompression - elif value == CompressionType.bzip2_compression: - self.copts.compression = options.kBZip2Compression - elif value == CompressionType.lz4_compression: - self.copts.compression = options.kLZ4Compression - elif value == CompressionType.lz4hc_compression: - self.copts.compression = options.kLZ4HCCompression - elif value == CompressionType.zstd_compression: - self.copts.compression = options.kZSTD - elif value == CompressionType.zstdnotfinal_compression: - self.copts.compression = options.kZSTDNotFinalCompression - elif value == CompressionType.disable_compression: - self.copts.compression = options.kDisableCompressionOption - else: - raise TypeError("Unknown compression: %s" % value) - - property max_compaction_bytes: - def __get__(self): - return self.copts.max_compaction_bytes - def __set__(self, value): - self.copts.max_compaction_bytes = value - - property num_levels: - def __get__(self): - return self.copts.num_levels - def __set__(self, value): - self.copts.num_levels = value - - property level0_file_num_compaction_trigger: - def __get__(self): - return self.copts.level0_file_num_compaction_trigger - def __set__(self, value): - self.copts.level0_file_num_compaction_trigger = value - - property level0_slowdown_writes_trigger: - def __get__(self): - return self.copts.level0_slowdown_writes_trigger - def __set__(self, value): - self.copts.level0_slowdown_writes_trigger = value - - property level0_stop_writes_trigger: - def __get__(self): - return self.copts.level0_stop_writes_trigger - def __set__(self, value): - self.copts.level0_stop_writes_trigger = value - - property max_mem_compaction_level: - def __get__(self): - return self.copts.max_mem_compaction_level - def __set__(self, value): - self.copts.max_mem_compaction_level = value - - property target_file_size_base: - def __get__(self): - return self.copts.target_file_size_base - def __set__(self, value): - self.copts.target_file_size_base = value - - property target_file_size_multiplier: - def __get__(self): - return self.copts.target_file_size_multiplier - def __set__(self, value): - self.copts.target_file_size_multiplier = value - - property max_bytes_for_level_base: - def __get__(self): - return self.copts.max_bytes_for_level_base - def __set__(self, value): - self.copts.max_bytes_for_level_base = value - - property max_bytes_for_level_multiplier: - def __get__(self): - return self.copts.max_bytes_for_level_multiplier - def __set__(self, value): - self.copts.max_bytes_for_level_multiplier = value - - property max_bytes_for_level_multiplier_additional: - def __get__(self): - return self.copts.max_bytes_for_level_multiplier_additional - def __set__(self, value): - self.copts.max_bytes_for_level_multiplier_additional = value - - property arena_block_size: - def __get__(self): - return self.copts.arena_block_size - def __set__(self, value): - self.copts.arena_block_size = value - - property disable_auto_compactions: - def __get__(self): - return self.copts.disable_auto_compactions - def __set__(self, value): - self.copts.disable_auto_compactions = value - - # FIXME: remove to util/options_helper.h - # property allow_os_buffer: - # def __get__(self): - # return self.copts.allow_os_buffer - # def __set__(self, value): - # self.copts.allow_os_buffer = value - - property compaction_style: - def __get__(self): - if self.copts.compaction_style == kCompactionStyleLevel: - return 'level' - if self.copts.compaction_style == kCompactionStyleUniversal: - return 'universal' - if self.copts.compaction_style == kCompactionStyleFIFO: - return 'fifo' - if self.copts.compaction_style == kCompactionStyleNone: - return 'none' - raise Exception("Unknown compaction_style") - - def __set__(self, str value): - if value == 'level': - self.copts.compaction_style = kCompactionStyleLevel - elif value == 'universal': - self.copts.compaction_style = kCompactionStyleUniversal - elif value == 'fifo': - self.copts.compaction_style = kCompactionStyleFIFO - elif value == 'none': - self.copts.compaction_style = kCompactionStyleNone - else: - raise Exception("Unknown compaction style") - - property compaction_options_universal: - def __get__(self): - cdef universal_compaction.CompactionOptionsUniversal uopts - cdef dict ret_ob = {} - - uopts = self.copts.compaction_options_universal - - ret_ob['size_ratio'] = uopts.size_ratio - ret_ob['min_merge_width'] = uopts.min_merge_width - ret_ob['max_merge_width'] = uopts.max_merge_width - ret_ob['max_size_amplification_percent'] = uopts.max_size_amplification_percent - ret_ob['compression_size_percent'] = uopts.compression_size_percent - - if uopts.stop_style == kCompactionStopStyleSimilarSize: - ret_ob['stop_style'] = 'similar_size' - elif uopts.stop_style == kCompactionStopStyleTotalSize: - ret_ob['stop_style'] = 'total_size' - else: - raise Exception("Unknown compaction style") - - return ret_ob - - def __set__(self, dict value): - cdef universal_compaction.CompactionOptionsUniversal* uopts - uopts = cython.address(self.copts.compaction_options_universal) - - if 'size_ratio' in value: - uopts.size_ratio = value['size_ratio'] - - if 'min_merge_width' in value: - uopts.min_merge_width = value['min_merge_width'] - - if 'max_merge_width' in value: - uopts.max_merge_width = value['max_merge_width'] - - if 'max_size_amplification_percent' in value: - uopts.max_size_amplification_percent = value['max_size_amplification_percent'] - - if 'compression_size_percent' in value: - uopts.compression_size_percent = value['compression_size_percent'] - - if 'stop_style' in value: - if value['stop_style'] == 'similar_size': - uopts.stop_style = kCompactionStopStyleSimilarSize - elif value['stop_style'] == 'total_size': - uopts.stop_style = kCompactionStopStyleTotalSize - else: - raise Exception("Unknown compaction style") - - # Deprecate - # property filter_deletes: - # def __get__(self): - # return self.copts.filter_deletes - # def __set__(self, value): - # self.copts.filter_deletes = value - - property max_sequential_skip_in_iterations: - def __get__(self): - return self.copts.max_sequential_skip_in_iterations - def __set__(self, value): - self.copts.max_sequential_skip_in_iterations = value - - property inplace_update_support: - def __get__(self): - return self.copts.inplace_update_support - def __set__(self, value): - self.copts.inplace_update_support = value - - property table_factory: - def __get__(self): - return self.py_table_factory - - def __set__(self, PyTableFactory value): - self.py_table_factory = value - self.copts.table_factory = value.get_table_factory() - - property memtable_factory: - def __get__(self): - return self.py_memtable_factory - - def __set__(self, PyMemtableFactory value): - self.py_memtable_factory = value - self.copts.memtable_factory = value.get_memtable_factory() - - property inplace_update_num_locks: - def __get__(self): - return self.copts.inplace_update_num_locks - def __set__(self, value): - self.copts.inplace_update_num_locks = value - - property comparator: - def __get__(self): - return self.py_comparator.get_ob() - - def __set__(self, value): - if isinstance(value, PyComparator): - if (value).get_comparator() == NULL: - raise Exception("Cannot set %s as comparator" % value) - else: - self.py_comparator = value - else: - self.py_comparator = PyGenericComparator(value) - - self.copts.comparator = self.py_comparator.get_comparator() - - property merge_operator: - def __get__(self): - if self.py_merge_operator is None: - return None - return self.py_merge_operator.get_ob() - - def __set__(self, value): - self.py_merge_operator = PyMergeOperator(value) - self.copts.merge_operator = self.py_merge_operator.get_operator() - - property prefix_extractor: - def __get__(self): - if self.py_prefix_extractor is None: - return None - return self.py_prefix_extractor.get_ob() - - def __set__(self, value): - self.py_prefix_extractor = PySliceTransform(value) - self.copts.prefix_extractor = self.py_prefix_extractor.get_transformer() - - -cdef class Options(ColumnFamilyOptions): - # pxd defines: - # cdef options.Options* opts - # cdef PyCache py_row_cache - - def __cinit__(self): - # Destroy the existing ColumnFamilyOptions() - del self.copts - self.opts = NULL - self.copts = self.opts = new options.Options() - self.in_use = False - - def __dealloc__(self): - if not self.opts == NULL: - self.copts = NULL - del self.opts - - def __init__(self, **kwargs): - ColumnFamilyOptions.__init__(self) - self.py_row_cache = None - - for key, value in kwargs.items(): - setattr(self, key, value) - - property create_if_missing: - def __get__(self): - return self.opts.create_if_missing - def __set__(self, value): - self.opts.create_if_missing = value - - property error_if_exists: - def __get__(self): - return self.opts.error_if_exists - def __set__(self, value): - self.opts.error_if_exists = value - - property paranoid_checks: - def __get__(self): - return self.opts.paranoid_checks - def __set__(self, value): - self.opts.paranoid_checks = value - - property max_open_files: - def __get__(self): - return self.opts.max_open_files - def __set__(self, value): - self.opts.max_open_files = value - - property use_fsync: - def __get__(self): - return self.opts.use_fsync - def __set__(self, value): - self.opts.use_fsync = value - - property db_log_dir: - def __get__(self): - return string_to_path(self.opts.db_log_dir) - def __set__(self, value): - self.opts.db_log_dir = path_to_string(value) - - property wal_dir: - def __get__(self): - return string_to_path(self.opts.wal_dir) - def __set__(self, value): - self.opts.wal_dir = path_to_string(value) - - property delete_obsolete_files_period_micros: - def __get__(self): - return self.opts.delete_obsolete_files_period_micros - def __set__(self, value): - self.opts.delete_obsolete_files_period_micros = value - - property max_background_compactions: - def __get__(self): - return self.opts.max_background_compactions - def __set__(self, value): - self.opts.max_background_compactions = value - - property max_background_flushes: - def __get__(self): - return self.opts.max_background_flushes - def __set__(self, value): - self.opts.max_background_flushes = value - - property max_log_file_size: - def __get__(self): - return self.opts.max_log_file_size - def __set__(self, value): - self.opts.max_log_file_size = value - - property db_write_buffer_size: - def __get__(self): - return self.opts.db_write_buffer_size - def __set__(self, value): - self.opts.db_write_buffer_size = value - - property log_file_time_to_roll: - def __get__(self): - return self.opts.log_file_time_to_roll - def __set__(self, value): - self.opts.log_file_time_to_roll = value - - property keep_log_file_num: - def __get__(self): - return self.opts.keep_log_file_num - def __set__(self, value): - self.opts.keep_log_file_num = value - - property max_manifest_file_size: - def __get__(self): - return self.opts.max_manifest_file_size - def __set__(self, value): - self.opts.max_manifest_file_size = value - - property table_cache_numshardbits: - def __get__(self): - return self.opts.table_cache_numshardbits - def __set__(self, value): - self.opts.table_cache_numshardbits = value - - property wal_ttl_seconds: - def __get__(self): - return self.opts.WAL_ttl_seconds - def __set__(self, value): - self.opts.WAL_ttl_seconds = value - - property wal_size_limit_mb: - def __get__(self): - return self.opts.WAL_size_limit_MB - def __set__(self, value): - self.opts.WAL_size_limit_MB = value - - property manifest_preallocation_size: - def __get__(self): - return self.opts.manifest_preallocation_size - def __set__(self, value): - self.opts.manifest_preallocation_size = value - - property enable_write_thread_adaptive_yield: - def __get__(self): - return self.opts.enable_write_thread_adaptive_yield - def __set__(self, value): - self.opts.enable_write_thread_adaptive_yield = value - - property allow_concurrent_memtable_write: - def __get__(self): - return self.opts.allow_concurrent_memtable_write - def __set__(self, value): - self.opts.allow_concurrent_memtable_write = value - - property allow_mmap_reads: - def __get__(self): - return self.opts.allow_mmap_reads - def __set__(self, value): - self.opts.allow_mmap_reads = value - - property allow_mmap_writes: - def __get__(self): - return self.opts.allow_mmap_writes - def __set__(self, value): - self.opts.allow_mmap_writes = value - - property is_fd_close_on_exec: - def __get__(self): - return self.opts.is_fd_close_on_exec - def __set__(self, value): - self.opts.is_fd_close_on_exec = value - - property stats_dump_period_sec: - def __get__(self): - return self.opts.stats_dump_period_sec - def __set__(self, value): - self.opts.stats_dump_period_sec = value - - property advise_random_on_open: - def __get__(self): - return self.opts.advise_random_on_open - def __set__(self, value): - self.opts.advise_random_on_open = value - - # TODO: need to remove -Wconversion to make this work - # property access_hint_on_compaction_start: - # def __get__(self): - # return self.opts.access_hint_on_compaction_start - # def __set__(self, AccessHint value): - # self.opts.access_hint_on_compaction_start = value - - property use_adaptive_mutex: - def __get__(self): - return self.opts.use_adaptive_mutex - def __set__(self, value): - self.opts.use_adaptive_mutex = value - - property bytes_per_sync: - def __get__(self): - return self.opts.bytes_per_sync - def __set__(self, value): - self.opts.bytes_per_sync = value - - property row_cache: - def __get__(self): - return self.py_row_cache - - def __set__(self, value): - if value is None: - self.py_row_cache = None - self.opts.row_cache.reset() - elif not isinstance(value, PyCache): - raise Exception("row_cache must be a Cache object") - else: - self.py_row_cache = value - self.opts.row_cache = self.py_row_cache.get_cache() - - - # cpp_bool skip_checking_sst_file_sizes_on_db_open - property skip_checking_sst_file_sizes_on_db_open: - def __get__(self): - return self.opts.skip_checking_sst_file_sizes_on_db_open - def __set__(self, value): - self.opts.skip_checking_sst_file_sizes_on_db_open = value - - # cpp_bool skip_stats_update_on_db_open - property skip_stats_update_on_db_open: - def __get__(self): - return self.opts.skip_stats_update_on_db_open - def __set__(self, value): - self.opts.skip_stats_update_on_db_open = value - - -cdef class TransactionDBOptions(object): - # pxd defines: - # cdef transaction.TransactionDBOptions* opts - # cdef bint in_use - - def __cinit__(self): - self.opts = new transaction.TransactionDBOptions() - self.in_use = False - - def __dealloc__(self): - if self.opts != NULL: - del self.opts - self.opts = NULL - - def __init__(self, **kwargs): - for key, value in kwargs.items(): - setattr(self, key, value) - - property max_num_locks: - def __get__(self): - return self.opts.max_num_locks - def __set__(self, value): - self.opts.max_num_locks = value - - property max_num_deadlocks: - def __get__(self): - return self.opts.max_num_deadlocks - def __set__(self, value): - self.opts.max_num_deadlocks = value - - property num_stripes: - def __get__(self): - return self.opts.num_stripes - def __set__(self, value): - self.opts.num_stripes = value - - property transaction_lock_timeout: - def __get__(self): - return self.opts.transaction_lock_timeout - def __set__(self, value): - self.opts.transaction_lock_timeout = value - - property default_lock_timeout: - def __get__(self): - return self.opts.default_lock_timeout - def __set__(self, value): - self.opts.default_lock_timeout = value - - property write_policy: - def __get__(self): - if self.opts.write_policy == transaction.WRITE_COMMITTED: - return TxnDBWritePolicy.write_committed - elif self.opts.write_policy == transaction.WRITE_PREPARED: - return TxnDBWritePolicy.write_prepared - elif self.opts.write_policy == transaction.WRITE_UNPREPARED: - return TxnDBWritePolicy.write_unprepared - raise TypeError("Unknown write policy value: %r" % self.opts.write_policy) - - def __set__(self, value): - if value in (TxnDBWritePolicy.write_committed, b'write_committed', 'write_committed'): - self.opts.write_policy = transaction.WRITE_COMMITTED - elif value in (TxnDBWritePolicy.write_prepared, b'write_prepared', 'write_prepared'): - self.opts.write_policy = transaction.WRITE_PREPARED - elif value in (TxnDBWritePolicy.write_unprepared, b'write_unprepared', 'write_unprepared'): - self.opts.write_policy = transaction.WRITE_UNPREPARED - else: - raise TypeError("Unknown transaction write policy: %r" % value) - - property rollback_merge_operands: - def __get__(self): - return self.opts.rollback_merge_operands - def __set__(self, value): - self.opts.rollback_merge_operands = value - - property skip_concurrency_control: - def __get__(self): - return self.opts.skip_concurrency_control - def __set__(self, value): - self.opts.skip_concurrency_control = value - - property default_write_batch_flush_threshold: - def __get__(self): - return self.opts.default_write_batch_flush_threshold - def __set__(self, value): - self.opts.default_write_batch_flush_threshold = value - - -cdef class TransactionOptions(object): - # pxd defines: - # cdef transaction.TransactionOptions* opts - - def __cinit__(self): - self.opts = new transaction.TransactionOptions() - - def __dealloc__(self): - if self.opts != NULL: - del self.opts - self.opts = NULL - - def __init__(self, **kwargs): - for key, value in kwargs.items(): - setattr(self, key, value) - - property set_snapshot: - def __get__(self): - return self.opts.set_snapshot - def __set__(self, value): - self.opts.set_snapshot = value - - property deadlock_detect: - def __get__(self): - return self.opts.deadlock_detect - def __set__(self, value): - self.opts.deadlock_detect = value - - property use_only_the_last_commit_time_batch_for_recovery: - def __get__(self): - return self.opts.use_only_the_last_commit_time_batch_for_recovery - def __set__(self, value): - self.opts.use_only_the_last_commit_time_batch_for_recovery = value - - property lock_timeout: - def __get__(self): - return self.opts.lock_timeout - def __set__(self, value): - self.opts.lock_timeout = value - - property expiration: - def __get__(self): - return self.opts.expiration - def __set__(self, value): - self.opts.expiration = value - - property deadlock_detect_depth: - def __get__(self): - return self.opts.deadlock_detect_depth - def __set__(self, value): - self.opts.deadlock_detect_depth = value - - property max_write_batch_size: - def __get__(self): - return self.opts.max_write_batch_size - def __set__(self, value): - self.opts.max_write_batch_size = value - - property skip_concurrency_control: - def __get__(self): - return self.opts.skip_concurrency_control - def __set__(self, value): - self.opts.skip_concurrency_control = value - - property skip_prepare: - def __get__(self): - return self.opts.skip_prepare - def __set__(self, value): - self.opts.skip_prepare = value - - property write_batch_flush_threshold: - def __get__(self): - return self.opts.write_batch_flush_threshold - def __set__(self, value): - self.opts.write_batch_flush_threshold = value - - - -# TODO inherit from writableDB -cdef class WriteBatch(object): - # pxd defines: - # cdef db.WriteBatch* batch - - def __cinit__(self, data=None): - self.batch = NULL - if data is not None: - self.batch = new db.WriteBatch(bytes_to_string(data)) - else: - self.batch = new db.WriteBatch() - - def __dealloc__(self): - if not self.batch == NULL: - del self.batch - - cpdef void put(self, bytes key, bytes value, ColumnFamilyHandle column_family = None): - cdef db.ColumnFamilyHandle* cf_handle = NULL - if column_family is not None: - cf_handle = column_family.get_handle() - # nullptr is default family - self.batch.Put(cf_handle, bytes_to_slice(key), bytes_to_slice(value)) - - cpdef void merge(self, bytes key, bytes value, ColumnFamilyHandle column_family = None): - cdef db.ColumnFamilyHandle* cf_handle = NULL - if column_family is not None: - cf_handle = column_family.get_handle() - # nullptr is default family - self.batch.Merge(cf_handle, bytes_to_slice(key), bytes_to_slice(value)) - - # Here delete is with def for backwards compatibility. - # Cython has a bug that doesn't allow a method with name `delete` - # so we have to use a different name for `cpdef`-ed ones. - def delete(self, bytes key, ColumnFamilyHandle column_family = None): - return self.delete_single(key, column_family) - - cpdef void delete_single(self, bytes key, ColumnFamilyHandle column_family = None): - cdef db.ColumnFamilyHandle* cf_handle = NULL - if column_family is not None: - cf_handle = column_family.get_handle() - # nullptr is default family - self.batch.Delete(cf_handle, bytes_to_slice(key)) - - cpdef void delete_range(self, bytes begin_key, bytes end_key, ColumnFamilyHandle column_family = None): - cdef db.ColumnFamilyHandle* cf_handle = NULL - if column_family is not None: - cf_handle = column_family.get_handle() - - # nullptr is default family - self.batch.DeleteRange(cf_handle, bytes_to_slice(begin_key), bytes_to_slice(end_key)) - - cpdef void clear(self): - self.batch.Clear() - - cpdef data(self): - return string_to_bytes(self.batch.Data()) - - cpdef int count(self): - return self.batch.Count() - - def __iter__(self): - return WriteBatchIterator(self) - - -cdef class WriteBatchIterator(object): - # Need a reference to the WriteBatch. - # The BatchItems are only pointers to the memory in WriteBatch. - - # pxd defines: - # cdef WriteBatch batch - # cdef vector[db.BatchItem] items - # cdef size_t pos - - def __init__(self, WriteBatch batch): - cdef Status st - - self.batch = batch - self.pos = 0 - - st = db.get_batch_items(batch.batch, cython.address(self.items)) - check_status(st) - - def __iter__(self): - return self - - def __next__(self): - if self.pos == self.items.size(): - raise StopIteration() - - cdef str op - - if self.items[self.pos].op == db.BatchItemOpPut: - op = "Put" - elif self.items[self.pos].op == db.BatchItemOpMerge: - op = "Merge" - elif self.items[self.pos].op == db.BatchItemOpDelte: - op = "Delete" - - if self.items[self.pos].column_family_id != 0: # Column Family is set - ret = ( - op, - ( - self.items[self.pos].column_family_id, - slice_to_bytes(self.items[self.pos].key) - ), - slice_to_bytes(self.items[self.pos].value) - ) - else: - ret = ( - op, - slice_to_bytes(self.items[self.pos].key), - slice_to_bytes(self.items[self.pos].value) - ) - self.pos += 1 - return ret - - -# TODO add writableDB, ReadablewritableDB -# TODO add WriteBatch iniherited from writableDB - - -cdef class IDB(object): - # Cython requires to implement methods in the class definition - # even for abstract classes. - - # TODO move write option arguments to a separate class - cpdef void put(self, bytes key, bytes value, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - pass - cpdef void delete_single(self, bytes key, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - pass - cpdef void delete_range(self, bytes begin_key, bytes end_key, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - pass - cpdef void flush(self): - pass - cpdef void flush_wal(self, cpp_bool sync = False): - pass - cpdef void merge(self, bytes key, bytes value, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - pass - cpdef void write(self, WriteBatch batch, cpp_bool sync = False, cpp_bool disable_wal = False): - pass - cpdef get(self, bytes key, ColumnFamilyHandle column_family = None): - pass - cpdef multi_get(self, keys): - pass - cpdef key_may_exist(self, bytes key, cpp_bool fetch = False, ColumnFamilyHandle column_family = None): - pass - cpdef Iterator iterkeys(self, ColumnFamilyHandle column_family = None): - pass - cpdef Iterator itervalues(self, ColumnFamilyHandle column_family = None): - pass - cpdef Iterator iteritems(self, ColumnFamilyHandle column_family = None): - pass - - -@cython.no_gc_clear -cdef class DB(IDB): - # pxd defines: - # cdef Options opts - # cdef db.DB* db - # cdef list cf_handles - # cdef list cf_options - - def __cinit__( - self, - db_name, - Options opts, - dict column_families=None, - read_only=False, - secondary_path=None, - txn_db_opts=None, - ): - cdef Status st - cdef string db_path - cdef string secondary_path_c - cdef vector[db.ColumnFamilyDescriptor] column_family_descriptors - cdef vector[db.ColumnFamilyHandle*] column_family_handles - cdef bytes default_cf_name = db.kDefaultColumnFamilyName - self._iterators = set() - self._snapshots = set() - self._transactions = set() - self.db = NULL - self.opts = None - self.cf_handles = [] - self.cf_options = [] - - # TransactionDB subclasses handle opening the underlying C++ handle - # themselves. Skipping here prevents double initialisation that leads to - # use-after-free during teardown. - if isinstance(self, TransactionDB): - return - - # TransactionDB passes txn_db_opts so it can manage opening the C++ - # TransactionDB itself. When present we skip the vanilla DB open here - # and let the subclass finish initialisation. - if txn_db_opts is not None: - return - - if opts.in_use: - raise Exception("Options object is already used by another DB") - - db_path = path_to_string(db_name) - if not column_families or default_cf_name not in column_families: - # Always add the default column family - column_family_descriptors.push_back( - db.ColumnFamilyDescriptor( - db.kDefaultColumnFamilyName, - options.ColumnFamilyOptions(deref(opts.opts)) - ) - ) - self.cf_options.append(None) # Since they are the same as db - if column_families: - for cf_name, cf_options in column_families.items(): - if not isinstance(cf_name, bytes): - raise TypeError( - f"column family name {cf_name!r} is not of type {bytes}!" - ) - if not isinstance(cf_options, ColumnFamilyOptions): - raise TypeError( - f"column family options {cf_options!r} is not of type " - f"{ColumnFamilyOptions}!" - ) - if (cf_options).in_use: - raise Exception( - f"ColumnFamilyOptions object for {cf_name} is already " - "used by another Column Family" - ) - (cf_options).in_use = True - column_family_descriptors.push_back( - db.ColumnFamilyDescriptor( - cf_name, - deref((cf_options).copts) - ) - ) - self.cf_options.append(cf_options) - - if secondary_path is not None: - assert read_only - secondary_path_c = path_to_string(secondary_path) - with nogil: - st = db.DB_OpenAsSecondary_ColumnFamilies( - deref(opts.opts), - db_path, - secondary_path_c, - column_family_descriptors, - &column_family_handles, - &self.db) - elif read_only: - with nogil: - st = db.DB_OpenForReadOnly_ColumnFamilies( - deref(opts.opts), - db_path, - column_family_descriptors, - &column_family_handles, - &self.db, - False) - else: - with nogil: - st = db.DB_Open_ColumnFamilies( - deref(opts.opts), - db_path, - column_family_descriptors, - &column_family_handles, - &self.db) - check_status(st) - - for handle in column_family_handles: - wrapper = _ColumnFamilyHandle.from_handle_ptr(handle) - self.cf_handles.append(wrapper) - - # Inject the loggers into the python callbacks - cdef shared_ptr[logger.Logger] info_log = self.db.GetOptions( - self.db.DefaultColumnFamily()).info_log - if opts.py_comparator is not None: - opts.py_comparator.set_info_log(info_log) - - if opts.py_table_factory is not None: - opts.py_table_factory.set_info_log(info_log) - - if opts.prefix_extractor is not None: - opts.py_prefix_extractor.set_info_log(info_log) - - cdef ColumnFamilyOptions copts - for idx, copts in enumerate(self.cf_options): - if not copts: - continue - - info_log = self.db.GetOptions(column_family_handles[idx]).info_log - - if copts.py_comparator is not None: - copts.py_comparator.set_info_log(info_log) - - if copts.py_table_factory is not None: - copts.py_table_factory.set_info_log(info_log) - - if copts.prefix_extractor is not None: - copts.py_prefix_extractor.set_info_log(info_log) - - self.opts = opts - self.opts.in_use = True - - def __dealloc__(self): - self.close() - - cdef int _check_open(self) except -1: - if self.db == NULL: - raise RuntimeError("DB is closed") - return 0 - - cpdef void close(self): - """Close the DB. Live iterators and snapshots are invalidated first. - - Close only after every thread is done with the DB and its iterators: - rdbpy does no locking of its own. - """ - cdef ColumnFamilyOptions copts - cdef db.DB* tmp_db - if self.db != NULL: - # Iterators and snapshots point into the DB: free them first. - _invalidate_iterators(self._iterators) - _release_snapshots(self) - - # We have to make sure we delete the handles so rocksdb doesn't - # assert when we delete the db - self.cf_handles.clear() - - tmp_db = self.db - self.db = NULL - with nogil: - del tmp_db - - # Column family options hold the comparators and merge operators - # the DB calls into, so release them only after the DB is gone. - for copts in self.cf_options: - if copts: - copts.in_use = False - self.cf_options.clear() - - if self.opts is not None: - self.opts.in_use = False - - @property - def column_families(self): - return [handle.weakref for handle in self.cf_handles] - - cpdef get_column_family(self, bytes name): - for handle in self.cf_handles: - if handle.name == name: - return handle.weakref - - cpdef void put(self, bytes key, bytes value, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - self._check_open() - cdef Status st - cdef options.WriteOptions opts - opts.sync = sync - opts.disableWAL = disable_wal - - cdef Slice c_key = bytes_to_slice(key) - cdef Slice c_value = bytes_to_slice(value) - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - st = self.db.Put(opts, cf_handle, c_key, c_value) - check_status(st) - - def delete(self, bytes key, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - self.delete_single(key, sync=sync, disable_wal=disable_wal, column_family=column_family) - - cpdef void delete_single(self, bytes key, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - self._check_open() - cdef Status st - cdef options.WriteOptions opts - opts.sync = sync - opts.disableWAL = disable_wal - - cdef Slice c_key = bytes_to_slice(key) - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - st = self.db.Delete(opts, cf_handle, c_key) - check_status(st) - - cpdef void delete_range(self, bytes begin_key, bytes end_key, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - self._check_open() - cdef Status st - cdef options.WriteOptions opts - opts.sync = sync - opts.disableWAL = disable_wal - - cdef Slice c_begin_key = bytes_to_slice(begin_key) - cdef Slice c_end_key = bytes_to_slice(end_key) - - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - st = self.db.DeleteRange(opts, cf_handle, c_begin_key, c_end_key) - check_status(st) - - cpdef void flush(self): - self._check_open() - cdef Status st - cdef FlushOptions options - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - - with nogil: - st = self.db.Flush(options, cf_handle) - check_status(st) - - cpdef void flush_wal(self, cpp_bool sync = False): - self._check_open() - cdef Status st - cdef cpp_bool c_sync = sync - with nogil: - st = self.db.FlushWAL(c_sync) - check_status(st) - - cpdef void merge(self, bytes key, bytes value, cpp_bool sync = False, cpp_bool disable_wal = False, ColumnFamilyHandle column_family = None): - self._check_open() - cdef Status st - cdef options.WriteOptions opts - opts.sync = sync - opts.disableWAL = disable_wal - - cdef Slice c_key = bytes_to_slice(key) - cdef Slice c_value = bytes_to_slice(value) - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - st = self.db.Merge(opts, cf_handle, c_key, c_value) - check_status(st) - - cpdef void write(self, WriteBatch batch, cpp_bool sync = False, cpp_bool disable_wal = False): - if batch is None: - raise TypeError("batch must be a WriteBatch, not None") - self._check_open() - cdef Status st - cdef options.WriteOptions opts - opts.sync = sync - opts.disableWAL = disable_wal - - with nogil: - st = self.db.Write(opts, batch.batch) - check_status(st) - - cpdef get(self, bytes key, ColumnFamilyHandle column_family = None): - self._check_open() - cdef string res - cdef Status st - cdef options.ReadOptions opts - - cdef Slice c_key = bytes_to_slice(key) - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - st = self.db.Get(opts, cf_handle, c_key, cython.address(res)) - - if st.ok(): - return string_to_bytes(res) - elif st.IsNotFound(): - return None - else: - check_status(st) - - cpdef multi_get(self, keys): - self._check_open() - cdef vector[string] values - values.resize(len(keys)) - - cdef db.ColumnFamilyHandle* cf_handle - cdef vector[db.ColumnFamilyHandle*] cf_handles - cdef vector[Slice] c_keys - # Read once: iterating keys can run Python code that closes the DB. - # The pointer is only used after the re-check below the loop. - cdef db.ColumnFamilyHandle* default_cf = self.db.DefaultColumnFamily() - for key in keys: - if isinstance(key, tuple): - py_handle, key = key - cf_handle = (py_handle).get_handle() - else: - cf_handle = default_cf - c_keys.push_back(bytes_to_slice(key)) - cf_handles.push_back(cf_handle) - - cdef options.ReadOptions opts - - cdef vector[Status] res - # Iterating keys may have run Python code. - self._check_open() - with nogil: - res = self.db.MultiGet( - opts, - cf_handles, - c_keys, - cython.address(values)) - - cdef dict ret_dict = {} - for index in range(len(keys)): - if res[index].ok(): - ret_dict[keys[index]] = string_to_bytes(values[index]) - elif res[index].IsNotFound(): - ret_dict[keys[index]] = None - else: - check_status(res[index]) - - return ret_dict - - cpdef key_may_exist(self, bytes key, cpp_bool fetch = False, ColumnFamilyHandle column_family = None): - self._check_open() - cdef string value - cdef cpp_bool value_found - cdef cpp_bool exists - cdef options.ReadOptions opts - cdef Slice c_key - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - - if column_family is not None: - cf_handle = column_family.get_handle() - - c_key = bytes_to_slice(key) - exists = False - - if fetch: - value_found = False - with nogil: - exists = self.db.KeyMayExist( - opts, - cf_handle, - c_key, - cython.address(value), - cython.address(value_found)) - - if exists: - if value_found: - return (True, string_to_bytes(value)) - else: - return (True, None) - else: - return (False, None) - else: - with nogil: - exists = self.db.KeyMayExist( - opts, - cf_handle, - c_key, - cython.address(value)) - - return (exists, None) - - cpdef Iterator iterkeys(self, ColumnFamilyHandle column_family = None): - cdef options.ReadOptions opts - cdef db.ColumnFamilyHandle* cf_handle - # Allocate first: an allocation may run gc, and a finalizer may close us. - cdef KeysIterator it = KeysIterator(self) - it.owner = self - self._check_open() - cf_handle = self.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - it.ptr = self.db.NewIterator(opts, cf_handle) - self._iterators.add(_addr(it)) - return it - - cpdef Iterator itervalues(self, ColumnFamilyHandle column_family = None): - cdef options.ReadOptions opts - cdef db.ColumnFamilyHandle* cf_handle - # Allocate first: an allocation may run gc, and a finalizer may close us. - cdef ValuesIterator it = ValuesIterator(self) - it.owner = self - self._check_open() - cf_handle = self.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - it.ptr = self.db.NewIterator(opts, cf_handle) - self._iterators.add(_addr(it)) - return it - - cpdef Iterator iteritems(self, ColumnFamilyHandle column_family = None): - cdef options.ReadOptions opts - cdef db.ColumnFamilyHandle* cf_handle - # Allocate first: an allocation may run gc, and a finalizer may close us. - cdef ItemsIterator it = ItemsIterator.__new__(ItemsIterator) - it.db = self - it.owner = self - self._check_open() - cf_handle = self.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - - with nogil: - it.ptr = self.db.NewIterator(opts, cf_handle) - self._iterators.add(_addr(it)) - return it - - cpdef iterskeys(self, column_families): - cdef vector[db.Iterator*] iters - cdef Status st - cdef options.ReadOptions opts - cdef KeysIterator it - cdef db.ColumnFamilyHandle* cf_handle - cdef vector[db.ColumnFamilyHandle*] cf_handles - cdef Py_ssize_t i - - # Build every wrapper first: allocations may run gc, and a finalizer - # may close us. Nothing below allocates until the pointers are owned. - cdef list ret = [KeysIterator(self, column_family) for column_family in column_families] - self._check_open() - for column_family in column_families: - cf_handle = (column_family).get_handle() - cf_handles.push_back(cf_handle) - # Iterating column_families may have run Python code. - self._check_open() - if cf_handles.size() != len(ret): - raise ValueError("column_families must be a sequence") - iters.resize(cf_handles.size()) - - with nogil: - st = self.db.NewIterators(opts, cf_handles, &iters) - check_status(st) - if iters.size() != len(ret): - raise RuntimeError("NewIterators returned an unexpected number of iterators") - - for i in range(len(ret)): - it = ret[i] - it.ptr = iters[i] - it.owner = self - self._iterators.add(_addr(it)) - return ret - - cpdef itersvalues(self, column_families): - cdef vector[db.Iterator*] iters - cdef Status st - cdef options.ReadOptions opts - cdef ValuesIterator it - cdef db.ColumnFamilyHandle* cf_handle - cdef vector[db.ColumnFamilyHandle*] cf_handles - cdef Py_ssize_t i - - # Build every wrapper first: allocations may run gc, and a finalizer - # may close us. Nothing below allocates until the pointers are owned. - cdef list ret = [ValuesIterator(self) for column_family in column_families] - self._check_open() - for column_family in column_families: - cf_handle = (column_family).get_handle() - cf_handles.push_back(cf_handle) - # Iterating column_families may have run Python code. - self._check_open() - if cf_handles.size() != len(ret): - raise ValueError("column_families must be a sequence") - iters.resize(cf_handles.size()) - - with nogil: - st = self.db.NewIterators(opts, cf_handles, &iters) - check_status(st) - if iters.size() != len(ret): - raise RuntimeError("NewIterators returned an unexpected number of iterators") - - for i in range(len(ret)): - it = ret[i] - it.ptr = iters[i] - it.owner = self - self._iterators.add(_addr(it)) - return ret - - cpdef itersitems(self, column_families): - cdef vector[db.Iterator*] iters - cdef Status st - cdef options.ReadOptions opts - cdef ItemsIterator it - cdef db.ColumnFamilyHandle* cf_handle - cdef vector[db.ColumnFamilyHandle*] cf_handles - cdef Py_ssize_t i - - # Build every wrapper first: allocations may run gc, and a finalizer - # may close us. Nothing below allocates until the pointers are owned. - cdef list ret = [ItemsIterator(self, column_family) for column_family in column_families] - self._check_open() - for column_family in column_families: - cf_handle = (column_family).get_handle() - cf_handles.push_back(cf_handle) - # Iterating column_families may have run Python code. - self._check_open() - if cf_handles.size() != len(ret): - raise ValueError("column_families must be a sequence") - iters.resize(cf_handles.size()) - - with nogil: - st = self.db.NewIterators(opts, cf_handles, &iters) - check_status(st) - if iters.size() != len(ret): - raise RuntimeError("NewIterators returned an unexpected number of iterators") - - for i in range(len(ret)): - it = ret[i] - it.ptr = iters[i] - it.owner = self - self._iterators.add(_addr(it)) - return ret - - cpdef snapshot(self): - return Snapshot(self) - - cpdef get_property(self, prop, ColumnFamilyHandle column_family = None): - self._check_open() - cdef string value - cdef Slice c_prop = bytes_to_slice(prop) - cdef cpp_bool ret = False - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - if column_family: - cf_handle = column_family.get_handle() - - with nogil: - ret = self.db.GetProperty(cf_handle, c_prop, cython.address(value)) - - if ret: - return string_to_bytes(value) - else: - return None - - cpdef try_catch_up_with_primary(self): - self._check_open() - self.db.TryCatchUpWithPrimary() - - cpdef get_live_files_metadata(self): - self._check_open() - cdef vector[db.LiveFileMetaData] metadata - - with nogil: - self.db.GetLiveFilesMetaData(cython.address(metadata)) - - ret = [] - for ob in metadata: - t = {} - t['name'] = string_to_path(ob.name) - t['level'] = ob.level - t['size'] = ob.size - t['smallestkey'] = string_to_bytes(ob.smallestkey) - t['largestkey'] = string_to_bytes(ob.largestkey) - t['smallest_seqno'] = ob.smallest_seqno - t['largest_seqno'] = ob.largest_seqno - - ret.append(t) - - return ret - - # TODO replace arguments with a single CompactRangeOptions cython wrapper - cpdef void compact_range(self, - bytes begin=None, - bytes end=None, - cpp_bool change_level = False, - int target_level = -1, - str bottommost_level_compaction = 'if_compaction_filter', - ColumnFamilyHandle column_family = None - ): - self._check_open() - cdef options.CompactRangeOptions c_options - - c_options.change_level = change_level - c_options.target_level = target_level - - blc = bottommost_level_compaction - if blc == 'skip': - c_options.bottommost_level_compaction = options.blc_skip - elif blc == 'if_compaction_filter': - c_options.bottommost_level_compaction = options.blc_is_filter - elif blc == 'force': - c_options.bottommost_level_compaction = options.blc_force - else: - raise ValueError("bottommost_level_compaction is not valid") - - cdef Status st - cdef Slice begin_val - cdef Slice end_val - - cdef Slice* begin_ptr - cdef Slice* end_ptr - - begin_ptr = NULL - end_ptr = NULL - - if begin is not None: - begin_val = bytes_to_slice(begin) - begin_ptr = cython.address(begin_val) - - if end is not None: - end_val = bytes_to_slice(end) - end_ptr = cython.address(end_val) - - cdef db.ColumnFamilyHandle* cf_handle = self.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - - st = self.db.CompactRange(c_options, cf_handle, begin_ptr, end_ptr) - check_status(st) - - @staticmethod - def __parse_read_opts( - verify_checksums=False, - fill_cache=True, - snapshot=None, - read_tier="all"): - - # TODO: Is this really effiencet ? - return locals() - - cdef options.ReadOptions build_read_opts(self, dict py_opts): - cdef options.ReadOptions opts - opts.verify_checksums = py_opts['verify_checksums'] - opts.fill_cache = py_opts['fill_cache'] - if py_opts['snapshot'] is not None: - opts.snapshot = ((py_opts['snapshot'])).ptr - - if py_opts['read_tier'] == "all": - opts.read_tier = options.kReadAllTier - elif py_opts['read_tier'] == 'cache': - opts.read_tier = options.kBlockCacheTier - else: - raise ValueError("Invalid read_tier") - - return opts - - property options: - def __get__(self): - return self.opts - - cpdef create_column_family(self, bytes name, ColumnFamilyOptions copts): - self._check_open() - cdef db.ColumnFamilyHandle* cf_handle - cdef Status st - cdef string c_name = name - - for handle in self.cf_handles: - if handle.name == name: - raise ValueError(f"{name} is already an existing column family") - - if copts.in_use: - raise Exception("ColumnFamilyOptions are in_use by another column family") - - copts.in_use = True - with nogil: - st = self.db.CreateColumnFamily(deref(copts.copts), c_name, &cf_handle) - check_status(st) - - handle = _ColumnFamilyHandle.from_handle_ptr(cf_handle) - - self.cf_handles.append(handle) - self.cf_options.append(copts) - return handle.weakref - - cpdef void drop_column_family(self, ColumnFamilyHandle weak_handle): - self._check_open() - cdef db.ColumnFamilyHandle* cf_handle - cdef ColumnFamilyOptions copts - cdef Status st - - cf_handle = weak_handle.get_handle() - - with nogil: - st = self.db.DropColumnFamily(cf_handle) - check_status(st) - - py_handle = weak_handle._ref() - index = self.cf_handles.index(py_handle) - copts = self.cf_options.pop(index) - del self.cf_handles[index] - del py_handle - if copts: - copts.in_use = False - - -@cython.no_gc_clear -cdef class TransactionDB(DB): - def __cinit__( - self, - db_name, - Options opts, - TransactionDBOptions txn_db_opts = None, - dict column_families = None): - cdef Status st - cdef string db_path - cdef vector[db.ColumnFamilyDescriptor] column_family_descriptors - cdef vector[db.ColumnFamilyHandle*] column_family_handles - cdef bytes default_cf_name = db.kDefaultColumnFamilyName - - self.txn_db = NULL - self.txn_opts = None - self.db = NULL - self.opts = None - self.cf_handles = [] - self.cf_options = [] - - if opts.in_use: - raise Exception("Options object is already used by another DB") - - if txn_db_opts is None: - txn_db_opts = TransactionDBOptions() - - if txn_db_opts.in_use: - raise Exception("TransactionDBOptions object is already used by another DB") - - db_path = path_to_string(db_name) - - if not column_families or default_cf_name not in column_families: - column_family_descriptors.push_back( - db.ColumnFamilyDescriptor( - db.kDefaultColumnFamilyName, - options.ColumnFamilyOptions(deref(opts.opts)) - ) - ) - self.cf_options.append(None) - - if column_families: - for cf_name, cf_options in column_families.items(): - if not isinstance(cf_name, bytes): - raise TypeError( - f"column family name {cf_name!r} is not of type {bytes}!" - ) - if not isinstance(cf_options, ColumnFamilyOptions): - raise TypeError( - f"column family options {cf_options!r} is not of type " - f"{ColumnFamilyOptions}!" - ) - if (cf_options).in_use: - raise Exception( - f"ColumnFamilyOptions object for {cf_name} is already " - "used by another Column Family" - ) - (cf_options).in_use = True - column_family_descriptors.push_back( - db.ColumnFamilyDescriptor( - cf_name, - deref((cf_options).copts) - ) - ) - self.cf_options.append(cf_options) - - with nogil: - st = transaction.TransactionDB_Open_CF( - deref(opts.opts), - deref(txn_db_opts.opts), - db_path, - column_family_descriptors, - &column_family_handles, - &self.txn_db) - - check_status(st) - - for handle in column_family_handles: - wrapper = _ColumnFamilyHandle.from_handle_ptr(handle) - self.cf_handles.append(wrapper) - - self.db = self.txn_db - - cdef shared_ptr[logger.Logger] info_log = self.db.GetOptions( - self.db.DefaultColumnFamily()).info_log - if opts.py_comparator is not None: - opts.py_comparator.set_info_log(info_log) - - if opts.py_table_factory is not None: - opts.py_table_factory.set_info_log(info_log) - - if opts.prefix_extractor is not None: - opts.py_prefix_extractor.set_info_log(info_log) - - cdef ColumnFamilyOptions copts - for idx, copts in enumerate(self.cf_options): - if not copts: - continue - - info_log = self.db.GetOptions(column_family_handles[idx]).info_log - - if copts.py_comparator is not None: - copts.py_comparator.set_info_log(info_log) - - if copts.py_table_factory is not None: - copts.py_table_factory.set_info_log(info_log) - - if copts.py_prefix_extractor is not None: - copts.py_prefix_extractor.set_info_log(info_log) - - self.opts = opts - self.opts.in_use = True - self.txn_opts = txn_db_opts - self.txn_opts.in_use = True - - cpdef begin_transaction( - self, - TransactionOptions txn_options = None, - dict write_options = None, - Transaction reuse = None): - - if self.txn_db == NULL: - raise RuntimeError("TransactionDB is closed") - - cdef options.WriteOptions wopts - wopts.sync = False - wopts.disableWAL = False - - if write_options is not None: - if 'sync' in write_options: - wopts.sync = write_options['sync'] - if 'disable_wal' in write_options: - wopts.disableWAL = write_options['disable_wal'] - if 'disableWAL' in write_options: - wopts.disableWAL = write_options['disableWAL'] - - cdef transaction.TransactionOptions stack_opts = transaction.TransactionOptions() - cdef transaction.TransactionOptions* txn_opts_ptr - - if txn_options is not None: - if txn_options.opts == NULL: - raise ValueError("TransactionOptions is invalid") - txn_opts_ptr = txn_options.opts - else: - txn_opts_ptr = cython.address(stack_opts) - - cdef transaction.Transaction* raw_txn = NULL - - if reuse is not None: - if reuse.txn == NULL: - raise ValueError("Reuse transaction handle is closed") - if reuse.db is not self: - raise ValueError("Reuse transaction belongs to a different TransactionDB") - # Reinitializing clears the write batch the iterators point into. - _invalidate_iterators(reuse._iterators) - if reuse.txn == NULL: - raise ValueError("Reuse transaction handle is closed") - if self.txn_db == NULL: - raise RuntimeError("TransactionDB is closed") - raw_txn = self.txn_db.BeginTransaction( - wopts, - deref(txn_opts_ptr), - reuse.txn) - if raw_txn == NULL: - raise RuntimeError("BeginTransaction returned NULL") - reuse.txn = raw_txn - reuse.db = self - reuse.closed = False - return reuse - - # Allocate the wrapper first: an allocation may run gc, and a - # finalizer may close this DB. Nothing allocates after the check. - cdef Transaction txn = Transaction.__new__(Transaction) - if self.txn_db == NULL: - raise RuntimeError("TransactionDB is closed") - raw_txn = self.txn_db.BeginTransaction( - wopts, - deref(txn_opts_ptr)) - - if raw_txn == NULL: - raise RuntimeError("BeginTransaction returned NULL") - - txn.txn = raw_txn - txn.db = self - txn.closed = False - self._transactions.add(_addr(txn)) - return txn - - def __dealloc__(self): - # CRITICAL: NO RETURN STATEMENT - self.close() - - cpdef void close(self): - """Close the DB. Open transactions are rolled back and live - iterators and snapshots are invalidated first. - - Close only after every thread is done with the DB, its transactions - and iterators: rdbpy does no locking of its own. - """ - cdef Transaction txn - cdef ColumnFamilyOptions copts - cdef transaction.CppTransactionDB* tmp_txn_db - - # Transactions (and their iterators), DB iterators and snapshots - # point into the DB: free them first. - if self._transactions is not None: - while self._transactions: - txn = self._transactions.pop() - txn._release() - if self.txn_db != NULL: - _invalidate_iterators(self._iterators) - _release_snapshots(self) - - # Clear handles first - self.cf_handles.clear() - - # Delete the C++ object ONCE. Both pointers are NULL before the - # delete so nothing can reach the DB while it is being freed; - # the aliased self.db must not be deleted again by DB.close(). - tmp_txn_db = self.txn_db - self.txn_db = NULL - self.db = NULL - with nogil: - del tmp_txn_db - - for copts in self.cf_options: - if copts: - copts.in_use = False - self.cf_options.clear() - - # Release options - if self.opts is not None: - self.opts.in_use = False - -@cython.no_gc_clear -cdef class Transaction(object): - """A RocksDB transaction. - - A transaction and its iterators belong to one thread: do not share them - between threads. commit(), rollback(), close() and - rollback_to_save_point() invalidate its iterators. - """ - # pxd should define: - # cdef transaction.Transaction* txn - # cdef object db # Reference to TransactionDB - # cdef cpp_bool closed - - def __cinit__(self): - self.txn = NULL - self.db = None - self.closed = True - self._iterators = set() - - def __dealloc__(self): - # RocksDB's BeginTransaction returns a heap-allocated Transaction* - # that the caller owns. Commit() and Rollback() do NOT delete the - # object - we must `del` it explicitly. Without this, every - # committed/rolled-back transaction leaks its WriteBatch and - # tracking state. - # Unregister first, so a concurrent TransactionDB.close() never - # reaches a transaction that is being freed. - if self.db is not None and self.db._transactions is not None: - self.db._transactions.discard(_addr(self)) - self._release() - - cdef void _release(self): - # Iterators point into the transaction: free them first. The GIL is - # held throughout, so the parent DB cannot be closed underneath. - cdef transaction.Transaction* tmp - _invalidate_iterators(self._iterators) - tmp = self.txn - if tmp != NULL: - self.txn = NULL - if not self.closed: - tmp.Rollback() - del tmp - self.closed = True - - cpdef void close(self): - """Close the transaction by rolling it back.""" - if not self.closed: - self.rollback() - self.closed = True - - cdef void _ensure_open(self): - if self.txn == NULL or self.closed: - raise RuntimeError("Transaction is closed") - if self.db is None or (self.db).txn_db == NULL: - raise RuntimeError("Parent TransactionDB is closed") - - cpdef void commit(self): - """Commit and free the transaction. Its iterators are invalidated.""" - self._ensure_open() - _invalidate_iterators(self._iterators) - cdef Status st - cdef transaction.Transaction* tmp = self.txn - if tmp == NULL or self.closed: - raise RuntimeError("Transaction is closed") - self.txn = NULL - self.closed = True - with nogil: - st = tmp.Commit() - del tmp - check_status(st) - - cpdef void rollback(self): - """Roll back and free the transaction. Its iterators are invalidated.""" - if self.closed: - return # Idempotent - if self.txn == NULL: - return - _invalidate_iterators(self._iterators) - cdef Status st - cdef transaction.Transaction* tmp = self.txn - if tmp == NULL or self.closed: - return - self.txn = NULL - self.closed = True - with nogil: - st = tmp.Rollback() - del tmp - check_status(st) - - cpdef void prepare(self): - self._ensure_open() - cdef Status st - st = self.txn.Prepare() - check_status(st) - - cpdef void set_snapshot(self): - self._ensure_open() - self.txn.SetSnapshot() - - cpdef void clear_snapshot(self): - self._ensure_open() - self.txn.ClearSnapshot() - - cpdef snapshot(self): - self._ensure_open() - cdef const snapshot.Snapshot* ptr = self.txn.GetSnapshot() - if ptr == NULL: - return None - return TransactionSnapshot(self, ptr) - - cpdef void save_point(self): - self._ensure_open() - self.txn.SetSavePoint() - - cpdef void rollback_to_save_point(self): - self._ensure_open() - cdef Status st - st = self.txn.RollbackToSavePoint() - # With no save point RocksDB changes nothing and returns NotFound; - # otherwise the rebuilt write batch index invalidates the iterators. - # Nothing allocates between the call and the invalidation. - if st.ok(): - _invalidate_iterators(self._iterators) - check_status(st) - - cpdef void pop_save_point(self): - self._ensure_open() - cdef Status st - st = self.txn.PopSavePoint() - check_status(st) - - cpdef set_name(self, name): - self._ensure_open() - cdef string c_name - if isinstance(name, bytes): - c_name = bytes_to_string(name) - elif isinstance(name, str): - c_name = bytes_to_string(name.encode('utf-8')) - else: - raise TypeError("Transaction name must be bytes or str") - - cdef Status st - st = self.txn.SetName(c_name) - check_status(st) - - cpdef get_name(self): - self._ensure_open() - cdef string name = self.txn.GetName() - return string_to_bytes(name).decode('utf-8', 'ignore') - - cpdef get_id(self): - self._ensure_open() - return self.txn.GetID() - - cpdef void put(self, bytes key, bytes value, ColumnFamilyHandle column_family = None, cpp_bool assume_tracked = False): - self._ensure_open() - cdef Status st - cdef Slice c_key = bytes_to_slice(key) - cdef Slice c_value = bytes_to_slice(value) - cdef db.ColumnFamilyHandle* cf_handle - if column_family is not None: - cf_handle = column_family.get_handle() - with nogil: - st = self.txn.Put(cf_handle, c_key, c_value, assume_tracked) - else: - with nogil: - st = self.txn.Put(c_key, c_value) - check_status(st) - - cpdef void merge(self, bytes key, bytes value, ColumnFamilyHandle column_family = None, cpp_bool assume_tracked = False): - self._ensure_open() - cdef Status st - cdef Slice c_key = bytes_to_slice(key) - cdef Slice c_value = bytes_to_slice(value) - cdef db.ColumnFamilyHandle* cf_handle - if column_family is not None: - cf_handle = column_family.get_handle() - with nogil: - st = self.txn.Merge(cf_handle, c_key, c_value, assume_tracked) - else: - with nogil: - st = self.txn.Merge(c_key, c_value) - check_status(st) - - cpdef void delete_single(self, bytes key, ColumnFamilyHandle column_family = None, cpp_bool assume_tracked = False): - self._ensure_open() - cdef Status st - cdef Slice c_key = bytes_to_slice(key) - cdef db.ColumnFamilyHandle* cf_handle - if column_family is not None: - cf_handle = column_family.get_handle() - with nogil: - st = self.txn.Delete(cf_handle, c_key, assume_tracked) - else: - with nogil: - st = self.txn.Delete(c_key) - check_status(st) - - cpdef get(self, bytes key, ColumnFamilyHandle column_family = None): - self._ensure_open() - cdef Status st - cdef string res - cdef options.ReadOptions opts - cdef Slice c_key = bytes_to_slice(key) - cdef db.ColumnFamilyHandle* cf_handle = self.db.db.DefaultColumnFamily() - if column_family is not None: - cf_handle = column_family.get_handle() - with nogil: - st = self.txn.Get(opts, cf_handle, c_key, cython.address(res)) - - if st.ok(): - return string_to_bytes(res) - elif st.IsNotFound(): - return None - else: - check_status(st) - - cpdef multi_get(self, keys): - self._ensure_open() - cdef vector[string] values - values.resize(len(keys)) - - cdef db.ColumnFamilyHandle* cf_handle - cdef vector[db.ColumnFamilyHandle*] cf_handles - cdef vector[Slice] c_keys - # Read once: iterating keys can run Python code that closes the DB. - # The pointer is only used after the re-check below the loop. - cdef db.ColumnFamilyHandle* default_cf = self.db.db.DefaultColumnFamily() - for key in keys: - if isinstance(key, tuple): - py_handle, key = key - cf_handle = (py_handle).get_handle() - else: - cf_handle = default_cf - c_keys.push_back(bytes_to_slice(key)) - cf_handles.push_back(cf_handle) - - cdef options.ReadOptions opts - cdef vector[Status] res - - # Iterating keys may have run Python code. - self._ensure_open() - res = self.txn.MultiGet( - opts, - cf_handles, - c_keys, - cython.address(values)) - - cdef dict ret_dict = {} - for index in range(len(keys)): - if res[index].ok(): - ret_dict[keys[index]] = string_to_bytes(values[index]) - elif res[index].IsNotFound(): - ret_dict[keys[index]] = None - else: - check_status(res[index]) - return ret_dict - - cpdef Iterator iterkeys(self, ColumnFamilyHandle column_family = None): - self._ensure_open() - cdef options.ReadOptions opts - cdef db.ColumnFamilyHandle* cf_handle = NULL - # Allocate first: an allocation may run gc, and a finalizer may end - # this transaction. Nothing allocates between the check and register. - cdef KeysIterator it = KeysIterator(self.db, column_family) - it.owner = self - if column_family is not None: - cf_handle = column_family.get_handle() - self._ensure_open() - if cf_handle != NULL: - it.ptr = transaction.Transaction_GetIterator_CF(self.txn, opts, cf_handle) - else: - it.ptr = transaction.Transaction_GetIterator(self.txn, opts) - self._iterators.add(_addr(it)) - return it - - cpdef Iterator itervalues(self, ColumnFamilyHandle column_family = None): - self._ensure_open() - cdef options.ReadOptions opts - cdef db.ColumnFamilyHandle* cf_handle = NULL - # Allocate first: an allocation may run gc, and a finalizer may end - # this transaction. Nothing allocates between the check and register. - cdef ValuesIterator it = ValuesIterator(self.db, column_family) - it.owner = self - if column_family is not None: - cf_handle = column_family.get_handle() - self._ensure_open() - if cf_handle != NULL: - it.ptr = transaction.Transaction_GetIterator_CF(self.txn, opts, cf_handle) - else: - it.ptr = transaction.Transaction_GetIterator(self.txn, opts) - self._iterators.add(_addr(it)) - return it - - cpdef Iterator iteritems(self, ColumnFamilyHandle column_family = None): - self._ensure_open() - cdef options.ReadOptions opts - cdef db.ColumnFamilyHandle* cf_handle = NULL - # Allocate first: an allocation may run gc, and a finalizer may end - # this transaction. Nothing allocates between the check and register. - cdef ItemsIterator it = ItemsIterator.__new__(ItemsIterator) - it.db = self.db - it.handle = column_family - it.owner = self - if column_family is not None: - cf_handle = column_family.get_handle() - self._ensure_open() - if cf_handle != NULL: - it.ptr = transaction.Transaction_GetIterator_CF(self.txn, opts, cf_handle) - else: - it.ptr = transaction.Transaction_GetIterator(self.txn, opts) - self._iterators.add(_addr(it)) - return it - - cpdef void disable_indexing(self): - self._ensure_open() - self.txn.DisableIndexing() - - cpdef void enable_indexing(self): - self._ensure_open() - self.txn.EnableIndexing() - - -class TransactionSnapshot: - __slots__ = ("transaction", "pointer") - - def __init__(self, transaction, pointer): - self.transaction = transaction - self.pointer = pointer - - def __bool__(self): - return bool(self.pointer) - - def __repr__(self): - state = "set" if self.pointer else "unset" - return f"" - - -cpdef repair_db(db_name, Options opts): - cdef Status st - cdef string db_path - - db_path = path_to_string(db_name) - st = db.RepairDB(db_path, deref(opts.opts)) - check_status(st) - - -cpdef list_column_families(db_name, Options opts): - cdef Status st - cdef string db_path - cdef vector[string] column_families - - db_path = path_to_string(db_name) - with nogil: - st = db.ListColumnFamilies(deref(opts.opts), db_path, &column_families) - check_status(st) - - return column_families - - -@cython.no_gc_clear -cdef class Snapshot(object): - # pxd defines: - # cdef const snapshot.Snapshot* ptr - # cdef DB db - - def __cinit__(self, DB db not None): - db._check_open() - self.db = db - self.ptr = NULL - with nogil: - self.ptr = db.db.GetSnapshot() - db._snapshots.add(_addr(self)) - - def __dealloc__(self): - # Release with the GIL held, so the DB cannot be closed underneath, - # then unregister (the release itself cannot fail). - if self.ptr != NULL: - self.db.db.ReleaseSnapshot(self.ptr) - self.ptr = NULL - if self.db is not None and self.db._snapshots is not None: - self.db._snapshots.discard(_addr(self)) - - -cdef class Iterator: - def __cinit__(self): - self._current_value = None - - def __iter__(self): - return self - - def __next__(self): - item = self.next() - if item is None: - raise StopIteration - return item - - # NOTE Iterator interface defines sentinel value of `None` so it can't - # yield None values. However, one can still overwrite cpython's __next__ instead. - cpdef object next(self): - return None - - cpdef object get(self): - if self._current_value is None: - self._current_value = self.next() - return self._current_value - - cpdef void skip(self): - self._current_value = None - - cpdef void skip_back(self): - self._current_value = None - - -@cython.no_gc_clear -cdef class BaseIterator(Iterator): - # pxd defines: - # cdef iterator.Iterator* ptr - # cdef DB db - # cdef ColumnFamilyHandle handle - - def __cinit__(self, DB db = None, ColumnFamilyHandle handle = None): - self.db = db - self.ptr = NULL - self.handle = handle - self.owner = db - - def __dealloc__(self): - # Free the native iterator first (the parent is alive: we hold it), - # then unregister; nothing in between can run Python code. - if self.ptr != NULL: - del self.ptr - self.ptr = NULL - if isinstance(self.owner, Transaction): - if (self.owner)._iterators is not None: - (self.owner)._iterators.discard(_addr(self)) - elif isinstance(self.owner, DB): - if (self.owner)._iterators is not None: - (self.owner)._iterators.discard(_addr(self)) - - cdef int _check_valid(self) except -1: - if self.ptr == NULL: - raise RuntimeError("Iterator is invalid: its transaction ended or its DB was closed") - return 0 - - cdef void _invalidate(self): - if self.ptr != NULL: - del self.ptr - self.ptr = NULL - - cpdef object next(self): - self._check_valid() - if not self.ptr.Valid(): - return None - - cdef object ret = self.get_ob() - # Building ret may have run gc, and a finalizer may have ended our - # transaction. - self._check_valid() - with nogil: - self.ptr.Next() - check_status(self.ptr.status()) - return ret - - cpdef object get(self): - self._check_valid() - if not self.ptr.Valid(): - raise ValueError() - - cdef object ret = self.get_ob() - return ret - - cpdef void skip(self): - self._check_valid() - if not self.ptr.Valid(): - raise ValueError() - with nogil: - self.ptr.Next() - check_status(self.ptr.status()) - - cpdef void skip_back(self): - self._check_valid() - if not self.ptr.Valid(): - raise ValueError() - with nogil: - self.ptr.Prev() - check_status(self.ptr.status()) - - def __reversed__(self): - return ReversedIterator(self) - - cpdef void seek_to_first(self): - self._check_valid() - with nogil: - self.ptr.SeekToFirst() - check_status(self.ptr.status()) - - cpdef void seek_to_last(self): - self._check_valid() - with nogil: - self.ptr.SeekToLast() - check_status(self.ptr.status()) - - cpdef void seek(self, bytes key): - self._check_valid() - cdef Slice c_key = bytes_to_slice(key) - with nogil: - self.ptr.Seek(c_key) - check_status(self.ptr.status()) - - cpdef void seek_for_prev(self, bytes key): - self._check_valid() - cdef Slice c_key = bytes_to_slice(key) - with nogil: - self.ptr.SeekForPrev(c_key) - check_status(self.ptr.status()) - - cdef object get_ob(self): - return None - - -cdef class KeysIterator(BaseIterator): - cdef object get_ob(self): - cdef Slice c_key - with nogil: - c_key = self.ptr.key() - check_status(self.ptr.status()) - return slice_to_bytes(c_key) - - -cdef class ValuesIterator(BaseIterator): - cdef object get_ob(self): - cdef Slice c_value - with nogil: - c_value = self.ptr.value() - check_status(self.ptr.status()) - return slice_to_bytes(c_value) - - -cdef class ItemsIterator(BaseIterator): - cdef object get_ob(self): - cdef Slice c_key - cdef Slice c_value - with nogil: - c_key = self.ptr.key() - c_value = self.ptr.value() - check_status(self.ptr.status()) - return (slice_to_bytes(c_key), slice_to_bytes(c_value)) - - -cdef class ReversedIterator(object): - # pxd defines: - # cdef BaseIterator it - - def __cinit__(self, BaseIterator it not None): - self.it = it - - cpdef void seek_to_first(self): - self.it.seek_to_first() - - cpdef void seek_to_last(self): - self.it.seek_to_last() - - cpdef void seek(self, bytes key): - self.it.seek(key) - - cpdef void seek_for_prev(self, bytes key): - self.it.seek_for_prev(key) - - cpdef object get(self): - return self.it.get() - - def __iter__(self): - return self - - def __reversed__(self): - return self.it - - def __next__(self): - self.it._check_valid() - if not self.it.ptr.Valid(): - raise StopIteration() - - cdef object ret = self.it.get_ob() - # Building ret may have run gc, and a finalizer may have ended our - # transaction. - self.it._check_valid() - with nogil: - self.it.ptr.Prev() - check_status(self.it.ptr.status()) - return ret - - -cdef class BackupEngine(object): - # pxd defines: - # cdef backup.BackupEngine* engine - - def __cinit__(self, backup_dir): - cdef Status st - cdef string c_backup_dir - self.engine = NULL - - c_backup_dir = path_to_string(backup_dir) - st = backup.BackupEngine_Open( - env.Env_Default(), - backup.BackupEngineOptions(c_backup_dir), - cython.address(self.engine)) - - check_status(st) - - def __dealloc__(self): - if not self.engine == NULL: - with nogil: - del self.engine - - cpdef create_backup(self, DB db, flush_before_backup=False): - if db is None: - raise TypeError("db must be a DB, not None") - cdef Status st - cdef cpp_bool c_flush_before_backup - - c_flush_before_backup = flush_before_backup - db._check_open() - - with nogil: - st = self.engine.CreateNewBackup(db.db, c_flush_before_backup) - check_status(st) - - cpdef restore_backup(self, backup_id, db_dir, wal_dir): - cdef Status st - cdef backup.BackupID c_backup_id - cdef string c_db_dir - cdef string c_wal_dir - - c_backup_id = backup_id - c_db_dir = path_to_string(db_dir) - c_wal_dir = path_to_string(wal_dir) - - with nogil: - st = self.engine.RestoreDBFromBackup( - c_backup_id, - c_db_dir, - c_wal_dir) - - check_status(st) - - cpdef restore_latest_backup(self, db_dir, wal_dir): - cdef Status st - cdef string c_db_dir - cdef string c_wal_dir - - c_db_dir = path_to_string(db_dir) - c_wal_dir = path_to_string(wal_dir) - - with nogil: - st = self.engine.RestoreDBFromLatestBackup(c_db_dir, c_wal_dir) - - check_status(st) - - cpdef stop_backup(self): - with nogil: - self.engine.StopBackup() - - cpdef purge_old_backups(self, num_backups_to_keep): - cdef Status st - cdef uint32_t c_num_backups_to_keep - - c_num_backups_to_keep = num_backups_to_keep - - with nogil: - st = self.engine.PurgeOldBackups(c_num_backups_to_keep) - check_status(st) - - cpdef delete_backup(self, backup_id): - cdef Status st - cdef backup.BackupID c_backup_id - - c_backup_id = backup_id - - with nogil: - st = self.engine.DeleteBackup(c_backup_id) - - check_status(st) - - cpdef get_backup_info(self): - cdef vector[backup.BackupInfo] backup_info - - with nogil: - self.engine.GetBackupInfo(cython.address(backup_info)) - - ret = [] - for ob in backup_info: - t = {} - t['backup_id'] = ob.backup_id - t['timestamp'] = ob.timestamp - t['size'] = ob.size - ret.append(t) - - return ret diff --git a/src/rdbpy/lib_utils.py b/src/rdbpy/lib_utils.py deleted file mode 100644 index ce7599d..0000000 --- a/src/rdbpy/lib_utils.py +++ /dev/null @@ -1,52 +0,0 @@ -import ctypes -import os -import platform -from glob import glob - - -def get_include_dir(): - dirname = os.path.dirname(__file__) - abs_dirname = os.path.abspath(dirname) - path = os.path.join(abs_dirname, "include") - return path - - -def get_lib_dir(): - dirname = os.path.dirname(__file__) - abs_dirname = os.path.abspath(dirname) - path = abs_dirname - return path - - -def get_libs(): - return [ - "rocksdb", - ] - - -def get_lib_filename(name, lib_dir): - if platform.system() == "Darwin": - pattern = f"lib{name}*.dylib" - else: - pattern = f"lib{name}*.so*" - - files = glob(os.path.join(lib_dir, pattern)) - assert len(files) == 1 - return os.path.basename(files[0]) - - -def get_lib_filenames(): - local_lib_dir = get_lib_dir() - return [get_lib_filename(name, local_lib_dir) for name in get_libs()] - - -def load_lib(filename) -> None: - local_lib_dir = get_lib_dir() - path = os.path.join(local_lib_dir, filename) - print(f"Loading runtime library from {path}") - ctypes.CDLL(path) - - -def load_libs() -> None: - for filename in get_lib_filenames(): - load_lib(filename) diff --git a/src/rdbpy/logger.pxd b/src/rdbpy/logger.pxd deleted file mode 100644 index d0b7b72..0000000 --- a/src/rdbpy/logger.pxd +++ /dev/null @@ -1,5 +0,0 @@ -cdef extern from "rocksdb/env.h" namespace "rocksdb": - cdef cppclass Logger: - pass - - void Log(Logger*, const char*, ...) nogil except+ diff --git a/src/rdbpy/memtablerep.pxd b/src/rdbpy/memtablerep.pxd deleted file mode 100644 index 9349bf8..0000000 --- a/src/rdbpy/memtablerep.pxd +++ /dev/null @@ -1,12 +0,0 @@ -from libc.stdint cimport int32_t - -cdef extern from "rocksdb/memtablerep.h" namespace "rocksdb": - cdef cppclass MemTableRepFactory: - MemTableRepFactory() - - cdef MemTableRepFactory* NewHashSkipListRepFactory(size_t, int32_t, int32_t) - cdef MemTableRepFactory* NewHashLinkListRepFactory(size_t) - -cdef extern from "rdb_include/memtable_factories.hpp" namespace "py_rocks": - cdef MemTableRepFactory* NewVectorRepFactory(size_t) - cdef MemTableRepFactory* NewSkipListFactory() diff --git a/src/rdbpy/merge_operator.pxd b/src/rdbpy/merge_operator.pxd deleted file mode 100644 index 1b41fb5..0000000 --- a/src/rdbpy/merge_operator.pxd +++ /dev/null @@ -1,46 +0,0 @@ -from libcpp.string cimport string -from libcpp cimport bool as cpp_bool -from libcpp.deque cimport deque -from rdbpy.slice_ cimport Slice -from rdbpy.logger cimport Logger -from rdbpy.std_memory cimport shared_ptr - -cdef extern from "rocksdb/merge_operator.h" namespace "rocksdb": - cdef cppclass MergeOperator: - pass - -ctypedef cpp_bool (*merge_func)( - void*, - const Slice&, - const Slice*, - const Slice&, - string*, - Logger*) - -ctypedef cpp_bool (*full_merge_func)( - void* ctx, - const Slice& key, - const Slice* existing_value, - const deque[string]& operand_list, - string* new_value, - Logger* logger) - -ctypedef cpp_bool (*partial_merge_func)( - void* ctx, - const Slice& key, - const Slice& left_op, - const Slice& right_op, - string* new_value, - Logger* logger) - -cdef extern from "rdb_include/merge_operator_wrapper.hpp" namespace "py_rocks": - cdef cppclass AssociativeMergeOperatorWrapper: - AssociativeMergeOperatorWrapper(string, void*, merge_func) nogil except+ - - cdef cppclass MergeOperatorWrapper: - MergeOperatorWrapper( - string, - void*, - void*, - full_merge_func, - partial_merge_func) nogil except+ diff --git a/src/rdbpy/merge_operators.py b/src/rdbpy/merge_operators.py deleted file mode 100644 index 39154df..0000000 --- a/src/rdbpy/merge_operators.py +++ /dev/null @@ -1,25 +0,0 @@ -import struct as py_struct - -from rdbpy.interfaces import AssociativeMergeOperator - - -class UintAddOperator(AssociativeMergeOperator): - def merge(self, key, existing_value, value): - if existing_value: - s = py_struct.unpack("Q", existing_value)[0] + py_struct.unpack("Q", value)[0] - return (True, py_struct.pack("Q", s)) - return (True, value) - - def name(self) -> bytes: - return b"uint64add" - - -class StringAppendOperator(AssociativeMergeOperator): - def merge(self, key, existing_value, value): - if existing_value: - s = existing_value + b"," + value - return (True, s) - return (True, value) - - def name(self) -> bytes: - return b"StringAppendOperator" diff --git a/src/rdbpy/options.pxd b/src/rdbpy/options.pxd deleted file mode 100644 index d325ba3..0000000 --- a/src/rdbpy/options.pxd +++ /dev/null @@ -1,179 +0,0 @@ -from libcpp cimport bool as cpp_bool -from libcpp.string cimport string -from libcpp.vector cimport vector -from libc.stdint cimport uint64_t -from libc.stdint cimport uint32_t -from rdbpy.std_memory cimport shared_ptr -from rdbpy.comparator cimport Comparator -from rdbpy.merge_operator cimport MergeOperator -from rdbpy.logger cimport Logger -from rdbpy.slice_ cimport Slice -from rdbpy.snapshot cimport Snapshot -from rdbpy.slice_transform cimport SliceTransform -from rdbpy.table_factory cimport TableFactory -from rdbpy.memtablerep cimport MemTableRepFactory -from rdbpy.universal_compaction cimport CompactionOptionsUniversal -from rdbpy.cache cimport Cache - -cdef extern from "rocksdb/options.h" namespace "rocksdb": - cdef cppclass CompressionOptions: - int window_bits; - int level; - int strategy; - uint32_t max_dict_bytes - CompressionOptions() except + - CompressionOptions(int, int, int, int) except + - - ctypedef enum CompactionStyle: - kCompactionStyleLevel - kCompactionStyleUniversal - kCompactionStyleFIFO - kCompactionStyleNone - - ctypedef enum CompressionType: - kNoCompression - kSnappyCompression - kZlibCompression - kBZip2Compression - kLZ4Compression - kLZ4HCCompression - kXpressCompression - kZSTD - kZSTDNotFinalCompression - kDisableCompressionOption - - ctypedef enum ReadTier: - kReadAllTier - kBlockCacheTier - - ctypedef enum CompactionPri: - kByCompensatedSize - kOldestLargestSeqFirst - kOldestSmallestSeqFirst - kMinOverlappingRatio - - # This needs to be in _rocksdb.pxd so it will export into python - #cpdef enum AccessHint "rocksdb::DBOptions::AccessHint": - # NONE, - # NORMAL, - # SEQUENTIAL, - # WILLNEED - - cdef cppclass DBOptions: - cpp_bool create_if_missing - cpp_bool create_missing_column_families - cpp_bool error_if_exists - cpp_bool paranoid_checks - # TODO: env - shared_ptr[Logger] info_log - int max_open_files - int max_file_opening_threads - # TODO: statistics - cpp_bool use_fsync - string db_log_dir - string wal_dir - uint64_t delete_obsolete_files_period_micros - int max_background_jobs - int max_background_compactions - uint32_t max_subcompactions - int max_background_flushes - size_t max_log_file_size - size_t log_file_time_to_roll - size_t keep_log_file_num - size_t recycle_log_file_num - uint64_t max_manifest_file_size - int table_cache_numshardbits - uint64_t WAL_ttl_seconds - uint64_t WAL_size_limit_MB - size_t manifest_preallocation_size - cpp_bool allow_mmap_reads - cpp_bool allow_mmap_writes - cpp_bool use_direct_reads - cpp_bool use_direct_io_for_flush_and_compaction - cpp_bool allow_fallocate - cpp_bool is_fd_close_on_exec - unsigned int stats_dump_period_sec - cpp_bool advise_random_on_open - size_t db_write_buffer_size - # AccessHint access_hint_on_compaction_start - cpp_bool use_adaptive_mutex - uint64_t bytes_per_sync - cpp_bool allow_concurrent_memtable_write - cpp_bool enable_write_thread_adaptive_yield - shared_ptr[Cache] row_cache - - cpp_bool skip_checking_sst_file_sizes_on_db_open - cpp_bool skip_stats_update_on_db_open - - cdef cppclass ColumnFamilyOptions: - ColumnFamilyOptions() - ColumnFamilyOptions(const Options& options) - const Comparator* comparator - shared_ptr[MergeOperator] merge_operator - # TODO: compaction_filter - # TODO: compaction_filter_factory - size_t write_buffer_size - int max_write_buffer_number - int min_write_buffer_number_to_merge - CompressionType compression - CompactionPri compaction_pri - # TODO: compression_per_level - shared_ptr[SliceTransform] prefix_extractor - int num_levels - int level0_file_num_compaction_trigger - int level0_slowdown_writes_trigger - int level0_stop_writes_trigger - int max_mem_compaction_level - uint64_t target_file_size_base - int target_file_size_multiplier - uint64_t max_bytes_for_level_base - double max_bytes_for_level_multiplier - vector[int] max_bytes_for_level_multiplier_additional - int expanded_compaction_factor - int source_compaction_factor - int max_grandparent_overlap_factor - cpp_bool disableDataSync - size_t arena_block_size - # TODO: PrepareForBulkLoad() - cpp_bool disable_auto_compactions - cpp_bool allow_os_buffer - cpp_bool verify_checksums_in_compaction - CompactionStyle compaction_style - CompactionOptionsUniversal compaction_options_universal - cpp_bool filter_deletes - uint64_t max_sequential_skip_in_iterations - shared_ptr[MemTableRepFactory] memtable_factory - shared_ptr[TableFactory] table_factory - # TODO: table_properties_collectors - cpp_bool inplace_update_support - size_t inplace_update_num_locks - # TODO: remove options source_compaction_factor, max_grandparent_overlap_bytes and expanded_compaction_factor from document - uint64_t max_compaction_bytes - CompressionOptions compression_opts - - cdef cppclass Options(DBOptions, ColumnFamilyOptions): - pass - - cdef cppclass WriteOptions: - cpp_bool sync - cpp_bool disableWAL - - cdef cppclass ReadOptions: - cpp_bool verify_checksums - cpp_bool fill_cache - const Snapshot* snapshot - ReadTier read_tier - - cdef cppclass FlushOptions: - cpp_bool wait - - ctypedef enum BottommostLevelCompaction: - blc_skip "rocksdb::BottommostLevelCompaction::kSkip" - blc_is_filter "rocksdb::BottommostLevelCompaction::kIfHaveCompactionFilter" - blc_force "rocksdb::BottommostLevelCompaction::kForce" - - cdef cppclass CompactRangeOptions: - cpp_bool change_level - int target_level - uint32_t target_path_id - BottommostLevelCompaction bottommost_level_compaction diff --git a/tests/functional/__init__.py b/src/rdbpy/py.typed similarity index 100% rename from tests/functional/__init__.py rename to src/rdbpy/py.typed diff --git a/src/rdbpy/slice_.pxd b/src/rdbpy/slice_.pxd deleted file mode 100644 index 6ee070c..0000000 --- a/src/rdbpy/slice_.pxd +++ /dev/null @@ -1,20 +0,0 @@ -from libcpp.string cimport string -from libcpp cimport bool as cpp_bool - -cdef extern from "rocksdb/slice.h" namespace "rocksdb": - cdef cppclass Slice: - Slice() nogil - Slice(const char*, size_t) nogil - Slice(const string&) nogil - Slice(const char*) nogil - - const char* data() nogil - size_t size() nogil - cpp_bool empty() nogil - char operator[](int) nogil - void clear() nogil - void remove_prefix(size_t) nogil - string ToString() nogil - string ToString(cpp_bool) nogil - int compare(const Slice&) nogil - cpp_bool starts_with(const Slice&) nogil diff --git a/src/rdbpy/slice_transform.pxd b/src/rdbpy/slice_transform.pxd deleted file mode 100644 index 22baec5..0000000 --- a/src/rdbpy/slice_transform.pxd +++ /dev/null @@ -1,37 +0,0 @@ -from rdbpy.slice_ cimport Slice -from libcpp.string cimport string -from libcpp cimport bool as cpp_bool -from rdbpy.logger cimport Logger -from rdbpy.std_memory cimport shared_ptr - -cdef extern from "rocksdb/slice_transform.h" namespace "rocksdb": - cdef cppclass SliceTransform: - pass - -ctypedef Slice (*transform_func)( - void*, - Logger*, - string&, - const Slice&) - -ctypedef cpp_bool (*in_domain_func)( - void*, - Logger*, - string&, - const Slice&) - -ctypedef cpp_bool (*in_range_func)( - void*, - Logger*, - string&, - const Slice&) - -cdef extern from "rdb_include/slice_transform_wrapper.hpp" namespace "py_rocks": - cdef cppclass SliceTransformWrapper: - SliceTransformWrapper( - string name, - void*, - transform_func, - in_domain_func, - in_range_func) nogil except+ - void set_info_log(shared_ptr[Logger]) nogil except+ diff --git a/src/rdbpy/snapshot.pxd b/src/rdbpy/snapshot.pxd deleted file mode 100644 index 9cea04d..0000000 --- a/src/rdbpy/snapshot.pxd +++ /dev/null @@ -1,3 +0,0 @@ -cdef extern from "rocksdb/db.h" namespace "rocksdb": - cdef cppclass Snapshot: - pass diff --git a/src/rdbpy/status.pxd b/src/rdbpy/status.pxd deleted file mode 100644 index f92bbf1..0000000 --- a/src/rdbpy/status.pxd +++ /dev/null @@ -1,15 +0,0 @@ -from libcpp cimport bool as cpp_bool -from libcpp.string cimport string - -cdef extern from "rocksdb/status.h" namespace "rocksdb": - cdef cppclass Status: - Status() - cpp_bool ok() nogil - cpp_bool IsNotFound() nogil const - cpp_bool IsCorruption() nogil const - cpp_bool IsNotSupported() nogil const - cpp_bool IsInvalidArgument() nogil const - cpp_bool IsIOError() nogil const - cpp_bool IsMergeInProgress() nogil const - cpp_bool IsIncomplete() nogil const - string ToString() nogil except+ diff --git a/src/rdbpy/std_memory.pxd b/src/rdbpy/std_memory.pxd deleted file mode 100644 index ea573ee..0000000 --- a/src/rdbpy/std_memory.pxd +++ /dev/null @@ -1,7 +0,0 @@ -cdef extern from "" namespace "std": - cdef cppclass shared_ptr[T]: - shared_ptr() nogil except+ - shared_ptr(T*) nogil except+ - void reset() nogil except+ - void reset(T*) nogil except+ - T* get() nogil except+ diff --git a/src/rdbpy/table_factory.pxd b/src/rdbpy/table_factory.pxd deleted file mode 100644 index ae1f11e..0000000 --- a/src/rdbpy/table_factory.pxd +++ /dev/null @@ -1,59 +0,0 @@ -from libc.stdint cimport uint32_t -from libcpp cimport bool as cpp_bool -from rdbpy.std_memory cimport shared_ptr - -from rdbpy.cache cimport Cache -from rdbpy.filter_policy cimport FilterPolicy - -cdef extern from "rocksdb/table.h" namespace "rocksdb": - cdef cppclass TableFactory: - TableFactory() - - ctypedef enum BlockBasedTableIndexType: - kBinarySearch "rocksdb::BlockBasedTableOptions::IndexType::kBinarySearch" - kHashSearch "rocksdb::BlockBasedTableOptions::IndexType::kHashSearch" - - ctypedef enum ChecksumType: - kCRC32c - kxxHash - - cdef cppclass BlockBasedTableOptions: - BlockBasedTableOptions() - BlockBasedTableIndexType index_type - cpp_bool hash_index_allow_collision - ChecksumType checksum - cpp_bool no_block_cache - size_t block_size - int block_size_deviation - int block_restart_interval - cpp_bool whole_key_filtering - cpp_bool cache_index_and_filter_blocks - cpp_bool cache_index_and_filter_blocks_with_high_priority - cpp_bool pin_l0_filter_and_index_blocks_in_cache - cpp_bool pin_top_level_index_and_filter - cpp_bool partition_filters - size_t metadata_block_size - uint32_t format_version - cpp_bool optimize_filters_for_memory - int read_amp_bytes_per_bit - shared_ptr[Cache] block_cache - shared_ptr[Cache] block_cache_compressed - shared_ptr[FilterPolicy] filter_policy - - cdef TableFactory* NewBlockBasedTableFactory(const BlockBasedTableOptions&) - - ctypedef enum EncodingType: - kPlain - kPrefix - - cdef cppclass PlainTableOptions: - uint32_t user_key_len - int bloom_bits_per_key - double hash_table_ratio - size_t index_sparseness - size_t huge_page_tlb_size - EncodingType encoding_type - cpp_bool full_scan_mode - cpp_bool store_index_in_file - - cdef TableFactory* NewPlainTableFactory(const PlainTableOptions&) diff --git a/src/rdbpy/transaction.pxd b/src/rdbpy/transaction.pxd deleted file mode 100644 index 7c59179..0000000 --- a/src/rdbpy/transaction.pxd +++ /dev/null @@ -1,154 +0,0 @@ -from libc.stddef cimport size_t -from libc.stdint cimport int64_t, uint32_t, uint64_t -from libcpp cimport bool as cpp_bool -from libcpp.string cimport string -from libcpp.vector cimport vector - -from rdbpy.slice_ cimport Slice -from rdbpy.snapshot cimport Snapshot -from rdbpy.status cimport Status -from rdbpy.std_memory cimport shared_ptr - -cimport rdbpy.db as db -cimport rdbpy.iterator as iterator -cimport rdbpy.options as options - - -cdef extern from "rocksdb/utilities/transaction_db_mutex.h" namespace "rocksdb": - cdef cppclass TransactionDBMutexFactory: - pass - - -cdef extern from "rocksdb/utilities/transaction_db.h" namespace "rocksdb": - ctypedef uint64_t TransactionID - ctypedef string TransactionName - - cdef enum TxnDBWritePolicy: - WRITE_COMMITTED - WRITE_PREPARED - WRITE_UNPREPARED - - cdef cppclass LockManager: - pass - - cdef cppclass LockManagerHandle: - LockManager* getLockManager() nogil except+ - - cdef cppclass TransactionDBOptions: - TransactionDBOptions() nogil except+ - int64_t max_num_locks - uint32_t max_num_deadlocks - size_t num_stripes - int64_t transaction_lock_timeout - int64_t default_lock_timeout - shared_ptr[TransactionDBMutexFactory] custom_mutex_factory - TxnDBWritePolicy write_policy - cpp_bool rollback_merge_operands - shared_ptr[LockManagerHandle] lock_mgr_handle - cpp_bool skip_concurrency_control - int64_t default_write_batch_flush_threshold - - cdef cppclass TransactionDBWriteOptimizations: - TransactionDBWriteOptimizations() nogil except+ - cpp_bool skip_concurrency_control - cpp_bool skip_duplicate_key_check - - cdef cppclass TransactionOptions: - TransactionOptions() nogil except+ - cpp_bool set_snapshot - cpp_bool deadlock_detect - cpp_bool use_only_the_last_commit_time_batch_for_recovery - int64_t lock_timeout - int64_t expiration - int64_t deadlock_detect_depth - size_t max_write_batch_size - cpp_bool skip_concurrency_control - cpp_bool skip_prepare - int64_t write_batch_flush_threshold - - cdef cppclass Transaction: - Status Commit() nogil except+ - Status Rollback() nogil except+ - Status Prepare() nogil except+ - void SetSnapshot() nogil except+ - const Snapshot* GetSnapshot() nogil except+ - void ClearSnapshot() nogil except+ - Status SetName(const TransactionName&) nogil except+ - TransactionName GetName() nogil except+ - TransactionID GetID() nogil except+ - void SetSavePoint() nogil except+ - Status PopSavePoint() nogil except+ - Status RollbackToSavePoint() nogil except+ - void DisableIndexing() nogil except+ - void EnableIndexing() nogil except+ - Status Put(db.ColumnFamilyHandle*, const Slice&, const Slice&, cpp_bool assume_tracked) nogil except+ - Status Put(const Slice&, const Slice&) nogil except+ - Status Merge(db.ColumnFamilyHandle*, const Slice&, const Slice&, cpp_bool assume_tracked) nogil except+ - Status Merge(const Slice&, const Slice&) nogil except+ - Status Delete(db.ColumnFamilyHandle*, const Slice&, cpp_bool assume_tracked) nogil except+ - Status Delete(const Slice&) nogil except+ - Status SingleDelete(db.ColumnFamilyHandle*, const Slice&, cpp_bool assume_tracked) nogil except+ - Status SingleDelete(const Slice&) nogil except+ - Status Get(const options.ReadOptions&, db.ColumnFamilyHandle*, const Slice&, string*) nogil except+ - Status Get(const options.ReadOptions&, const Slice&, string*) nogil except+ - vector[Status] MultiGet( - const options.ReadOptions&, - const vector[db.ColumnFamilyHandle*]&, - const vector[Slice]&, - vector[string]*) nogil except+ - vector[Status] MultiGet( - const options.ReadOptions&, - const vector[Slice]&, - vector[string]*) nogil except+ - iterator.Iterator* GetIterator(const options.ReadOptions&) nogil except+ - iterator.Iterator* GetIterator(const options.ReadOptions&, db.ColumnFamilyHandle*) nogil except+ - - cdef cppclass CppTransactionDB "rocksdb::TransactionDB"(db.DB): - Transaction* BeginTransaction( - const options.WriteOptions&, - const TransactionOptions&, - Transaction* old_txn) nogil except+ - Transaction* BeginTransaction( - const options.WriteOptions&, - const TransactionOptions&) nogil except+ - Transaction* GetTransactionByName(const TransactionName&) nogil except+ - void GetAllPreparedTransactions(vector[Transaction*]*) nogil except+ - - cdef Status TransactionDB_Open "rocksdb::TransactionDB::Open"( - const options.Options&, - const TransactionDBOptions&, - const string&, - CppTransactionDB**) nogil except+ - - cdef Status TransactionDB_Open_CF "rocksdb::TransactionDB::Open"( - const options.DBOptions&, - const TransactionDBOptions&, - const string&, - const vector[db.ColumnFamilyDescriptor]&, - vector[db.ColumnFamilyHandle*]*, - CppTransactionDB**) nogil except+ - - -# Helper functions to disambiguate overloaded Transaction methods -cdef extern from "rocksdb/utilities/transaction.h": - """ - static inline rocksdb::Iterator* Transaction_GetIterator( - rocksdb::Transaction* txn, - const rocksdb::ReadOptions& opts) { - return txn->GetIterator(opts); - } - - static inline rocksdb::Iterator* Transaction_GetIterator_CF( - rocksdb::Transaction* txn, - const rocksdb::ReadOptions& opts, - rocksdb::ColumnFamilyHandle* cf) { - return txn->GetIterator(opts, cf); - } - """ - iterator.Iterator* Transaction_GetIterator( - Transaction*, - const options.ReadOptions&) nogil except+ - iterator.Iterator* Transaction_GetIterator_CF( - Transaction*, - const options.ReadOptions&, - db.ColumnFamilyHandle*) nogil except+ diff --git a/src/rdbpy/universal_compaction.pxd b/src/rdbpy/universal_compaction.pxd deleted file mode 100644 index 8622dba..0000000 --- a/src/rdbpy/universal_compaction.pxd +++ /dev/null @@ -1,15 +0,0 @@ -cdef extern from "rocksdb/universal_compaction.h" namespace "rocksdb": - - ctypedef enum CompactionStopStyle: - kCompactionStopStyleSimilarSize - kCompactionStopStyleTotalSize - - cdef cppclass CompactionOptionsUniversal: - CompactionOptionsUniversal() - - unsigned int size_ratio - unsigned int min_merge_width - unsigned int max_merge_width - unsigned int max_size_amplification_percent - int compression_size_percent - CompactionStopStyle stop_style diff --git a/tests/conftest.py b/tests/conftest.py index 45dd17e..7fc4392 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,9 +1,44 @@ -"""Shared test configuration and fixtures for all test types.""" +"""Shared fixtures: fresh databases in a temporary directory.""" import pytest +import rdbpy -def pytest_configure(config: pytest.Config) -> None: - """Register custom markers.""" - # Package markers - config.addinivalue_line("markers", "rdbpy: Tests for RocksDB bindings") + +@pytest.fixture +def path(tmp_path): + n = [0] + + def make(): + n[0] += 1 + return str(tmp_path / f"db{n[0]}") + + return make + + +@pytest.fixture +def db(path): + d = rdbpy.DB(path(), rdbpy.Options(create_if_missing=True)) + yield d + d.close() + + +@pytest.fixture +def tdb(path): + d = rdbpy.TransactionDB( + path(), rdbpy.Options(create_if_missing=True), lock_timeout_ms=200, default_lock_timeout_ms=200 + ) + yield d + d.close() + + +@pytest.fixture +def odb(path): + d = rdbpy.OptimisticTransactionDB(path(), rdbpy.Options(create_if_missing=True)) + yield d + d.close() + + +def fill(db, n=100, prefix=b"k"): + for i in range(n): + db.put(prefix + b"%04d" % i, b"v%04d" % i) diff --git a/tests/functional/test_db.py b/tests/functional/test_db.py deleted file mode 100644 index 79db006..0000000 --- a/tests/functional/test_db.py +++ /dev/null @@ -1,696 +0,0 @@ -import gc -import shutil -import struct -import tempfile -import unittest -from itertools import takewhile -from pathlib import Path - -import rdbpy -from rdbpy.merge_operators import StringAppendOperator, UintAddOperator - - -def int_to_bytes(ob: object) -> bytes: - return str(ob).encode("ascii") - - -class TestHelper(unittest.TestCase): - def setUp(self) -> None: - self.db_loc = tempfile.mkdtemp() - self.addCleanup(self._close_db) - - def _close_db(self) -> None: - del self.db - gc.collect() - if Path(self.db_loc).exists(): - shutil.rmtree(self.db_loc) - - -class TestDB(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options(create_if_missing=True) - self.db = rdbpy.DB(str(Path(self.db_loc) / "test"), opts) - - def test_options_used_twice(self) -> None: - assert_raises_regex = self.assertRaisesRegex - expected = "Options object is already used by another DB" - with assert_raises_regex(Exception, expected): - rdbpy.DB(str(Path(self.db_loc) / "test2"), self.db.options) - - def test_unicode_path(self) -> None: - name = str(Path(self.db_loc) / b"M\xc3\xbcnchen".decode("utf8")) - rdbpy.DB(name, rdbpy.Options(create_if_missing=True)) - self.addCleanup(shutil.rmtree, name) - self.assertTrue(Path(name).is_dir()) - - def test_get_none(self) -> None: - self.assertIsNone(self.db.get(b"xxx")) - - def test_put_get(self) -> None: - self.db.put(b"a", b"b") - self.assertEqual(b"b", self.db.get(b"a")) - - def test_multi_get(self) -> None: - self.db.put(b"a", b"1") - self.db.put(b"b", b"2") - self.db.put(b"c", b"3") - - ret = self.db.multi_get([b"a", b"b", b"c"]) - ref = {b"a": b"1", b"c": b"3", b"b": b"2"} - self.assertEqual(ref, ret) - - def test_delete(self) -> None: - self.db.put(b"a", b"b") - self.assertEqual(b"b", self.db.get(b"a")) - self.db.delete(b"a") - self.assertIsNone(self.db.get(b"a")) - - def test_write_batch(self) -> None: - batch = rdbpy.WriteBatch() - batch.put(b"key", b"v1") - batch.delete(b"key") - batch.put(b"key", b"v2") - batch.put(b"key", b"v3") - batch.put(b"a", b"b") - - self.db.write(batch) - ref = {b"a": b"b", b"key": b"v3"} - ret = self.db.multi_get([b"key", b"a"]) - self.assertEqual(ref, ret) - - def test_write_batch_iter(self) -> None: - batch = rdbpy.WriteBatch() - self.assertEqual([], list(batch)) - - batch.put(b"key1", b"v1") - batch.put(b"key2", b"v2") - batch.put(b"key3", b"v3") - batch.delete(b"a") - batch.delete(b"key1") - batch.merge(b"xxx", b"value") - - it = iter(batch) - del batch - ref = [ - ("Put", b"key1", b"v1"), - ("Put", b"key2", b"v2"), - ("Put", b"key3", b"v3"), - ("Delete", b"a", b""), - ("Delete", b"key1", b""), - ("Merge", b"xxx", b"value"), - ] - self.assertEqual(ref, list(it)) - - def test_key_may_exists(self) -> None: - self.db.put(b"a", b"1") - - self.assertEqual((False, None), self.db.key_may_exist(b"x")) - self.assertEqual((False, None), self.db.key_may_exist(b"x", True)) - self.assertEqual((True, None), self.db.key_may_exist(b"a")) - self.assertEqual((True, b"1"), self.db.key_may_exist(b"a", True)) - - def test_seek_for_prev(self) -> None: - self.db.put(b"a1", b"a1_value") - self.db.put(b"a3", b"a3_value") - self.db.put(b"b1", b"b1_value") - self.db.put(b"b2", b"b2_value") - self.db.put(b"c2", b"c2_value") - self.db.put(b"c4", b"c4_value") - - self.assertEqual(self.db.get(b"a1"), b"a1_value") - - it = self.db.iterkeys() - - it.seek(b"a1") - self.assertEqual(it.get(), b"a1") - it.seek(b"a3") - self.assertEqual(it.get(), b"a3") - it.seek_for_prev(b"c4") - self.assertEqual(it.get(), b"c4") - it.seek_for_prev(b"c3") - self.assertEqual(it.get(), b"c2") - - it = self.db.itervalues() - it.seek(b"a1") - self.assertEqual(it.get(), b"a1_value") - it.seek(b"a3") - self.assertEqual(it.get(), b"a3_value") - it.seek_for_prev(b"c4") - self.assertEqual(it.get(), b"c4_value") - it.seek_for_prev(b"c3") - self.assertEqual(it.get(), b"c2_value") - - it = self.db.iteritems() - it.seek(b"a1") - self.assertEqual(it.get(), (b"a1", b"a1_value")) - it.seek(b"a3") - self.assertEqual(it.get(), (b"a3", b"a3_value")) - it.seek_for_prev(b"c4") - self.assertEqual(it.get(), (b"c4", b"c4_value")) - it.seek_for_prev(b"c3") - self.assertEqual(it.get(), (b"c2", b"c2_value")) - - reversed(it) - it.seek_for_prev(b"c3") - self.assertEqual(it.get(), (b"c2", b"c2_value")) - - def test_iter_keys(self) -> None: - for x in range(300): - self.db.put(int_to_bytes(x), int_to_bytes(x)) - - it = self.db.iterkeys() - - self.assertEqual([], list(it)) - - it.seek_to_last() - self.assertEqual([b"99"], list(it)) - - ref = sorted([int_to_bytes(x) for x in range(300)]) - it.seek_to_first() - self.assertEqual(ref, list(it)) - - it.seek(b"90") - ref = [b"90", b"91", b"92", b"93", b"94", b"95", b"96", b"97", b"98", b"99"] - self.assertEqual(ref, list(it)) - - def test_iter_values(self) -> None: - for x in range(300): - self.db.put(int_to_bytes(x), int_to_bytes(x * 1000)) - - it = self.db.itervalues() - - self.assertEqual([], list(it)) - - it.seek_to_last() - self.assertEqual([b"99000"], list(it)) - - ref = sorted([int_to_bytes(x) for x in range(300)]) - ref = [int_to_bytes(int(x) * 1000) for x in ref] - it.seek_to_first() - self.assertEqual(ref, list(it)) - - it.seek(b"90") - ref = [int_to_bytes(x * 1000) for x in range(90, 100)] - self.assertEqual(ref, list(it)) - - def test_iter_items(self) -> None: - for x in range(300): - self.db.put(int_to_bytes(x), int_to_bytes(x * 1000)) - - it = self.db.iteritems() - - self.assertEqual([], list(it)) - - it.seek_to_last() - self.assertEqual([(b"99", b"99000")], list(it)) - - ref = sorted([int_to_bytes(x) for x in range(300)]) - ref = [(x, int_to_bytes(int(x) * 1000)) for x in ref] - it.seek_to_first() - self.assertEqual(ref, list(it)) - - it.seek(b"90") - ref = [(int_to_bytes(x), int_to_bytes(x * 1000)) for x in range(90, 100)] - self.assertEqual(ref, list(it)) - - def test_reverse_iter(self) -> None: - for x in range(100): - self.db.put(int_to_bytes(x), int_to_bytes(x * 1000)) - - it = self.db.iteritems() - it.seek_to_last() - - ref = sorted([int_to_bytes(x) for x in range(100)], reverse=True) - ref = [(x, int_to_bytes(int(x) * 1000)) for x in ref] - - self.assertEqual(ref, list(reversed(it))) - - def test_iter_skip_back(self) -> None: - for x in range(10): - self.db.put(int_to_bytes(x), int_to_bytes(x * 10)) - - it = self.db.iteritems() - it.seek(b"5") - self.assertEqual(it.get(), (b"5", b"50")) - it.skip_back() - self.assertEqual(it.get(), (b"4", b"40")) - it.skip_back() - self.assertEqual(it.get(), (b"3", b"30")) - it.skip() - self.assertEqual(it.get(), (b"4", b"40")) - - it = self.db.iterkeys() - it.seek_to_last() - self.assertEqual(it.get(), b"9") - it.skip_back() - self.assertEqual(it.get(), b"8") - - it = self.db.iterkeys() - it.seek_to_first() - with self.assertRaises(ValueError): - for _ in range(20): - it.skip_back() - - def test_snapshot(self) -> None: - self.db.put(b"a", b"1") - self.db.put(b"b", b"2") - - self.db.snapshot() - self.db.put(b"a", b"2") - self.db.delete(b"b") - - it = self.db.iteritems() - it.seek_to_first() - self.assertEqual({b"a": b"2"}, dict(it)) - - # it = self.db.iteritems(snapshot=snapshot) - # it.seek_to_first() - # self.assertEqual({b'a': b'1', b'b': b'2'}, dict(it)) - - def test_get_property(self) -> None: - for x in range(300): - x = int_to_bytes(x) - self.db.put(x, x) - - self.assertIsNotNone(self.db.get_property(b"rocksdb.stats")) - self.assertIsNotNone(self.db.get_property(b"rocksdb.sstables")) - self.assertIsNotNone(self.db.get_property(b"rocksdb.num-files-at-level0")) - self.assertIsNone(self.db.get_property(b"does not exsits")) - - def test_compact_range(self) -> None: - for x in range(10000): - x = int_to_bytes(x) - self.db.put(x, x) - - self.db.compact_range() - - -class AssocCounter(rdbpy.interfaces.AssociativeMergeOperator): - def merge(self, key: bytes, existing_value: bytes | None, value: bytes) -> tuple[bool, bytes]: - if existing_value: - return (True, int_to_bytes(int(existing_value) + int(value))) - return (True, value) - - def name(self) -> bytes: - return b"AssocCounter" - - -class TestUint64Merge(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options() - opts.create_if_missing = True - opts.merge_operator = UintAddOperator() - self.db = rdbpy.DB(str(Path(self.db_loc) / "test"), opts) - - def test_merge(self) -> None: - self.db.put(b"a", struct.pack("Q", 5566)) - for x in range(1000): - self.db.merge(b"a", struct.pack("Q", x)) - self.assertEqual(5566 + sum(range(1000)), struct.unpack("Q", self.db.get(b"a"))[0]) - - -# class TestPutMerge(TestHelper): -# def setUp(self): -# TestHelper.setUp(self) -# opts = rocksdb.Options() -# opts.create_if_missing = True -# opts.merge_operator = "put" -# self.db = rocksdb.DB(os.path.join(self.db_loc, 'test'), opts) - -# def test_merge(self): -# self.db.put(b'a', b'ccc') -# self.db.merge(b'a', b'ddd') -# self.assertEqual(self.db.get(b'a'), 'ddd') - -# class TestPutV1Merge(TestHelper): -# def setUp(self): -# TestHelper.setUp(self) -# opts = rocksdb.Options() -# opts.create_if_missing = True -# opts.merge_operator = "put_v1" -# self.db = rocksdb.DB(os.path.join(self.db_loc, 'test'), opts) - -# def test_merge(self): -# self.db.put(b'a', b'ccc') -# self.db.merge(b'a', b'ddd') -# self.assertEqual(self.db.get(b'a'), 'ddd') - - -class TestStringAppendOperatorMerge(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options() - opts.create_if_missing = True - opts.merge_operator = StringAppendOperator() - self.db = rdbpy.DB(str(Path(self.db_loc) / "test"), opts) - - # NOTE(sileht): Raise "Corruption: Error: Could not perform merge." on PY3 - # @unittest.skipIf(sys.version_info[0] == 3, - # "Unexpected behavior on PY3") - def test_merge(self) -> None: - self.db.put(b"a", b"ccc") - self.db.merge(b"a", b"ddd") - self.assertEqual(self.db.get(b"a"), b"ccc,ddd") - - -# class TestStringMaxOperatorMerge(TestHelper): -# def setUp(self): -# TestHelper.setUp(self) -# opts = rocksdb.Options() -# opts.create_if_missing = True -# opts.merge_operator = "max" -# self.db = rocksdb.DB(os.path.join(self.db_loc, 'test'), opts) - -# def test_merge(self): -# self.db.put(b'a', int_to_bytes(55)) -# self.db.merge(b'a', int_to_bytes(56)) -# self.assertEqual(int(self.db.get(b'a')), 56) - - -class TestAssocMerge(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options() - opts.create_if_missing = True - opts.merge_operator = AssocCounter() - self.db = rdbpy.DB(str(Path(self.db_loc) / "test"), opts) - - def test_merge(self) -> None: - for x in range(1000): - self.db.merge(b"a", int_to_bytes(x)) - self.assertEqual(sum(range(1000)), int(self.db.get(b"a"))) - - -class FullCounter(rdbpy.interfaces.MergeOperator): - def name(self) -> bytes: - return b"fullcounter" - - def full_merge( - self, key: bytes, existing_value: bytes | None, operand_list: list[bytes] - ) -> tuple[bool, bytes]: - ret = sum(int(x) for x in operand_list) - if existing_value: - ret += int(existing_value) - - return (True, int_to_bytes(ret)) - - def partial_merge(self, key: bytes, left: bytes, right: bytes) -> tuple[bool, bytes]: - return (True, int_to_bytes(int(left) + int(right))) - - -class TestFullMerge(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options() - opts.create_if_missing = True - opts.merge_operator = FullCounter() - self.db = rdbpy.DB(str(Path(self.db_loc) / "test"), opts) - - def test_merge(self) -> None: - for x in range(1000): - self.db.merge(b"a", int_to_bytes(x)) - self.assertEqual(sum(range(1000)), int(self.db.get(b"a"))) - - -class SimpleComparator(rdbpy.interfaces.Comparator): - def name(self) -> bytes: - return b"mycompare" - - def compare(self, a: bytes, b: bytes) -> int: - a = int(a) - b = int(b) - if a < b: - return -1 - if a == b: - return 0 - if a > b: - return 1 - - -class TestComparator(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options() - opts.create_if_missing = True - opts.comparator = SimpleComparator() - self.db = rdbpy.DB(str(Path(self.db_loc) / "test"), opts) - - def test_compare(self) -> None: - for x in range(1000): - self.db.put(int_to_bytes(x), int_to_bytes(x)) - - self.assertEqual(b"300", self.db.get(b"300")) - - -class StaticPrefix(rdbpy.interfaces.SliceTransform): - def name(self) -> bytes: - return b"static" - - def transform(self, src: bytes) -> tuple[int, int]: - return (0, 5) - - def in_domain(self, src: bytes) -> bool: - return len(src) >= 5 - - def in_range(self, dst: bytes) -> bool: - return len(dst) == 5 - - -class TestPrefixExtractor(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options(create_if_missing=True) - opts.prefix_extractor = StaticPrefix() - self.db = rdbpy.DB(str(Path(self.db_loc) / "test"), opts) - - def _fill_db(self) -> None: - for x in range(3000): - keyx = hex(x)[2:].zfill(5).encode("utf8") + b".x" - keyy = hex(x)[2:].zfill(5).encode("utf8") + b".y" - keyz = hex(x)[2:].zfill(5).encode("utf8") + b".z" - self.db.put(keyx, b"x") - self.db.put(keyy, b"y") - self.db.put(keyz, b"z") - - def test_prefix_iterkeys(self) -> None: - self._fill_db() - self.assertEqual(b"x", self.db.get(b"00001.x")) - self.assertEqual(b"y", self.db.get(b"00001.y")) - self.assertEqual(b"z", self.db.get(b"00001.z")) - - it = self.db.iterkeys() - it.seek(b"00002") - - ref = [b"00002.x", b"00002.y", b"00002.z"] - ret = takewhile(lambda key: key.startswith(b"00002"), it) - self.assertEqual(ref, list(ret)) - - def test_prefix_iteritems(self) -> None: - self._fill_db() - - it = self.db.iteritems() - it.seek(b"00002") - - ref = {b"00002.z": b"z", b"00002.y": b"y", b"00002.x": b"x"} - ret = takewhile(lambda item: item[0].startswith(b"00002"), it) - self.assertEqual(ref, dict(ret)) - - -class TestDBColumnFamilies(TestHelper): - def setUp(self) -> None: - TestHelper.setUp(self) - opts = rdbpy.Options(create_if_missing=True) - self.db = rdbpy.DB( - str(Path(self.db_loc) / "test"), - opts, - ) - - self.cf_a = self.db.create_column_family(b"A", rdbpy.ColumnFamilyOptions()) - self.cf_b = self.db.create_column_family(b"B", rdbpy.ColumnFamilyOptions()) - - def test_column_families(self) -> None: - families = self.db.column_families - names = [handle.name for handle in families] - self.assertEqual([b"default", b"A", b"B"], names) - for name in names: - self.assertIn(self.db.get_column_family(name), families) - - self.assertEqual( - names, - rdbpy.list_column_families( - str(Path(self.db_loc) / "test"), - rdbpy.Options(), - ), - ) - - def test_get_none(self) -> None: - self.assertIsNone(self.db.get(b"k")) - self.assertIsNone(self.db.get(b"k", column_family=self.cf_a)) - self.assertIsNone(self.db.get(b"k", column_family=self.cf_b)) - - def test_put_get(self) -> None: - self.db.put(b"k", b"v", column_family=self.cf_a) - self.assertEqual(b"v", self.db.get(b"k", column_family=self.cf_a)) - self.assertIsNone(self.db.get(b"k")) - self.assertIsNone(self.db.get(b"k", column_family=self.cf_b)) - - def test_multi_get(self) -> None: - data = [ - (b"a", b"1default"), - (b"b", b"2default"), - (b"c", b"3default"), - ((self.cf_a, b"a"), b"1a"), - ((self.cf_a, b"b"), b"2a"), - ((self.cf_a, b"c"), b"3a"), - ((self.cf_b, b"a"), b"1b"), - ((self.cf_b, b"b"), b"2b"), - ((self.cf_b, b"c"), b"3b"), - ] - for key, value in data: - if not isinstance(key, tuple): - key = (None, key) - self.db.put(key[1], value, column_family=key[0]) - - multi_get_lookup = [value[0] for value in data] - - ret = self.db.multi_get(multi_get_lookup) - ref = {value[0]: value[1] for value in data} - self.assertEqual(ref, ret) - - def test_delete(self) -> None: - self.db.put(b"a", b"b", column_family=self.cf_a) - self.assertEqual(b"b", self.db.get(b"a", column_family=self.cf_a)) - self.db.delete(b"a", column_family=self.cf_a) - self.assertIsNone(self.db.get(b"a", column_family=self.cf_a)) - - def test_write_batch(self) -> None: - cfa = self.db.get_column_family(b"A") - batch = rdbpy.WriteBatch() - batch.put(b"key", b"v1", column_family=cfa) - batch.delete(b"key", column_family=self.cf_a) - batch.put(b"key", b"v2", column_family=cfa) - batch.put(b"key", b"v3", column_family=cfa) - batch.put(b"a", b"1", column_family=cfa) - batch.put(b"b", b"2", column_family=cfa) - - self.db.write(batch) - query = [(cfa, b"key"), (cfa, b"a"), (cfa, b"b")] - ret = self.db.multi_get(query) - - self.assertEqual(b"v3", ret[query[0]]) - self.assertEqual(b"1", ret[query[1]]) - self.assertEqual(b"2", ret[query[2]]) - - def test_key_may_exists(self) -> None: - self.db.put(b"a", b"1", column_family=self.cf_a) - - self.assertEqual((False, None), self.db.key_may_exist(b"x", column_family=self.cf_a)) - self.assertEqual( - (False, None), self.db.key_may_exist(b"x", fetch=True, column_family=self.cf_a) - ) - self.assertEqual((True, None), self.db.key_may_exist(b"a", column_family=self.cf_a)) - self.assertEqual( - (True, b"1"), self.db.key_may_exist(b"a", fetch=True, column_family=self.cf_a) - ) - - def test_iter_keys(self) -> None: - for x in range(300): - self.db.put(int_to_bytes(x), int_to_bytes(x), column_family=self.cf_a) - - it = self.db.iterkeys(self.cf_a) - self.assertEqual([], list(it)) - - it.seek_to_last() - self.assertEqual([b"99"], list(it)) - - ref = sorted([int_to_bytes(x) for x in range(300)]) - it.seek_to_first() - self.assertEqual(ref, list(it)) - - it.seek(b"90") - ref = sorted([int_to_bytes(x) for x in range(90, 100)]) - self.assertEqual(ref, list(it)) - - def test_iter_values(self) -> None: - for x in range(300): - self.db.put(int_to_bytes(x), int_to_bytes(x * 1000), column_family=self.cf_b) - - it = self.db.itervalues(self.cf_b) - self.assertEqual([], list(it)) - - it.seek_to_last() - self.assertEqual([b"99000"], list(it)) - - ref = sorted([int_to_bytes(x) for x in range(300)]) - ref = [int_to_bytes(int(x) * 1000) for x in ref] - it.seek_to_first() - self.assertEqual(ref, list(it)) - - it.seek(b"90") - ref = [int_to_bytes(x * 1000) for x in range(90, 100)] - self.assertEqual(ref, list(it)) - - def test_iter_items(self) -> None: - for x in range(300): - self.db.put(int_to_bytes(x), int_to_bytes(x * 1000), column_family=self.cf_b) - - it = self.db.iteritems(self.cf_b) - self.assertEqual([], list(it)) - - it.seek_to_last() - self.assertEqual([(b"99", b"99000")], list(it)) - - ref = sorted([int_to_bytes(x) for x in range(300)]) - ref = [(x, int_to_bytes(int(x) * 1000)) for x in ref] - it.seek_to_first() - self.assertEqual(ref, list(it)) - - it.seek(b"90") - ref = [(int_to_bytes(x), int_to_bytes(x * 1000)) for x in range(90, 100)] - self.assertEqual(ref, list(it)) - - def test_reverse_iter(self) -> None: - for x in range(100): - self.db.put(int_to_bytes(x), int_to_bytes(x * 1000), column_family=self.cf_a) - - it = self.db.iteritems(self.cf_a) - it.seek_to_last() - - ref = sorted([int_to_bytes(x) for x in range(100)], reverse=True) - ref = [(x, int_to_bytes(int(x) * 1000)) for x in ref] - - self.assertEqual(ref, list(reversed(it))) - - def test_snapshot(self) -> None: - cfa = self.db.get_column_family(b"A") - self.db.put(b"a", b"1", column_family=cfa) - self.db.put(b"b", b"2", column_family=cfa) - - self.db.snapshot() - self.db.put(b"a", b"2", column_family=cfa) - self.db.delete(b"b", column_family=cfa) - - it = self.db.iteritems(cfa) - it.seek_to_first() - self.assertEqual({b"a": b"2"}, dict(it)) - - # it = self.db.iteritems(cfa, snapshot=snapshot) - # it.seek_to_first() - # self.assertEqual({(cfa, b'a'): b'1', (cfa, b'b'): b'2'}, dict(it)) - - def test_get_property(self) -> None: - for x in range(300): - x = int_to_bytes(x) - self.db.put(x, x, column_family=self.cf_a) - - self.assertEqual(b"300", self.db.get_property(b"rocksdb.estimate-num-keys", self.cf_a)) - self.assertIsNone(self.db.get_property(b"does not exsits", self.cf_a)) - - def test_compact_range(self) -> None: - for x in range(10000): - x = int_to_bytes(x) - self.db.put(x, x, column_family=self.cf_b) - - self.db.compact_range(column_family=self.cf_b) diff --git a/tests/functional/test_lifetime.py b/tests/functional/test_lifetime.py deleted file mode 100644 index e7ea188..0000000 --- a/tests/functional/test_lifetime.py +++ /dev/null @@ -1,483 +0,0 @@ -"""Lifetime of iterators, snapshots and transactions relative to their parent. - -A use-after-free here crashes the interpreter, so every scenario runs in its -own subprocess with freed memory poisoned: PYTHONMALLOC=debug for Python -objects, MallocScribble (macOS) and MALLOC_PERTURB_ (glibc) for native ones. -A test passes only if the child exits cleanly and printed the expected -markers. - -Several scenarios force gc to run inside rdbpy calls (via gc thresholds, -which bite on CPython <= 3.11, or a gc thread, which bites on any version). -""" - -import os -import subprocess -import sys -import textwrap - -import pytest - - -PRELUDE = """ -import gc -import os -import tempfile - -import rdbpy - -TMP = tempfile.mkdtemp() -_n = [0] - - -def path(): - _n[0] += 1 - return os.path.join(TMP, "db%d" % _n[0]) - - -def txndb(p=None): - return rdbpy.TransactionDB(p or path(), rdbpy.Options(create_if_missing=True)) - - -def plaindb(p=None): - return rdbpy.DB(p or path(), rdbpy.Options(create_if_missing=True)) - - -def fill(db, n=2000): - for i in range(n): - db.put(b"k%06d" % i, b"v" * 64) - db.flush() - - -def raises(fn, exc=RuntimeError): - try: - fn() - except exc as e: - print("RAISED", type(e).__name__) - return - print("NO RAISE") -""" - - -def run(body: str, *expected: str) -> None: - env = dict(os.environ) - env["PYTHONPATH"] = os.pathsep.join(p for p in sys.path if p) - env["PYTHONMALLOC"] = "debug" - env["MallocScribble"] = "1" - env["MALLOC_PERTURB_"] = "85" - code = PRELUDE + textwrap.dedent(body) + '\nprint("DONE")\n' - proc = subprocess.run( # noqa: S603 - [sys.executable, "-c", code], - env=env, - capture_output=True, - text=True, - timeout=120, - ) - out = proc.stdout + proc.stderr - assert proc.returncode == 0, f"child exited with {proc.returncode}:\n{out}" - assert "NO RAISE" not in out, out - for marker in (*expected, "DONE"): - assert marker in out, f"missing {marker!r}:\n{out}" - - -@pytest.mark.parametrize("end", ["commit", "rollback", "close"]) -def test_txn_iterator_invalid_after_txn_ends(end: str) -> None: - run( - f""" - db = txndb() - fill(db) - txn = db.begin_transaction() - txn.put(b"a", b"1") - it = txn.iteritems() - it.seek_to_first() - it.get() - txn.{end}() - raises(it.seek_to_first) - raises(it.get) - raises(it.next) - raises(it.skip) - raises(it.skip_back) - raises(lambda: it.seek(b"k")) - raises(lambda: it.seek_for_prev(b"k")) - raises(it.seek_to_last) - del it - gc.collect() - """, - "RAISED RuntimeError", - ) - - -def test_txn_iterator_invalid_after_rollback_to_save_point() -> None: - run( - """ - db = txndb() - txn = db.begin_transaction() - txn.save_point() - for i in range(5000): - txn.put(b"t%06d" % i, b"x" * 64) - it = txn.iteritems() - it.seek_to_first() - txn.rollback_to_save_point() - raises(it.get) - txn.commit() - """, - "RAISED RuntimeError", - ) - - -def test_txn_iterator_invalid_after_reuse() -> None: - run( - """ - db = txndb() - txn = db.begin_transaction() - for i in range(5000): - txn.put(b"t%06d" % i, b"x" * 64) - it = txn.iterkeys() - it.seek_to_first() - db.begin_transaction(reuse=txn) - raises(it.get) - txn.rollback() - """, - "RAISED RuntimeError", - ) - - -def test_reversed_iterator_invalid_after_commit() -> None: - run( - """ - db = txndb() - fill(db) - txn = db.begin_transaction() - rit = reversed(txn.iterkeys()) - rit.seek_to_last() - txn.commit() - raises(lambda: next(rit)) - """, - "RAISED RuntimeError", - ) - - -def test_db_iterator_across_db_close() -> None: - run( - """ - db = plaindb() - fill(db) - it = db.iteritems() - it.seek_to_first() - dropped = db.iterkeys() - dropped.seek_to_first() - db.close() - del dropped - gc.collect() - raises(it.get) - del it - del db - gc.collect() - """, - "RAISED RuntimeError", - ) - - -def test_plain_db_close_then_free() -> None: - run( - """ - db = plaindb() - db.put(b"a", b"1") - db.close() - db.close() - del db - gc.collect() - print("FREED") - """, - "FREED", - ) - - -@pytest.mark.parametrize("kind", ["plaindb", "txndb"]) -def test_db_methods_after_close_raise(kind: str) -> None: - run( - f""" - db = {kind}() - db.put(b"a", b"1") - db.close() - raises(lambda: db.get(b"a")) - raises(lambda: db.put(b"a", b"2")) - raises(lambda: db.iterkeys()) - raises(lambda: db.iteritems()) - raises(lambda: db.snapshot()) - raises(lambda: db.write(rdbpy.WriteBatch())) - raises(lambda: db.get_property(b"rocksdb.stats")) - """, - "RAISED RuntimeError", - ) - - -def test_live_txn_and_iterator_across_txndb_close() -> None: - run( - """ - p = path() - db = txndb(p) - fill(db) - txn = db.begin_transaction() - txn.put(b"uncommitted", b"1") - it = txn.iterkeys() - it.seek_to_first() - db.close() - raises(lambda: txn.put(b"b", b"2")) - raises(txn.commit) - raises(it.get) - txn.rollback() - txn.close() - del it, txn, db - gc.collect() - db = txndb(p) - print("VISIBLE", db.get(b"uncommitted")) - """, - "RAISED RuntimeError", - "VISIBLE None", - ) - - -def test_snapshot_across_db_close() -> None: - run( - """ - db = plaindb() - db.put(b"a", b"1") - snap = db.snapshot() - db.close() - del snap - gc.collect() - print("FREED") - """, - "FREED", - ) - - -def test_iterator_only_reachable_from_garbage_traceback() -> None: - # gc may clear the iterator before the frame that owns it; the iterator - # must still free its native state before its transaction and DB go. - run( - """ - class Store: - def __init__(self, p): - self.db = txndb(p) - fill(self.db) - - def scan_then_fail(store): - txn = store.db.begin_transaction() - it = txn.iterkeys() - it.seek_to_first() - store.self_ref = store - raise AttributeError("boom") - - for _ in range(20): - try: - scan_then_fail(Store(path())) - except AttributeError as e: - err = e - err.self_ref = err - del err - gc.collect() - """, - ) - - -def test_generator_finally_commits_during_gc() -> None: - # The commit runs from gc's finalizer phase, after weakrefs to garbage are - # cleared; the still-alive iterator must be invalidated anyway. - run( - """ - class Store: - def __init__(self, p): - self.db = txndb(p) - fill(self.db) - - def scan(store): - txn = store.db.begin_transaction() - it = txn.iterkeys() - it.seek_to_first() - try: - while True: - yield it.next() - finally: - txn.commit() - raises(it.get) - - for _ in range(20): - store = Store(path()) - g = scan(store) - next(g) - store.g = g - del store, g - gc.collect() - """, - "RAISED RuntimeError", - ) - - -def test_close_while_gc_frees_other_transactions() -> None: - # Live transactions with iterators plus garbage transactions in cycles. - # Releasing the live ones during close() must not let gc (triggered by an - # allocation at a chosen point) free a garbage transaction that close() - # still has queued. - run( - """ - for extra in range(10): - db = txndb() - db.put(b"a", b"1") - keep = [] - for i in range(30): - t = db.begin_transaction() - keep.append((t, t.iterkeys())) - gc.disable() - gc.collect() - for i in range(30): - t = db.begin_transaction() - cyc = [t] - cyc.append(cyc) - del cyc, t - gc.set_threshold(gc.get_count()[0] + extra, 10, 10) - gc.enable() - db.close() - gc.set_threshold(700, 10, 10) - del keep, db - gc.collect() - """, - ) - - -def test_close_while_other_thread_collects() -> None: - # gc can run on any thread, even one that never touches the DB. - run( - """ - import threading - - stop = [] - - def collector(): - while not stop: - gc.collect(0) - - threading.Thread(target=collector, daemon=True).start() - for rnd in range(10): - db = txndb() - live = [] - for i in range(20): - t = db.begin_transaction() - t.put(b"k%d" % i, b"v") - live.append((t, t.iterkeys())) - for i in range(40): - t = db.begin_transaction() - t.put(b"g%d" % i, b"v") - cyc = [t] - cyc.append(cyc) - del cyc, t - snap = db.snapshot() - db.close() - del live, db, snap - stop.append(1) - """, - ) - - -@pytest.mark.parametrize("end", ["commit", "close"]) -def test_finalizer_ends_txn_during_commit_or_close(end: str) -> None: - # A garbage scan generator whose finally rolls back the transaction runs - # from gc while commit()/close() are mid-way through the same transaction. - run( - f""" - def scan(t): - it = t.iterkeys() - it.seek_to_first() - try: - while True: - yield it.next() - finally: - t.rollback() - - for extra in range(7): - db = txndb() - db.put(b"a", b"1") - txn = db.begin_transaction() - txn.put(b"b", b"2") - gc.disable() - gc.collect() - g = scan(txn) - next(g) - cyc = [g] - cyc.append(cyc) - del g, cyc - gc.set_threshold(gc.get_count()[0] + extra, 10, 10) - gc.enable() - if "{end}" == "close": - db.close() - else: - try: - txn.commit() - except RuntimeError: - pass - gc.set_threshold(700, 10, 10) - del txn, db - gc.collect() - """, - ) - - -@pytest.mark.parametrize("kind", ["db", "txn"]) -def test_multi_get_keys_iterable_closes_db(kind: str) -> None: - run( - f""" - db = txndb() if "{kind}" == "txn" else plaindb() - target = db.begin_transaction() if "{kind}" == "txn" else db - - class Keys: - def __len__(self): - return 2 - - def __getitem__(self, i): - return [b"a", b"b"][i] - - def __iter__(self): - yield b"a" - db.close() - yield b"b" - - raises(lambda: target.multi_get(Keys())) - """, - "RAISED RuntimeError", - ) - - -def test_bare_iterator_raises() -> None: - run( - """ - db = plaindb() - raises(lambda: rdbpy.KeysIterator(db).next()) - """, - "RAISED RuntimeError", - ) - - -def test_many_iterators_random_order() -> None: - run( - """ - import random - - db = txndb() - fill(db) - rnd = random.Random(0) - for _ in range(200): - txn = db.begin_transaction() - its = [rnd.choice([txn.iterkeys, txn.iteritems, db.iterkeys])() for _ in range(5)] - for it in its: - it.seek_to_first() - rnd.shuffle(its) - del its[:2] - rnd.choice([txn.commit, txn.rollback])() - del its, txn - live = db.iterkeys() - live.seek_to_first() - db.close() - del live - gc.collect() - """, - ) diff --git a/tests/functional/test_memtable.py b/tests/functional/test_memtable.py deleted file mode 100644 index 060a5ce..0000000 --- a/tests/functional/test_memtable.py +++ /dev/null @@ -1,30 +0,0 @@ -# content of test_sample.py -import shutil -import tempfile -from pathlib import Path - -import rdbpy - - -def test_open_skiplist_memtable_factory() -> None: - opts = rdbpy.Options() - opts.memtable_factory = rdbpy.SkipListMemtableFactory() - opts.create_if_missing = True - - loc = tempfile.mkdtemp() - try: - rdbpy.DB(str(Path(loc) / "test"), opts) - finally: - shutil.rmtree(loc) - - -def test_open_vector_memtable_factory() -> None: - opts = rdbpy.Options() - opts.allow_concurrent_memtable_write = False - opts.memtable_factory = rdbpy.VectorMemtableFactory() - opts.create_if_missing = True - loc = tempfile.mkdtemp() - try: - rdbpy.DB(str(Path(loc) / "test"), opts) - finally: - shutil.rmtree(loc) diff --git a/tests/functional/test_options.py b/tests/functional/test_options.py deleted file mode 100644 index ac6b46d..0000000 --- a/tests/functional/test_options.py +++ /dev/null @@ -1,171 +0,0 @@ -import unittest -from collections.abc import Sequence - -import rdbpy - - -class TestFilterPolicy(rdbpy.interfaces.FilterPolicy): - def create_filter(self, keys: Sequence[bytes]) -> bytes: - return b"nix" - - def key_may_match(self, key: bytes, fil: bytes) -> bool: - return True - - def name(self) -> bytes: - return b"testfilter" - - -class TestMergeOperator(rdbpy.interfaces.MergeOperator): - def full_merge(self, *args: object, **kwargs: object) -> tuple[bool, bytes | None]: - return (False, None) - - def partial_merge(self, *args: object, **kwargs: object) -> tuple[bool, bytes | None]: - return (False, None) - - def name(self) -> bytes: - return b"testmergeop" - - -class TestOptions(unittest.TestCase): - # def test_default_merge_operator(self): - # opts = rocksdb.Options() - # self.assertEqual(True, opts.paranoid_checks) - # opts.paranoid_checks = False - # self.assertEqual(False, opts.paranoid_checks) - - # self.assertIsNone(opts.merge_operator) - # opts.merge_operator = "uint64add" - # self.assertIsNotNone(opts.merge_operator) - # self.assertEqual(opts.merge_operator, "uint64add") - # with self.assertRaises(TypeError): - # opts.merge_operator = "not an operator" - - # FIXME: travis test should include the latest version of rocksdb - # def test_compaction_pri(self): - # opts = rocksdb.Options() - # default compaction_pri - # self.assertEqual(opts.compaction_pri, rocksdb.CompactionPri.by_compensated_size) - # self.assertEqual(opts.compaction_pri, rocksdb.CompactionPri.min_overlapping_ratio) - # opts.compaction_pri = rocksdb.CompactionPri.by_compensated_size - # self.assertEqual(opts.compaction_pri, rocksdb.CompactionPri.by_compensated_size) - # opts.compaction_pri = rocksdb.CompactionPri.oldest_largest_seq_first - # self.assertEqual(opts.compaction_pri, rocksdb.CompactionPri.oldest_largest_seq_first) - # opts.compaction_pri = rocksdb.CompactionPri.min_overlapping_ratio - # self.assertEqual(opts.compaction_pri, rocksdb.CompactionPri.min_overlapping_ratio) - - def test_enable_write_thread_adaptive_yield(self) -> None: - opts = rdbpy.Options() - self.assertEqual(opts.enable_write_thread_adaptive_yield, True) - opts.enable_write_thread_adaptive_yield = False - self.assertEqual(opts.enable_write_thread_adaptive_yield, False) - - def test_allow_concurrent_memtable_write(self) -> None: - opts = rdbpy.Options() - self.assertEqual(opts.allow_concurrent_memtable_write, True) - opts.allow_concurrent_memtable_write = False - self.assertEqual(opts.allow_concurrent_memtable_write, False) - - def test_compression_opts(self) -> None: - opts = rdbpy.Options() - compression_opts = opts.compression_opts - # default value - self.assertEqual(isinstance(compression_opts, dict), True) - self.assertEqual(compression_opts["window_bits"], -14) - # This doesn't match rocksdb latest - # self.assertEqual(compression_opts['level'], -1) - self.assertEqual(compression_opts["strategy"], 0) - self.assertEqual(compression_opts["max_dict_bytes"], 0) - - with self.assertRaises(TypeError): - opts.compression_opts = list(1, 2) - - opts.compression_opts = {"window_bits": 1, "level": 2, "strategy": 3, "max_dict_bytes": 4} - compression_opts = opts.compression_opts - self.assertEqual(compression_opts["window_bits"], 1) - self.assertEqual(compression_opts["level"], 2) - self.assertEqual(compression_opts["strategy"], 3) - self.assertEqual(compression_opts["max_dict_bytes"], 4) - - def test_simple(self) -> None: - opts = rdbpy.Options() - self.assertEqual(True, opts.paranoid_checks) - opts.paranoid_checks = False - self.assertEqual(False, opts.paranoid_checks) - - self.assertIsNone(opts.merge_operator) - ob = TestMergeOperator() - opts.merge_operator = ob - self.assertEqual(opts.merge_operator, ob) - - self.assertIsInstance(opts.comparator, rdbpy.BytewiseComparator) - - self.assertIn( - opts.compression, - (rdbpy.CompressionType.no_compression, rdbpy.CompressionType.snappy_compression), - ) - - opts.compression = rdbpy.CompressionType.zstd_compression - self.assertEqual(rdbpy.CompressionType.zstd_compression, opts.compression) - - def test_block_options(self) -> None: - rdbpy.BlockBasedTableFactory( - block_size=4096, filter_policy=TestFilterPolicy(), block_cache=rdbpy.LRUCache(100) - ) - - def test_unicode_path(self) -> None: - name = b"/tmp/M\xc3\xbcnchen".decode("utf8") - opts = rdbpy.Options() - opts.db_log_dir = name - opts.wal_dir = name - - self.assertEqual(name, opts.db_log_dir) - self.assertEqual(name, opts.wal_dir) - - def test_table_factory(self) -> None: - opts = rdbpy.Options() - self.assertIsNone(opts.table_factory) - - opts.table_factory = rdbpy.BlockBasedTableFactory() - opts.table_factory = rdbpy.PlainTableFactory() - - def test_compaction_style(self) -> None: - opts = rdbpy.Options() - self.assertEqual("level", opts.compaction_style) - - opts.compaction_style = "universal" - self.assertEqual("universal", opts.compaction_style) - - opts.compaction_style = "level" - self.assertEqual("level", opts.compaction_style) - - assert_raises_regex = self.assertRaisesRegex - - with assert_raises_regex(Exception, "Unknown compaction style"): - opts.compaction_style = "foo" - - def test_compaction_opts_universal(self) -> None: - opts = rdbpy.Options() - uopts = opts.compaction_options_universal - self.assertEqual(-1, uopts["compression_size_percent"]) - self.assertEqual(200, uopts["max_size_amplification_percent"]) - self.assertEqual("total_size", uopts["stop_style"]) - self.assertEqual(1, uopts["size_ratio"]) - self.assertEqual(2, uopts["min_merge_width"]) - self.assertGreaterEqual(4294967295, uopts["max_merge_width"]) - - new_opts = {"stop_style": "similar_size", "max_merge_width": 30} - opts.compaction_options_universal = new_opts - uopts = opts.compaction_options_universal - - self.assertEqual(-1, uopts["compression_size_percent"]) - self.assertEqual(200, uopts["max_size_amplification_percent"]) - self.assertEqual("similar_size", uopts["stop_style"]) - self.assertEqual(1, uopts["size_ratio"]) - self.assertEqual(2, uopts["min_merge_width"]) - self.assertEqual(30, uopts["max_merge_width"]) - - def test_row_cache(self) -> None: - opts = rdbpy.Options() - self.assertIsNone(opts.row_cache) - opts.row_cache = cache = rdbpy.LRUCache(2 * 1024 * 1024) - self.assertEqual(cache, opts.row_cache) diff --git a/tests/functional/test_transaction.py b/tests/functional/test_transaction.py deleted file mode 100644 index 3e3b897..0000000 --- a/tests/functional/test_transaction.py +++ /dev/null @@ -1,116 +0,0 @@ -import gc -import shutil -import tempfile -import unittest -from pathlib import Path - -import rdbpy - - -class TransactionTestHelper(unittest.TestCase): - def setUp(self) -> None: - self.db_loc = tempfile.mkdtemp() - self.addCleanup(self._cleanup_db) - - def _cleanup_db(self) -> None: - if hasattr(self, "db"): - del self.db - gc.collect() - if Path(self.db_loc).exists(): - shutil.rmtree(self.db_loc) - - -class TestTransactionDB(TransactionTestHelper): - def setUp(self) -> None: - super().setUp() - opts = rdbpy.Options(create_if_missing=True) - self.txn_opts = rdbpy.TransactionDBOptions() - self.db = rdbpy.TransactionDB( - str(Path(self.db_loc) / "txn"), - opts, - txn_db_opts=self.txn_opts, - ) - - def test_commit_persists_changes(self) -> None: - txn = self.db.begin_transaction() - txn.put(b"a", b"1") - txn.commit() - txn.close() - self.assertEqual(self.db.get(b"a"), b"1") - - def test_rollback_discards_changes(self) -> None: - txn = self.db.begin_transaction() - txn.put(b"a", b"1") - txn.rollback() - txn.close() - self.assertIsNone(self.db.get(b"a")) - - def test_savepoint_and_rollback(self) -> None: - txn = self.db.begin_transaction() - txn.put(b"a", b"1") - txn.save_point() - txn.put(b"b", b"2") - txn.rollback_to_save_point() - txn.commit() - txn.close() - - self.assertEqual(self.db.get(b"a"), b"1") - self.assertIsNone(self.db.get(b"b")) - - def test_transaction_iterators_include_uncommitted(self) -> None: - txn = self.db.begin_transaction() - txn.put(b"a", b"1") - txn.put(b"b", b"2") - - it = txn.iteritems() - it.seek_to_first() - self.assertEqual(it.get(), (b"a", b"1")) - it.seek(b"b") - self.assertEqual(it.get(), (b"b", b"2")) - - txn.rollback() - txn.close() - - def test_multi_get_inside_transaction(self) -> None: - txn = self.db.begin_transaction() - txn.put(b"a", b"1") - txn.put(b"b", b"2") - - result = txn.multi_get([b"a", b"b", b"missing"]) - self.assertEqual(result[b"a"], b"1") - self.assertEqual(result[b"b"], b"2") - self.assertIsNone(result[b"missing"]) - - txn.commit() - txn.close() - - def test_disable_enable_indexing_roundtrip(self) -> None: - txn = self.db.begin_transaction() - txn.disable_indexing() - txn.enable_indexing() - txn.rollback() - txn.close() - - def test_named_transaction_metadata(self) -> None: - txn = self.db.begin_transaction() - txn.set_name("primary") - self.assertTrue(txn.get_name().startswith("primary")) - self.assertIsInstance(txn.get_id(), int) - txn.rollback() - txn.close() - - -class TestTransactionOptionsSemantics(unittest.TestCase): - def test_write_policy_roundtrip(self) -> None: - opts = rdbpy.TransactionDBOptions() - opts.write_policy = rdbpy.TxnDBWritePolicy.write_prepared - self.assertEqual( - opts.write_policy, - rdbpy.TxnDBWritePolicy.write_prepared, - ) - - def test_transaction_options_defaults(self) -> None: - txn_opts = rdbpy.TransactionOptions() - self.assertFalse(txn_opts.set_snapshot) - txn_opts.set_snapshot = True - self.assertTrue(txn_opts.set_snapshot) diff --git a/tests/test_db.py b/tests/test_db.py new file mode 100644 index 0000000..429af75 --- /dev/null +++ b/tests/test_db.py @@ -0,0 +1,200 @@ +"""Plain DB: open modes, options, point ops, batches, maintenance.""" + +import os + +import pytest + +import rdbpy +from conftest import fill + + +def test_open_put_get_delete(db): + assert db.get(b"a") is None + db.put(b"a", b"1") + assert db.get(b"a") == b"1" + db.delete(b"a") + assert db.get(b"a") is None + db.delete(b"never") # deleting a missing key is fine + + +def test_default_options_create(path): + p = path() + with rdbpy.DB(p) as db: + db.put(b"a", b"1") + assert os.path.exists(os.path.join(p, "CURRENT")) + + +def test_open_missing_without_create_raises(path): + with pytest.raises(rdbpy.InvalidArgument): + rdbpy.DB(path(), rdbpy.Options(create_if_missing=False)) + + +def test_error_if_exists(path): + p = path() + rdbpy.DB(p).close() + with pytest.raises(rdbpy.InvalidArgument): + rdbpy.DB(p, rdbpy.Options(create_if_missing=True, error_if_exists=True)) + + +def test_second_open_of_same_dir_is_io_error(path): + p = path() + db = rdbpy.DB(p) + try: + with pytest.raises(rdbpy.RocksIOError): + rdbpy.DB(p) + finally: + db.close() + + +def test_bytes_only(db): + with pytest.raises(TypeError): + db.put("a", b"1") + with pytest.raises(TypeError): + db.put(b"a", "1") + with pytest.raises(TypeError): + db.get("a") + + +def test_empty_key_and_value(db): + db.put(b"", b"") + assert db.get(b"") == b"" + db.put(b"k", b"") + assert db.get(b"k") == b"" + + +def test_large_values(db): + v = os.urandom(2_000_000) + db.put(b"big", v) + assert db.get(b"big") == v + + +def test_multi_get(db): + fill(db, 5) + out = db.multi_get([b"k0001", b"nope", b"k0004"]) + assert out == [b"v0001", None, b"v0004"] + assert db.multi_get([]) == [] + assert db.multi_get(iter([b"k0000"])) == [b"v0000"] + with pytest.raises(TypeError): + db.multi_get(["k0000"]) + + +def test_write_batch(db): + db.put(b"gone", b"x") + wb = rdbpy.WriteBatch() + wb.put(b"a", b"1") + wb.put(b"b", b"2") + wb.delete(b"gone") + assert len(wb) == 3 + assert wb.count() == 3 + db.write(wb) + assert db.get(b"a") == b"1" + assert db.get(b"b") == b"2" + assert db.get(b"gone") is None + wb.clear() + assert len(wb) == 0 + db.write(wb) # empty batch is a no-op + + +def test_write_options(db): + db.put(b"a", b"1", sync=True) + db.put(b"b", b"2", disable_wal=True) + wb = rdbpy.WriteBatch() + wb.put(b"c", b"3") + db.write(wb, sync=True) + assert db.multi_get([b"a", b"b", b"c"]) == [b"1", b"2", b"3"] + + +def test_close_and_use_raises(path): + db = rdbpy.DB(path()) + assert not db.closed + db.close() + assert db.closed + db.close() # idempotent + for call in ( + lambda: db.get(b"a"), + lambda: db.put(b"a", b"1"), + lambda: db.delete(b"a"), + lambda: db.iterator(), + lambda: db.snapshot(), + lambda: db.write(rdbpy.WriteBatch()), + lambda: db.flush(), + ): + with pytest.raises(RuntimeError): + call() + assert "closed" in repr(db) + + +def test_context_manager_closes(path): + with rdbpy.DB(path()) as db: + db.put(b"a", b"1") + assert db.closed + + +def test_reopen_persists(path): + p = path() + with rdbpy.DB(p) as db: + db.put(b"a", b"1") + with rdbpy.DB(p, rdbpy.Options(create_if_missing=False)) as db: + assert db.get(b"a") == b"1" + + +def test_read_only(path): + p = path() + with rdbpy.DB(p) as db: + db.put(b"a", b"1") + with rdbpy.DB(p, read_only=True) as ro: + assert ro.get(b"a") == b"1" + with pytest.raises(rdbpy.NotSupported): + ro.put(b"b", b"2") + + +def test_secondary_catches_up(path, tmp_path): + p = path() + primary = rdbpy.DB(p) + primary.put(b"a", b"1") + primary.flush() + secondary = rdbpy.DB(p, secondary_path=str(tmp_path / "secondary")) + try: + assert secondary.get(b"a") == b"1" + primary.put(b"b", b"2") + primary.flush() + secondary.try_catch_up_with_primary() + assert secondary.get(b"b") == b"2" + finally: + secondary.close() + primary.close() + + +def test_flush_compact_property(db): + fill(db, 50) + db.flush() + db.flush_wal(sync=True) + db.compact_range() + db.compact_range(b"k0010", b"k0020") + assert db.get_property("rocksdb.estimate-num-keys") is not None + assert db.get_property("rocksdb.no-such-property") is None + assert db.latest_sequence_number >= 50 + + +def test_destroy_db(path): + p = path() + with rdbpy.DB(p) as db: + db.put(b"a", b"1") + rdbpy.destroy_db(p) + with rdbpy.DB(p) as db: + assert db.get(b"a") is None + + +def test_path_and_options_attrs(path): + p = path() + opts = rdbpy.Options(create_if_missing=True) + with rdbpy.DB(p, opts) as db: + assert db.path == p + assert db.options is opts + with rdbpy.DB(os.fsencode(p)) as db: + assert db.path == p + + +def test_version(): + assert rdbpy.__version__ == "0.3.0" + assert rdbpy.rocksdb_version() == "6.29.5" diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 0000000..e96804d --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,42 @@ +"""Status code mapping and the exception hierarchy.""" + +import pytest + +import rdbpy +from rdbpy import errors + + +def test_hierarchy(): + for cls in ( + rdbpy.NotFound, rdbpy.Corruption, rdbpy.NotSupported, rdbpy.InvalidArgument, + rdbpy.RocksIOError, rdbpy.MergeInProgress, rdbpy.Incomplete, rdbpy.ShutdownInProgress, + rdbpy.TimedOut, rdbpy.Aborted, rdbpy.Busy, rdbpy.Expired, rdbpy.TryAgain, + rdbpy.CompactionTooLarge, rdbpy.ColumnFamilyDropped, + ): + assert issubclass(cls, rdbpy.RocksDBError) + assert issubclass(rdbpy.Deadlock, rdbpy.Busy) + assert issubclass(rdbpy.LockLimit, rdbpy.RocksDBError) + assert not issubclass(rdbpy.TimedOut, rdbpy.Busy) + assert not issubclass(rdbpy.TryAgain, rdbpy.Busy) + + +def test_error_for_mapping(): + assert type(errors.error_for(11, 0, "x")) is rdbpy.Busy + assert type(errors.error_for(11, 5, "x")) is rdbpy.Deadlock + assert type(errors.error_for(9, 2, "x")) is rdbpy.TimedOut + assert type(errors.error_for(13, 0, "x")) is rdbpy.TryAgain + assert type(errors.error_for(10, 3, "x")) is rdbpy.LockLimit + assert type(errors.error_for(11, 3, "x")) is rdbpy.LockLimit + assert type(errors.error_for(1, 0, "x")) is rdbpy.NotFound + assert type(errors.error_for(99, 0, "x")) is rdbpy.RocksDBError + e = errors.error_for(9, 2, "lock timeout") + assert e.code == 9 and e.subcode == 2 + assert e.message == "lock timeout" + assert str(e) == "lock timeout" + + +def test_raised_errors_carry_codes(path): + with pytest.raises(rdbpy.InvalidArgument) as ei: + rdbpy.DB(path(), rdbpy.Options(create_if_missing=False)) + assert ei.value.code == 4 + assert "does not exist" in str(ei.value) diff --git a/tests/test_gil.py b/tests/test_gil.py new file mode 100644 index 0000000..9d7e6a2 --- /dev/null +++ b/tests/test_gil.py @@ -0,0 +1,125 @@ +"""The GIL is released inside blocking RocksDB calls: a thread stuck in a lock +wait must not stop other Python threads.""" + +import threading +import time + +import pytest + +import rdbpy + + +def test_lock_wait_does_not_block_other_threads(tdb): + tdb.put(b"a", b"1") + holder = tdb.begin() + holder.get_for_update(b"a") + waiter = tdb.begin(lock_timeout_ms=1500) + started = threading.Event() + result = [] + + def wait_on_lock(): + started.set() + try: + waiter.get_for_update(b"a") + result.append("ok") + except rdbpy.TimedOut: + result.append("timeout") + + th = threading.Thread(target=wait_on_lock) + th.start() + started.wait() + time.sleep(0.05) + assert th.is_alive() + # Main thread makes progress, including its own rocksdb calls, while the + # waiter sits inside GetForUpdate. + t0 = time.monotonic() + n = 0 + while time.monotonic() - t0 < 0.5: + assert tdb.get(b"a") == b"1" + n += 1 + assert n > 100 + assert th.is_alive() + holder.rollback() + th.join(timeout=3) + assert result == ["ok"] + waiter.rollback() + + +def test_parallel_readers_overlap(db): + for i in range(2000): + db.put(b"k%05d" % i, b"x" * 200) + db.flush() + barrier = threading.Barrier(4) + counts = [] + + def reader(): + barrier.wait() + n = 0 + t0 = time.monotonic() + while time.monotonic() - t0 < 0.3: + for row in db.iterator().next_batch(500): + n += 1 + counts.append(n) + + threads = [threading.Thread(target=reader) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join() + assert len(counts) == 4 + assert all(c > 0 for c in counts) + + +def test_concurrent_writers_on_txn_db(tdb): + tdb.put(b"n", b"0") + errors = [] + + def inc(): + for _ in range(20): + while True: + txn = tdb.begin(lock_timeout_ms=2000) + try: + v = int(txn.get_for_update(b"n")) + txn.put(b"n", b"%d" % (v + 1)) + txn.commit() + break + except (rdbpy.Busy, rdbpy.TimedOut): + txn.rollback() + except Exception as e: # pragma: no cover + errors.append(e) + txn.rollback() + break + + threads = [threading.Thread(target=inc) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join() + assert errors == [] + assert tdb.get(b"n") == b"80" + + +def test_optimistic_retry_loop(odb): + odb.put(b"n", b"0") + attempts = [0] + + def inc(): + for _ in range(20): + while True: + txn = odb.begin() + attempts[0] += 1 + v = int(txn.get_for_update(b"n")) + txn.put(b"n", b"%d" % (v + 1)) + try: + txn.commit() + break + except rdbpy.Busy: + pass + + threads = [threading.Thread(target=inc) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join() + assert odb.get(b"n") == b"80" + assert attempts[0] >= 80 diff --git a/tests/test_iterator.py b/tests/test_iterator.py new file mode 100644 index 0000000..ea64515 --- /dev/null +++ b/tests/test_iterator.py @@ -0,0 +1,278 @@ +"""Iterators: seeks, direction, bounds, prefix, keys_only, batches, txn merge.""" + +import pytest + +import rdbpy +from conftest import fill + + +def keys(it): + return [k for k, _ in it] + + +def test_forward_and_reverse(db): + fill(db, 5) + assert keys(db.iterator()) == [b"k%04d" % i for i in range(5)] + assert keys(db.iterator(reverse=True)) == [b"k%04d" % i for i in range(4, -1, -1)] + assert list(db.iterator(keys_only=True)) == [b"k%04d" % i for i in range(5)] + assert list(db.iterator(keys_only=True, reverse=True))[0] == b"k0004" + + +def test_items_are_bytes(db): + db.put(b"a", b"1") + rows = list(db.iterator()) + assert rows == [(b"a", b"1")] + assert isinstance(rows[0][0], bytes) + + +def test_empty_db(db): + assert list(db.iterator()) == [] + assert db.iterator().next_batch() == [] + it = db.iterator() + it.seek_to_first() + assert not it.valid() + with pytest.raises(RuntimeError): + it.key() + + +def test_raw_cursor(db): + fill(db, 10) + it = db.iterator() + it.seek(b"k0003") + assert it.valid() + assert it.key() == b"k0003" + assert it.value() == b"v0003" + assert it.item() == (b"k0003", b"v0003") + it.next() + assert it.key() == b"k0004" + it.prev() + assert it.key() == b"k0003" + it.seek_to_last() + assert it.key() == b"k0009" + it.next() + assert not it.valid() + it.seek_to_first() + assert it.key() == b"k0000" + it.prev() + assert not it.valid() + it.status() + + +def test_seek_between_keys(db): + fill(db, 10) + it = db.iterator() + it.seek(b"k0003x") + assert it.key() == b"k0004" + it.seek_for_prev(b"k0003x") + assert it.key() == b"k0003" + it.seek(b"zzz") + assert not it.valid() + it.seek_for_prev(b"\x00") + assert not it.valid() + it.seek_for_prev(b"zzz") + assert it.key() == b"k0009" + + +def test_seek_then_iterate_in_direction(db): + fill(db, 10) + it = db.iterator() + it.seek(b"k0007") + assert keys(it) == [b"k0007", b"k0008", b"k0009"] + it = db.iterator(reverse=True) + it.seek_for_prev(b"k0002") + assert keys(it) == [b"k0002", b"k0001", b"k0000"] + + +def test_bounds(db): + fill(db, 10) + assert keys(db.iterator(lower=b"k0003", upper=b"k0006")) == [b"k0003", b"k0004", b"k0005"] + assert keys(db.iterator(lower=b"k0003", upper=b"k0006", reverse=True)) == [ + b"k0005", + b"k0004", + b"k0003", + ] + assert keys(db.iterator(lower=b"k0008")) == [b"k0008", b"k0009"] + assert keys(db.iterator(upper=b"k0002")) == [b"k0000", b"k0001"] + # seeks cannot leave the window + it = db.iterator(lower=b"k0003", upper=b"k0006") + it.seek(b"k0000") + assert it.key() == b"k0003" + it.seek(b"k0009") + assert not it.valid() + it.seek_for_prev(b"k0009") + assert it.key() == b"k0005" + it.seek_to_last() + assert it.key() == b"k0005" + it.seek_to_first() + assert it.key() == b"k0003" + + +def test_prefix(db): + fill(db, 3, prefix=b"a/") + fill(db, 3, prefix=b"b/") + fill(db, 3, prefix=b"c/") + assert keys(db.iterator(prefix=b"b/")) == [b"b/0000", b"b/0001", b"b/0002"] + assert keys(db.iterator(prefix=b"b/", reverse=True)) == [b"b/0002", b"b/0001", b"b/0000"] + assert keys(db.iterator(prefix=b"zz")) == [] + with pytest.raises(ValueError): + db.iterator(prefix=b"b/", lower=b"a") + + +def test_prefix_0xff_edge(db): + db.put(b"\xff\xff", b"1") + db.put(b"\xff\xffa", b"2") + db.put(b"\xfe", b"0") + assert keys(db.iterator(prefix=b"\xff\xff")) == [b"\xff\xff", b"\xff\xffa"] + assert keys(db.iterator(prefix=b"\xfe\xff")) == [] + assert rdbpy.next_prefix(b"ab") == b"ac" + assert rdbpy.next_prefix(b"a\xff") == b"b" + assert rdbpy.next_prefix(b"\xff") is None + assert rdbpy.next_prefix(b"") is None + + +def test_with_prefix_extractor_total_order(path): + o = rdbpy.Options(create_if_missing=True, prefix_extractor_len=2, bloom_bits_per_key=10) + with rdbpy.DB(path(), o) as db: + fill(db, 3, prefix=b"aa") + fill(db, 3, prefix=b"bb") + db.flush() + it = db.iterator() + it.seek(b"ab") + assert it.key() == b"bb0000" # total order seek crosses prefixes + assert keys(db.iterator(prefix=b"bb")) == [b"bb0000", b"bb0001", b"bb0002"] + + +def test_next_batch(db): + fill(db, 10) + it = db.iterator() + assert it.next_batch(4) == [(b"k%04d" % i, b"v%04d" % i) for i in range(4)] + assert [k for k, _ in it.next_batch(4)] == [b"k%04d" % i for i in range(4, 8)] + assert [k for k, _ in it.next_batch(4)] == [b"k0008", b"k0009"] + assert it.next_batch(4) == [] + it = db.iterator(keys_only=True, reverse=True) + assert it.next_batch(3) == [b"k0009", b"k0008", b"k0007"] + assert it.next_batch() == [b"k%04d" % i for i in range(6, -1, -1)] + with pytest.raises(ValueError): + it.next_batch(0) + + +def test_next_batch_after_seek(db): + fill(db, 10) + it = db.iterator(reverse=True) + it.seek_for_prev(b"k0004") + assert [k for k, _ in it.next_batch(2)] == [b"k0004", b"k0003"] + assert [k for k, _ in it.next_batch(100)] == [b"k0002", b"k0001", b"k0000"] + + +def test_iterator_is_live_view_at_latest(db): + db.put(b"a", b"1") + it = db.iterator() + db.put(b"b", b"2") # after the iterator was created: not visible + assert keys(it) == [b"a"] + assert keys(db.iterator()) == [b"a", b"b"] + + +def test_close_and_context_manager(db): + db.put(b"a", b"1") + with db.iterator() as it: + assert keys(it) == [b"a"] + assert it.closed + with pytest.raises(RuntimeError): + it.seek_to_first() + it.close() # idempotent + + +def test_many_iterators(db): + fill(db, 10) + its = [db.iterator(lower=b"k%04d" % i) for i in range(10)] + for i, it in enumerate(its): + assert len(list(it)) == 10 - i + del its + + +def test_txn_iterator_merges_own_writes(tdb): + fill(tdb, 5) + txn = tdb.begin() + txn.put(b"k0002", b"mine") + txn.put(b"k0009", b"new") + txn.delete(b"k0000") + rows = dict(txn.iterator()) + assert rows == { + b"k0001": b"v0001", + b"k0002": b"mine", + b"k0003": b"v0003", + b"k0004": b"v0004", + b"k0009": b"new", + } + assert list(txn.iterator(keys_only=True, reverse=True))[0] == b"k0009" + assert keys(txn.iterator(prefix=b"k000", lower=None)) == [ + b"k0001", + b"k0002", + b"k0003", + b"k0004", + b"k0009", + ] + assert keys(txn.iterator(lower=b"k0002", upper=b"k0004")) == [b"k0002", b"k0003"] + it = txn.iterator() + assert it.next_batch(2) == [(b"k0001", b"v0001"), (b"k0002", b"mine")] + txn.rollback() + with pytest.raises(RuntimeError): + it.next_batch(2) + + +def test_optimistic_txn_iterator(odb): + fill(odb, 3) + txn = odb.begin() + txn.put(b"k0001", b"mine") + assert dict(txn.iterator())[b"k0001"] == b"mine" + txn.commit() + assert odb.get(b"k0001") == b"mine" + + +def test_iterator_from_txn_after_commit_raises(tdb): + tdb.put(b"a", b"1") + txn = tdb.begin() + it = txn.iterator() + txn.commit() + assert it.closed + with pytest.raises(RuntimeError): + it.seek_to_first() + + +def test_db_close_invalidates_iterators(path): + db = rdbpy.DB(path()) + db.put(b"a", b"1") + it = db.iterator() + db.close() + assert it.closed + with pytest.raises(RuntimeError): + list(it) + + +@pytest.mark.parametrize("which", ["tdb", "odb"]) +def test_txn_iterator_bounds_cover_own_writes(request, which): + # RocksDB 6.29 does not bound a transaction's pending writes; rdbpy does. + d = request.getfixturevalue(which) + for k in (b"b", b"d", b"f"): + d.put(k, b"db") + txn = d.begin() + for k in (b"a", b"c", b"e", b"g"): + txn.put(k, b"own") + assert keys(txn.iterator(lower=b"c", upper=b"e")) == [b"c", b"d"] + assert keys(txn.iterator(lower=b"c", upper=b"e", reverse=True)) == [b"d", b"c"] + assert keys(txn.iterator(lower=b"c")) == [b"c", b"d", b"e", b"f", b"g"] + assert keys(txn.iterator(lower=b"c", reverse=True)) == [b"g", b"f", b"e", b"d", b"c"] + assert keys(txn.iterator(upper=b"e", reverse=True)) == [b"d", b"c", b"b", b"a"] + assert list(txn.iterator(prefix=b"c", keys_only=True)) == [b"c"] + assert txn.iterator(lower=b"c", upper=b"e").next_batch(10) == [(b"c", b"own"), (b"d", b"db")] + it = txn.iterator(lower=b"c", upper=b"e") + it.seek(b"a") + assert it.key() == b"c" + it.seek_for_prev(b"z") + assert it.key() == b"d" + it.next() + assert not it.valid() + it.seek_to_first() + it.prev() + assert not it.valid() + txn.rollback() diff --git a/tests/test_lifetime.py b/tests/test_lifetime.py new file mode 100644 index 0000000..55c49a5 --- /dev/null +++ b/tests/test_lifetime.py @@ -0,0 +1,301 @@ +"""Lifetime of iterators, snapshots and transactions relative to their parent. + +A use-after-free here crashes the interpreter, so every scenario runs in its +own subprocess with freed memory poisoned (PYTHONMALLOC=debug for Python +objects, MALLOC_PERTURB_ / MallocScribble for native ones). A test passes +only if the child exits cleanly and printed the expected markers. +""" + +import os +import subprocess +import sys +import textwrap + +import pytest + + +PRELUDE = """ +import gc +import os +import tempfile +import threading + +import rdbpy + +TMP = tempfile.mkdtemp() +_n = [0] + + +def path(): + _n[0] += 1 + return os.path.join(TMP, "db%d" % _n[0]) + + +def txndb(p=None): + return rdbpy.TransactionDB(p or path(), lock_timeout_ms=100) + + +def plaindb(p=None): + return rdbpy.DB(p or path()) + + +def fill(db, n=2000): + for i in range(n): + db.put(b"k%06d" % i, b"v" * 64) + db.flush() + + +def raises(fn, exc=RuntimeError): + try: + fn() + except exc as e: + print("RAISED", type(e).__name__) + return + print("NO RAISE") +""" + + +def run(body: str, *expected: str) -> None: + env = dict(os.environ) + env["PYTHONMALLOC"] = "debug" + env["MALLOC_PERTURB_"] = "165" + env["MallocScribble"] = "1" + env["PYTHONPATH"] = os.pathsep.join( + p for p in [os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/src", + env.get("PYTHONPATH", "")] if p + ) + code = PRELUDE + textwrap.dedent(body) + "\nprint('DONE')\n" + proc = subprocess.run( + [sys.executable, "-c", code], env=env, capture_output=True, text=True, timeout=60 + ) + assert proc.returncode == 0, f"exit {proc.returncode}\n{proc.stdout}\n{proc.stderr}" + out = proc.stdout.splitlines() + for marker in expected: + assert marker in out, f"missing {marker!r} in {out}" + assert "DONE" in out + + +@pytest.mark.parametrize("end", ["commit", "rollback"]) +def test_txn_iterator_invalid_after_txn_ends(end): + run( + f""" + db = txndb() + fill(db) + txn = db.begin() + it = txn.iterator() + it.seek_to_first() + txn.{end}() + raises(it.valid) + raises(lambda: it.next_batch(10)) + del it + gc.collect() + db.close() + """, + "RAISED RuntimeError", + ) + + +def test_db_close_frees_children_then_objects(): + run( + """ + db = txndb() + fill(db) + it = db.iterator() + it.seek_to_first() + snap = db.snapshot() + txn = db.begin() + txn.put(b"x", b"1") + tit = txn.iterator() + db.close() + raises(it.valid) + raises(lambda: db.get(b"k000000", snapshot=snap)) + raises(lambda: txn.get(b"x")) + raises(tit.valid) + print("ACTIVE", txn.active, snap.released, it.closed) + del it, snap, txn, tit + gc.collect() + del db + gc.collect() + """, + "RAISED RuntimeError", + "ACTIVE False True True", + ) + + +def test_children_outlive_db_reference(): + run( + """ + db = plaindb() + fill(db) + it = db.iterator() + it.seek_to_first() + snap = db.snapshot() + del db + gc.collect() + print("STILL", it.valid(), snap.sequence > 0) + del it + gc.collect() + del snap + gc.collect() + """, + "STILL True True", + ) + + +def test_txn_outlives_db_reference_and_commits(): + run( + """ + p = path() + db = txndb(p) + txn = db.begin() + txn.put(b"a", b"1") + del db + gc.collect() + txn.commit() + del txn + gc.collect() + with plaindb(p) as check: + print("VALUE", check.get(b"a")) + """, + "VALUE b'1'", + ) + + +def test_gc_frees_live_txn_and_iterator_in_any_order(): + run( + """ + db = txndb() + fill(db) + txn = db.begin() + txn.put(b"a", b"1") + its = [txn.iterator() for _ in range(5)] + for it in its: + it.seek_to_first() + del its[2] + del txn + gc.collect() + print("IT", its[0].closed) + del its + gc.collect() + db.close() + """, + "IT True", + ) + + +def test_many_iterators_random_order(): + run( + """ + import random + db = txndb() + fill(db) + txn = db.begin() + objs = [db.iterator() for _ in range(50)] + [txn.iterator() for _ in range(50)] + objs += [db.snapshot() for _ in range(20)] + random.seed(7) + random.shuffle(objs) + for o in objs[:60]: + if isinstance(o, rdbpy.Iterator): + o.seek_to_first() + del objs[:60] + gc.collect() + txn.rollback() + del objs + gc.collect() + db.close() + """, + ) + + +def test_generator_finally_rolls_back_during_gc(): + run( + """ + db = txndb() + fill(db) + + def scan(): + txn = db.begin() + it = txn.iterator() + try: + for row in it: + yield row + finally: + txn.rollback() + + g = scan() + next(g) + del g # generator finalizer ends the txn while its iterator is live + gc.collect() + db.close() + """, + ) + + +def test_close_while_other_thread_collects(): + run( + """ + db = txndb() + fill(db) + stop = threading.Event() + + def churn(): + while not stop.is_set(): + gc.collect() + + t = threading.Thread(target=churn) + t.start() + for _ in range(200): + txn = db.begin() + it = txn.iterator() + it.seek_to_first() + del txn, it + db.close() + stop.set() + t.join() + """, + ) + + +def test_snapshot_after_txn_ends_and_db_closes(): + run( + """ + db = txndb() + txn = db.begin(set_snapshot=True) + view = txn.snapshot + txn.commit() + print("VIEW", view.released) + owned = db.snapshot() + db.close() + print("OWNED", owned.released) + del view, owned + gc.collect() + """, + "VIEW True", + "OWNED True", + ) + + + +def test_close_refused_while_another_thread_is_inside_a_call(): + # Closing would free the txn another thread is blocked in (a crash before). + run( + """ + import time + db = rdbpy.TransactionDB(path(), lock_timeout_ms=2000) + holder = db.begin() + holder.put(b"k", b"1") + waiter = db.begin() + out = [] + th = threading.Thread(target=lambda: out.append(waiter.get_for_update(b"k"))) + th.start() + time.sleep(0.2) + raises(db.close) + holder.rollback() + th.join() + print("GOT", out) + db.close() + raises(lambda: waiter.get(b"k")) + """, + "RAISED RuntimeError", + "GOT [None]", + ) diff --git a/tests/test_options.py b/tests/test_options.py new file mode 100644 index 0000000..1788e9e --- /dev/null +++ b/tests/test_options.py @@ -0,0 +1,125 @@ +"""Options: kwargs, properties, table options, errors.""" + +import pytest + +import rdbpy + + +def test_defaults_and_setters(): + o = rdbpy.Options() + assert o.create_if_missing is False + o.create_if_missing = True + assert o.create_if_missing is True + assert o.compression == "snappy" + o.compression = "lz4" + assert o.compression == "lz4" + o.write_buffer_size = 1 << 20 + assert o.write_buffer_size == 1 << 20 + o.max_write_buffer_size_to_maintain = -1 + assert o.max_write_buffer_size_to_maintain == -1 + o.compaction_style = "universal" + assert o.compaction_style == "universal" + + +def test_kwargs(): + o = rdbpy.Options( + create_if_missing=True, + paranoid_checks=False, + max_open_files=100, + max_background_jobs=2, + write_buffer_size=4 << 20, + max_write_buffer_number=3, + level0_file_num_compaction_trigger=4, + target_file_size_base=8 << 20, + max_bytes_for_level_base=64 << 20, + disable_auto_compactions=True, + compression="none", + bottommost_compression="zstd", + block_cache_size=16 << 20, + block_size=8192, + bloom_bits_per_key=10, + cache_index_and_filter_blocks=True, + pin_l0_filter_and_index_blocks_in_cache=True, + partition_filters=False, + whole_key_filtering=True, + format_version=5, + prefix_extractor_len=4, + ) + assert o.max_open_files == 100 + assert o.compression == "none" + assert o.bottommost_compression == "zstd" + assert o.block_cache_size == 16 << 20 + assert o.block_size == 8192 + assert o.bloom_bits_per_key == 10 + assert o.format_version == 5 + assert o.prefix_extractor_len == 4 + + +def test_unknown_kwarg(): + with pytest.raises(TypeError): + rdbpy.Options(no_such_option=1) + + +def test_bad_values(): + with pytest.raises(ValueError): + rdbpy.Options(compression="brotli") + with pytest.raises(ValueError): + rdbpy.Options(compaction_style="zigzag") + with pytest.raises((OverflowError, TypeError)): + rdbpy.Options(write_buffer_size=-1) + + +def test_wal_dir(path): + import os + + p = path() + wal = p + "_wal" + o = rdbpy.Options(create_if_missing=True, wal_dir=wal) + assert o.wal_dir == wal + with rdbpy.DB(p, o) as db: + db.put(b"a", b"1") + assert os.path.isdir(wal) + + +@pytest.mark.parametrize("compression", ["none", "snappy", "lz4", "zstd", "zlib", "bz2"]) +def test_compression_roundtrip(path, compression): + o = rdbpy.Options(create_if_missing=True, compression=compression) + with rdbpy.DB(path(), o) as db: + v = b"abc" * 10000 + db.put(b"a", v) + db.flush() + assert db.get(b"a") == v + + +def test_table_options_in_use(path): + o = rdbpy.Options( + create_if_missing=True, + block_cache_size=1 << 20, + bloom_bits_per_key=10, + cache_index_and_filter_blocks=True, + block_size=4096, + ) + with rdbpy.DB(path(), o) as db: + for i in range(1000): + db.put(b"k%05d" % i, b"x" * 100) + db.flush() + assert db.get(b"k00500") == b"x" * 100 + assert db.get(b"missing") is None + assert int(db.get_property("rocksdb.block-cache-usage")) > 0 + + +def test_no_block_cache(path): + o = rdbpy.Options(create_if_missing=True, block_cache_size=0) + with rdbpy.DB(path(), o) as db: + db.put(b"a", b"1") + db.flush() + assert db.get(b"a") == b"1" + + +def test_options_reusable_across_dbs(path): + o = rdbpy.Options(create_if_missing=True, block_size=4096) + with rdbpy.DB(path(), o) as a, rdbpy.DB(path(), o) as b: + a.put(b"a", b"1") + b.put(b"b", b"2") + assert a.get(b"b") is None + assert b.get(b"b") == b"2" diff --git a/tests/test_snapshot.py b/tests/test_snapshot.py new file mode 100644 index 0000000..d914556 --- /dev/null +++ b/tests/test_snapshot.py @@ -0,0 +1,207 @@ +"""Snapshots are honoured by every read path: write after the snapshot, +read through it, see the old value.""" + +import pytest + +import rdbpy + + +def test_db_get_honours_snapshot(db): + db.put(b"a", b"old") + snap = db.snapshot() + db.put(b"a", b"new") + db.put(b"b", b"born") + assert db.get(b"a", snapshot=snap) == b"old" + assert db.get(b"b", snapshot=snap) is None + assert db.get(b"a") == b"new" + assert db.multi_get([b"a", b"b"], snapshot=snap) == [b"old", None] + assert db.multi_get([b"a", b"b"]) == [b"new", b"born"] + snap.release() + + +def test_snapshot_sees_deletes_as_present(db): + db.put(b"a", b"old") + with db.snapshot() as snap: + db.delete(b"a") + assert db.get(b"a", snapshot=snap) == b"old" + assert db.get(b"a") is None + assert snap.released + + +def test_db_iterator_honours_snapshot(db): + db.put(b"a", b"1") + db.put(b"b", b"2") + snap = db.snapshot() + db.put(b"b", b"2b") + db.put(b"c", b"3") + db.delete(b"a") + assert list(db.iterator(snapshot=snap)) == [(b"a", b"1"), (b"b", b"2")] + assert list(db.iterator(snapshot=snap, reverse=True, keys_only=True)) == [b"b", b"a"] + assert db.iterator(snapshot=snap, prefix=b"b").next_batch() == [(b"b", b"2")] + assert list(db.iterator()) == [(b"b", b"2b"), (b"c", b"3")] + + +def test_snapshot_sequence_and_release(db): + db.put(b"a", b"1") + snap = db.snapshot() + seq = snap.sequence + assert seq == db.latest_sequence_number + db.put(b"a", b"2") + assert db.snapshot().sequence > seq + snap.release() + assert snap.released + snap.release() # idempotent + with pytest.raises(RuntimeError): + db.get(b"a", snapshot=snap) + with pytest.raises(RuntimeError): + snap.sequence + + +def test_snapshot_of_other_db_rejected(db, path): + other = rdbpy.DB(path()) + try: + snap = other.snapshot() + with pytest.raises(ValueError): + db.get(b"a", snapshot=snap) + with pytest.raises(TypeError): + db.get(b"a", snapshot=object()) + finally: + other.close() + + +def test_db_close_releases_snapshots(path): + db = rdbpy.DB(path()) + snap = db.snapshot() + db.close() + assert snap.released + snap.release() + + +@pytest.mark.parametrize("kind", ["pessimistic", "optimistic"]) +def test_txn_get_honours_explicit_snapshot(path, kind): + cls = rdbpy.TransactionDB if kind == "pessimistic" else rdbpy.OptimisticTransactionDB + db = cls(path()) + try: + db.put(b"a", b"old") + snap = db.snapshot() + db.put(b"a", b"new") + txn = db.begin() + assert txn.get(b"a", snapshot=snap) == b"old" + assert txn.get(b"a") == b"new" + # own writes win over the snapshot + txn.put(b"a", b"mine") + assert txn.get(b"a", snapshot=snap) == b"mine" + assert txn.get(b"b", snapshot=snap) is None + txn.rollback() + snap.release() + finally: + db.close() + + +@pytest.mark.parametrize("kind", ["pessimistic", "optimistic"]) +def test_txn_own_snapshot_is_default_for_reads(path, kind): + cls = rdbpy.TransactionDB if kind == "pessimistic" else rdbpy.OptimisticTransactionDB + db = cls(path()) + try: + db.put(b"a", b"old") + txn = db.begin(set_snapshot=True) + assert txn.snapshot is not None + db.put(b"a", b"new") + db.put(b"b", b"born") + assert txn.get(b"a") == b"old" + assert txn.get(b"b") is None + assert list(txn.iterator()) == [(b"a", b"old")] + assert txn.iterator(keys_only=True).next_batch() == [b"a"] + # the view is also usable on the plain db + assert db.get(b"a", snapshot=txn.snapshot) == b"old" + assert db.get(b"a") == b"new" + txn.rollback() + finally: + db.close() + + +def test_txn_set_snapshot_later(tdb): + tdb.put(b"a", b"1") + txn = tdb.begin() + assert txn.snapshot is None + tdb.put(b"a", b"2") + txn.set_snapshot() + view = txn.snapshot + tdb.put(b"a", b"3") + assert txn.get(b"a") == b"2" + assert tdb.get(b"a", snapshot=view) == b"2" + txn.set_snapshot() # moves forward, old view is gone + assert view.released + assert txn.get(b"a") == b"3" + txn.clear_snapshot() + assert txn.snapshot is None + tdb.put(b"a", b"4") + assert txn.get(b"a") == b"4" + txn.rollback() + + +def test_txn_snapshot_view_dies_with_txn(tdb): + txn = tdb.begin(set_snapshot=True) + view = txn.snapshot + txn.commit() + assert view.released + with pytest.raises(RuntimeError): + tdb.get(b"a", snapshot=view) + + +def test_get_for_update_honours_snapshot_pessimistic(tdb): + tdb.put(b"a", b"old") + txn = tdb.begin(set_snapshot=True) + tdb.put(b"a", b"new") + # key changed after the snapshot: a validated lock must fail + with pytest.raises(rdbpy.Busy): + txn.get_for_update(b"a") + # validate=False reads latest and locks + assert txn.get_for_update(b"a", validate=False) == b"new" + txn.rollback() + + # an explicit snapshot picks what is read; conflict checks always use + # the transaction's own snapshot (none here), so this locks and reads old + txn = tdb.begin() + snap = tdb.snapshot() + tdb.put(b"a", b"newer") + assert txn.get_for_update(b"a", snapshot=snap) == b"new" + assert txn.get_for_update(b"a") == b"newer" + txn.rollback() + snap.release() + + +def test_get_for_update_unchanged_key_passes_pessimistic(tdb): + tdb.put(b"a", b"old") + tdb.put(b"b", b"x") + txn = tdb.begin(set_snapshot=True) + tdb.put(b"b", b"y") # unrelated key + assert txn.get_for_update(b"a") == b"old" + txn.put(b"a", b"mine") + txn.commit() + assert tdb.get(b"a") == b"mine" + + +def test_get_for_update_honours_snapshot_optimistic(odb): + odb.put(b"a", b"old") + txn = odb.begin(set_snapshot=True) + odb.put(b"a", b"new") + assert txn.get_for_update(b"a") == b"old" # reads at the snapshot + txn.put(b"b", b"1") + with pytest.raises(rdbpy.Busy): # tracked read conflicts at commit + txn.commit() + assert not txn.active + assert odb.get(b"b") is None + + +def test_snapshot_from_db_is_pinned_across_flush(db): + db.put(b"a", b"1") + snap = db.snapshot() + for i in range(200): + db.put(b"k%04d" % i, b"x" * 1000) + db.put(b"a", b"2") + db.flush() + db.compact_range() + assert db.get(b"a", snapshot=snap) == b"1" + assert len(list(db.iterator(snapshot=snap))) == 1 + snap.release() diff --git a/tests/test_transaction.py b/tests/test_transaction.py new file mode 100644 index 0000000..f6b3911 --- /dev/null +++ b/tests/test_transaction.py @@ -0,0 +1,493 @@ +"""Transactions: pessimistic and optimistic semantics, conflicts, typed errors.""" + +import threading +import time + +import pytest + +import rdbpy + + +# --------------------------------------------------------------------------- +# basics, both flavours +# --------------------------------------------------------------------------- + + +@pytest.fixture(params=["pessimistic", "optimistic"]) +def anydb(request, path): + if request.param == "pessimistic": + d = rdbpy.TransactionDB(path(), lock_timeout_ms=200) + else: + d = rdbpy.OptimisticTransactionDB(path()) + yield d + d.close() + + +def test_read_own_writes_and_commit(anydb): + anydb.put(b"a", b"1") + txn = anydb.begin() + assert txn.active + assert txn.optimistic == isinstance(anydb, rdbpy.OptimisticTransactionDB) + assert txn.get(b"a") == b"1" + txn.put(b"a", b"2") + txn.put(b"b", b"3") + txn.delete(b"a") + assert txn.get(b"a") is None + assert txn.get(b"b") == b"3" + assert anydb.get(b"b") is None # not visible outside before commit + assert txn.num_keys == 2 + txn.commit() + assert txn.committed + assert not txn.active + assert anydb.get(b"a") is None + assert anydb.get(b"b") == b"3" + + +def test_rollback_discards(anydb): + anydb.put(b"a", b"1") + txn = anydb.begin() + txn.put(b"a", b"2") + txn.rollback() + assert not txn.active + assert not txn.committed + assert anydb.get(b"a") == b"1" + txn.rollback() # idempotent + + +def test_ended_txn_raises(anydb): + txn = anydb.begin() + txn.commit() + for call in ( + lambda: txn.get(b"a"), + lambda: txn.put(b"a", b"1"), + lambda: txn.delete(b"a"), + lambda: txn.get_for_update(b"a"), + lambda: txn.iterator(), + lambda: txn.set_snapshot(), + lambda: txn.commit(), + lambda: txn.id, + ): + with pytest.raises(RuntimeError): + call() + txn.rollback() # no-op + + +def test_context_manager_rolls_back(anydb): + with anydb.begin() as txn: + txn.put(b"a", b"1") + assert not txn.active + assert anydb.get(b"a") is None + with anydb.begin() as txn: + txn.put(b"a", b"1") + txn.commit() + assert anydb.get(b"a") == b"1" + with pytest.raises(ZeroDivisionError): + with anydb.begin() as txn: + txn.put(b"a", b"2") + 1 / 0 + assert anydb.get(b"a") == b"1" + + +def test_db_close_rolls_back_live_txn(path): + db = rdbpy.TransactionDB(path()) + txn = db.begin() + txn.put(b"a", b"1") + db.close() + assert not txn.active + with rdbpy.DB(db.path) as plain: + assert plain.get(b"a") is None + + +def test_many_sequential_txns(anydb): + for i in range(200): + txn = anydb.begin() + txn.put(b"k", b"%d" % i) + txn.commit() + assert anydb.get(b"k") == b"199" + + +def test_write_options_on_begin(anydb): + txn = anydb.begin(sync=True, disable_wal=False) + txn.put(b"a", b"1") + txn.commit() + txn = anydb.begin(disable_wal=True) + txn.put(b"b", b"2") + txn.commit() + assert anydb.multi_get([b"a", b"b"]) == [b"1", b"2"] + + +def test_txn_id(tdb): + a = tdb.begin() + b = tdb.begin() + assert a.id != b.id + a.rollback() + b.rollback() + + +# --------------------------------------------------------------------------- +# pessimistic: locks, timeouts, deadlocks +# --------------------------------------------------------------------------- + + +def test_get_for_update_conflict_times_out(tdb): + tdb.put(b"a", b"1") + t1 = tdb.begin() + assert t1.get_for_update(b"a") == b"1" + t2 = tdb.begin(lock_timeout_ms=100) + t0 = time.monotonic() + with pytest.raises(rdbpy.TimedOut) as ei: + t2.get_for_update(b"a") + assert time.monotonic() - t0 < 1.0 + assert ei.value.code == 9 + with pytest.raises(rdbpy.TimedOut): + t2.put(b"a", b"2") + with pytest.raises(rdbpy.TimedOut): + t2.delete(b"a") + # plain reads are never blocked + assert t2.get(b"a") == b"1" + assert tdb.get(b"a") == b"1" + t1.put(b"a", b"mine") + t1.commit() + # lock released: t2 can proceed now and sees the committed value + assert t2.get_for_update(b"a") == b"mine" + t2.rollback() + + +def test_lock_timeout_zero_fails_immediately(tdb): + t1 = tdb.begin() + t1.put(b"a", b"1") + t2 = tdb.begin(lock_timeout_ms=0) + t0 = time.monotonic() + with pytest.raises(rdbpy.TimedOut): + t2.put(b"a", b"2") + assert time.monotonic() - t0 < 0.1 + t1.rollback() + t2.rollback() + + +def test_db_level_default_lock_timeout(path): + db = rdbpy.TransactionDB(path(), lock_timeout_ms=50, default_lock_timeout_ms=50) + try: + t1 = db.begin() + t1.put(b"a", b"1") + t0 = time.monotonic() + with pytest.raises(rdbpy.TimedOut): + db.put(b"a", b"2") # plain put also takes the lock + with pytest.raises(rdbpy.TimedOut): + db.begin().put(b"a", b"3") + assert time.monotonic() - t0 < 1.0 + t1.rollback() + db.put(b"a", b"2") + assert db.get(b"a") == b"2" + finally: + db.close() + + +def test_shared_locks_allow_concurrent_readers(tdb): + tdb.put(b"a", b"1") + t1 = tdb.begin() + t2 = tdb.begin() + assert t1.get_for_update(b"a", exclusive=False) == b"1" + assert t2.get_for_update(b"a", exclusive=False) == b"1" + with pytest.raises(rdbpy.TimedOut): + t2.put(b"a", b"2") # upgrade blocked by t1's shared lock + t1.rollback() + t2.put(b"a", b"2") + t2.commit() + assert tdb.get(b"a") == b"2" + + +def test_lock_wait_succeeds_when_holder_commits(tdb): + tdb.put(b"a", b"1") + t1 = tdb.begin() + t1.get_for_update(b"a") + t2 = tdb.begin(lock_timeout_ms=2000) + got = [] + + def waiter(): + got.append(t2.get_for_update(b"a")) + + th = threading.Thread(target=waiter) + th.start() + time.sleep(0.1) + assert th.is_alive() + t1.put(b"a", b"2") + t1.commit() + th.join(timeout=3) + assert not th.is_alive() + assert got == [b"2"] + t2.rollback() + + +def test_deadlock_detection(tdb): + tdb.put(b"a", b"1") + tdb.put(b"b", b"1") + t1 = tdb.begin(lock_timeout_ms=5000, deadlock_detect=True) + t2 = tdb.begin(lock_timeout_ms=5000, deadlock_detect=True) + t1.put(b"a", b"t1") + t2.put(b"b", b"t2") + done = threading.Event() + outcome = [] + + def t1_waits_for_b(): + try: + t1.put(b"b", b"t1") + outcome.append("ok") + except rdbpy.RocksDBError as e: + outcome.append(type(e).__name__) + done.set() + + th = threading.Thread(target=t1_waits_for_b) + th.start() + time.sleep(0.1) + t0 = time.monotonic() + with pytest.raises(rdbpy.Deadlock) as ei: + t2.put(b"a", b"t2") # closes the cycle: detected at once + assert time.monotonic() - t0 < 1.0 + assert isinstance(ei.value, rdbpy.Busy) + assert ei.value.subcode == 5 + t2.rollback() # frees b, t1 proceeds + assert done.wait(3) + assert outcome == ["ok"] + t1.commit() + assert tdb.get(b"a") == b"t1" + assert tdb.get(b"b") == b"t1" + + +def test_no_deadlock_detect_times_out_instead(tdb): + t1 = tdb.begin(lock_timeout_ms=300) + t2 = tdb.begin(lock_timeout_ms=300) + t1.put(b"a", b"1") + t2.put(b"b", b"1") + th = threading.Thread(target=lambda: pytest.raises(rdbpy.RocksDBError, t1.put, b"b", b"1")) + th.start() + time.sleep(0.05) + with pytest.raises(rdbpy.TimedOut): + t2.put(b"a", b"1") + th.join() + t1.rollback() + t2.rollback() + + +def test_expiration(path): + db = rdbpy.TransactionDB(path()) + try: + txn = db.begin(expiration_ms=50) + txn.put(b"a", b"1") + time.sleep(0.15) + with pytest.raises(rdbpy.Expired): + txn.commit() + assert not txn.active + assert db.get(b"a") is None + finally: + db.close() + + +def test_lock_limit(path): + db = rdbpy.TransactionDB(path(), max_num_locks=2) + try: + txn = db.begin() + txn.put(b"a", b"1") + txn.put(b"b", b"1") + with pytest.raises(rdbpy.LockLimit) as ei: + txn.put(b"c", b"1") + assert ei.value.subcode == 3 + txn.rollback() + finally: + db.close() + + +def test_pessimistic_commit_after_snapshot_write_conflict(tdb): + # put (no snapshot) locks the key: the other writer times out, no Busy. + tdb.put(b"a", b"1") + t1 = tdb.begin() + t1.put(b"a", b"t1") + with pytest.raises(rdbpy.TimedOut): + tdb.put(b"a", b"outside") + t1.commit() + assert tdb.get(b"a") == b"t1" + + +def test_pessimistic_put_with_snapshot_detects_conflict(tdb): + tdb.put(b"a", b"1") + t1 = tdb.begin(set_snapshot=True) + tdb.put(b"a", b"outside") + with pytest.raises(rdbpy.Busy): + t1.put(b"a", b"t1") + t1.rollback() + + +# --------------------------------------------------------------------------- +# optimistic: validation at commit +# --------------------------------------------------------------------------- + + +def test_optimistic_commit_conflict_on_written_key(odb): + odb.put(b"a", b"1") + t1 = odb.begin() + t1.put(b"a", b"t1") + odb.put(b"a", b"outside") # no locks: this goes through + with pytest.raises(rdbpy.Busy) as ei: + t1.commit() + assert ei.value.code == 11 + assert not t1.active + assert odb.get(b"a") == b"outside" + + +def test_optimistic_two_txns_first_wins(odb): + odb.put(b"counter", b"0") + t1 = odb.begin() + t2 = odb.begin() + v1 = int(t1.get_for_update(b"counter")) + v2 = int(t2.get_for_update(b"counter")) + t1.put(b"counter", b"%d" % (v1 + 1)) + t2.put(b"counter", b"%d" % (v2 + 1)) + t1.commit() + with pytest.raises(rdbpy.Busy): + t2.commit() + assert odb.get(b"counter") == b"1" + + +def test_optimistic_untracked_read_does_not_conflict(odb): + odb.put(b"a", b"1") + t1 = odb.begin() + assert t1.get(b"a") == b"1" # plain get: not tracked + odb.put(b"a", b"2") + t1.put(b"b", b"1") + t1.commit() # fine + assert odb.get(b"b") == b"1" + + +def test_optimistic_tracked_read_conflicts(odb): + odb.put(b"a", b"1") + t1 = odb.begin() + assert t1.get_for_update(b"a") == b"1" + odb.put(b"a", b"2") + t1.put(b"b", b"1") + with pytest.raises(rdbpy.Busy): + t1.commit() + assert odb.get(b"b") is None + + +def test_optimistic_tracked_missing_key_conflicts_on_insert(odb): + t1 = odb.begin() + assert t1.get_for_update(b"new") is None + odb.put(b"new", b"someone") + t1.put(b"other", b"1") + with pytest.raises(rdbpy.Busy): + t1.commit() + + +def test_optimistic_no_conflict_commits(odb): + odb.put(b"a", b"1") + t1 = odb.begin(set_snapshot=True) + assert t1.get_for_update(b"a") == b"1" + odb.put(b"unrelated", b"x") + t1.put(b"a", b"2") + t1.commit() + assert odb.get(b"a") == b"2" + + +def test_optimistic_serial_policy(path): + db = rdbpy.OptimisticTransactionDB(path(), validate_policy="serial") + try: + t = db.begin() + t.put(b"a", b"1") + db.put(b"a", b"2") + with pytest.raises(rdbpy.Busy): + t.commit() + finally: + db.close() + with pytest.raises(ValueError): + rdbpy.OptimisticTransactionDB(path(), validate_policy="nope") + + +def test_optimistic_survives_flush_with_history(path): + # The txn outlives a memtable flush; with memtable history kept the commit + # validates (TryAgain would mean history was too short). + db = rdbpy.OptimisticTransactionDB( + path(), rdbpy.Options(create_if_missing=True, max_write_buffer_size_to_maintain=-1) + ) + try: + db.put(b"a", b"1") + t = db.begin() + t.get_for_update(b"a") + for i in range(100): + db.put(b"k%d" % i, b"x" * 100) + db.flush() + t.put(b"b", b"1") + t.commit() + assert db.get(b"b") == b"1" + finally: + db.close() + + +def _options_file_value(dbpath, name): + import glob + + f = sorted(glob.glob(dbpath + "/OPTIONS-*"))[-1] + for line in open(f): + line = line.strip() + if line.startswith(name + "="): + return int(line.split("=", 1)[1]) + raise AssertionError(name) + + +def test_optimistic_keeps_memtable_history_by_default(path): + p = path() + db = rdbpy.OptimisticTransactionDB(p, rdbpy.Options(create_if_missing=True)) + db.close() + assert _options_file_value(p, "max_write_buffer_size_to_maintain") > 0 + # An explicit size from the caller is kept as is. + p = path() + db = rdbpy.OptimisticTransactionDB( + p, rdbpy.Options(create_if_missing=True, max_write_buffer_size_to_maintain=1 << 20) + ) + db.close() + assert _options_file_value(p, "max_write_buffer_size_to_maintain") == 1 << 20 + + +def test_optimistic_commit_after_flush_default_options(odb): + odb.put(b"a", b"1") + odb.flush() + t = odb.begin() + assert t.get_for_update(b"a") == b"1" + t.put(b"a", b"2") + t.commit() + assert odb.get(b"a") == b"2" + # A txn that outlives a flush still validates. + t = odb.begin() + assert t.get_for_update(b"a") == b"2" + for i in range(100): + odb.put(b"k%d" % i, b"x" * 100) + odb.flush() + t.put(b"a", b"3") + t.commit() + assert odb.get(b"a") == b"3" + + +def test_optimistic_real_conflict_after_flush_is_busy(odb): + odb.put(b"a", b"1") + odb.flush() + t = odb.begin() + assert t.get_for_update(b"a") == b"1" + odb.put(b"a", b"outside") + odb.flush() # the conflicting write is now only in memtable history / SST + t.put(b"a", b"2") + with pytest.raises(rdbpy.Busy): + t.commit() + assert odb.get(b"a") == b"outside" + + +def test_get_for_update_validate_false_rejects_snapshot(anydb): + anydb.put(b"a", b"1") + t = anydb.begin() + s = anydb.snapshot() + try: + with pytest.raises(ValueError): + t.get_for_update(b"a", validate=False, snapshot=s) + assert t.get_for_update(b"a", validate=False) == b"1" + assert t.get_for_update(b"a", snapshot=s) == b"1" + finally: + t.rollback() + s.release()