Skip to content

MySQL Adapter API ​

@toshihiko/mysql-adapter implements the Adapter contract with the mysql2/promise pool.

typescript
import {
  MySQLAdapter,
  MySQLSqlBuilder,
  type MySQLAdapterOptions,
} from '@toshihiko/mysql-adapter';

MySQLAdapter ​

Constructor ​

typescript
new MySQLAdapter(options?)
new MySQLAdapter(parent, options)

Applications normally let Toshihiko use the second form:

typescript
const database = new Toshihiko(MySQLAdapter, {
  database: 'app',
  host: '127.0.0.1',
  password: 'secret',
  user: 'root',
});

Options ​

MySQLAdapterOptions extends mysql2 PoolOptions, except that Toshihiko redeclares the following properties.

typescript
type MySQLValue =
  | string
  | number
  | bigint
  | boolean
  | Date
  | null
  | undefined
  | Blob
  | Buffer
  | Uint8Array
  | Raw
  | ({} | null | undefined)[]
  | { [key: string]: MySQLValue };

type MySQLValues =
  | readonly MySQLValue[]
  | Readonly<Record<string, MySQLValue>>;
type MySQLShowSql = false | true | ((sql: string) => void);

interface MySQLAdapterOptions extends Omit<
  PoolOptions,
  'database' | 'password' | 'user'
> {
  readonly cache?: CacheSource;
  readonly database?: string;
  readonly password?: string;
  readonly package?: string;
  readonly pool?: MySQLPool;
  readonly showSql?: MySQLShowSql;
  readonly user?: string;
  readonly username?: string;
}
OptionTypeDefaultDescription
databasestring'toshihiko'Database name and Cache namespace
hoststring'localhost'MySQL host name or IP address
portnumber3306MySQL port
userstring''MySQL user name
usernamestring—Compatibility spelling for user; wins when both are present
passwordstring''MySQL password
poolMySQLPool—Injects an existing Pool; omitting it creates one from the other options
showSqlfalse | true | ((sql: string) => void)falseSQL logging switch or logger function
cacheCache | CacheOptions—An existing Cache or module configuration with module, path, name, and its constructor arguments; inherited by Models
packagestring—Compatibility field; runtime driver remains mysql2
Other optionsmysql2.PoolOptionsSet by mysql2Passed to mysql2.createPool()

Because MySQLAdapterOptions extends mysql2 PoolOptions, it also accepts driver settings such as connectionLimit, charset, ssl, and connectTimeout.

Properties ​

PropertyTypeDescription
databasestringNormalized database name
usernamestringNormalized user name
mysqlPoolPromise pool
package'mysql2'Driver identifier
format(sql: string, values?: MySQLValues) => stringPool-bound SQL formatter
optionsMySQLAdapterOptionsPublic copied options

The owning Toshihiko instance exposes database.pool as the same pool.

execute() ​

typescript
type MySQLExecuteArguments =
  | readonly [sql: string, values?: MySQLValues]
  | readonly [connection: MySQLConnection | null, sql: string, values?: MySQLValues];

type MySQLQueryExecuteArguments = readonly [sql: string, values?: MySQLValues];

adapter.execute(...args: MySQLExecuteArguments): Promise<MySQLQueryResult>
database.execute(...args: MySQLExecuteArguments): Promise<MySQLQueryResult>
query.execute(...args: MySQLQueryExecuteArguments): Promise<MySQLQueryResult>

values may be an array or an object. Array values use connection.execute() unless the SQL contains ??; object values and ?? use connection.query(). When no connection is supplied, the pool executes the statement.

showSql receives the formatted SQL before execution.

Query operations ​

MethodReturn typeBehavior
find(query: MySQLQuery, options?: AdapterFindOptions)Promise<AdapterRow | readonly AdapterRow[] | null>Uses Cache unless absent or noCache is true
count(query)Promise<number>Compiles COUNT(0)
updateByQuery(query)Promise<ResultSetHeader>Invalidates related Cache entries before execution
deleteByQuery(query)Promise<ResultSetHeader>Invalidates related Cache entries before execution
insert(model, connection, data)Promise<AdapterRow>Inserts and reads the row back
update(model, connection, key, data)Promise<ResultSetHeader>Uses original key values and rejects stale updates

insert() rejects when the mutation result is absent or readback cannot find the inserted row. update() rejects empty locators, empty write data, and a result with no affected rows.

Transactions ​

typescript
adapter.beginTransaction(): Promise<MySQLConnection>
adapter.commit(connection): Promise<void>
adapter.rollback(connection): Promise<void>

beginTransaction() acquires a pool connection and releases it if transaction start fails. Both completion methods release the connection after the driver call succeeds.

Cache-aware reads ​

typescript
adapter.findWithNoCache(model: MySQLModel, options?: MySQLQueryOptions): Promise<AdapterRow | readonly AdapterRow[] | null>
adapter.findWithCache(cache: NonNullable<MySQLModel['cache']>, model: MySQLModel, options?: MySQLQueryOptions): Promise<AdapterRow | readonly AdapterRow[] | null>

The Cache path first selects primary keys, reads cached rows, loads misses with a concurrency limit, and then restores requested field selection.

Compatibility SQL helpers ​

The Adapter exposes these public methods for existing integrations:

typescript
makeFieldWhere(field, value): string
makeArrayWhere(model, values, logic?): string
makeWhere(model, where): string
makeOrder(model, order): string
makeLimit(model, limit): string
makeIndex(model, index?): string
makeSet(model, update): string
makeFind(model, options?): string
makeUpdate(model, options?): string
makeDelete(model, options?): string
makeSql(type, model, options?): string

They delegate to MySQLSqlBuilder and return formatted SQL strings.

MySQLSqlBuilder ​

The builder exposes make*() string helpers and compile*() methods returning parameterized statements:

typescript
interface MySQLStatement {
  readonly sql: string;
  readonly values: readonly MySQLValue[];
}

compileFieldWhere(model: MySQLModel, key: string, condition: DataValue, logic?: string): MySQLStatement
compileArrayWhere(model: MySQLModel, condition: readonly DataRow[], logic?: string): MySQLStatement
compileWhere(model: MySQLModel, condition: DataRow | readonly DataRow[], logic?: string): MySQLStatement
compileSet(model: MySQLModel, update: DataRow): MySQLStatement
compileValue(field: MySQLField, value: DataValue): MySQLStatement
compileFind(model: MySQLModel, options?: MySQLQueryOptions): MySQLStatement
compileUpdate(model: MySQLModel, options?: MySQLQueryOptions): MySQLStatement
compileDelete(model: MySQLModel, options?: MySQLQueryOptions): MySQLStatement
compileSql(type: string, model: MySQLModel, options?: MySQLQueryOptions): MySQLStatement

Prefer compileFind(), compileUpdate(), compileDelete(), compileWhere(), and compileSql() when executing generated SQL. The make*() forms format values into a string and are mainly compatibility and inspection helpers.

Exported types ​

TypeDescription
MySQLAdapterOptionsPool and Toshihiko options
MySQLConnection, MySQLPoolmysql2/promise connection and pool
MySQLQueryResultDriver query-result union
MySQLMutationResultResultSetHeader
MySQLValuesArray or named values
MySQLExecuteArgumentsToshihiko.execute() overload tuple
MySQLQueryOptionsSQL-builder input state
MySQLStatementParameterized SQL and values
MySQLModel, MySQLQuery, MySQLFieldAdapter boundary contracts

Released under the MIT License.