@flowblade/source-kysely
v1.13.2
Published
Kysely datasource
Readme
@flowblade/source-kysely
A source adapter for Kysely.
Install
pnpm add @flowblade/source-kysely kysely
# Install optional drivers
# 01. for Ms SqlServer or Azure Sql Edge
pnpm add tedious tarnKysely supports
Quick start
import { KyselyDatasource } from "@flowblade/source-kysely";
// Your Kysely instance, see the Utils section for Ms SqlServer
import { db } from "@/config/db.config.ts";
const ds = new KyselyDatasource({ connection: db });
const query = ds.queryBuilder // This gives access to Kysely expression builder
.selectFrom("brand as b")
.select(["b.id", "b.name"])
.leftJoin("product as p", "p.brand_id", "b.id")
.select(["p.id as product_id", "p.name as product_name"])
.where("b.created_at", "<", new Date())
.orderBy("b.name", "desc");
const result = await ds.query(query);
// Or with query information (will be sent in the metadata)
// const result = await ds.query(query, {
// name: 'getBrands'
// });
// Option 1: the QResult object contains the data, metadata and error
// - data: the result rows (TData or undefined if error)
// - error: the error (QError or undefined if success)
// - meta: the metadata (always present)
const { data, meta, error } = result;
// Option 2: You operate over the result, ie: mapping the data
const { data: data2 } = result.map((row) => {
return {
...row,
key: `key-${row.product_id}`,
};
});
// Or get the rows, throws a QErrors.QueryFailed on error (the driver error as cause)
const { data: rows } = await ds.queryOrThrow(query);KyselyDatasource uses the supplied Kysely instance but does not own or destroy it. Close its database connections when your application shuts down:
await db.destroy();Query a single row
queryOne() expects at most one row. Like query() it never throws: data holds the row, or null when the query returns no row.
const query = ds.queryBuilder
.selectFrom("brand as b")
.select(["b.id", "b.name"])
.where("b.id", "=", id);
const { data: brand, error } = await ds.queryOne(query);
if (error) {
// Query failure, or more than one row (error.code === "TOO_MANY_RESULTS")
throw new Error(error.message, { cause: error.cause });
}
if (brand === null) {
// Not found, ie: return a 404
}
// Optionally: map the row (null is kept as is, the mapper isn't called)
const { data: item } = (await ds.queryOne(query)).map((row) => ({
...row,
key: `key-${row.id}`,
}));queryOneOrThrow() returns the row, and throws when there isn't exactly one:
import { QErrors } from "@flowblade/source-kysely";
import { HttpNotFound } from "@httpx/exception";
// Throws a QErrors.NoResult (no row) or a QErrors.TooManyResults (more than one)
const { data: row, meta } = await ds.queryOneOrThrow(query);
// Return a default value when there's no row (still throws on query
// failure and when there's more than one row)
const { data: settings } = await ds.queryOneOrThrow(settingsQuery, {
defaultValue: defaultSettings,
});
// Throw your own errors
const { data: brand } = await ds.queryOneOrThrow(query, {
onNoResult: ({ error }) =>
new HttpNotFound({ message: `${id} not found`, cause: error }),
});
// Or recognize the flowblade errors
try {
await ds.queryOneOrThrow(query);
} catch (e) {
if (e instanceof QErrors.NoResult) {
// e.statusCode === 404
} else if (e instanceof QErrors.TooManyResults) {
console.error(`Expected one row, got ${e.rowCount}`); // e.statusCode === 500
}
throw e;
}The error factories can also be set once for the whole datasource with defaultOptions, keyed by method name (the options passed per query win):
import { HttpInternalServerError, HttpNotFound } from "@httpx/exception";
const ds = new KyselyDatasource({
connection: db,
defaultOptions: {
// Used by queryOneOrThrow() only, queryOne() never throws
queryOneOrThrow: {
// onError: ({ error }) => ..., for query failures
onNoResult: ({ error }) =>
new HttpNotFound({ message: "Resource not found", cause: error }),
onTooManyResults: ({ error, rowCount }) =>
new HttpInternalServerError({
message: `Expected one row, got ${rowCount}`,
cause: error,
}),
},
},
});QErrors.NoResult and QErrors.TooManyResults carry a suggested http statusCode (404 and 500), see Error handling.
Migrating from queryOne().getOrThrow()
QResult.getOrThrow() is deprecated, use queryOneOrThrow(). By default it throws the same errors, but it also applies the defaultOptions.queryOneOrThrow factories, which getOrThrow() ignored: when they're set, pass onError: ({ error }) => error (and onTooManyResults) to keep the default errors. Set defaultValue: null to keep getting null when there's no row:
// ⚠️ Deprecated
const row = (await ds.queryOne(query)).getOrThrow();
// ✅ Same behavior: null when there's no row
const { data: row } = await ds.queryOneOrThrow(query, { defaultValue: null });Prefer defaultValue (or checking error) to falling back on data, which hides failures:
// ✅ Query failures and more than one row still throw
const { data: settings } = await ds.queryOneOrThrow(query, {
defaultValue: defaultSettings,
});
// ❌ On error, data is undefined: the fallback hides the failure
const { data } = await ds.queryOne(query);
const settings = data ?? defaultSettings;Note: the SQL is never rewritten (no
LIMITadded) and checking the row count costs nothing, but all rows are fetched. When the query isn't constrained by a unique key, bound it to 2 rows (ie:.limit(2), or.top(2)on Ms SqlServer).
Streaming
import { KyselyDatasource } from "@flowblade/source-kysely";
const ds = new KyselyDatasource({ connection: db });
const query = ds.queryBuilder // This gives access to Kysely expression builder
.selectFrom("brand as b")
.select(["b.id", "b.name"]);
const stream = ds.stream(query, {
name: "getBrands",
// Chunksize used when reading the database (only some dialects, ie: postgres)
// @default undefined
chunkSize: undefined,
// Optional abort signal, see "Aborting queries"
signal: AbortSignal.timeout(30_000),
});
for await (const brand of stream) {
console.log(brand.name);
if (brand.name === "Something") {
// Breaking or returning before the stream has ended will release
// the database connection and invalidate the stream.
break;
}
}A failed stream throws a QErrors.QueryFailed with the driver error as cause, or a QErrors.Aborted (see Aborting queries).
Error handling
query() never throws, failures are returned in result.error with the original driver error as cause (or the abort reason when aborted):
const result = await ds.query(query);
if (result.error) {
console.log(result.error.message);
// The original driver error, ie: a tedious RequestError for Ms SqlServer
const cause = result.error.cause as { number?: number } | undefined;
if (cause?.number === 1205) {
// SQL Server deadlock, the query can be retried
}
}
// The cause is never serialized, safe to send to clients
const json = result.toJsonifiable();Every error has a code, to switch over:
const { data, error } = await ds.query(query);
if (error) {
switch (error.code) {
case "QUERY_FAILED": // the driver error is the cause
case "ABORTED": // aborted with the signal, the abort reason is the cause
case "TOO_MANY_RESULTS": // queryOne() got more than one row
case "MAP_FAILED": // the result.map() transform threw
}
}The throwing methods (queryOrThrow(), queryOneOrThrow() and stream()) throw errors exported under the QErrors namespace, usable with instanceof:
| Error | When | statusCode |
| --- | --- | --- |
| QErrors.QueryFailed | the query failed, message prefixed with "Query failed: ", the driver error as cause | 500 |
| QErrors.Aborted | the query was aborted, message prefixed with "Query aborted: ", the abort reason as cause | 504 on timeout, 499 otherwise |
| QErrors.NoResult | queryOneOrThrow() got no row | 404 |
| QErrors.TooManyResults | queryOne() / queryOneOrThrow() got more than one row (with rowCount) | 500 |
The statusCode is a suggested http status, recognized by http error helpers such as isErrorWithErrorStatusCode() from @httpx/exception:
import { QErrors } from "@flowblade/source-kysely";
import { isErrorWithErrorStatusCode } from "@httpx/exception";
try {
const { data } = await ds.queryOrThrow(query, {
signal: AbortSignal.timeout(5_000),
});
} catch (e) {
if (e instanceof QErrors.Aborted) {
// e.statusCode === 504, e.cause is the TimeoutError
}
if (isErrorWithErrorStatusCode(e)) {
// ie: return new Response(null, { status: e.statusCode });
}
throw e;
}To throw your own errors, the throwing methods accept error factories, per call or as datasource defaults (defaultOptions, keyed by method name, the options passed per call win). Each factory receives the default error, useful as cause:
| Method | Factories | Datasource defaults |
| --- | --- | --- |
| queryOrThrow() | onError | defaultOptions.queryOrThrow |
| queryOneOrThrow() | onError, onNoResult, onTooManyResults | defaultOptions.queryOneOrThrow |
onError({ error, qError, meta }) handles query failures (qError.code: "QUERY_FAILED" or "ABORTED"), the row count errors have their own factories.
import { HttpGatewayTimeout, HttpInternalServerError } from "@httpx/exception";
const onError = ({ error, qError }) =>
qError.code === "ABORTED"
? new HttpGatewayTimeout({ cause: error })
: new HttpInternalServerError({ cause: error });
// Per call
const { data } = await ds.queryOrThrow(query, { onError });
// Or for the whole datasource
const ds = new KyselyDatasource({
connection: db,
defaultOptions: {
queryOrThrow: { onError },
queryOneOrThrow: { onError },
},
});Transactions
Run queries in a transaction with transaction() (returns a QResult, never throws) or transactionOrThrow(). The callback receives a datasource (tx) running its queries in the transaction: committed when the callback returns, rolled back when it throws or calls tx.rollback(). Throw QErrors.DomainRollback for an expected business rejection.
const {
data: orderId,
error,
meta,
} = await ds.transaction(
async (tx) => {
const { data: order } = await tx.queryOneOrThrow(
tx.queryBuilder
.insertInto("order")
.values({ customer_id: customerId })
.output(["inserted.id"])
);
const { data: stock } = await tx.queryOneOrThrow(getStock);
if (stock.quantity < quantity) {
tx.rollback("out of stock"); // error.code: "ROLLED_BACK"
}
await tx.queryOrThrow(insertOrderLines(order.id));
return order.id;
},
{
name: "createOrder",
isolationLevel: "serializable", // optional, also: accessMode, signal
retry: { maxRetries: 3 }, // serializable: run it again on conflict
}
);
if (error) {
// "ROLLED_BACK": callback threw unexpectedly (ie: tx.queryOrThrow()) or called tx.rollback()
// "DOMAIN_ROLLBACK": callback threw QErrors.DomainRollback; reason/details are preserved
// "TRANSACTION_FAILED": a query failed (handled by the callback), or couldn't begin, commit or roll back
// "TRANSACTION_CONFLICT": conflicts with a concurrent transaction, see retry
// "ABORTED": aborted with signal, never committed
console.error(error.code, error.message, error.cause);
}
// meta: a "transaction" span followed by the spans of the queries
// Or throw: the error thrown by the callback as is, a QErrors.TransactionConflict, QErrors.TransactionFailed or QErrors.Aborted
const { data } = await ds.transactionOrThrow(async (tx) => {
/* ... */
});Throw QErrors.DomainRollback from the transaction callback for an expected domain rejection that should roll back. transaction() reports DOMAIN_ROLLBACK with serializable reason and details; transactionOrThrow() rethrows the error instance for instanceof handling. See the core transaction guide for an example.
On SQL Server, a trigger or other database logic can roll back the transaction before Flowblade starts its cleanup. If the cleanup rollback then returns driver error 3903 (no corresponding active transaction), Flowblade treats that rollback as already complete and preserves the original callback error, including QErrors.DomainRollback. Other rollback errors are still reported as TRANSACTION_FAILED.
PostgreSQL behaves differently: a trigger exception marks the transaction as aborted, but the transaction remains open until the client issues ROLLBACK. Flowblade's rollback succeeds in that state, so the original callback/domain error is preserved without special handling for PostgreSQL.
Conflicts with a concurrent transaction (serialization failure, deadlock) are reported as TRANSACTION_CONFLICT, run the transaction again with the retry option (the callback is called again: keep its side effects in the transaction):
const { data, error } = await ds.transaction(fn, {
isolationLevel: "serializable",
// waits 25-50ms, 50-100ms then 100-200ms by default (exponential backoff
// with jitter), or set delayMs: (retry) => ms
retry: { maxRetries: 3 },
});The retry policy can be set for all the transactions of the datasource with defaultOptions.transaction.retry, the retry fields passed per transaction win (ie: { maxRetries: 0 } disables the retries). createExponentialBackoff() configures the delay (initialDelayMs, maxDelayMs and jitter: "equal" by default, "full" or "none"):
import { createExponentialBackoff } from "@flowblade/core";
const ds = new KyselyDatasource({
connection: db,
defaultOptions: {
transaction: {
retry: {
maxRetries: 3,
// 0-100ms, 0-200ms then 0-400ms
delayMs: createExponentialBackoff({
initialDelayMs: 100,
maxDelayMs: 2000,
jitter: "full",
}),
},
},
},
});Postgres, SQL Server and MySQL conflicts are recognized, set the isTransactionConflict param for other databases.
Savepoints
tx.savepoint() (returns a QResult) and tx.savepointOrThrow() run a part of the transaction that can be rolled back alone: released when the callback returns, rolled back when it throws or a query failed in it, the transaction goes on. Savepoints can be nested.
await ds.transactionOrThrow(async (tx) => {
await tx.queryOrThrow(insertOrder);
// a duplicate tag is fine: only the savepoint is rolled back
const { error } = await tx.savepoint((sp) => sp.queryOrThrow(insertTag), {
name: "insertTag",
});
await tx.queryOrThrow(insertOrderLines);
});It's the way to recover from a failed query on Postgres, which aborts the whole transaction otherwise. A conflict or a failed savepoint statement fails the transaction too. With onFailedQuery: "commit", a savepoint whose failed query was handled by the callback is released, its other queries are committed. tx.savepointOrThrow() rolls back the savepoint then rethrows: catch the error for the transaction to go on. Requires a dialect supporting savepoints (Postgres, MySQL, SQL Server, SQLite).
Failed queries handled by the callback
By default a failed query is never committed, even when handled by the callback (onFailedQuery: "rollback"). With SQL Server (without XACT_ABORT) or MySQL, a failed statement doesn't abort the transaction: set onFailedQuery: "commit" to commit anyway (never with Postgres, the commit would silently roll back; prefer a savepoint when possible).
await ds.transaction(fn, { onFailedQuery: "commit" });Note: by default (
onFailedQuery: "rollback"), a failed query is never committed, even when handled by the callback (ie:tx.query()never throws): the transaction is rolled back with aTRANSACTION_FAILEDerror (Postgres aborts the transaction on error and would silently roll back on commit). Prefer the throwing methods in the callback. Always usetx(notds) in the callback (a query built withds.queryBuilderand run withtxruns in the transaction), nested transactions aren't supported.
Aborting queries
All the query methods and stream() accept an AbortSignal:
const result = await ds.query(query, {
signal: AbortSignal.timeout(5_000),
});
// An aborted query returns an error result with code "ABORTED", the throwing
// methods and streams throw a QErrors.Aborted (504 on timeout, 499 otherwise).
// In both cases the error cause is the abort reason (ie: AbortError, TimeoutError)By default the query keeps running on the database once aborted, only the result is ignored. Use inflightQueryAbortStrategy to cancel it on the database (ie: Ms SqlServer, Postgres, MySQL):
const ds = new KyselyDatasource({
connection: db,
defaultOptions: {
// Used by query(), queryOrThrow(), queryOne() and queryOneOrThrow()
query: {
// 'ignore query' (default) | 'cancel query' | 'kill session'
inflightQueryAbortStrategy: "cancel query",
},
},
});
// Or per query
await ds.query(query, {
signal,
inflightQueryAbortStrategy: "cancel query",
});Note: Dialects that can't cancel fall back to
'ignore query'with a warning. Postgres and MySQL cancel through an extra connection, Ms SqlServer through the same one.
Logging
Queries are logged with LogTape under the ["flowblade", "kysely"] category: debug when starting, info on success (time and affected rows), error on failure. queryOne() and queryOneOrThrow() also log more than one row as a warning and no row at debug level. Nothing is logged until LogTape is configured by your application:
import { flowbladeLogtapeKyselyConfig } from "@flowblade/source-kysely";
import { configure, getConsoleSink } from "@logtape/logtape";
await configure({
sinks: { console: getConsoleSink() },
loggers: [
{
category: flowbladeLogtapeKyselyConfig.categories,
lowestLevel: "info",
sinks: ["console"],
},
],
});Logs include the sql and its params. When params might contain sensitive data, leave them out of the logs (they stay available in the result meta):
const ds = new KyselyDatasource({ connection: db, logParams: false });A custom LogTape logger can also be given with the logger option.
Utils
createKyselyMssqlDialect
Create a Kysely dialect for Ms SqlServer or Azure Sql Edge.
import {
TediousConnUtils,
createKyselyMssqlDialect,
} from "@flowblade/source-kysely";
import * as Tedious from "tedious";
const jdbcDsn =
"sqlserver://localhost:1433;database=db;user=sa;password=pwd;trustServerCertificate=true;encrypt=false";
const tediousConfig = TediousConnUtils.fromJdbcDsn(jdbcDsn);
const dialect = createKyselyMssqlDialect({
tediousConfig,
// 👉 Optional tarn pool options
poolOptions: {
min: 0, // 👉 Minimum number of connections, default 0
max: 10, // 👉 Maximum number of connections, default 10
propagateCreateError: true, // 👉 Propagate connection creation errors, default false
},
dialectConfig: {
/**
* When true, connections are validated before being acquired from the pool,
* resulting in additional requests to the database.
*
* In safe scenarios, this can be set to false to improve performance.
*
* Defaults to `true`.
*/
validateConnections: true,
/**
* When true, connections are reset to their initial states when released back to the pool,
* resulting in additional requests to the database.
*
* Defaults to `false`.
*/
resetConnectionsOnRelease: false,
// 👉 Override Tedious types to enhance compatibility and modern support
tediousTypes: {
...Tedious.TYPES,
// see https://github.com/kysely-org/kysely/issues/1161#issuecomment-2384539764
NVarChar: Tedious.TYPES.VarChar,
// see https://github.com/kysely-org/kysely/issues/1596#issuecomment-3341591075
DateTime: Tedious.TYPES.DateTime2,
},
},
});
const db = new Kysely<DB>({
dialect,
});Note: For performance you can avoid connection roundtrips by setting
validateConnectionstofalseandresetConnectionsOnReleasetofalse.
TediousConnUtils
fromJdbcDsn
Parse and validate a JDBC connection string and return a Tedious connection configuration.
import { TediousConnUtils } from "@flowblade/source-kysely";
import * as Tedious from "tedious";
// In your .env file
// DB_JDBC_DSN="sqlserver://localhost:1433;database=db;user=sa;password=pwd;trustServerCertificate=true;encrypt=false";
const tediousConfig = TediousConnUtils.fromJdbcDsn(process.env.DB_JDBC_DSN);
const tediousConnection = new Tedious.Connection(tediousConfig);Compatibility
| Level | CI | Description | | --- | --- | --- | | Node | ✅ | Requires 22.18+, CI for 22.x, 24.x & 26.x | | Bun | ✅ | Bun 1.4+, unit tests run on CI with the latest Bun | | Deno | ✅ | Deno LTS, unit tests run on CI with Deno 2 | | Browserslist | ✅ | > 95% on 01/2025. Chrome 96+, Firefox 90+, Edge 19+, ios 15+, Safari 15+ and Opera 77+ | | Typescript | ✅ | TS 5.0 + / are-the-type-wrong checks on CI. | | ES2022 | ✅ | Dist files checked with es-check |
Contributors
Contributions are welcome. Have a look to the CONTRIBUTING document.
Sponsors
Sponsor, coffee, or star – All is spent for quality time with loved ones. Thanks ! 🙏❤️
Special thanks to
License
MIT © Sébastien Vanvelthem and contributors.
