@probitas/client-sql-postgres
PostgreSQL client for Probitas scenario testing framework.
This package provides a PostgreSQL client designed for integration testing, with transaction support and LISTEN/NOTIFY capabilities.
Features
- Query Execution: Parameterized queries with type-safe results
- Transactions: Full transaction support with isolation levels
- LISTEN/NOTIFY: Real-time notifications for async testing
- COPY Protocol: High-performance bulk data loading
- Connection Pooling: Configurable pool with idle timeout
- Resource Management: Implements
AsyncDisposablefor proper cleanup
Installation
deno add jsr:@probitas/client-sql-postgres
Quick Start
import { createPostgresClient } from "@probitas/client-sql-postgres";
const client = await createPostgresClient({
url: "postgres://user:pass@localhost:5432/mydb",
});
// Query with parameters
const result = await client.query<{ id: number; name: string }>(
"SELECT id, name FROM users WHERE active = $1",
[true]
);
console.log(result.rows);
// Get first row
const user = await client.queryOne<{ id: number; name: string }>(
"SELECT * FROM users WHERE id = $1",
[1]
);
await client.close();
Transactions
import { createPostgresClient } from "@probitas/client-sql-postgres";
import type { SqlTransaction } from "@probitas/client-sql";
const client = await createPostgresClient({
url: "postgres://localhost:5432/testdb",
});
await client.transaction(async (tx: SqlTransaction) => {
await tx.query("INSERT INTO accounts (id, balance) VALUES ($1, $2)", [1, 100]);
await tx.query("INSERT INTO accounts (id, balance) VALUES ($1, $2)", [2, 200]);
// Automatically committed if no error, rolled back on exception
}, { isolationLevel: "serializable" });
await client.close();
LISTEN/NOTIFY
import { createPostgresClient } from "@probitas/client-sql-postgres";
const client = await createPostgresClient({
url: "postgres://localhost:5432/testdb",
});
// Listen for notifications
const listener = await client.listen("events");
for await (const notification of listener) {
console.log("Received:", notification.payload);
break;
}
// Send notification
await client.notify("events", JSON.stringify({ type: "created", id: 123 }));
await client.close();
Using with using Statement
import { createPostgresClient } from "@probitas/client-sql-postgres";
await using client = await createPostgresClient({
url: "postgres://localhost:5432/testdb",
});
const result = await client.query("SELECT 1 as n");
// Client automatically closed when block exits
Related Packages
| Package | Description |
|---|---|
| `@probitas/client-sql` | Common SQL types and utilities |
| `@probitas/client-sql-mysql` | MySQL client |
| `@probitas/client-sql-sqlite` | SQLite client |
| `@probitas/client-sql-duckdb` | DuckDB client |
Links
Installation
deno add jsr:@probitas/client-sql-postgresClasses
#ConstraintError
class ConstraintError extends SqlErrorSqlErrorError thrown when a constraint violation occurs.
| Name | Description |
|---|---|
name | — |
kind | — |
constraint | — |
Constructor
new ConstraintError(
message: string,
constraint: string,
options?: SqlErrorOptions,
)Properties
- readonly
namestring - readonly
kind"constraint" - readonly
constraintstring
#DeadlockError
class DeadlockError extends SqlErrorSqlErrorError thrown when a deadlock is detected.
Constructor
new DeadlockError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"deadlock"
#PostgresTransaction
class PostgresTransaction implements SqlTransactionSqlTransactionPostgreSQL transaction implementation.
Wraps a postgres.js reserved connection to provide transaction semantics.
| Name | Description |
|---|---|
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. |
Constructor
new PostgresTransaction(sql: postgres.ReservedSql)Creates a new PostgresTransaction.
Methods
query(): unknownExecute a query within the transaction.
queryOne(): unknownExecute a query and return the first row or undefined.
commit(): unknownCommit the transaction.
rollback(): unknownRollback the transaction.
#QuerySyntaxError
class QuerySyntaxError extends SqlErrorSqlErrorError thrown when a SQL query has syntax errors.
Constructor
new QuerySyntaxError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"query"
#SqlConnectionError
class SqlConnectionError extends SqlErrorSqlErrorError 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
Constructor
new SqlConnectionError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"connection"
#SqlError
class SqlError extends ClientErrorClientErrorBase error class for SQL-specific errors. Extends ClientError with SQL-specific properties.
Constructor
new SqlError(message: string, kind: SqlErrorKind, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
sqlStatestring | null
Interfaces
#PostgresClient
interface PostgresClient extends AsyncDisposablePostgreSQL client interface.
| Name | Description |
|---|---|
config | The client configuration. |
dialect | The database dialect. |
query() | Execute a SQL query. |
queryOne() | Execute a query and return the first row or undefined. |
transaction() | Execute a function within a transaction. |
copyFrom() | Copy data from an iterable into a table using PostgreSQL COPY protocol. |
copyTo() | Copy data from a query result using PostgreSQL COPY protocol. |
listen() | Listen for notifications on a channel. |
notify() | Send a notification on a channel. |
close() | Close the client and release all connections. |
Properties
The client configuration.
- readonly
dialect"postgres"The database dialect.
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
options?SqlQueryOptions- 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
options?SqlQueryOptions- Optional query options
transaction<T>(
fn: (tx: SqlTransaction) => unknown,
options?: SqlTransactionOptions,
): Promise<T>Execute a function within a transaction.
The transaction is automatically committed if the function completes successfully, or rolled back if the function throws an error.
Parameters
fn(tx: SqlTransaction) => unknown- Function to execute within the transaction
options?SqlTransactionOptions- Transaction options
copyFrom(table: string, data: AsyncIterable<unknown[]>): Promise<number>Copy data from an iterable into a table using PostgreSQL COPY protocol.
Parameters
tablestring- Target table name
dataAsyncIterable<unknown[]>- Async iterable of row arrays
copyTo(query: string): AsyncIterable<unknown[]>Copy data from a query result using PostgreSQL COPY protocol.
Parameters
querystring- SQL query to copy from
listen(channel: string): AsyncIterable<PostgresNotification>Listen for notifications on a channel.
Parameters
channelstring- Channel name to listen on
notify(channel: string, payload?: string): Promise<void>Send a notification on a channel.
Parameters
channelstring- Channel name
payload?string- Optional notification payload
close(): Promise<void>Close the client and release all connections.
#PostgresClientConfig
interface PostgresClientConfig extends CommonOptionsConfiguration for creating a PostgreSQL client.
| Name | Description |
|---|---|
url | Connection URL string or configuration object. |
pool | Pool configuration |
applicationName | Application name for PostgreSQL connection |
throwOnError | Whether to throw an error for query failures. |
Properties
Connection URL string or configuration object.
Pool configuration
- readonly
applicationName?stringApplication name for PostgreSQL connection
- readonly
throwOnError?booleanWhether to throw an error for query failures. When false, failures are returned as SqlQueryResultError or SqlQueryResultFailure. Can be overridden per-query via SqlQueryOptions.
#PostgresConnectionConfig
interface PostgresConnectionConfig extends CommonConnectionConfigPostgreSQL connection configuration.
Extends CommonConnectionConfig with PostgreSQL-specific options.
Properties
- readonly
database?stringDatabase name to connect to.
SSL/TLS configuration.
#PostgresErrorLike
interface PostgresErrorLikePostgreSQL error structure from the driver.
| Name | Description |
|---|---|
message | — |
code | — |
constraint | — |
Properties
- readonly
messagestring - readonly
code?string - readonly
constraint?string
#PostgresNotification
interface PostgresNotificationPostgreSQL LISTEN/NOTIFY notification.
| Name | Description |
|---|---|
channel | Channel name |
payload | Notification payload |
processId | Process ID of the notifying backend |
Properties
- readonly
channelstringChannel name
- readonly
payloadstringNotification payload
- readonly
processIdnumberProcess ID of the notifying backend
#PostgresPoolConfig
interface PostgresPoolConfigPool configuration for PostgreSQL.
| Name | Description |
|---|---|
max | Maximum number of connections in the pool |
idleTimeout | Idle timeout in milliseconds before closing unused connections |
connectTimeout | Connection timeout in milliseconds |
Properties
- readonly
max?numberMaximum number of connections in the pool
- readonly
idleTimeout?numberIdle timeout in milliseconds before closing unused connections
- readonly
connectTimeout?numberConnection timeout in milliseconds
#PostgresSslConfig
interface PostgresSslConfigSSL/TLS configuration for PostgreSQL connection.
| Name | Description |
|---|---|
rejectUnauthorized | Whether to reject unauthorized certificates. |
ca | CA certificate(s) for verification. |
cert | Client certificate for mutual TLS. |
key | Client private key for mutual TLS. |
Properties
- readonly
ca?stringCA certificate(s) for verification.
- readonly
cert?stringClient certificate for mutual TLS.
- readonly
key?stringClient private key for mutual TLS.
#SqlErrorOptions
interface SqlErrorOptions extends ErrorOptionsOptions for SqlError constructor.
| Name | Description |
|---|---|
sqlState | SQL State code (e.g., "23505" for unique violation) |
Properties
- readonly
sqlState?stringSQL State code (e.g., "23505" for unique violation)
#SqlQueryOptions
interface SqlQueryOptions extends CommonOptionsOptions for individual SQL queries.
| Name | Description |
|---|---|
throwOnError | Whether to throw an error for query failures. |
Properties
- readonly
throwOnError?booleanWhether to throw an error for query failures. When false, failures are returned as SqlQueryResultError or SqlQueryResultFailure.
#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.
| Name | Description |
|---|---|
processed | Server processed the query. |
ok | Query failed. |
error | Error describing the SQL error. |
rows | Empty rows for failed queries. |
rowCount | Zero affected rows for failed queries. |
lastInsertId | No lastInsertId for failed queries. |
warnings | No warnings for failed queries. |
Properties
- readonly
processedtrueServer processed the query.
- readonly
okfalseQuery failed.
Error describing the SQL error.
- readonly
rowsreadonly never[]Empty rows for failed queries.
- readonly
rowCount0Zero affected rows for failed queries.
- readonly
lastInsertIdnullNo lastInsertId for failed queries.
- readonly
warningsnullNo warnings for failed queries.
#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.).
| Name | Description |
|---|---|
processed | Server did not process the query. |
ok | Query failed. |
error | Error describing the failure. |
rows | No rows (query didn't reach server). |
rowCount | No row count (query didn't reach server). |
lastInsertId | No lastInsertId (query didn't reach server). |
warnings | No warnings (query didn't reach server). |
Properties
- readonly
processedfalseServer did not process the query.
- readonly
okfalseQuery failed.
Error describing the failure.
- readonly
rowsnullNo rows (query didn't reach server).
- readonly
rowCountnullNo row count (query didn't reach server).
- readonly
lastInsertIdnullNo lastInsertId (query didn't reach server).
- readonly
warningsnullNo warnings (query didn't reach server).
#SqlQueryResultSuccess
interface SqlQueryResultSuccess<T = any> extends SqlQueryResultBase<T>SQL query result for successful queries.
The query was executed successfully and returned results.
| Name | Description |
|---|---|
processed | Server processed the query. |
ok | Query succeeded. |
error | No error for successful queries. |
rows | Query result rows. |
rowCount | Number of affected rows. |
lastInsertId | Last inserted ID (for INSERT statements). |
warnings | Warning messages from the database. |
Properties
- readonly
processedtrueServer processed the query.
- readonly
oktrueQuery succeeded.
- readonly
errornullNo error for successful queries.
- readonly
rowsreadonly T[]Query result rows.
- readonly
rowCountnumberNumber of affected rows.
- readonly
lastInsertIdbigint | string | nullLast inserted ID (for INSERT statements).
- readonly
warningsunknown | nullWarning messages from the database.
#SqlQueryResultSuccessParams
interface SqlQueryResultSuccessParams<T = any>Parameters for creating a SqlQueryResultSuccess.
| Name | Description |
|---|---|
rows | The result rows |
rowCount | Number of affected rows (for INSERT/UPDATE/DELETE) |
duration | Query execution duration in milliseconds |
lastInsertId | Last inserted ID (for INSERT statements) |
warnings | Warning messages from the database |
Properties
- readonly
rowsreadonly T[]The result rows
- readonly
rowCountnumberNumber of affected rows (for INSERT/UPDATE/DELETE)
- readonly
durationnumberQuery execution duration in milliseconds
- readonly
lastInsertId?bigint | stringLast inserted ID (for INSERT statements)
- readonly
warnings?readonly string[]Warning messages from the database
#SqlTransaction
interface SqlTransactionSQL transaction interface. Implementations should provide actual database-specific transaction handling.
| Name | Description |
|---|---|
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
options?SqlQueryOptions- 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
options?SqlQueryOptions- Optional query options
commit(): Promise<void>Commit the transaction.
rollback(): Promise<void>Rollback the transaction.
#SqlTransactionOptions
interface SqlTransactionOptionsOptions for starting a transaction.
| Name | Description |
|---|---|
isolationLevel | Isolation level for the transaction |
Properties
Isolation level for the transaction
Functions
#createPostgresClient
async function createPostgresClient(
config: PostgresClientConfig,
): Promise<PostgresClient>Create a new PostgreSQL client instance.
The client provides connection pooling, parameterized queries, transaction support, and PostgreSQL-specific features like COPY and LISTEN/NOTIFY.
Parameters
configPostgresClientConfig- PostgreSQL client configuration
Returns
Promise<PostgresClient> — A promise resolving to a new PostgreSQL client instance
Examples
Using URL string
import { createPostgresClient } from "@probitas/client-sql-postgres";
const client = await createPostgresClient({
url: "postgres://user:pass@localhost:5432/mydb",
});
const result = await client.query("SELECT * FROM users WHERE id = $1", [1]);
if (result.ok) {
console.log(result.rows[0]);
}
await client.close();
Using connection config object
import { createPostgresClient } from "@probitas/client-sql-postgres";
const client = await createPostgresClient({
url: {
host: "localhost",
port: 5432,
database: "mydb",
username: "user",
password: "pass",
},
pool: { max: 10 },
applicationName: "my-app",
});
await client.close();
Transaction with auto-commit/rollback
import { createPostgresClient } from "@probitas/client-sql-postgres";
import type { SqlTransaction } from "@probitas/client-sql";
const client = await createPostgresClient({
url: "postgres://localhost:5432/mydb",
});
const user = await client.transaction(async (tx: SqlTransaction) => {
await tx.query("INSERT INTO users (name) VALUES ($1)", ["John"]);
return await tx.queryOne("SELECT * FROM users WHERE name = $1", ["John"]);
});
await client.close();
LISTEN/NOTIFY for real-time events
import { createPostgresClient } from "@probitas/client-sql-postgres";
const client = await createPostgresClient({
url: "postgres://localhost:5432/mydb",
});
// Listen for notifications
for await (const notification of client.listen("user_events")) {
console.log("Received:", notification.payload);
}
// In another session
await client.notify("user_events", JSON.stringify({ userId: 123 }));
await client.close();
Using await using for automatic cleanup
import { createPostgresClient } from "@probitas/client-sql-postgres";
await using client = await createPostgresClient({
url: "postgres://localhost:5432/mydb",
});
const result = await client.query("SELECT 1");
// Client automatically closed when scope exits
#isConnectionError
function isConnectionError(error: PostgresErrorLike): booleanCheck if an error is a connection-level error based on SQLSTATE or error characteristics.
Parameters
errorPostgresErrorLike
#mapPostgresError
function mapPostgresError(error: PostgresErrorLike): SqlErrorMaps a PostgreSQL error to the appropriate SqlError subclass.
Parameters
errorPostgresErrorLike- PostgreSQL error from the driver
Returns
SqlError — Mapped SqlError or subclass
Types
#SqlErrorKind
type SqlErrorKind = "query" | "constraint" | "deadlock" | "connection" | "unknown"SQL-specific error kinds.
#SqlFailureError
type SqlFailureError = SqlConnectionError | AbortError | TimeoutErrorError types that indicate the operation was not processed. These are errors that occur before the query reaches the SQL server.
#SqlIsolationLevel
type SqlIsolationLevel = "read_uncommitted" | "read_committed" | "repeatable_read" | "serializable"Transaction isolation level.
#SqlOperationError
type SqlOperationError = QuerySyntaxError | ConstraintError | DeadlockError | SqlErrorError types that indicate an operation was processed by the server. These errors occur after the query reaches the SQL server.
#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
