Examples

This section provides concise examples of how to use the pyrex library, a Python wrapper for RocksDB. The examples focus on demonstrating core functionalities directly.

Basic Put and Get

Open a database, store a key-value pair, and retrieve it.

basic_put_get.py
 1import pyrex
 2import os
 3import shutil
 4
 5db_path = "/tmp/pyrex_example_basic"
 6if os.path.exists(db_path):
 7    shutil.rmtree(db_path)
 8
 9db = pyrex.PyRocksDB(db_path)
10
11# Put a key-value pair
12db.put(b"my_key", b"my_value")
13
14# Get the value
15value = db.get(b"my_key")
16print(f"Retrieved: {value.decode()}") # Expected: my_value
17
18# Get a non-existent key
19none_value = db.get(b"non_existent")
20print(f"Retrieved non-existent: {none_value}") # Expected: None
21
22del db # Close the DB
23shutil.rmtree(db_path) # Clean up

Configuring Options

Customize database behavior using PyOptions.

config_options.py
 1import pyrex
 2import os
 3import shutil
 4
 5db_path = "/tmp/pyrex_example_config"
 6if os.path.exists(db_path):
 7    shutil.rmtree(db_path)
 8
 9options = pyrex.PyOptions()
10options.create_if_missing = True
11options.max_open_files = 1000
12options.compression = pyrex.CompressionType.kLZ4Compression
13options.optimize_for_small_db() # Apply an optimization preset
14
15db = pyrex.PyRocksDB(db_path, options)
16
17# Verify some configured options (values might be adjusted by RocksDB internally)
18retrieved_options = db.get_options()
19print(f"Configured max_open_files: {retrieved_options.max_open_files}") # Expected: 5000 (adjusted by optimize_for_small_db)
20print(f"Configured compression: {retrieved_options.compression}") # Expected: CompressionType.kLZ4Compression
21
22del db
23shutil.rmtree(db_path)

Atomic Write Batch

Perform multiple put and delete operations in a single, atomic transaction.

write_batch.py
 1import pyrex
 2import os
 3import shutil
 4
 5db_path = "/tmp/pyrex_example_batch"
 6if os.path.exists(db_path):
 7    shutil.rmtree(db_path)
 8
 9db = pyrex.PyRocksDB(db_path)
10
11# Prepare some initial data
12db.put(b"key1", b"value1")
13db.put(b"key2", b"value2")
14
15# Create a write batch
16batch = pyrex.PyWriteBatch()
17batch.put(b"key3", b"value3")       # Add new key
18batch.delete(b"key1")               # Delete existing key
19batch.put(b"key2", b"updated_value2") # Update existing key
20
21db.write(batch) # Apply the batch atomically
22
23# Verify results
24print(f"Key1: {db.get(b'key1')}")       # Expected: None
25print(f"Key2: {db.get(b'key2').decode()}") # Expected: updated_value2
26print(f"Key3: {db.get(b'key3').decode()}") # Expected: value3
27
28del db
29shutil.rmtree(db_path)

Iterating Data

Traverse key-value pairs using PyRocksDBIterator for forward and backward scans.

iterator_usage.py
 1import pyrex
 2import os
 3import shutil
 4
 5db_path = "/tmp/pyrex_example_iterator"
 6if os.path.exists(db_path):
 7    shutil.rmtree(db_path)
 8
 9db = pyrex.PyRocksDB(db_path)
10
11# Insert sample data
12db.put(b"alpha", b"A")
13db.put(b"beta", b"B")
14db.put(b"gamma", b"G")
15
16it = db.new_iterator()
17
18print("Forward iteration:")
19it.seek_to_first()
20while it.valid():
21    print(f"  Key: {it.key().decode()}, Value: {it.value().decode()}")
22    it.next()
23it.check_status() # Check for errors
24
25print("\nSeek and backward iteration:")
26it.seek(b"gamma") # Seek to 'gamma'
27while it.valid():
28    print(f"  Key: {it.key().decode()}, Value: {it.value().decode()}")
29    it.prev() # Move backward
30
31del db
32shutil.rmtree(db_path)

Error Handling

Catch RocksDB-specific exceptions for robust applications.

error_handling.py
 1import pyrex
 2import os
 3import shutil
 4
 5db_path = "/tmp/pyrex_example_error"
 6if os.path.exists(db_path):
 7    shutil.rmtree(db_path)
 8
 9# Create an options object to trigger an error
10options = pyrex.PyOptions()
11options.create_if_missing = True
12options.error_if_exists = True
13
14try:
15    # First open creates the DB
16    db1 = pyrex.PyRocksDB(db_path, options)
17    db1.put(b"foo", b"bar")
18    del db1 # Close it so we can try to open again
19
20    # This second open should fail because error_if_exists is True
21    print("Attempting to open existing DB with error_if_exists=True...")
22    db2 = pyrex.PyRocksDB(db_path, options) # This line should raise an exception
23    print("This line should not be reached.") # If it is, the error wasn't caught
24except pyrex.RocksDBException as e:
25    print(f"Caught expected RocksDBException: {e}")
26    # Assert that the error message contains the expected string
27    assert "exists (error_if_exists is true)" in str(e)
28finally:
29    # Clean up the database directory regardless of success or failure
30    if os.path.exists(db_path):
31        shutil.rmtree(db_path)
32        print(f"Cleaned up database at {db_path}")