Skip to main content

Database

The Database class is the main entry point for interacting with jasonisnthappy. It manages database connections, transactions, collections, and database-level operations.

Opening a database

Database.open()

Opens a database at the specified path with default options.
static open(path: string): Database
path
string
required
Path to the database file. If the file doesn’t exist, it will be created.
Database
Database
A new Database instance
Example
import { Database } from '@sohzm/jasonisnthappy';

const db = Database.open('./my-database.db');

Database.openWithOptions()

Opens a database with custom configuration options.
static openWithOptions(path: string, options: DatabaseOptions): Database
path
string
required
Path to the database file
options
DatabaseOptions
required
Configuration options for the database
Example
import { Database } from '@sohzm/jasonisnthappy';

const db = Database.openWithOptions('./my-database.db', {
  cacheSize: 1024 * 1024 * 50, // 50MB cache
  autoCheckpointThreshold: 1000,
  readOnly: false,
  maxBulkOperations: 10000,
  maxDocumentSize: 1024 * 1024 * 5 // 5MB per document
});

Database.defaultDatabaseOptions()

Returns the default database options.
static defaultDatabaseOptions(): DatabaseOptions
options
DatabaseOptions
The default configuration options
Example
const defaults = Database.defaultDatabaseOptions();
console.log(defaults);

Database information

getPath()

Returns the file path of the database.
getPath(): string
path
string
The absolute path to the database file

isReadOnly()

Checks if the database is opened in read-only mode.
isReadOnly(): boolean
readOnly
boolean
true if database is read-only, false otherwise

databaseInfo()

Returns comprehensive information about the database.
databaseInfo(): DatabaseInfo
info
DatabaseInfo
Database metadata and statistics
Example
const info = db.databaseInfo();
console.log(`Database: ${info.path}`);
console.log(`Total documents: ${info.total_documents}`);
console.log(`File size: ${info.file_size} bytes`);

maxBulkOperations()

Returns the maximum number of operations allowed in a bulk write.
maxBulkOperations(): number

maxDocumentSize()

Returns the maximum document size in bytes.
maxDocumentSize(): number

maxRequestBodySize()

Returns the maximum request body size for the web server.
maxRequestBodySize(): number

Collections

listCollections()

Returns an array of all collection names in the database.
listCollections(): string[]
collections
string[]
Array of collection names
Example
const collections = db.listCollections();
console.log('Collections:', collections);
// Output: Collections: ['users', 'posts', 'comments']

getCollection()

Returns a typed Collection instance for performing operations.
getCollection<T extends Document>(name: string): Collection<T>
name
string
required
Name of the collection
collection
Collection<T>
A typed Collection instance
Example
interface User extends Document {
  _id: string;
  name: string;
  email: string;
  age: number;
}

const users = db.getCollection<User>('users');
const user = users.findById('user123');

collectionStats()

Returns detailed statistics for a specific collection.
collectionStats(collectionName: string): CollectionInfo
collectionName
string
required
Name of the collection
stats
CollectionInfo
Collection metadata and statistics
Example
const stats = db.collectionStats('users');
console.log(`Documents: ${stats.document_count}`);
console.log(`Indexes: ${stats.indexes.length}`);

Indexes

listIndexes()

Returns all indexes for a collection.
listIndexes(collectionName: string): IndexInfo[]
collectionName
string
required
Name of the collection
indexes
IndexInfo[]
Array of index information

createIndex()

Creates a single-field index.
creatIndex(collectionName: string, indexName: string, field: string, unique: boolean): void
collectionName
string
required
Name of the collection
indexName
string
required
Name for the new index
field
string
required
Field to index
unique
boolean
required
Whether to enforce uniqueness constraint
Example
// Create unique index on email field
db.createIndex('users', 'email_idx', 'email', true);

// Create non-unique index on age field
db.createIndex('users', 'age_idx', 'age', false);

createCompoundIndex()

Creates a multi-field compound index.
createCompoundIndex(collectionName: string, indexName: string, fields: string[], unique: boolean): void
collectionName
string
required
Name of the collection
indexName
string
required
Name for the new index
fields
string[]
required
Array of field names to include in the index
unique
boolean
required
Whether to enforce uniqueness constraint
Example
// Create compound index on lastName and firstName
db.createCompoundIndex('users', 'name_idx', ['lastName', 'firstName'], false);

createTextIndex()

Creates a full-text search index on a field.
createTextIndex(collectionName: string, indexName: string, field: string): void
collectionName
string
required
Name of the collection
indexName
string
required
Name for the new text index
field
string
required
Field to index for full-text search
Example
// Create text index for searching post content
db.createTextIndex('posts', 'content_text_idx', 'content');

dropIndex()

Drops an index from a collection.
dropIndex(collectionName: string, indexName: string): void
collectionName
string
required
Name of the collection
indexName
string
required
Name of the index to drop
Example
db.dropIndex('users', 'email_idx');

Schema validation

setSchema()

Sets a JSON schema for validating documents in a collection.
setSchema(collectionName: string, schema: Record<string, unknown>): void
collectionName
string
required
Name of the collection
schema
Record<string, unknown>
required
JSON Schema object for validation
Example
db.setSchema('users', {
  type: 'object',
  required: ['name', 'email'],
  properties: {
    name: { type: 'string', minLength: 1 },
    email: { type: 'string', format: 'email' },
    age: { type: 'number', minimum: 0 }
  }
});

getSchema()

Retrieves the current schema for a collection.
getSchema(collectionName: string): Record<string, unknown> | null
collectionName
string
required
Name of the collection
schema
Record<string, unknown> | null
The JSON Schema object, or null if no schema is set

removeSchema()

Removes the schema validation from a collection.
removeSchema(collectionName: string): void
collectionName
string
required
Name of the collection

Transactions

beginTransaction()

Starts a new transaction.
beginTransaction(): Transaction
transaction
Transaction
A new Transaction instance
Example
const txn = db.beginTransaction();

try {
  txn.insert('users', { name: 'Alice', email: 'alice@example.com' });
  txn.insert('users', { name: 'Bob', email: 'bob@example.com' });
  txn.commit();
} catch (error) {
  txn.rollback();
  throw error;
}

defaultTransactionConfig()

Returns the default transaction configuration.
defaultTransactionConfig(): TransactionConfig
config
TransactionConfig
Default transaction retry configuration

setTransactionConfig()

Sets the transaction retry configuration.
setTransactionConfig(config: TransactionConfig): void
config
TransactionConfig
required
Transaction retry configuration
Example
db.setTransactionConfig({
  maxRetries: 5,
  retryBackoffBaseMs: 10,
  maxRetryBackoffMs: 1000
});

getTransactionConfig()

Gets the current transaction retry configuration.
getTransactionConfig(): TransactionConfig
config
TransactionConfig
Current transaction retry configuration

Maintenance operations

checkpoint()

Forces a checkpoint, writing all in-memory changes to disk.
checkpoint(): void
Example
db.checkpoint();
console.log('Database checkpointed');

setAutoCheckpointThreshold()

Sets the auto-checkpoint threshold.
setAutoCheckpointThreshold(threshold: number): void
threshold
number
required
Number of pages written before auto-checkpoint triggers

garbageCollect()

Runs garbage collection to reclaim deleted pages.
garbageCollect(): GarbageCollectResult
result
GarbageCollectResult
Statistics about freed resources
Example
const result = db.garbageCollect();
console.log(`Freed ${result.pages_freed} pages (${result.bytes_freed} bytes)`);

frameCount()

Returns the current number of frames in the page cache.
frameCount(): number
count
number
Number of cached pages

Backup and restore

backup()

Creates a backup of the database.
backup(destPath: string): void
destPath
string
required
Destination path for the backup file
Example
db.backup('./backup/my-database-backup.db');
console.log('Backup created successfully');

Database.verifyBackup()

Verifies and returns information about a backup file.
static verifyBackup(backupPath: string): BackupInfo
backupPath
string
required
Path to the backup file to verify
info
BackupInfo
Backup file metadata
Example
const backupInfo = Database.verifyBackup('./backup/my-database-backup.db');
console.log(`Backup contains ${backupInfo.total_documents} documents`);
console.log(`Collections: ${backupInfo.collections.join(', ')}`);

Metrics

metrics()

Returns database operation metrics.
metrics(): MetricsSnapshot
metrics
MetricsSnapshot
Database operation statistics
Example
const metrics = db.metrics();
console.log(`Reads: ${metrics.documents_read}`);
console.log(`Writes: ${metrics.documents_written}`);
console.log(`Conflicts: ${metrics.transaction_conflicts}`);

Web server

startWebUi()

Starts a web-based admin interface for the database.
startWebUi(addr: string): WebServer
addr
string
required
Address and port to bind the web server (e.g., “127.0.0.1:8080”)
server
WebServer
A WebServer instance that can be stopped
Example
const server = db.startWebUi('127.0.0.1:8080');
console.log('Web UI started at http://127.0.0.1:8080');

// Later, stop the server
server.stop();

Closing the database

close()

Closes the database and releases resources.
close(): void
Example
db.close();
console.log('Database closed');

Build docs developers (and LLMs) love