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 to the database file. If the file doesn’t exist, it will be created.
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 to the database file
Configuration options for the database Show DatabaseOptions properties
Size of the page cache in bytes
Number of pages written before auto-checkpoint triggers
Unix file permissions for the database file (e.g., 0o644)
Open database in read-only mode
Maximum number of operations allowed in a single bulk write
Maximum size of a single document in bytes
Maximum request body size for web server (if enabled)
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
The default configuration options
Example
const defaults = Database . defaultDatabaseOptions ();
console . log ( defaults );
getPath()
Returns the file path of the database.
The absolute path to the database file
isReadOnly()
Checks if the database is opened in read-only mode.
true if database is read-only, false otherwise
databaseInfo()
Returns comprehensive information about the database.
databaseInfo (): DatabaseInfo
Database metadata and statistics Show DatabaseInfo properties
Total number of pages in the database
Database file size in bytes
Array of collection information objects
Total number of documents across all collections
Whether database is in read-only mode
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 []
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 >
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
Collection metadata and statistics Show CollectionInfo properties
Number of documents in the collection
Root page number of the B-tree index
Array of index information objects
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 []
Array of index information Show IndexInfo properties
Array of field names in the index
Whether the index enforces uniqueness
Type of index (btree or text)
createIndex()
Creates a single-field index.
creatIndex ( collectionName : string , indexName : string , field : string , unique : boolean ): void
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
Array of field names to include in the index
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
Name for the new text index
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
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
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
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
Transactions
beginTransaction()
Starts a new transaction.
beginTransaction (): 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
Default transaction retry configuration Show TransactionConfig properties
Maximum number of retry attempts for conflicted transactions
Base delay in milliseconds for exponential backoff
Maximum delay in milliseconds between retries
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
Current transaction retry configuration
Maintenance operations
checkpoint()
Forces a checkpoint, writing all in-memory changes to disk.
Example
db . checkpoint ();
console . log ( 'Database checkpointed' );
setAutoCheckpointThreshold()
Sets the auto-checkpoint threshold.
setAutoCheckpointThreshold ( threshold : number ): void
Number of pages written before auto-checkpoint triggers
garbageCollect()
Runs garbage collection to reclaim deleted pages.
garbageCollect (): GarbageCollectResult
Statistics about freed resources Show GarbageCollectResult properties
Number of pages reclaimed
Bytes of storage reclaimed
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.
Backup and restore
backup()
Creates a backup of the database.
backup ( destPath : string ): void
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
Path to the backup file to verify
Backup file metadata Show BackupInfo properties
Array of collection names in the backup
Total number of documents in the backup
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
Database operation statistics Show MetricsSnapshot properties
Total number of document write operations
Total number of document read operations
total_document_operations
Total number of all document operations
Number of I/O errors encountered
Number of transaction conflicts
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
Address and port to bind the web server (e.g., “127.0.0.1:8080”)
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.
Example
db . close ();
console . log ( 'Database closed' );