Database Operations
Learn how to open, configure, and manage jasonisnthappy databases
Opening a Database
Open or create a database file. If the file doesn't exist, it will be created automatically. The database uses write-ahead logging (WAL), so you'll also see a .db-wal file.
use jasonisnthappy::Database;
let db = Database::open("path/to/database.db")?;
from jasonisnthappy import Database
db = Database.open("./mydb.db")
import { Database } from 'jasonisnthappy';
const db = Database.open('./mydb.db');
import jasonisnthappy "github.com/jasonisnthappy/jasonisnthappy-rs/bindings/go"
db, err := jasonisnthappy.Open("./mydb.db")
if err != nil {
log.Fatal(err)
}
Opening with Custom Options
Configure cache size, checkpoint threshold, file permissions, and read-only mode:
use jasonisnthappy::{Database, DatabaseOptions};
let options = DatabaseOptions {
cache_size: 1000,
auto_checkpoint_threshold: 1000,
file_permissions: 0o644,
read_only: false,
};
let db = Database::open_with_options("mydb.db", options)?;
from jasonisnthappy import Database
options = Database.default_database_options()
options.cache_size = 1000
options.auto_checkpoint_threshold = 1000
options.file_permissions = 0o644
options.read_only = False
db = Database.open_with_options("./mydb.db", options)
import { Database } from 'jasonisnthappy';
const options = {
cacheSize: 1000,
autoCheckpointThreshold: 1000,
filePermissions: 0o644,
readOnly: false
};
const db = Database.openWithOptions('./mydb.db', options);
import jasonisnthappy "github.com/jasonisnthappy/jasonisnthappy-rs/bindings/go"
options := jasonisnthappy.DatabaseOptions{
CacheSize: 1000,
AutoCheckpointThreshold: 1000,
FilePermissions: 0o644,
ReadOnly: false,
}
db, err := jasonisnthappy.OpenWithOptions("./mydb.db", options)
Closing a Database
Always close the database before your application exits. This ensures all pending writes are flushed to disk.
db.close()?;
# Manual close
db.close()
# Or use context manager for automatic cleanup
with Database.open("./mydb.db") as db:
# Database automatically closed on exit
pass
await db.close();
db.Close()
// Or use defer for automatic cleanup
defer db.Close()
Configuration
Transaction Configuration
Configure retry behavior for transactions including max retries and backoff timing:
use jasonisnthappy::TransactionConfig;
let config = TransactionConfig {
max_retries: 5,
retry_backoff_base_ms: 10,
max_retry_backoff_ms: 1000,
};
db.set_transaction_config(config)?;
// Get current config
let current = db.get_transaction_config()?;
println!("Max retries: {}", current.max_retries);
config = Database.default_transaction_config()
config.max_retries = 5
config.retry_backoff_base_ms = 10
config.max_retry_backoff_ms = 1000
db.set_transaction_config(config)
# Get current config
current = db.get_transaction_config()
print(f"Max retries: {current.max_retries}")
db.setTransactionConfig({
maxRetries: 5,
retryBackoffBaseMs: 10,
maxRetryBackoffMs: 1000
});
// Get current config
const config = db.getTransactionConfig();
console.log('Max retries:', config.maxRetries);
config := jasonisnthappy.TransactionConfig{
MaxRetries: 5,
RetryBackoffBaseMs: 10,
MaxRetryBackoffMs: 1000,
}
db.SetTransactionConfig(config)
// Get current config
current, err := db.GetTransactionConfig()
fmt.Printf("Max retries: %d\n", current.MaxRetries)
Auto-Checkpoint Threshold
Set the WAL (Write-Ahead Log) auto-checkpoint threshold in frames. When the WAL grows to this size, it will automatically checkpoint:
db.set_auto_checkpoint_threshold(1000)?;
db.set_auto_checkpoint_threshold(1000)
db.setAutoCheckpointThreshold(1000);
db.SetAutoCheckpointThreshold(1000)
Database Information
Get Database Path
Returns the file path of the database:
let path = db.path();
println!("Database: {}", path);
path = db.get_path()
print(f"Database: {path}")
const path = db.getPath();
console.log('Database:', path);
path, err := db.GetPath()
fmt.Printf("Database: %s\n", path)
Check Read-Only Mode
Check if the database was opened in read-only mode:
if db.is_read_only() {
println!("Database is read-only");
}
if db.is_read_only():
print("Database is read-only")
if (db.isReadOnly()) {
console.log('Database is read-only');
}
if readOnly, _ := db.IsReadOnly(); readOnly {
fmt.Println("Database is read-only")
}
Database Info and Metrics
Get comprehensive information about the database including collections, size, and performance metrics:
// Get database information
let info = db.info()?;
println!("{:?}", info);
// Get performance metrics
let metrics = db.metrics()?;
println!("{:?}", metrics);
// Get WAL frame count
let frames = db.frame_count()?;
println!("WAL frames: {}", frames);
# Get database information
info = db.database_info()
print(info)
# Get performance metrics
metrics = db.metrics()
print(metrics)
# Get WAL frame count
frames = db.frame_count()
print(f"WAL frames: {frames}")
// Get database information
const info = db.databaseInfo();
console.log(info);
// Get performance metrics
const metrics = db.metrics();
console.log(metrics);
// Get WAL frame count
const frames = db.frameCount();
console.log('WAL frames:', frames);
// Get database information
info, err := db.DatabaseInfo()
fmt.Printf("%+v\n", info)
// Get performance metrics
metrics, err := db.Metrics()
fmt.Printf("%+v\n", metrics)
// Get WAL frame count
frames, err := db.FrameCount()
fmt.Printf("WAL frames: %d\n", frames)
Collection Management
List Collections
Get a list of all collections in the database:
let collections = db.list_collections()?;
for name in collections {
println!("Collection: {}", name);
}
collections = db.list_collections()
for name in collections:
print(f"Collection: {name}")
const collections = db.listCollections();
collections.forEach(name => {
console.log('Collection:', name);
});
collections, err := db.ListCollections()
for _, name := range collections {
fmt.Printf("Collection: %s\n", name)
}
Collection Statistics
Get statistics for a specific collection including document count and size:
let stats = db.collection_stats("users")?;
println!("Documents: {}", stats.document_count);
stats = db.collection_stats("users")
print(f"Documents: {stats['document_count']}")
const stats = db.collectionStats('users');
console.log('Documents:', stats.document_count);
stats, err := db.CollectionStats("users")
fmt.Printf("Documents: %v\n", stats["document_count"])
Get Collection Handle
Get a handle to a collection for performing operations:
let users = db.collection("users");
# Get collection handle
coll = db.get_collection("users")
try:
# Use collection...
pass
finally:
coll.close()
const users = db.collection('users');
users := db.Collection("users")
Maintenance Operations
Manual Checkpoint
Manually checkpoint the WAL to flush changes to the main database file:
db.checkpoint()?;
db.checkpoint()
db.checkpoint();
err := db.Checkpoint()
Create Backup
Create a consistent backup of the database:
db.backup("backup.db")?;
db.backup("./backup.db")
db.backup('./backup.db');
err := db.Backup("./backup.db")
Verify Backup
Verify the integrity of a backup file:
match Database::verify_backup("backup.db") {
Ok(_) => println!("Backup is valid"),
Err(e) => eprintln!("Backup invalid: {}", e),
}
try:
Database.verify_backup("./backup.db")
print("Backup is valid")
except RuntimeError as e:
print(f"Backup invalid: {e}")
try {
const info = Database.verifyBackup('./backup.db');
console.log('Backup is valid:', info);
} catch (err) {
console.error('Backup invalid:', err);
}
info, err := jasonisnthappy.VerifyBackup("./backup.db")
if err != nil {
fmt.Printf("Backup invalid: %v\n", err)
} else {
fmt.Printf("Backup is valid: %+v\n", info)
}
Garbage Collection
Perform garbage collection to reclaim space:
db.garbage_collect()?;
db.garbage_collect()
db.garbageCollect();
err := db.GarbageCollect()