Initializing playground…
← Back to roadmap

🗃️ SQL I/O — Interactive Playground

readSql, readSqlQuery, readSqlTable, and toSql mirror pandas read_sql() and DataFrame.to_sql(). Because tsb has zero runtime dependencies, you pass a SqlConnection adapter for your database driver. Edit any code block below and press ▶ Run (or Ctrl+Enter) to execute it live in your browser.

1 · readSqlQuery — run a SELECT statement

Pass a SQL string and a SqlConnection adapter. The result is a DataFrame. An optional indexCol promotes a column to the row index.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

2 · readSqlTable — load an entire table

Pass a table name (not a SQL string). Use columns to select a subset, or indexCol to set the row index.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

3 · readSql — auto-detect query vs table name

readSql inspects the first argument: if it looks like a SQL statement it calls readSqlQuery; otherwise it calls readSqlTable.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

4 · toSql — write a DataFrame to a SQL table

Writes rows from a DataFrame into the database. Returns the number of rows written. The ifExists option controls what happens when the table already exists: "fail", "replace", or "append".

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

API Reference

All four functions accept a SqlConnection adapter — implement query() plus optional listTables() and insert() for your database driver.

interface SqlConnection {
  query(sql: string, params?: readonly SqlValue[]): SqlResult;
  listTables?(): string[];
  insert?(table: string, rows: object[], columns: string[], ifExists: IfExistsOption): number;
}

readSqlQuery(sql: string, con: SqlConnection, options?: ReadSqlOptions): DataFrame
readSqlTable(table: string, con: SqlConnection, options?: ReadSqlOptions): DataFrame
readSql(sqlOrTable: string, con: SqlConnection, options?: ReadSqlOptions): DataFrame
toSql(df: DataFrame, name: string, con: SqlConnection, options?: ToSqlOptions): number

interface ReadSqlOptions {
  indexCol?: string | string[];
  columns?:  string[];
  params?:   readonly SqlValue[];
  parseDates?: string[];
}

interface ToSqlOptions {
  ifExists?: "fail" | "replace" | "append";  // default: "fail"
  index?:    boolean;                          // include index column (default: true)
  chunkSize?: number;
}