CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sqlite

SQLite client for Node.js applications with SQL-based migrations API written in TypeScript

Pending
Overview
Eval results
Files

types.mddocs/

Type Definitions

Complete type definitions and interfaces for the sqlite package, providing TypeScript support for database operations, migrations, and configuration.

Core Configuration Types

namespace ISqlite {
  /** Database configuration interface for opening connections */
  interface Config {
    /** 
     * Database filename, ":memory:" for anonymous in-memory database,
     * or empty string for anonymous disk-based database
     */
    filename: string;
    /** 
     * One or more of sqlite3.OPEN_READONLY, sqlite3.OPEN_READWRITE, sqlite3.OPEN_CREATE
     * Default: OPEN_READWRITE | OPEN_CREATE
     */
    mode?: number;
    /** 
     * Database driver instance (e.g., sqlite3.Database or sqlite3.cached.Database)
     * Must conform to sqlite3 API
     */
    driver: any;
  }

  /** Database configuration options for configure() method */
  type ConfigureOption = 'trace' | 'profile' | 'busyTimeout';
}

Query and Result Types

namespace ISqlite {
  /** Internal SQL object structure used by utility functions */
  interface SqlObj {
    sql: string;
    params?: any[];
  }

  /** SQL template string structure (for sql-template-strings compatibility) */
  interface SQLStatement {
    sql: string;
    values?: any[];
  }

  /** Union type accepting SQL strings or template string objects */
  type SqlType = SQLStatement | string;

  /** Result object returned by run() operations */
  interface RunResult<Stmt extends sqlite3.Statement = sqlite3.Statement> {
    /** 
     * Statement object (automatically finalized after Database.run())
     * Not possible to run again after Database.run() execution
     */
    stmt: Statement<Stmt>;
    /** 
     * Row ID of the inserted row
     * Only valid for successful INSERT statements
     */
    lastID?: number;
    /** 
     * Number of rows changed
     * Only valid for successful UPDATE or DELETE statements
     */
    changes?: number;
  }
}

Migration System Types

namespace IMigrate {
  /** Configuration parameters for database migrations */
  interface MigrationParams {
    /** 
     * Force rollback and re-apply the latest migration on each launch
     * Useful during development
     */
    force?: boolean;
    /** 
     * Migration table name for tracking applied migrations
     * Default: 'migrations'
     */
    table?: string;
    /** 
     * Path to the migrations folder
     * Default: path.join(process.cwd(), 'migrations')
     */
    migrationsPath?: string;
    /** 
     * Migration data read from files or provided programmatically
     * If provided, migrationsPath will be ignored
     */
    migrations?: readonly MigrationData[];
  }

  /** Represents a migration file with extracted metadata */
  interface MigrationFile {
    /** Migration ID extracted from filename */
    id: number;
    /** Migration name extracted from filename */
    name: string;
    /** Full filename including extension */
    filename: string;
  }

  /** Complete migration data including SQL content */
  interface MigrationData {
    /** Unique migration ID (must be sequential) */
    id: number;
    /** Descriptive migration name */
    name: string;
    /** SQL statements for applying the migration */
    up: string;
    /** SQL statements for rolling back the migration */
    down: string;
  }
}

Class Type Definitions

/** 
 * Main database class providing promise-based SQLite operations
 * Generic types allow specification of underlying driver types
 */
class Database<
  Driver extends sqlite3.Database = sqlite3.Database,
  Stmt extends sqlite3.Statement = sqlite3.Statement
> {
  /** Database configuration used during initialization */
  config: ISqlite.Config;
  /** Underlying sqlite3 database instance */
  db: Driver;

  constructor(config: ISqlite.Config);
}

/** 
 * Prepared statement wrapper providing promise-based operations
 * Generic type allows specification of underlying statement type
 */
class Statement<S extends sqlite3.Statement = sqlite3.Statement> {
  /** Underlying sqlite3 statement instance */
  stmt: S;

  constructor(stmt: S);
}

Generic Type Usage Examples

The library provides extensive generic type support for type-safe database operations:

// Specify database and statement types
import sqlite3 from "sqlite3";

const db = await open<sqlite3.Database, sqlite3.Statement>({
  filename: ":memory:",
  driver: sqlite3.Database
});

// Type-safe query results
interface User {
  id: number;
  name: string;
  email: string;
  active: boolean;
}

// get() with typed result
const user = await db.get<User>(
  "SELECT id, name, email, active FROM users WHERE id = ?",
  1
);
// user is typed as User | undefined

// all() with typed result array
const users = await db.all<User[]>(
  "SELECT id, name, email, active FROM users ORDER BY name"
);
// users is typed as User[]

// run() with typed RunResult
const result = await db.run(
  "INSERT INTO users (name, email, active) VALUES (?, ?, ?)",
  "Alice",
  "alice@example.com",
  true
);
// result.lastID is number | undefined
// result.changes is number | undefined

// Prepared statements with types
const stmt = await db.prepare<sqlite3.Statement>(
  "SELECT * FROM users WHERE active = ?"
);

const activeUsers = await stmt.all<User[]>(true);
await stmt.finalize();

Error Types

/** 
 * Error objects are formatted consistently through the formatError utility
 * All database errors are converted to standard Error instances with preserved properties
 */
interface FormattedError extends Error {
  /** Original error message */
  message: string;
  /** Additional error properties from underlying sqlite3 errors */
  [key: string]: any;
}

Driver Compatibility Types

The library is designed to work with any sqlite3-compatible driver:

/** Example driver interfaces the library expects */
interface DriverInterface {
  /** Database constructor */
  new (filename: string, callback?: (err: Error | null) => void): DatabaseInstance;
  new (filename: string, mode?: number, callback?: (err: Error | null) => void): DatabaseInstance;
}

interface DatabaseInstance {
  /** Core database methods that must be implemented */
  run(sql: string, ...params: any[]): this;
  get(sql: string, ...params: any[]): this;
  all(sql: string, ...params: any[]): this;
  each(sql: string, ...params: any[]): this;
  exec(sql: string, callback?: (err: Error | null) => void): this;
  prepare(sql: string, ...params: any[]): StatementInstance;
  close(callback?: (err: Error | null) => void): void;
  
  /** Event emitter methods */
  on(event: string, listener: (...args: any[]) => void): this;
  
  /** Configuration methods */
  configure(option: string, value: any): void;
  loadExtension(path: string, callback?: (err: Error | null) => void): this;
}

interface StatementInstance {
  /** Statement methods that must be implemented */
  bind(...params: any[]): this;
  reset(callback?: () => void): this;
  finalize(callback?: (err: Error) => void): DatabaseInstance;
  run(...params: any[]): this;
  get(...params: any[]): this;
  all(...params: any[]): this;
  each(...params: any[]): this;
}

Utility Type Functions

/** 
 * Convert various SQL input formats to standardized SqlObj format
 * Supports both plain strings and sql-template-strings objects
 */
function toSqlParams(
  sql: ISqlite.SqlType,
  params?: any[]
): ISqlite.SqlObj;

/** 
 * Format error objects to ensure consistent Error instance types
 * Preserves all error properties while ensuring Error prototype
 */
function formatError(err: any): Error;

These utility functions handle internal type conversions and error formatting to provide a consistent API experience regardless of input format or underlying driver implementation.

Install with Tessl CLI

npx tessl i tessl/npm-sqlite

docs

database-operations.md

index.md

migrations.md

statement-operations.md

types.md

tile.json