@probitas/client-sql-mysql

MySQL client for Probitas scenario testing framework.

This package provides a MySQL client designed for integration testing, with transaction support and prepared statement capabilities.

Features

  • Query Execution: Parameterized queries with type-safe results
  • Transactions: Full transaction support with isolation levels
  • Prepared Statements: Automatic parameter escaping and type conversion
  • Connection Pooling: Configurable pool with idle timeout
  • Resource Management: Implements AsyncDisposable for proper cleanup

Installation

deno add jsr:@probitas/client-sql-mysql

Quick Start

import { createMySqlClient } from "@probitas/client-sql-mysql";

const client = await createMySqlClient({
  url: {
    host: "localhost",
    port: 3306,
    username: "root",
    password: "secret",
    database: "mydb",
  },
});

// Query with parameters (uses ? placeholders)
const result = await client.query<{ id: number; name: string }>(
  "SELECT id, name FROM users WHERE active = ?",
  [true]
);
console.log(result.rows);

// Get first row
const user = await client.queryOne<{ id: number; name: string }>(
  "SELECT * FROM users WHERE id = ?",
  [1]
);

await client.close();

Transactions

import { createMySqlClient } from "@probitas/client-sql-mysql";
import type { SqlTransaction } from "@probitas/client-sql";

const client = await createMySqlClient({ url: "mysql://localhost:3306/testdb" });
await client.transaction(async (tx: SqlTransaction) => {
  await tx.query("INSERT INTO accounts (id, balance) VALUES (?, ?)", [1, 100]);
  await tx.query("INSERT INTO accounts (id, balance) VALUES (?, ?)", [2, 200]);
  // Automatically committed if no error, rolled back on exception
}, { isolationLevel: "serializable" });
await client.close();

Using with using Statement

import { createMySqlClient } from "@probitas/client-sql-mysql";

await using client = await createMySqlClient({
  url: { host: "localhost", username: "root", database: "testdb" },
});

const result = await client.query("SELECT 1 as n");
// Client automatically closed when block exits
PackageDescription
`@probitas/client-sql`Common SQL types and utilities
`@probitas/client-sql-postgres`PostgreSQL client
`@probitas/client-sql-sqlite`SQLite client
`@probitas/client-sql-duckdb`DuckDB client

Installation

deno add jsr:@probitas/client-sql-mysql

Classes

class

#AccessDeniedError

class AccessDeniedError extends MySqlError
ExtendsMySqlError

Error thrown when access is denied (wrong credentials).

NameDescription
name
mysqlKind
Constructor
new AccessDeniedError(message: string, options?: MySqlErrorOptions)
Properties
  • readonlynamestring
  • readonlymysqlKind"access_denied"
class

#ConnectionRefusedError

class ConnectionRefusedError extends MySqlError
ExtendsMySqlError

Error thrown when connection is refused.

NameDescription
name
mysqlKind
Constructor
new ConnectionRefusedError(message: string, options?: MySqlErrorOptions)
Properties
  • readonlynamestring
  • readonlymysqlKind"connection_refused"
class

#ConstraintError

class ConstraintError extends SqlError
ExtendsSqlError

Error thrown when a constraint violation occurs.

NameDescription
name
kind
constraint
Constructor
new ConstraintError(
  message: string,
  constraint: string,
  options?: SqlErrorOptions,
)
Properties
  • readonlynamestring
  • readonlykind"constraint"
  • readonlyconstraintstring
class

#DeadlockError

class DeadlockError extends SqlError
ExtendsSqlError

Error thrown when a deadlock is detected.

NameDescription
name
kind
Constructor
new DeadlockError(message: string, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"deadlock"
class

#MySqlError

class MySqlError extends SqlError
ExtendsSqlError

Base error class for MySQL-specific errors. Extends SqlError with MySQL-specific properties like errno.

NameDescription
name
errno
Constructor
new MySqlError(message: string, options?: MySqlErrorOptions)
Properties
  • readonlynamestring
  • readonlyerrno?number
class

#MySqlTransactionImpl

class MySqlTransactionImpl implements MySqlTransaction
Constructor
new MySqlTransactionImpl(connection: AnyPoolConnection)
Methods
static begin(): unknown

Begin a new transaction.

query(): unknown
queryOne(): unknown
commit(): unknown
rollback(): unknown
savepoint(): unknown
rollbackToSavepoint(): unknown
releaseSavepoint(): unknown
class

#QuerySyntaxError

class QuerySyntaxError extends SqlError
ExtendsSqlError

Error thrown when a SQL query has syntax errors.

NameDescription
name
kind
Constructor
new QuerySyntaxError(message: string, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"query"
class

#SqlConnectionError

class SqlConnectionError extends SqlError
ExtendsSqlError

Error thrown when a connection or network-level error occurs.

This includes:

  • Connection refused (server not running)
  • Authentication failure
  • Connection timeout
  • Pool exhaustion
  • TLS handshake failure
  • DNS resolution failure
NameDescription
name
kind
Constructor
new SqlConnectionError(message: string, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"connection"
class

#SqlError

class SqlError extends ClientError

Base error class for SQL-specific errors. Extends ClientError with SQL-specific properties.

NameDescription
name
kind
sqlState
Constructor
new SqlError(message: string, kind: SqlErrorKind, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykindSqlErrorKind
  • readonlysqlStatestring | null

Interfaces

interface

#MySqlClient

interface MySqlClient extends AsyncDisposable

MySQL client interface.

NameDescription
configThe client configuration.
dialectThe SQL dialect identifier.
query()Execute a SQL query.
queryOne()Execute a query and return the first row or undefined.
transaction()Execute a function within a transaction.
close()Close the client and release all connections.
Properties
  • readonlyconfigMySqlClientConfig

    The client configuration.

  • readonlydialect"mysql"

    The SQL dialect identifier.

Methods
query<T = Record<string, any>>(
  sql: string,
  params?: unknown[],
  options?: SqlQueryOptions,
): Promise<SqlQueryResult<T>>

Execute a SQL query.

Parameters
  • sqlstring
    • SQL query string
  • params?unknown[]
    • Optional query parameters
    • Optional query options
queryOne<T = Record<string, any>>(
  sql: string,
  params?: unknown[],
  options?: SqlQueryOptions,
): Promise<T | undefined>

Execute a query and return the first row or undefined.

Parameters
  • sqlstring
    • SQL query string
  • params?unknown[]
    • Optional query parameters
    • Optional query options
transaction<T>(
  fn: (tx: SqlTransaction) => unknown,
  options?: SqlTransactionOptions,
): Promise<T>

Execute a function within a transaction. Automatically commits on success or rolls back on error.

Parameters
close(): Promise<void>

Close the client and release all connections.

interface

#MySqlClientConfig

interface MySqlClientConfig extends CommonOptions

Configuration for creating a MySQL client.

NameDescription
urlConnection URL or configuration.
poolConnection pool configuration.
timezoneTimezone for the connection.
throwOnErrorWhether to throw an error for query failures.
Properties
  • readonlyurlstring | MySqlConnectionConfig

    Connection URL or configuration.

    Can be a connection URL string (e.g., "mysql://user:pass@host:port/database") or a detailed MySqlConnectionConfig object.

  • readonlypool?MySqlPoolConfig

    Connection pool configuration.

  • readonlytimezone?string

    Timezone for the connection.

  • readonlythrowOnError?boolean

    Whether to throw an error for query failures. When false, failures are returned as SqlQueryResultError or SqlQueryResultFailure. Can be overridden per-query via SqlQueryOptions.

interface

#MySqlConnectionConfig

interface MySqlConnectionConfig extends CommonConnectionConfig

MySQL connection configuration.

Extends CommonConnectionConfig with MySQL-specific options.

NameDescription
databaseDatabase name to connect to.
tlsTLS configuration.
charsetCharacter set.
Properties
  • readonlydatabase?string

    Database name to connect to.

  • readonlytls?MySqlTlsConfig

    TLS configuration.

  • readonlycharset?string

    Character set.

interface

#MySqlErrorOptions

interface MySqlErrorOptions extends SqlErrorOptions

Options for MySqlError constructor.

NameDescription
errnoMySQL error code (e.g., 1045, 1062).
Properties
  • readonlyerrno?number

    MySQL error code (e.g., 1045, 1062).

interface

#MySqlPoolConfig

interface MySqlPoolConfig

Connection pool configuration.

NameDescription
connectionLimitMaximum number of connections in the pool.
minConnectionsMinimum number of idle connections.
queueLimitMaximum number of connection requests the pool will queue.
waitForConnectionsWhether to wait for connections to become available.
idleTimeoutTime in milliseconds before connection is considered idle.
Properties
  • readonlyconnectionLimit?number

    Maximum number of connections in the pool.

  • readonlyminConnections?number

    Minimum number of idle connections.

  • readonlyqueueLimit?number

    Maximum number of connection requests the pool will queue.

  • readonlywaitForConnections?boolean

    Whether to wait for connections to become available.

  • readonlyidleTimeout?number

    Time in milliseconds before connection is considered idle.

interface

#MySqlTlsConfig

interface MySqlTlsConfig

TLS/SSL configuration for MySQL connections.

NameDescription
caRoot CA certificate (PEM format).
certClient certificate (PEM format).
keyClient private key (PEM format).
rejectUnauthorizedSkip server certificate verification (use only for testing).
Properties
  • readonlyca?string

    Root CA certificate (PEM format).

  • readonlycert?string

    Client certificate (PEM format).

  • readonlykey?string

    Client private key (PEM format).

  • readonlyrejectUnauthorized?boolean

    Skip server certificate verification (use only for testing).

interface

#MySqlTransaction

interface MySqlTransaction extends SqlTransaction

MySQL-specific transaction interface. Extends SqlTransaction with MySQL-specific features.

NameDescription
savepoint()Create a savepoint.
rollbackToSavepoint()Rollback to a savepoint.
releaseSavepoint()Release a savepoint.
Methods
savepoint(name: string): Promise<void>

Create a savepoint.

Parameters
  • namestring
    • Savepoint name
rollbackToSavepoint(name: string): Promise<void>

Rollback to a savepoint.

Parameters
  • namestring
    • Savepoint name
releaseSavepoint(name: string): Promise<void>

Release a savepoint.

Parameters
  • namestring
    • Savepoint name
interface

#SqlErrorOptions

interface SqlErrorOptions extends ErrorOptions

Options for SqlError constructor.

NameDescription
sqlStateSQL State code (e.g., "23505" for unique violation)
Properties
  • readonlysqlState?string

    SQL State code (e.g., "23505" for unique violation)

interface

#SqlQueryOptions

interface SqlQueryOptions extends CommonOptions

Options for individual SQL queries.

NameDescription
throwOnErrorWhether to throw an error for query failures.
Properties
  • readonlythrowOnError?boolean

    Whether to throw an error for query failures. When false, failures are returned as SqlQueryResultError or SqlQueryResultFailure.

interface

#SqlQueryResultError

interface SqlQueryResultError<T = any> extends SqlQueryResultBase<T>

SQL query result for query errors (syntax errors, constraint violations, etc.).

Server received and processed the query, but it failed due to a SQL error.

NameDescription
processedServer processed the query.
okQuery failed.
errorError describing the SQL error.
rowsEmpty rows for failed queries.
rowCountZero affected rows for failed queries.
lastInsertIdNo lastInsertId for failed queries.
warningsNo warnings for failed queries.
Properties
  • readonlyprocessedtrue

    Server processed the query.

  • readonlyokfalse

    Query failed.

  • readonlyerrorSqlError

    Error describing the SQL error.

  • readonlyrowsreadonly never[]

    Empty rows for failed queries.

  • readonlyrowCount0

    Zero affected rows for failed queries.

  • readonlylastInsertIdnull

    No lastInsertId for failed queries.

  • readonlywarningsnull

    No warnings for failed queries.

interface

#SqlQueryResultFailure

interface SqlQueryResultFailure<T = any> extends SqlQueryResultBase<T>

SQL query result for connection failures (network errors, timeouts, etc.).

Query could not be processed by the server (connection refused, timeout, pool exhausted, authentication failure, etc.).

NameDescription
processedServer did not process the query.
okQuery failed.
errorError describing the failure.
rowsNo rows (query didn't reach server).
rowCountNo row count (query didn't reach server).
lastInsertIdNo lastInsertId (query didn't reach server).
warningsNo warnings (query didn't reach server).
Properties
  • readonlyprocessedfalse

    Server did not process the query.

  • readonlyokfalse

    Query failed.

  • readonlyerrorSqlFailureError

    Error describing the failure.

  • readonlyrowsnull

    No rows (query didn't reach server).

  • readonlyrowCountnull

    No row count (query didn't reach server).

  • readonlylastInsertIdnull

    No lastInsertId (query didn't reach server).

  • readonlywarningsnull

    No warnings (query didn't reach server).

interface

#SqlQueryResultSuccess

interface SqlQueryResultSuccess<T = any> extends SqlQueryResultBase<T>

SQL query result for successful queries.

The query was executed successfully and returned results.

NameDescription
processedServer processed the query.
okQuery succeeded.
errorNo error for successful queries.
rowsQuery result rows.
rowCountNumber of affected rows.
lastInsertIdLast inserted ID (for INSERT statements).
warningsWarning messages from the database.
Properties
  • readonlyprocessedtrue

    Server processed the query.

  • readonlyoktrue

    Query succeeded.

  • readonlyerrornull

    No error for successful queries.

  • readonlyrowsreadonly T[]

    Query result rows.

  • readonlyrowCountnumber

    Number of affected rows.

  • readonlylastInsertIdbigint | string | null

    Last inserted ID (for INSERT statements).

  • readonlywarningsunknown | null

    Warning messages from the database.

interface

#SqlQueryResultSuccessParams

interface SqlQueryResultSuccessParams<T = any>

Parameters for creating a SqlQueryResultSuccess.

NameDescription
rowsThe result rows
rowCountNumber of affected rows (for INSERT/UPDATE/DELETE)
durationQuery execution duration in milliseconds
lastInsertIdLast inserted ID (for INSERT statements)
warningsWarning messages from the database
Properties
  • readonlyrowsreadonly T[]

    The result rows

  • readonlyrowCountnumber

    Number of affected rows (for INSERT/UPDATE/DELETE)

  • readonlydurationnumber

    Query execution duration in milliseconds

  • readonlylastInsertId?bigint | string

    Last inserted ID (for INSERT statements)

  • readonlywarnings?readonly string[]

    Warning messages from the database

interface

#SqlTransaction

interface SqlTransaction

SQL transaction interface. Implementations should provide actual database-specific transaction handling.

NameDescription
query()Execute a query within the transaction.
queryOne()Execute a query and return the first row or undefined.
commit()Commit the transaction.
rollback()Rollback the transaction.
Methods
query<T = Record<string, any>>(
  sql: string,
  params?: unknown[],
  options?: SqlQueryOptions,
): Promise<SqlQueryResult<T>>

Execute a query within the transaction.

Parameters
  • sqlstring
    • SQL query string
  • params?unknown[]
    • Optional query parameters
    • Optional query options
queryOne<T = Record<string, any>>(
  sql: string,
  params?: unknown[],
  options?: SqlQueryOptions,
): Promise<T | undefined>

Execute a query and return the first row or undefined.

Parameters
  • sqlstring
    • SQL query string
  • params?unknown[]
    • Optional query parameters
    • Optional query options
commit(): Promise<void>

Commit the transaction.

rollback(): Promise<void>

Rollback the transaction.

interface

#SqlTransactionOptions

interface SqlTransactionOptions

Options for starting a transaction.

NameDescription
isolationLevelIsolation level for the transaction
Properties

Functions

function

#convertMySqlError

function convertMySqlError(error: unknown): SqlError

Convert a mysql2 error to the appropriate error class.

Parameters
  • errorunknown
function

#createMySqlClient

async function createMySqlClient(
  config: MySqlClientConfig,
): Promise<MySqlClient>

Create a new MySQL client instance with connection pooling.

The client provides connection pooling, parameterized queries, transaction support, and automatic result type mapping.

Parameters
Returns

Promise<MySqlClient> — A promise resolving to a new MySQL client instance

Examples

Using URL string

import { createMySqlClient } from "@probitas/client-sql-mysql";

const client = await createMySqlClient({
  url: "mysql://user:password@localhost:3306/testdb",
});

const result = await client.query<{ id: number; name: string }>(
  "SELECT * FROM users WHERE id = ?",
  [1],
);
if (result.ok) {
  console.log(result.rows[0]);  // { id: 1, name: "Alice" }
}

await client.close();

Using connection config object

import { createMySqlClient } from "@probitas/client-sql-mysql";

const client = await createMySqlClient({
  url: {
    host: "localhost",
    port: 3306,
    username: "root",
    password: "password",
    database: "testdb",
  },
  pool: { connectionLimit: 20 },
});
await client.close();

Transaction with auto-commit/rollback

import { createMySqlClient } from "@probitas/client-sql-mysql";
import type { SqlTransaction } from "@probitas/client-sql";

const client = await createMySqlClient({ url: "mysql://localhost:3306/testdb" });
const user = await client.transaction(async (tx: SqlTransaction) => {
  await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
  return await tx.queryOne("SELECT LAST_INSERT_ID() as id");
});
await client.close();

Using await using for automatic cleanup

import { createMySqlClient } from "@probitas/client-sql-mysql";

await using client = await createMySqlClient({
  url: "mysql://localhost:3306/testdb",
});

const result = await client.query("SELECT 1");
// Client automatically closed when scope exits
function

#isConnectionError

function isConnectionError(error: unknown): boolean

Check if an error is a connection-level error.

Parameters
  • errorunknown

Types

type

#MySqlErrorKind

type MySqlErrorKind = "access_denied" | "connection_refused"

MySQL-specific error kinds.

type

#SqlErrorKind

type SqlErrorKind = "query" | "constraint" | "deadlock" | "connection" | "unknown"

SQL-specific error kinds.

type

#SqlFailureError

type SqlFailureError = SqlConnectionError | AbortError | TimeoutError

Error types that indicate the operation was not processed. These are errors that occur before the query reaches the SQL server.

type

#SqlIsolationLevel

type SqlIsolationLevel = "read_uncommitted" | "read_committed" | "repeatable_read" | "serializable"

Transaction isolation level.

type

#SqlOperationError

type SqlOperationError = QuerySyntaxError | ConstraintError | DeadlockError | SqlError

Error types that indicate an operation was processed by the server. These errors occur after the query reaches the SQL server.

type

#SqlQueryResult

type SqlQueryResult<T = any> = SqlQueryResultSuccess<T> | SqlQueryResultError<T> | SqlQueryResultFailure<T>

SQL query result union type representing all possible result states.

  • Success: processed: true, ok: true, error: null
  • Error: processed: true, ok: false, error: SqlError
  • Failure: processed: false, ok: false, error: SqlConnectionError
Search Documentation