Home SDK Docs Get Started
TypeScript SDK v0.5.0

Complete get-db9 API Documentation

Reference for every public export: installation, one-liner provisioning, full client surface, auth lifecycle, credential stores, error model, and all exported TypeScript interfaces.

Section 01

Installation

Install the SDK with your package manager. Runtime requirement is Node.js 18+ (native fetch), with TypeScript 5+ for full type exports.

bash
npm install get-db9
yarn add get-db9
pnpm add get-db9
bun add get-db9
RequirementMinimumNotes
Node.js18.0.0+Uses native fetch and modern ESM/CJS output.
TypeScript5.0+Required for complete type export support.
Credentials~/.db9/credentialsDefault token storage shared with db9 CLI.
Section 02

Quick Start

instantDatabase() automatically creates or reuses a database named default. Requires a valid token in the credential store (for example from db9 login, db9 claim, or db9 login --api-key).

typescript
import { instantDatabase } from 'get-db9';

const db = await instantDatabase({
  name: 'myapp',
  seed: 'CREATE TABLE users (id SERIAL PRIMARY KEY, email TEXT)'
});

console.log(db.databaseId);
console.log(db.connectionString);
console.log(db.adminUser, db.adminPassword);
console.log(db.state, db.createdAt);

Result shape returned from instantDatabase():

typescript
interface InstantDatabaseResult {
  databaseId: string;
  connectionString: string;
  adminUser: string;
  adminPassword: string;
  state: string;
  createdAt: string;
}
Section 03

instantDatabase(options?)

High-level API that wraps createDb9Client(), checks for an existing database by name, creates one if missing, and optionally executes seed SQL.

signature
function instantDatabase(
  options?: InstantDatabaseOptions
): Promise<InstantDatabaseResult>;
OptionTypeDescription
namestringDatabase name. Default: 'default'.
baseUrlstringOverride API endpoint.
fetchFetchFnCustom fetch implementation.
credentialStoreCredentialStoreToken load/save strategy.
seedstringSQL text executed via client.databases.sql().
seedFilestringSQL file content executed via client.databases.sqlFile().
timeoutnumberRequest timeout in milliseconds.
maxRetriesnumberRetry count for failed requests (capped at 3).
retryDelaynumberDelay between retries in milliseconds.
example
const db = await instantDatabase({
  name: 'analytics',
  seedFile: `
    CREATE TABLE events (
      id BIGSERIAL PRIMARY KEY,
      user_id TEXT NOT NULL,
      created_at TIMESTAMP DEFAULT NOW()
    );
  `
});
Section 04

createDb9Client(options?)

Low-level typed client exposing grouped APIs: auth, tokens, and databases. If no token is provided, it lazily loads from the credential store.

signature
function createDb9Client(options?: Db9ClientOptions): Db9Client;
OptionTypeDescription
baseUrlstringDefault: https://dev.db9.ai/api.
tokenstringOptional bearer token; skips credential store lookup.
fetchFetchFnInject custom HTTP implementation.
credentialStoreCredentialStoreLoad/save token state.
timeoutnumberRequest timeout in milliseconds.
maxRetriesnumberRetry count for failed requests (capped at 3).
retryDelaynumberDelay between retries in milliseconds.
  1. Create public client (no Authorization header).
  2. Lazy-load token from credential store on first protected call.
  3. If token missing, prompt user to run db9 login (or bootstrap via db9 db create) or set DB9_API_KEY.
  4. Create auth client with Authorization: Bearer <token>.
example
import { createDb9Client, MemoryCredentialStore } from 'get-db9';

const client = createDb9Client({
  baseUrl: 'https://dev.db9.ai/api',
  credentialStore: new MemoryCredentialStore()
});
Section 05

Authentication (client.auth)

Three auth entry modes: anonymous trial (auto-created on first db9 db create), Auth0 SSO (browser-based), and API key (for CI/CD and agents). Anonymous sessions can be upgraded with db9 claim.

recommended
# Zero-setup trial (auto creates anonymous account + token)
db9 db create --name quickstart

# Upgrade anonymous account to verified SSO identity
db9 claim
db9 claim --id-token <AUTH0_ID_TOKEN>

# Human operator login (prints verification URL + code, then opens browser)
db9 login

# API key login (CI/CD, agents)
db9 login --api-key <KEY>

# Mint an agent token once, then store in secret manager
db9 token create --name my-agent --expires-in-days 365

# Agent runtime
export DB9_API_KEY=<token>
  • me(): Promise<CustomerResponse> — Get current user profile
flow
First-time user
  |
  | db9 db create (no credentials found)
  v
Anonymous account + bearer token
  |
  | db9 claim (Auth0 id_token required)
  v
Verified customer account
  |
  | db9 token create --name my-agent
  v
Agent API token (recommended for automation)

Alternative
  |
  | db9 login
  | Auth0 SSO (browser)
  | Exchange verified identity for db9 bearer token
  v
Customer bearer token
  1. If no credentials are present, db9 db create automatically creates an anonymous account (default limit: 5 active databases).
  2. Run db9 claim to bind that account to a verified Auth0 identity; this removes anonymous-only limits.
  3. Use db9 login when you want to start directly with SSO; it prints the verification URL and code in console, and also attempts to open a browser.
  4. Agent workloads should use named API tokens from client.tokens.create() or db9 token create, then inject via DB9_API_KEY.
Section 06

Token Management (client.tokens)

Create, inspect, and revoke customer API tokens for CI/CD and programmatic access.

  • create(req: CreateTokenRequest): Promise<CreateTokenResponse> — Create named token with optional expiry
  • list(): Promise<TokenResponse[]>
  • revoke(tokenId: string): Promise<MessageResponse>
typescript
// Create a named API token
const newToken = await client.tokens.create({
  name: 'ci-deploy',
  expires_in_days: 90
});
console.log(newToken.token); // Use this for CI/CD

// List all tokens
const tokens = await client.tokens.list();
for (const token of tokens) {
  console.log(token.id, token.name, token.created_at, token.expires_at);
}

// Revoke a token
await client.tokens.revoke(tokens[0].id);
Section 07

Database Management (client.databases)

Core lifecycle APIs: create, enumerate, inspect, delete, reset admin password, and read observability snapshots.

  • create(req: CreateDatabaseRequest): Promise<DatabaseResponse>
  • list(): Promise<DatabaseResponse[]>
  • get(databaseId: string): Promise<DatabaseResponse>
  • delete(databaseId: string): Promise<MessageResponse>
  • resetPassword(databaseId: string): Promise<CustomerPasswordResetResponse>
  • observability(databaseId: string): Promise<TenantObservabilityResponse>
typescript
const db = await client.databases.create({
  name: 'billing',
  region: 'us-west',
  admin_password: 'StrongAdminPass1'
});

const all = await client.databases.list();
const current = await client.databases.get(db.id);

const rotated = await client.databases.resetPassword(db.id);
const metrics = await client.databases.observability(db.id);

await client.databases.delete(db.id);
Section 08

SQL Execution

Execute SQL strings or SQL file content through the customer API. Both methods return SqlResult.

  • sql(databaseId: string, query: string): Promise<SqlResult>
  • sqlFile(databaseId: string, fileContent: string): Promise<SqlResult>
typescript
const result = await client.databases.sql(
  databaseId,
  'SELECT id, email FROM users ORDER BY id LIMIT 10'
);

console.log(result.columns);
console.log(result.rows);
console.log(result.row_count, result.command, result.error);

const fromFile = await client.databases.sqlFile(databaseId, `
  CREATE TABLE audit_log (id BIGSERIAL PRIMARY KEY, event TEXT);
  INSERT INTO audit_log(event) VALUES ('created');
`);
SqlResult FieldTypeDescription
columnsColumnInfo[]Column metadata for result rows.
rowsunknown[][]Result values matrix.
row_countnumberRows affected/returned.
commandstringExecuted command label (SELECT, INSERT, etc.).
errorstring | SqlErrorDetailStructured error with message, code, detail, hint, and position.
Section 09

Schema & Dump

Introspect schema objects or export SQL dump payloads.

  • schema(databaseId: string): Promise<SchemaResponse>
  • dump(databaseId: string, req?: DumpRequest): Promise<DumpResponse>
typescript
const schema = await client.databases.schema(databaseId);
for (const table of schema.tables) {
  console.log(table.schema, table.name);
}

const ddlOnly = await client.databases.dump(databaseId, { ddl_only: true });
console.log(ddlOnly.object_count);
console.log(ddlOnly.sql);
Section 10

Migrations

Apply SQL migrations with checksums and inspect migration history metadata.

  • applyMigration(databaseId: string, req: MigrationApplyRequest): Promise<MigrationApplyResponse>
  • listMigrations(databaseId: string): Promise<MigrationMetadata[]>
typescript
await client.databases.applyMigration(databaseId, {
  name: '20260218_add_users',
  sql: 'CREATE TABLE users (id SERIAL PRIMARY KEY, email TEXT NOT NULL);',
  checksum: 'f0b9c43b'
});

const applied = await client.databases.listMigrations(databaseId);
for (const migration of applied) {
  console.log(migration.name, migration.applied_at, migration.checksum);
}
Section 11

Branching

Create database branches from an existing database using a new branch name.

  • branch(databaseId: string, req: BranchRequest): Promise<DatabaseResponse>
typescript
const featureDb = await client.databases.branch(databaseId, {
  name: 'feature-auth'
});

console.log(featureDb.id, featureDb.name, featureDb.connection_string);
Section 12

Database Users (client.databases.users)

Manage Postgres users inside a customer database.

  • list(databaseId: string): Promise<UserResponse[]>
  • create(databaseId: string, req: CreateUserRequest): Promise<MessageResponse>
  • delete(databaseId: string, username: string): Promise<MessageResponse>
typescript
await client.databases.users.create(databaseId, {
  username: 'app_user',
  password: 'AppUserPass!'
});

const users = await client.databases.users.list(databaseId);
users.forEach((u) => {
  console.log(u.name, u.can_login, u.can_create_db, u.is_superuser);
});

await client.databases.users.delete(databaseId, 'app_user');
Section 13

Credential Storage

Credential stores implement a shared async interface used by client auto-auth.

  • FileCredentialStore(path?) - TOML file store at ~/.db9/credentials.
  • MemoryCredentialStore - volatile in-memory store for tests/serverless.
  • defaultCredentialStore() - factory that returns new FileCredentialStore().
typescript
import {
  createDb9Client,
  FileCredentialStore,
  MemoryCredentialStore,
  defaultCredentialStore
} from 'get-db9';

const fileStore = new FileCredentialStore();
const customStore = new FileCredentialStore('/tmp/db9-credentials.toml');
const memStore = new MemoryCredentialStore();
const store = defaultCredentialStore();

const client = createDb9Client({ credentialStore: fileStore });
Section 14

Error Handling

API failures throw Db9Error subclasses based on HTTP status code.

  • Db9Error - base class with statusCode, message, and optional response.
  • Db9AuthError - status 401.
  • Db9NotFoundError - status 404.
  • Db9ConflictError - status 409.
typescript
import {
  Db9Error,
  Db9AuthError,
  Db9NotFoundError,
  Db9ConflictError
} from 'get-db9';

try {
  await client.databases.get('missing-id');
} catch (error) {
  if (error instanceof Db9NotFoundError) {
    console.error('Database not found');
  } else if (error instanceof Db9AuthError) {
    console.error('Authentication required');
  } else if (error instanceof Db9ConflictError) {
    console.error('Conflict while processing request');
  } else if (error instanceof Db9Error) {
    console.error(`db9 API error ${error.statusCode}: ${error.message}`);
  } else {
    throw error;
  }
}
Section 15

Filesystem (client.fs)

Cloud filesystem operations for reading, writing, and managing files attached to each database. Built for RAG pipelines, document ingestion, and agent workflows.

  • list(dbId, path, options?): Promise<Fs9FileEntry[]> — List directory contents
  • read(dbId, path): Promise<string> — Read file content as text
  • write(dbId, path, content): Promise<void> — Write text content to a file
  • stat(dbId, path): Promise<Fs9FileEntry> — Get file metadata
  • mkdir(dbId, path): Promise<void> — Create a directory (recursive)
  • remove(dbId, path): Promise<void> — Delete a file or directory
  • readBinary(dbId, path): Promise<ArrayBuffer> — Read file as binary
  • exists(dbId, path): Promise<boolean> — Check if file exists
  • events(dbId, opts?): Promise<Fs9EventEntry[]> — Get filesystem event log
typescript
import { createDb9Client } from 'get-db9/client';

const client = createDb9Client();
const dbId = 'my-database-id';

// Create directory and write a file
await client.fs.mkdir(dbId, '/data');
await client.fs.write(dbId, '/data/hello.txt', 'Hello from db9!');

// Read file content
const content = await client.fs.read(dbId, '/data/hello.txt');

// List directory
const files = await client.fs.list(dbId, '/data/');
for (const file of files) {
  console.log(file.path, file.file_type, file.size);
}

// Stat a file
const info = await client.fs.stat(dbId, '/data/hello.txt');
console.log(info.file_type, info.size, info.mtime);

// Check existence
const exists = await client.fs.exists(dbId, '/data/hello.txt');
console.log('File exists:', exists);

// Get events
const events = await client.fs.events(dbId, { limit: 10, path: '/data' });
for (const event of events) {
  console.log(event.type, event.path, event.timestamp);
}

// Cleanup
await client.fs.remove(dbId, '/data/hello.txt');
await client.fs.remove(dbId, '/data');
Fs9FileEntry
FieldTypeDescription
pathstringFull file path.
sizenumberFile size in bytes.
file_type'regular' | 'directory' | 'symlink'Entry type.
modenumberUnix file mode.
uidnumberOwner user ID.
gidnumberOwner group ID.
atimenumberLast access (Unix timestamp).
mtimenumberLast modified (Unix timestamp).
ctimenumberStatus change (Unix timestamp).
etagstringContent hash for caching.
Fs9ListOptions
OptionTypeDescription
recursivebooleanList entries recursively (default: false).
Section 16

TypeScript Types Reference (All Public Interfaces)

The package re-exports all interfaces from ./types in addition to InstantDatabaseOptions, InstantDatabaseResult, Db9ClientOptions, and credential/http types.

Common

Endpoint, MessageResponse, HealthResponse, ColumnInfo, SqlResult, SqlErrorDetail, TenantState

Customer Requests

CreateDatabaseRequest, SqlExecuteRequest, DumpRequest, MigrationApplyRequest, BranchRequest, CreateUserRequest, CreateTokenRequest

Customer Responses

CustomerResponse, DatabaseResponse, CustomerPasswordResetResponse, TokenResponse, CreateTokenResponse, DumpResponse, SchemaResponse, TableMetadata, ColumnMetadata, ViewMetadata, MigrationApplyResponse, MigrationMetadata, UserResponse, TenantObservabilityResponse, ObservabilitySummary, QuerySample

Filesystem

Fs9FileEntry, Fs9ListOptions, Fs9EventEntry, Fs9EventOptions

Credential & HTTP

Credentials, CredentialStore, FetchFn, HttpClient, HttpClientOptions, InstantDatabaseOptions, InstantDatabaseResult, Db9ClientOptions, Db9Client, Endpoint

exports
export function instantDatabase(options?: InstantDatabaseOptions): Promise<InstantDatabaseResult>;
export { createDb9Client } from './client';
export type { Db9ClientOptions, Db9Client } from './client';
export { Db9Error, Db9AuthError, Db9NotFoundError, Db9ConflictError } from './errors';
export { FileCredentialStore, MemoryCredentialStore, defaultCredentialStore } from './credentials';
export type * from './types';