Database
The main entry point for ctrodb
Database is the top-level object. It manages the connection, schema, collections, and plugins.
Constructor
const db = new Database(config?: DatabaseConfig)
| Option | Type | Default | Description |
|---|---|---|---|
name | string | "ctrodb" | Database name |
adapter | "indexeddb" | "memory" | StorageAdapter | auto | Storage backend |
schema | SchemaConfig | — | Schema definition |
plugins | CtroDBPlugin[] | — | Plugin list |
logLevel | "debug" | "info" | "warn" | "error" | "silent" | — | Accepted, currently not implemented |
Connect / Disconnect
await db.connect()
await db.disconnect()
connect() initializes the adapter and triggers onDatabaseInit on plugins.
Call once before using collections. disconnect() clears all collection caches.
Properties
db.isConnected // boolean
db.adapterName // "memory" | "indexeddb"
db.name // string
Collections
const todos = db.collection("todos")
Collections are lazily created — first access initializes a new Collection<T>.
Transactions
const result = await db.transaction(async (ctx) => {
const todos = ctx.collection("todos")
return todos.findAll()
})
If the callback throws, all changes are rolled back.
The transaction context provides raw CRUD methods — findAll(), findById(), create(), update(), delete() — not the full Collection API.
See the Transactions guide for details.
Plugins
const syncPlugin = db.plugin("sync")
Returns the plugin instance registered with the given name, or undefined.
Sync
These methods require the sync plugin to be registered.
await db.sync()
Triggers a full sync cycle (push local changes, pull remote changes).
const unsub = db.onSync((event) => {
console.log(event.phase, event.progress)
})
Subscribes to sync lifecycle events. Returns an unsubscribe function.
db.syncStatus
// { isSyncing: boolean, isConnected: boolean, lastSyncAt: string | null,
// pendingChanges: number, failedChanges: number, lastError: string | null }
Current sync status object. See SyncStatus for details.
const pending = await db.getPendingCount()
const failed = await db.getFailedCount()
Count of pending outbound changes and failed sync attempts.
Change events
const unsub = db.on((event) => {
console.log(event.type, event.collection, event.recordId)
})
unsub() // cleanup
| Field | Type | Description |
|---|---|---|
type | "create" | "update" | "delete" | What happened |
collection | string | Collection name |
recordId | number | string | Record ID |
record | unknown | New value (create/update) |
oldRecord | unknown | Previous value (update/delete) |
How is this guide?
Last updated on Jul 2, 2026