@relaybus/postgres 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pg-executor.ts","../src/identifiers.ts","../src/names.ts","../src/sql-fragments.ts","../src/schema.ts","../src/row-mapping.ts","../src/statements.ts","../src/postgres-event-store.ts"],"names":["ConfigurationError"],"mappings":";;;;AAQO,IAAM,aAAN,MAAyD;AAAA,EACrD,KAAA;AAAA,EAET,YAAY,IAAA,EAAY;AACtB,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AAAA,EACf;AAAA,EAEA,MAAM,YAAe,IAAA,EAA2D;AAC9E,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,KAAA,CAAM,OAAA,EAAQ;AACxC,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,MAAM,OAAO,CAAA;AAC1B,MAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,MAAM,CAAA;AAChC,MAAA,MAAM,MAAA,CAAO,MAAM,QAAQ,CAAA;AAC3B,MAAA,MAAA,CAAO,OAAA,EAAQ;AACf,MAAA,OAAO,MAAA;AAAA,IACT,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,IAAA,CAAK,oBAAoB,MAAM,CAAA;AACrC,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,KAAA,CACJ,GAAA,EACA,UAAA,EACA,WAAA,EACiC;AACjC,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,WAAA,IAAe,IAAA,CAAK,KAAA,EAAO,MAAmB,GAAA,EAAK,CAAC,GAAG,UAAU,CAAC,CAAA;AACxF,IAAA,OAAO,MAAA,CAAO,IAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAM,oBAAoB,MAAA,EAAmC;AAC3D,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,CAAO,MAAM,UAAU,CAAA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S,WAAA,CAAY,WAAA;AAAY,SAChD,CAAA;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,UAAA,EAAY,QAAA,EAAS;AACxC;AAEA,SAAS,WAAA,CACP,QACA,cAAA,EACY;AACZ,EAAA,MAAM,aAAA,GAAgB,IAAI,GAAA,CAAI,cAAc,CAAA;AAC5C,EAAA,OAAO,MAAA,CAAO,GAAA,CAAI,CAAC,KAAA,KAAU;AAC3B,IAAA,IAAI,QAAA,GAA0B,IAAA;AAC9B,IAAA,IAAI,KAAA,CAAM,QAAQ,IAAA,EAAM;AACtB,MAAA,MAAM,IAAA,GAAO,aAAA,CAAc,GAAA,CAAI,KAAA,CAAM,GAAG,CAAA;AACxC,MAAA,aAAA,CAAc,GAAA,CAAI,KAAA,CAAM,GAAA,EAAK,IAAA,GAAO,EAAE,CAAA;AACtC,MAAA,QAAA,GAAW,KAAK,QAAA,EAAS;AAAA,IAC3B;AACA,IAAA,OAAO;AAAA,MACL,IAAI,KAAA,CAAM,EAAA;AAAA,MACV,MAAM,KAAA,CAAM,IAAA;AAAA,MACZ,QAAQ,KAAA,CAAM,MAAA;AAAA,MACd,KAAK,KAAA,CAAM,GAAA;AAAA,MACX,QAAA;AAAA,MACA,SAAS,KAAA,CAAM,OAAA;AAAA,MACf,SAAS,KAAA,CAAM,OAAA;AAAA,MACf,gBAAgB,KAAA,CAAM,aAAA;AAAA,MACtB,cAAc,KAAA,CAAM,WAAA;AAAA,MACpB,WAAA,EAAa,KAAA,CAAM,UAAA,CAAW,WAAA;AAAY,KAC5C;AAAA,EACF,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["import type { Pool, PoolClient } from 'pg';\nimport type { PostgresExecutor, PostgresParameter, PostgresRow } from './executor.js';\n\n/**\n * Executor for a `pg` {@link Pool}. A transaction is a dedicated pool client\n * between `BEGIN` and `COMMIT`; it is handed to callers as the transaction\n * handle, so they can run their own queries on it.\n */\nexport class PgExecutor implements PostgresExecutor<PoolClient> {\n readonly #pool: Pool;\n\n constructor(pool: Pool) {\n this.#pool = pool;\n }\n\n async transaction<T>(work: (transaction: PoolClient) => Promise<T>): Promise<T> {\n const client = await this.#pool.connect();\n try {\n await client.query('BEGIN');\n const result = await work(client);\n await client.query('COMMIT');\n client.release();\n return result;\n } catch (error) {\n await this.#rollbackAndRelease(client);\n throw error;\n }\n }\n\n async query(\n sql: string,\n parameters: readonly PostgresParameter[],\n transaction?: PoolClient,\n ): Promise<readonly PostgresRow[]> {\n const result = await (transaction ?? this.#pool).query<PostgresRow>(sql, [...parameters]);\n return result.rows;\n }\n\n /** A client whose rollback fails is in an unknown state, so it is destroyed instead of reused. */\n async #rollbackAndRelease(client: PoolClient): Promise<void> {\n try {\n await client.query('ROLLBACK');\n client.release();\n } catch {\n client.release(true);\n }\n }\n}\n","import { ConfigurationError } from '@relaybus/core';\n\nconst IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_]*$/;\nconst MAXIMUM_IDENTIFIER_LENGTH = 63;\n\n/**\n * Throws {@link ConfigurationError} unless `value` is a plain lower-case\n * PostgreSQL identifier. Identifiers are interpolated into SQL text (they\n * cannot be bound as parameters), so this is the injection boundary: only\n * letters, digits and underscores survive, and nothing needs escaping.\n */\nexport function assertIdentifier(label: string, value: string): void {\n if (!IDENTIFIER_PATTERN.test(value) || value.length > MAXIMUM_IDENTIFIER_LENGTH) {\n throw new ConfigurationError(\n `${label} '${value}' must match ${String(IDENTIFIER_PATTERN)} and be at most ${MAXIMUM_IDENTIFIER_LENGTH} characters`,\n );\n }\n}\n\n/** Double-quotes an identifier that already passed {@link assertIdentifier}. */\nexport function quoteIdentifier(value: string): string {\n return `\"${value}\"`;\n}\n","import { ConfigurationError } from '@relaybus/core';\nimport { assertIdentifier, quoteIdentifier } from './identifiers.js';\n\n/** Where relaybus keeps its tables. */\nexport interface PostgresSchemaOptions {\n /** Schema that holds the tables. Created by `setup()` when it is not `public`. Default `'public'`. */\n readonly schema?: string;\n /**\n * Prepended to every table and index name, which makes the names\n * `<prefix>events`, `<prefix>deliveries` and `<prefix>key_sequences`.\n * Lower-case letters, digits and underscores. Default `'relaybus_'`.\n */\n readonly tablePrefix?: string;\n}\n\n/** Validated, quoted names used to build SQL. */\nexport interface PostgresNames {\n readonly schema: string;\n readonly quotedSchema: string;\n readonly events: string;\n readonly deliveries: string;\n readonly keySequences: string;\n /** Index names, quoted but not schema-qualified (an index lives in its table's schema). */\n readonly indexes: {\n readonly deliveryEventHandler: string;\n readonly deliveryDue: string;\n readonly deliveryDueUnkeyed: string;\n readonly deliveryHandlerCreated: string;\n readonly eventCreated: string;\n readonly deliveryKeyUnfinished: string;\n readonly deliveryKeyProcessing: string;\n readonly deliveryStatusCreated: string;\n readonly deliveryCompleted: string;\n readonly deliveryDead: string;\n };\n}\n\nconst DEFAULT_SCHEMA = 'public';\nconst DEFAULT_TABLE_PREFIX = 'relaybus_';\nconst TABLE_PREFIX_PATTERN = /^[a-z0-9_]*$/;\n\n/**\n * Validates the options and derives every name the store uses. Every name,\n * including the longest index name, is checked against the PostgreSQL 63\n * character limit so that a too-long prefix fails here and not as a\n * silently truncated, colliding name in the database.\n */\nexport function resolvePostgresNames(options: PostgresSchemaOptions = {}): PostgresNames {\n const schema = options.schema ?? DEFAULT_SCHEMA;\n const tablePrefix = options.tablePrefix ?? DEFAULT_TABLE_PREFIX;\n assertIdentifier('schema', schema);\n if (!TABLE_PREFIX_PATTERN.test(tablePrefix)) {\n throw new ConfigurationError(\n `tablePrefix '${tablePrefix}' must match ${String(TABLE_PREFIX_PATTERN)}`,\n );\n }\n const name = (suffix: string): string => {\n const identifier = `${tablePrefix}${suffix}`;\n assertIdentifier(`tablePrefix '${tablePrefix}' produces the name`, identifier);\n return identifier;\n };\n const quotedSchema = quoteIdentifier(schema);\n const table = (suffix: string): string => `${quotedSchema}.${quoteIdentifier(name(suffix))}`;\n const index = (suffix: string): string => quoteIdentifier(name(suffix));\n return {\n schema,\n quotedSchema,\n events: table('events'),\n deliveries: table('deliveries'),\n keySequences: table('key_sequences'),\n indexes: {\n deliveryEventHandler: index('deliveries_event_handler_unique'),\n deliveryDue: index('deliveries_due_idx'),\n deliveryDueUnkeyed: index('deliveries_due_unkeyed_idx'),\n deliveryHandlerCreated: index('deliveries_handler_created_idx'),\n eventCreated: index('events_created_idx'),\n deliveryKeyUnfinished: index('deliveries_key_unfinished_idx'),\n deliveryKeyProcessing: index('deliveries_key_processing_idx'),\n deliveryStatusCreated: index('deliveries_status_created_idx'),\n deliveryCompleted: index('deliveries_completed_idx'),\n deliveryDead: index('deliveries_dead_idx'),\n },\n };\n}\n","/**\n * The instant a delivery becomes claimable: `available_at` while pending,\n * `lease_expires_at` while processing. The claim query, the statistics query\n * and the partial index all use this exact expression, which is what lets\n * PostgreSQL answer \"earliest due delivery\" from an index.\n */\nexport function dueAtExpression(alias?: string): string {\n const prefix = alias === undefined ? '' : `${alias}.`;\n return `CASE WHEN ${prefix}status = 'pending' THEN ${prefix}available_at ELSE ${prefix}lease_expires_at END`;\n}\n\n/**\n * Renders a timestamptz as ISO-8601 text in UTC. Reading timestamps as text\n * makes results independent of the driver's type parsers (Drizzle, for\n * instance, replaces them) and of the session time zone.\n */\nexport function isoText(expression: string): string {\n return `to_char(${expression} AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"')`;\n}\n","import { resolvePostgresNames, type PostgresSchemaOptions } from './names.js';\nimport { dueAtExpression } from './sql-fragments.js';\n\n/**\n * Statements that create the schema, tables and indexes, in dependency order.\n * Every statement is idempotent (`IF NOT EXISTS`). Run them in one transaction\n * and serialize concurrent runs (see {@link PostgresEventStore.setup}), or\n * paste {@link createPostgresSchemaSql} into your own migration tool.\n *\n * `events.id` and `deliveries.id` are `text` so that any caller-supplied id\n * (UUID, ULID, deterministic business id) is accepted. `deliveries.id` uses the\n * `C` collation so that ordering by id matches a byte-wise comparison on every\n * database, whatever its locale.\n */\nexport function createPostgresSchemaStatements(options: PostgresSchemaOptions = {}): string[] {\n const names = resolvePostgresNames(options);\n const unfinished = `status IN ('pending', 'processing')`;\n const statements = [\n `CREATE TABLE IF NOT EXISTS ${names.events} (\n id text PRIMARY KEY,\n type text NOT NULL,\n source text NOT NULL,\n key text,\n sequence bigint,\n payload jsonb NOT NULL,\n headers jsonb NOT NULL DEFAULT '{}'::jsonb,\n correlation_id text,\n causation_id text,\n occurred_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL\n)`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.eventCreated} ON ${names.events} (created_at, id)`,\n `CREATE TABLE IF NOT EXISTS ${names.keySequences} (\n key text PRIMARY KEY,\n sequence bigint NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS ${names.deliveries} (\n id text COLLATE \"C\" PRIMARY KEY,\n event_id text NOT NULL REFERENCES ${names.events} (id) ON DELETE CASCADE,\n handler text NOT NULL,\n status text NOT NULL CHECK (status IN ('pending', 'processing', 'completed', 'dead')),\n attempts integer NOT NULL DEFAULT 0,\n available_at timestamptz NOT NULL,\n lease_owner text,\n lease_token text,\n lease_expires_at timestamptz,\n last_error jsonb,\n key text,\n sequence bigint,\n created_at timestamptz NOT NULL,\n updated_at timestamptz NOT NULL,\n completed_at timestamptz,\n CONSTRAINT ${names.indexes.deliveryEventHandler} UNIQUE (event_id, handler)\n)`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryDue} ON ${names.deliveries} ((${dueAtExpression()}), id) WHERE ${unfinished}`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryDueUnkeyed} ON ${names.deliveries} ((${dueAtExpression()}), id) WHERE key IS NULL AND ${unfinished}`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryKeyUnfinished} ON ${names.deliveries} (handler, key, sequence) WHERE key IS NOT NULL AND ${unfinished}`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryKeyProcessing} ON ${names.deliveries} (handler, key) WHERE key IS NOT NULL AND status = 'processing'`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryStatusCreated} ON ${names.deliveries} (status, created_at, id)`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryHandlerCreated} ON ${names.deliveries} (handler, created_at, id)`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryCompleted} ON ${names.deliveries} (completed_at, id) WHERE status = 'completed'`,\n `CREATE INDEX IF NOT EXISTS ${names.indexes.deliveryDead} ON ${names.deliveries} (updated_at, id) WHERE status = 'dead'`,\n ];\n if (names.schema !== 'public') {\n statements.unshift(`CREATE SCHEMA IF NOT EXISTS ${names.quotedSchema}`);\n }\n return statements;\n}\n\n/**\n * The statements of {@link createPostgresSchemaStatements} as one SQL script,\n * for migration tools. Pair it with `new RelayBus({ setupStore: false })`.\n */\nexport function createPostgresSchemaSql(options: PostgresSchemaOptions = {}): string {\n return `${createPostgresSchemaStatements(options).join(';\\n\\n')};\\n`;\n}\n","import type {\n ClaimedDelivery,\n DeliveryRecord,\n DeliveryStatus,\n ErrorInfo,\n EventEnvelope,\n EventHeaders,\n} from '@relaybus/core';\nimport type { PostgresRow } from './executor.js';\n\n// Rows come from statements written in this package, so their shape is known.\n// Casting here is the single place where driver output is trusted.\n\nfunction text(row: PostgresRow, column: string): string {\n return row[column] as string;\n}\n\nfunction nullableText(row: PostgresRow, column: string): string | null {\n return row[column] as string | null;\n}\n\nfunction nullableDate(row: PostgresRow, column: string): Date | null {\n const value = nullableText(row, column);\n return value === null ? null : new Date(value);\n}\n\n/** Count columns arrive as number, string or bigint depending on the driver. */\nexport function readCount(row: PostgresRow, column: string): number {\n return Number(row[column]);\n}\n\nexport function mapEventEnvelope(row: PostgresRow): EventEnvelope {\n return {\n id: text(row, 'event_id'),\n type: text(row, 'event_type'),\n source: text(row, 'event_source'),\n key: nullableText(row, 'event_key'),\n payload: JSON.parse(text(row, 'event_payload')) as unknown,\n headers: JSON.parse(text(row, 'event_headers')) as EventHeaders,\n correlationId: nullableText(row, 'event_correlation_id'),\n causationId: nullableText(row, 'event_causation_id'),\n occurredAt: new Date(text(row, 'event_occurred_at')),\n };\n}\n\nexport function mapClaimedDelivery(row: PostgresRow, leaseExpiresAt: Date): ClaimedDelivery {\n return {\n deliveryId: text(row, 'delivery_id'),\n leaseToken: text(row, 'lease_token'),\n handler: text(row, 'handler'),\n attempt: readCount(row, 'attempts'),\n leaseExpiresAt,\n event: mapEventEnvelope(row),\n };\n}\n\nexport function mapDeliveryRecord(row: PostgresRow): DeliveryRecord {\n const lastError = nullableText(row, 'last_error');\n return {\n id: text(row, 'delivery_id'),\n handler: text(row, 'handler'),\n status: text(row, 'status') as DeliveryStatus,\n attempts: readCount(row, 'attempts'),\n availableAt: new Date(text(row, 'available_at')),\n leaseOwner: nullableText(row, 'lease_owner'),\n leaseExpiresAt: nullableDate(row, 'lease_expires_at'),\n lastError: lastError === null ? null : (JSON.parse(lastError) as ErrorInfo),\n createdAt: new Date(text(row, 'created_at')),\n updatedAt: new Date(text(row, 'updated_at')),\n completedAt: nullableDate(row, 'completed_at'),\n event: mapEventEnvelope(row),\n };\n}\n\nexport function mapOldestDueAt(rows: readonly PostgresRow[]): Date | null {\n return rows.length === 0 ? null : new Date(text(rows[0]!, 'oldest_due_at'));\n}\n","import type { DeliveryQuery } from '@relaybus/core';\nimport type { PostgresNames } from './names.js';\nimport { dueAtExpression, isoText } from './sql-fragments.js';\nimport type { PostgresParameter } from './executor.js';\n\nexport interface PostgresStatement {\n readonly sql: string;\n readonly parameters: readonly PostgresParameter[];\n}\n\nconst DEFAULT_LIST_LIMIT = 100;\n\nfunction eventColumns(alias: string): string {\n return `${alias}.id AS event_id,\n ${alias}.type AS event_type,\n ${alias}.source AS event_source,\n ${alias}.key AS event_key,\n ${alias}.payload::text AS event_payload,\n ${alias}.headers::text AS event_headers,\n ${alias}.correlation_id AS event_correlation_id,\n ${alias}.causation_id AS event_causation_id,\n ${isoText(`${alias}.occurred_at`)} AS event_occurred_at`;\n}\n\n/** `WITH changed AS (<dml> RETURNING 1) SELECT count(*)`: a top-level SELECT works the same on every driver. */\nfunction countChanged(dml: string): string {\n return `WITH changed AS (${dml} RETURNING 1) SELECT count(*)::int AS count FROM changed`;\n}\n\n/**\n * Due deliveries the fast claim examines before it gives up and lets the slow\n * claim look at the heads of all keys.\n */\nconst CLAIM_SCAN_WINDOW = 256;\n\nconst UNFINISHED_PREDICATE = (alias: string): string =>\n `${alias}.status IN ('pending', 'processing')`;\n\nconst HANDLER_PREDICATE = `delivery.handler = ANY (ARRAY(SELECT jsonb_array_elements_text($2::jsonb)))`;\n\nconst CLEAR_LEASE = 'lease_owner = NULL, lease_token = NULL, lease_expires_at = NULL';\n\n/**\n * SQL text for every operation of the store. Statements take their data as\n * parameters; only validated identifiers are interpolated. Documents travel\n * as one JSON text parameter expanded server-side with `jsonb_to_recordset`,\n * which keeps the statements identical across drivers and avoids array\n * literal encoding differences.\n */\nexport class PostgresStatements {\n readonly #names: PostgresNames;\n\n constructor(names: PostgresNames) {\n this.#names = names;\n }\n\n /**\n * Lock advisory key text for {@link setupLock}. It is derived from the schema\n * name only, so stores with different table prefixes in one schema also\n * serialize their `CREATE SCHEMA IF NOT EXISTS`, which is not race-free.\n */\n get setupLockKey(): string {\n return `relaybus:${this.#names.schema}`;\n }\n\n get setupLock(): string {\n return 'SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))';\n }\n\n /**\n * Reserves sequence numbers per key. Parameters: `[{ key, count }]` as JSON.\n * Keys are locked in sorted order, so publishers cannot deadlock within one\n * call (across calls of one transaction they can, see the README); each row lock is held until the publishing transaction ends, which makes\n * sequence order equal commit order for a key.\n */\n get reserveSequences(): string {\n return `INSERT INTO ${this.#names.keySequences} AS reserved (key, sequence)\nSELECT requested.key, requested.count\nFROM jsonb_to_recordset($1::jsonb) AS requested (key text, count bigint)\nORDER BY requested.key\nON CONFLICT (key) DO UPDATE SET sequence = reserved.sequence + EXCLUDED.sequence\nRETURNING reserved.key AS key, reserved.sequence::text AS sequence`;\n }\n\n /** Parameters: `[eventsJson, createdAt]`. Returns the ids that were inserted. */\n get insertEvents(): string {\n return `INSERT INTO ${this.#names.events}\n (id, type, source, key, sequence, payload, headers, correlation_id, causation_id, occurred_at, created_at)\nSELECT incoming.id, incoming.type, incoming.source, incoming.key, incoming.sequence,\n COALESCE(incoming.payload, 'null'::jsonb), COALESCE(incoming.headers, '{}'::jsonb),\n incoming.correlation_id, incoming.causation_id, incoming.occurred_at, $2::timestamptz\nFROM jsonb_to_recordset($1::jsonb) AS incoming (\n id text, type text, source text, key text, sequence bigint, payload jsonb, headers jsonb,\n correlation_id text, causation_id text, occurred_at timestamptz)\nORDER BY incoming.id\nON CONFLICT (id) DO NOTHING\nRETURNING id`;\n }\n\n /**\n * Parameters: `[deliveriesJson, createdAt]`. Key and sequence are copied from\n * the stored event, so a delivery added later to an existing event keeps the\n * event's position in its key. Returns the ids that were inserted.\n */\n get insertDeliveries(): string {\n return `INSERT INTO ${this.#names.deliveries}\n (id, event_id, handler, status, attempts, available_at, key, sequence, created_at, updated_at)\nSELECT incoming.id, incoming.event_id, incoming.handler, 'pending', 0, incoming.available_at,\n event.key, event.sequence, $2::timestamptz, $2::timestamptz\nFROM jsonb_to_recordset($1::jsonb) AS incoming (id text, event_id text, handler text, available_at timestamptz)\nJOIN ${this.#names.events} AS event ON event.id = incoming.event_id\nORDER BY incoming.event_id, incoming.handler\nON CONFLICT (event_id, handler) DO NOTHING\nRETURNING id`;\n }\n\n /**\n * Fast claim: leases from the first {@link CLAIM_SCAN_WINDOW} due deliveries\n * in due order, which is everything the claim needs while the front of the\n * queue is not clogged with blocked followers of busy keys. Parameters:\n * `[now, handlersJson, limit, leaseOwner, leaseExpiresAt]`.\n *\n * Always returns one row per leased delivery, or a single row whose\n * `delivery_id` is null when nothing was leased. `window_saturated` says\n * whether the window was full: when it is and fewer than `limit` deliveries\n * were leased, deliveries beyond the window may still be claimable and the\n * caller runs {@link claimBehindBlockedKeys}. When the window is not\n * saturated every due delivery was examined, so the result is complete.\n *\n * Candidates are chosen with `FOR UPDATE SKIP LOCKED`, so two claimers never\n * lock the same row. A keyed delivery is a candidate only when it is the head\n * of its (handler, key), that is (a) no earlier delivery of that handler and\n * key is pending or processing, which is the ordering guarantee, and (b) no\n * other delivery of that handler and key holds a live lease. Rule b covers a\n * delivery that re-enters the key behind a running one (requeue, or a handler\n * added to an old event); an expired lease does not count, because its worker\n * is presumed dead and the key must not stall behind it.\n *\n * Why SKIP LOCKED alone is enough for ordering: only the head of a key can\n * ever be a candidate, and the head is a single row. Two claimers racing\n * for it either skip it (the other holds the row lock) or, if the other\n * already committed, re-check the row's new version (now processing and not\n * due), which excludes it. Followers stay blocked because their predecessor\n * remains pending or processing in every snapshot until it completes or is\n * buried, and that commit happens-before the next claim that sees it.\n */\n get claim(): string {\n const deliveries = this.#names.deliveries;\n return `WITH due_window AS MATERIALIZED (\n SELECT delivery.id\n FROM ${deliveries} AS delivery\n WHERE ${UNFINISHED_PREDICATE('delivery')}\n AND ${dueAtExpression('delivery')} <= $1::timestamptz\n AND ${HANDLER_PREDICATE}\n ORDER BY ${dueAtExpression('delivery')}, delivery.id\n LIMIT ${CLAIM_SCAN_WINDOW}\n), candidates AS MATERIALIZED (\n SELECT delivery.id, ${dueAtExpression('delivery')} AS due_at\n FROM due_window\n JOIN ${deliveries} AS delivery ON delivery.id = due_window.id\n WHERE ${UNFINISHED_PREDICATE('delivery')}\n AND ${dueAtExpression('delivery')} <= $1::timestamptz\n AND (\n delivery.key IS NULL\n OR NOT (\n EXISTS (\n SELECT 1 FROM ${deliveries} AS earlier\n WHERE earlier.key IS NOT NULL AND earlier.handler = delivery.handler AND earlier.key = delivery.key\n AND ${UNFINISHED_PREDICATE('earlier')}\n AND earlier.sequence < delivery.sequence\n )\n OR ${this.#liveLeaseElsewhere()}\n )\n )\n ORDER BY due_at, delivery.id\n LIMIT $3::int\n FOR UPDATE OF delivery SKIP LOCKED\n), ${this.#leaseCandidates()}\nSELECT (SELECT count(*) FROM due_window) >= ${CLAIM_SCAN_WINDOW} AS window_saturated, leased.*\nFROM (SELECT 1) AS anchor\nLEFT JOIN (${this.#leasedRows()}) AS leased ON true\nORDER BY leased.due_at, leased.delivery_id`;\n }\n\n /**\n * Slow claim, run when {@link claim} leased too few deliveries from a full\n * window: the front of the due queue is mostly followers of blocked keys.\n * Same parameters, rules and locking as {@link claim}, but heads are found\n * with `DISTINCT ON (handler, key)` over the unfinished-key index, so the\n * cost follows the number of unfinished keyed deliveries (one index-only\n * scan) instead of one probe per due follower.\n */\n get claimBehindBlockedKeys(): string {\n const deliveries = this.#names.deliveries;\n return `WITH heads AS MATERIALIZED (\n SELECT DISTINCT ON (head.handler, head.key) head.id\n FROM ${deliveries} AS head\n WHERE head.key IS NOT NULL\n AND ${UNFINISHED_PREDICATE('head')}\n AND head.handler = ANY (ARRAY(SELECT jsonb_array_elements_text($2::jsonb)))\n ORDER BY head.handler, head.key, head.sequence\n), keyed AS MATERIALIZED (\n SELECT delivery.id, ${dueAtExpression('delivery')} AS due_at\n FROM heads\n JOIN ${deliveries} AS delivery ON delivery.id = heads.id\n WHERE ${UNFINISHED_PREDICATE('delivery')}\n AND ${dueAtExpression('delivery')} <= $1::timestamptz\n AND NOT ${this.#liveLeaseElsewhere()}\n ORDER BY due_at, delivery.id\n LIMIT $3::int\n FOR UPDATE OF delivery SKIP LOCKED\n), unkeyed AS MATERIALIZED (\n SELECT delivery.id, ${dueAtExpression('delivery')} AS due_at\n FROM ${deliveries} AS delivery\n WHERE delivery.key IS NULL\n AND ${UNFINISHED_PREDICATE('delivery')}\n AND ${dueAtExpression('delivery')} <= $1::timestamptz\n AND ${HANDLER_PREDICATE}\n ORDER BY due_at, delivery.id\n LIMIT $3::int\n FOR UPDATE OF delivery SKIP LOCKED\n), candidates AS MATERIALIZED (\n SELECT id, due_at FROM (\n SELECT id, due_at FROM keyed\n UNION ALL\n SELECT id, due_at FROM unkeyed\n ) AS both_sets\n ORDER BY due_at, id\n LIMIT $3::int\n), ${this.#leaseCandidates()}\nSELECT false AS window_saturated, leased.*\nFROM (SELECT 1) AS anchor\nLEFT JOIN (${this.#leasedRows()}) AS leased ON true\nORDER BY leased.due_at, leased.delivery_id`;\n }\n\n /** True when another delivery of the candidate's handler and key holds a live lease. */\n #liveLeaseElsewhere(): string {\n return `EXISTS (\n SELECT 1 FROM ${this.#names.deliveries} AS running\n WHERE running.key IS NOT NULL\n AND running.handler = delivery.handler AND running.key = delivery.key\n AND running.status = 'processing' AND running.lease_expires_at > $1::timestamptz\n AND running.id <> delivery.id\n )`;\n }\n\n /** The `claimed` CTE: leases every row of `candidates`. */\n #leaseCandidates(): string {\n return `claimed AS (\n UPDATE ${this.#names.deliveries} AS target\n SET status = 'processing',\n attempts = target.attempts + 1,\n lease_owner = $4::text,\n lease_token = gen_random_uuid()::text,\n lease_expires_at = $5::timestamptz,\n updated_at = $1::timestamptz\n FROM candidates\n WHERE target.id = candidates.id\n RETURNING target.id, target.event_id, target.handler, target.attempts, target.lease_token, candidates.due_at\n)`;\n }\n\n /** Leased deliveries joined with their events, as the claim result columns. */\n #leasedRows(): string {\n return `SELECT claimed.due_at, claimed.id AS delivery_id, claimed.handler, claimed.attempts::int AS attempts, claimed.lease_token,\n ${eventColumns('event')}\nFROM claimed\nJOIN ${this.#names.events} AS event ON event.id = claimed.event_id`;\n }\n\n /** Parameters: `[deliveryId, leaseToken, leaseExpiresAt, now]`. */\n get extendLease(): string {\n return countChanged(`UPDATE ${this.#names.deliveries}\nSET lease_expires_at = $3::timestamptz, updated_at = $4::timestamptz\nWHERE id = $1::text AND status = 'processing' AND lease_token = $2::text`);\n }\n\n /** Parameters: `[deliveryId, leaseToken, now]`. */\n get complete(): string {\n return countChanged(`UPDATE ${this.#names.deliveries}\nSET status = 'completed', completed_at = $3::timestamptz, updated_at = $3::timestamptz, ${CLEAR_LEASE}\nWHERE id = $1::text AND status = 'processing' AND lease_token = $2::text`);\n }\n\n /** Parameters: `[deliveryId, leaseToken, availableAt, errorJson, now]`. */\n get reschedule(): string {\n return countChanged(`UPDATE ${this.#names.deliveries}\nSET status = 'pending', available_at = $3::timestamptz, last_error = $4::jsonb, updated_at = $5::timestamptz, ${CLEAR_LEASE}\nWHERE id = $1::text AND status = 'processing' AND lease_token = $2::text`);\n }\n\n /** Parameters: `[deliveryId, leaseToken, errorJson, now]`. */\n get bury(): string {\n return countChanged(`UPDATE ${this.#names.deliveries}\nSET status = 'dead', last_error = $3::jsonb, updated_at = $4::timestamptz, ${CLEAR_LEASE}\nWHERE id = $1::text AND status = 'processing' AND lease_token = $2::text`);\n }\n\n /**\n * Gives a leased delivery back without spending its attempt: pending, due\n * `now`, attempt count decremented. Parameters: `[deliveryId, leaseToken, now]`.\n */\n get release(): string {\n return countChanged(`UPDATE ${this.#names.deliveries}\nSET status = 'pending', available_at = $3::timestamptz, attempts = attempts - 1, updated_at = $3::timestamptz, ${CLEAR_LEASE}\nWHERE id = $1::text AND status = 'processing' AND lease_token = $2::text`);\n }\n\n /** Parameters: `[deliveryIdsJson, now]`. */\n get requeue(): string {\n return countChanged(`UPDATE ${this.#names.deliveries}\nSET status = 'pending', attempts = 0, available_at = $2::timestamptz, updated_at = $2::timestamptz\nWHERE id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb))) AND status = 'dead'`);\n }\n\n /** Builds the filtered, creation-ordered listing. */\n listDeliveries(query: DeliveryQuery): PostgresStatement {\n const parameters: PostgresParameter[] = [];\n const conditions: string[] = [];\n const bind = (value: PostgresParameter): string => {\n parameters.push(value);\n return `$${parameters.length}::${typeof value === 'number' ? 'int' : 'text'}`;\n };\n if (query.status !== undefined) {\n conditions.push(`delivery.status = ${bind(query.status)}`);\n }\n if (query.handler !== undefined) {\n conditions.push(`delivery.handler = ${bind(query.handler)}`);\n }\n if (query.eventType !== undefined) {\n conditions.push(`event.type = ${bind(query.eventType)}`);\n }\n if (query.eventId !== undefined) {\n conditions.push(`delivery.event_id = ${bind(query.eventId)}`);\n }\n const where = conditions.length === 0 ? '' : `WHERE ${conditions.join(' AND ')}`;\n const limit = bind(query.limit ?? DEFAULT_LIST_LIMIT);\n const sql = `SELECT delivery.id AS delivery_id, delivery.handler, delivery.status, delivery.attempts::int AS attempts,\n ${isoText('delivery.available_at')} AS available_at,\n delivery.lease_owner,\n ${isoText('delivery.lease_expires_at')} AS lease_expires_at,\n delivery.last_error::text AS last_error,\n ${isoText('delivery.created_at')} AS created_at,\n ${isoText('delivery.updated_at')} AS updated_at,\n ${isoText('delivery.completed_at')} AS completed_at,\n ${eventColumns('event')}\nFROM ${this.#names.deliveries} AS delivery\nJOIN ${this.#names.events} AS event ON event.id = delivery.event_id\n${where}\nORDER BY delivery.created_at, delivery.id\nLIMIT ${limit}`;\n return { sql, parameters };\n }\n\n get countByStatus(): string {\n return `SELECT status, count(*)::text AS count FROM ${this.#names.deliveries} GROUP BY status`;\n }\n\n /** Parameters: `[now]`. */\n get oldestDue(): string {\n return `SELECT ${isoText('due_at')} AS oldest_due_at FROM (\n SELECT ${dueAtExpression('delivery')} AS due_at\n FROM ${this.#names.deliveries} AS delivery\n WHERE delivery.status IN ('pending', 'processing') AND ${dueAtExpression('delivery')} <= $1::timestamptz\n ORDER BY due_at\n LIMIT 1\n) AS oldest`;\n }\n\n /**\n * Deletes one bounded batch of purgeable deliveries and returns the event id\n * of each deleted delivery. Parameters: `[cutoff, batchSize]`.\n * `FOR UPDATE SKIP LOCKED` keeps purge from waiting on, or being waited on by, anything.\n */\n purgeCompletedBatch(): string {\n return this.#purgeBatch(\n `status = 'completed' AND completed_at < $1::timestamptz`,\n 'completed_at',\n );\n }\n\n purgeDeadBatch(): string {\n return this.#purgeBatch(`status = 'dead' AND updated_at < $1::timestamptz`, 'updated_at');\n }\n\n /**\n * Selects and locks one bounded batch of events created before the cutoff\n * that no delivery references. Parameters: `[cutoff, batchSize]`. The ids go\n * through {@link deleteOrphanEvents}, which re-checks under a fresh snapshot.\n */\n get lockOrphanEventsBatch(): string {\n return `SELECT event.id FROM ${this.#names.events} AS event\nWHERE event.created_at < $1::timestamptz\n AND NOT EXISTS (SELECT 1 FROM ${this.#names.deliveries} AS delivery WHERE delivery.event_id = event.id)\nORDER BY event.created_at, event.id\nLIMIT $2::int\nFOR UPDATE OF event SKIP LOCKED`;\n }\n\n /**\n * Locks the given events, skipping any that a concurrent transaction is\n * referencing from a new delivery (a foreign key check holds `FOR KEY\n * SHARE`, which conflicts with this lock). Parameters: `[eventIdsJson]`.\n */\n get lockEvents(): string {\n return `SELECT id FROM ${this.#names.events}\nWHERE id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))\nFOR UPDATE SKIP LOCKED`;\n }\n\n /**\n * Deletes locked events that no delivery references. It must run as a\n * statement of its own after {@link lockEvents}: it then takes a fresh\n * snapshot that includes every delivery committed before the lock was\n * granted, so an event that just gained a delivery is never cascaded away.\n * Parameters: `[eventIdsJson]`.\n */\n get deleteOrphanEvents(): string {\n const events = this.#names.events;\n return countChanged(`DELETE FROM ${events} AS event\nWHERE event.id = ANY (ARRAY(SELECT jsonb_array_elements_text($1::jsonb)))\n AND NOT EXISTS (SELECT 1 FROM ${this.#names.deliveries} AS delivery WHERE delivery.event_id = event.id)`);\n }\n\n #purgeBatch(condition: string, orderColumn: string): string {\n const deliveries = this.#names.deliveries;\n return `WITH batch AS MATERIALIZED (\n SELECT id FROM ${deliveries}\n WHERE ${condition}\n ORDER BY ${orderColumn}, id\n LIMIT $2::int\n FOR UPDATE SKIP LOCKED\n), deleted AS (\n DELETE FROM ${deliveries} AS delivery USING batch WHERE delivery.id = batch.id RETURNING delivery.event_id\n)\nSELECT event_id FROM deleted`;\n }\n}\n","import {\n ConfigurationError,\n type AppendEntry,\n type AppendResult,\n type ClaimRequest,\n type ClaimedDelivery,\n type DeliveryQuery,\n type DeliveryRecord,\n type DeliveryStatus,\n type ErrorInfo,\n type EventEnvelope,\n type EventStore,\n type EventStoreStatistics,\n type LeaseReference,\n type PurgeRequest,\n type PurgeResult,\n type RelayBusLogger,\n} from '@relaybus/core';\nimport { Pool, type PoolClient, type PoolConfig } from 'pg';\nimport type { PostgresExecutor, PostgresParameter, PostgresRow } from './executor.js';\nimport { resolvePostgresNames, type PostgresSchemaOptions } from './names.js';\nimport { PgExecutor } from './pg-executor.js';\nimport { mapClaimedDelivery, mapDeliveryRecord, mapOldestDueAt, readCount } from './row-mapping.js';\nimport { createPostgresSchemaStatements } from './schema.js';\nimport { PostgresStatements } from './statements.js';\n\n/** Options shared by every way of connecting. */\nexport interface PostgresEventStoreSettings extends PostgresSchemaOptions {\n /**\n * Maximum deliveries deleted per transaction by `purge`. Smaller batches\n * hold row locks for less time; `purge` keeps going until nothing is left.\n * Default 1000.\n */\n readonly purgeBatchSize?: number;\n /**\n * Receives errors of idle connections in a pool the store creates itself\n * (database failover, `pg_terminate_backend`, network resets). Default\n * `console`. A pool you pass in is yours: attach `pool.on('error', ...)` to\n * it, otherwise `pg` raises an unhandled `error` event and the process exits.\n */\n readonly logger?: RelayBusLogger;\n}\n\n/** Use an existing `pg` pool. The store never closes it. */\nexport interface PostgresPoolOptions extends PostgresEventStoreSettings {\n readonly pool: Pool;\n readonly connectionString?: never;\n readonly poolConfig?: never;\n readonly executor?: never;\n}\n\n/** Let the store create (and on `close()` end) its own `pg` pool. */\nexport interface PostgresConnectionOptions extends PostgresEventStoreSettings {\n readonly connectionString: string;\n /** Extra `pg` pool settings, for example `max`. */\n readonly poolConfig?: Omit<PoolConfig, 'connectionString'>;\n readonly pool?: never;\n readonly executor?: never;\n}\n\n/** Use another database library through an adapter. The store never closes it. */\nexport interface PostgresExecutorOptions<TTransaction> extends PostgresEventStoreSettings {\n readonly executor: PostgresExecutor<TTransaction>;\n readonly pool?: never;\n readonly connectionString?: never;\n readonly poolConfig?: never;\n}\n\nexport type PostgresEventStoreOptions<TTransaction = PoolClient> =\n PostgresPoolOptions | PostgresConnectionOptions | PostgresExecutorOptions<TTransaction>;\n\nconst DEFAULT_PURGE_BATCH_SIZE = 1_000;\n\ninterface EventRow {\n readonly id: string;\n readonly type: string;\n readonly source: string;\n readonly key: string | null;\n readonly sequence: string | null;\n readonly payload: unknown;\n readonly headers: EventEnvelope['headers'];\n readonly correlation_id: string | null;\n readonly causation_id: string | null;\n readonly occurred_at: string;\n}\n\ninterface DeliveryRow {\n readonly id: string;\n readonly event_id: string;\n readonly handler: string;\n readonly available_at: string;\n}\n\n/**\n * PostgreSQL {@link EventStore} (PostgreSQL 13 or newer).\n *\n * The transaction handle is whatever the chosen driver uses: a `pg`\n * `PoolClient` by default, or a Kysely / Knex / TypeORM / Drizzle / Prisma\n * transaction through the adapters in `@relaybus/postgres/<library>`. Events\n * published with that handle commit and roll back together with the caller's\n * own writes.\n *\n * Guarantees:\n * - **Atomic publish.** Events and deliveries are written in the caller's transaction.\n * - **Per-key order.** Each key has a counter row in the key-sequence table.\n * Publishing locks that row and holds the lock until commit, so two\n * transactions publishing the same key are serialized and sequence order\n * equals commit order. Claiming then hands out only the lowest unfinished\n * sequence of a (handler, key).\n * - **Safe parallel claiming.** One `FOR UPDATE SKIP LOCKED` statement leases\n * deliveries; any number of processes can claim at once.\n * - **Fenced state changes.** Complete, reschedule, bury and extend only apply\n * to the lease token that claimed the delivery.\n * - **App clock.** Every timestamp comes from the `now` the caller passes in,\n * never from the database clock.\n */\nexport class PostgresEventStore<TTransaction = PoolClient> implements EventStore<TTransaction> {\n readonly #executor: PostgresExecutor<TTransaction>;\n readonly #statements: PostgresStatements;\n readonly #schemaStatements: readonly string[];\n readonly #setupLockKey: string;\n readonly #purgeBatchSize: number;\n #ownedPool: Pool | undefined;\n\n constructor(options: PostgresEventStoreOptions<TTransaction>) {\n const sources = [options.pool, options.connectionString, options.executor].filter(\n (source) => source !== undefined,\n );\n if (sources.length !== 1) {\n throw new ConfigurationError(\n 'PostgresEventStore needs exactly one of pool, connectionString or executor',\n );\n }\n const purgeBatchSize = options.purgeBatchSize ?? DEFAULT_PURGE_BATCH_SIZE;\n if (!Number.isInteger(purgeBatchSize) || purgeBatchSize < 1) {\n throw new ConfigurationError(\n `purgeBatchSize must be a positive integer, received ${String(purgeBatchSize)}`,\n );\n }\n const names = resolvePostgresNames(options);\n this.#statements = new PostgresStatements(names);\n this.#schemaStatements = createPostgresSchemaStatements(options);\n this.#setupLockKey = this.#statements.setupLockKey;\n this.#purgeBatchSize = purgeBatchSize;\n if (options.executor !== undefined) {\n this.#executor = options.executor;\n } else {\n const pool =\n options.pool ??\n new Pool({ ...options.poolConfig, connectionString: options.connectionString });\n if (options.pool === undefined) {\n const logger = options.logger ?? console;\n pool.on('error', (error) => {\n logger.error(\n `[PostgresEventStore](constructor) Idle connection failed, the pool replaces it | error=${error.message}`,\n );\n });\n this.#ownedPool = pool;\n }\n // Without an executor the transaction type is PoolClient, as the default type argument states.\n this.#executor = new PgExecutor(pool) as unknown as PostgresExecutor<TTransaction>;\n }\n }\n\n /**\n * Creates the schema, tables and indexes if they do not exist. Safe to call\n * from many processes at once: a transaction-scoped advisory lock serializes\n * the DDL, so racing `CREATE TABLE IF NOT EXISTS` statements cannot collide.\n * Skip it (`setupStore: false`) when a migration tool applies\n * `createPostgresSchemaSql()` instead.\n */\n async setup(): Promise<void> {\n await this.#executor.transaction(async (transaction) => {\n await this.#executor.query(this.#statements.setupLock, [this.#setupLockKey], transaction);\n for (const statement of this.#schemaStatements) {\n await this.#executor.query(statement, [], transaction);\n }\n });\n }\n\n transaction<T>(work: (transaction: TTransaction) => Promise<T>): Promise<T> {\n return this.#executor.transaction(work);\n }\n\n /**\n * Writes the entries in `transaction`. Keyed events reserve their sequence\n * numbers first (locking the key rows in sorted order, so publishers cannot\n * deadlock inside one call), then events, then deliveries, each in a single\n * multi-row statement ordered by primary key. Two transactions that append\n * keys in opposite order across several calls can still deadlock (40P01);\n * the database rolls one back and the caller retries.\n * A duplicate event id still consumes a sequence number; gaps are harmless\n * because only the order of sequences matters.\n */\n async append(\n transaction: TTransaction,\n entries: readonly AppendEntry[],\n now: Date,\n ): Promise<AppendResult> {\n const plan = planAppend(entries);\n const createdAt = now.toISOString();\n const sequences = await this.#reserveSequences(plan.events, transaction);\n const insertedEventIds = new Set(\n plan.events.length === 0\n ? []\n : (\n await this.#executor.query(\n this.#statements.insertEvents,\n [JSON.stringify(toEventRows(plan.events, sequences)), createdAt],\n transaction,\n )\n ).map((row) => row['id'] as string),\n );\n const insertedDeliveries =\n plan.deliveries.length === 0\n ? []\n : await this.#executor.query(\n this.#statements.insertDeliveries,\n [JSON.stringify(plan.deliveries), createdAt],\n transaction,\n );\n const appendedEventIds: string[] = [];\n const duplicateEventIds: string[] = [];\n for (const { eventId, repeated } of plan.outcomes) {\n (!repeated && insertedEventIds.has(eventId) ? appendedEventIds : duplicateEventIds).push(\n eventId,\n );\n }\n return {\n appendedEventIds,\n duplicateEventIds,\n appendedDeliveryCount: insertedDeliveries.length,\n };\n }\n\n /**\n * Leases up to `limit` due deliveries with `FOR UPDATE SKIP LOCKED`. The fast\n * statement examines the first due deliveries; only when they are mostly\n * blocked followers of busy keys does a second statement look at the heads of\n * all keys. See {@link PostgresStatements.claim} for why that keeps a\n * (handler, key) strictly one-at-a-time and in order.\n */\n async claim(request: ClaimRequest): Promise<ClaimedDelivery[]> {\n if (request.handlers.length === 0 || !(request.limit > 0)) {\n return [];\n }\n const parameters = (limit: number): PostgresParameter[] => [\n request.now.toISOString(),\n JSON.stringify(request.handlers),\n limit,\n request.leaseOwner,\n request.leaseExpiresAt.toISOString(),\n ];\n const fastRows = await this.#executor.query(this.#statements.claim, parameters(request.limit));\n const leased = fastRows.filter((row) => row['delivery_id'] !== null);\n if (leased.length < request.limit && fastRows[0]!['window_saturated'] === true) {\n leased.push(\n ...(\n await this.#executor.query(\n this.#statements.claimBehindBlockedKeys,\n parameters(request.limit - leased.length),\n )\n ).filter((row) => row['delivery_id'] !== null),\n );\n }\n return leased.map((row) => mapClaimedDelivery(row, request.leaseExpiresAt));\n }\n\n extendLease(lease: LeaseReference, leaseExpiresAt: Date, now: Date): Promise<boolean> {\n return this.#changed(this.#statements.extendLease, [\n lease.deliveryId,\n lease.leaseToken,\n leaseExpiresAt.toISOString(),\n now.toISOString(),\n ]);\n }\n\n complete(lease: LeaseReference, now: Date, transaction?: TTransaction): Promise<boolean> {\n return this.#changed(\n this.#statements.complete,\n [lease.deliveryId, lease.leaseToken, now.toISOString()],\n transaction,\n );\n }\n\n reschedule(\n lease: LeaseReference,\n availableAt: Date,\n error: ErrorInfo,\n now: Date,\n ): Promise<boolean> {\n return this.#changed(this.#statements.reschedule, [\n lease.deliveryId,\n lease.leaseToken,\n availableAt.toISOString(),\n JSON.stringify(error),\n now.toISOString(),\n ]);\n }\n\n bury(lease: LeaseReference, error: ErrorInfo, now: Date): Promise<boolean> {\n return this.#changed(this.#statements.bury, [\n lease.deliveryId,\n lease.leaseToken,\n JSON.stringify(error),\n now.toISOString(),\n ]);\n }\n\n /** Returns a leased delivery to pending, due now, without counting the attempt. */\n release(lease: LeaseReference, now: Date): Promise<boolean> {\n return this.#changed(this.#statements.release, [\n lease.deliveryId,\n lease.leaseToken,\n now.toISOString(),\n ]);\n }\n\n async listDeliveries(query: DeliveryQuery): Promise<DeliveryRecord[]> {\n const statement = this.#statements.listDeliveries(query);\n const rows = await this.#executor.query(statement.sql, statement.parameters);\n return rows.map(mapDeliveryRecord);\n }\n\n async requeue(deliveryIds: readonly string[], now: Date): Promise<number> {\n const rows = await this.#executor.query(this.#statements.requeue, [\n JSON.stringify(deliveryIds),\n now.toISOString(),\n ]);\n return readCount(rows[0]!, 'count');\n }\n\n /**\n * Deletes purgeable deliveries in batches of `purgeBatchSize`, one short\n * transaction per batch, then the events those batches left without any\n * delivery. Finally, events created before the earliest given cutoff that\n * have no delivery at all are removed: they are what a publish leaves behind\n * when its last delivery was purged in the same instant, or when no handler\n * was subscribed. Events that a concurrent publish is attaching a delivery\n * to are skipped and kept.\n */\n async purge(request: PurgeRequest): Promise<PurgeResult> {\n const total = { deletedDeliveries: 0, deletedEvents: 0 };\n const batches: Array<[string, Date | undefined]> = [\n [this.#statements.purgeCompletedBatch(), request.completedBefore],\n [this.#statements.purgeDeadBatch(), request.deadBefore],\n ];\n for (const [sql, cutoff] of batches) {\n if (cutoff === undefined) {\n continue;\n }\n let deletedInBatch = this.#purgeBatchSize;\n while (deletedInBatch === this.#purgeBatchSize) {\n const batch = await this.#purgeBatch(sql, cutoff);\n deletedInBatch = batch.deletedDeliveries;\n total.deletedDeliveries += batch.deletedDeliveries;\n total.deletedEvents += batch.deletedEvents;\n }\n }\n const orphanCutoff = [request.completedBefore, request.deadBefore]\n .filter((cutoff) => cutoff !== undefined)\n .sort((first, second) => first.getTime() - second.getTime())[0];\n if (orphanCutoff !== undefined) {\n total.deletedEvents += await this.#purgeOrphanEvents(orphanCutoff);\n }\n return total;\n }\n\n async statistics(now: Date): Promise<EventStoreStatistics> {\n const counts: Record<DeliveryStatus, number> = {\n pending: 0,\n processing: 0,\n completed: 0,\n dead: 0,\n };\n for (const row of await this.#executor.query(this.#statements.countByStatus, [])) {\n // A CHECK constraint restricts the column to the four statuses.\n counts[row['status'] as DeliveryStatus] = readCount(row, 'count');\n }\n const oldestDue = await this.#executor.query(this.#statements.oldestDue, [now.toISOString()]);\n return { ...counts, oldestDueAt: mapOldestDueAt(oldestDue) };\n }\n\n /** Ends the pool this store created from `connectionString`. Pools and executors you passed in stay open. */\n async close(): Promise<void> {\n const pool = this.#ownedPool;\n this.#ownedPool = undefined;\n await pool?.end();\n }\n\n async #changed(\n sql: string,\n parameters: readonly PostgresParameter[],\n transaction?: TTransaction,\n ): Promise<boolean> {\n const rows = await this.#executor.query(sql, parameters, transaction);\n return readCount(rows[0]!, 'count') > 0;\n }\n\n async #reserveSequences(\n events: readonly EventEnvelope[],\n transaction: TTransaction,\n ): Promise<Map<string, bigint>> {\n const counts = new Map<string, number>();\n for (const event of events) {\n if (event.key !== null) {\n counts.set(event.key, (counts.get(event.key) ?? 0) + 1);\n }\n }\n const firstSequences = new Map<string, bigint>();\n if (counts.size === 0) {\n return firstSequences;\n }\n const requested = [...counts].map(([key, count]) => ({ key, count }));\n const rows = await this.#executor.query(\n this.#statements.reserveSequences,\n [JSON.stringify(requested)],\n transaction,\n );\n for (const row of rows) {\n const key = row['key'] as string;\n firstSequences.set(key, BigInt(row['sequence'] as string) - BigInt(counts.get(key)!) + 1n);\n }\n return firstSequences;\n }\n\n async #purgeOrphanEvents(cutoff: Date): Promise<number> {\n let deletedEvents = 0;\n let removedInBatch = this.#purgeBatchSize;\n while (removedInBatch === this.#purgeBatchSize) {\n removedInBatch = await this.#executor.transaction(async (transaction) => {\n const locked = await this.#executor.query(\n this.#statements.lockOrphanEventsBatch,\n [cutoff.toISOString(), this.#purgeBatchSize],\n transaction,\n );\n const removed = await this.#executor.query(\n this.#statements.deleteOrphanEvents,\n [JSON.stringify(locked.map((row: PostgresRow) => row['id'] as string))],\n transaction,\n );\n return readCount(removed[0]!, 'count');\n });\n deletedEvents += removedInBatch;\n }\n return deletedEvents;\n }\n\n async #purgeBatch(\n sql: string,\n cutoff: Date,\n ): Promise<{ deletedDeliveries: number; deletedEvents: number }> {\n return this.#executor.transaction(async (transaction) => {\n const deleted = await this.#executor.query(\n sql,\n [cutoff.toISOString(), this.#purgeBatchSize],\n transaction,\n );\n if (deleted.length === 0) {\n return { deletedDeliveries: 0, deletedEvents: 0 };\n }\n const eventIds = JSON.stringify([\n ...new Set(deleted.map((row) => row['event_id'] as string)),\n ]);\n const locked = await this.#executor.query(\n this.#statements.lockEvents,\n [eventIds],\n transaction,\n );\n const removed = await this.#executor.query(\n this.#statements.deleteOrphanEvents,\n [JSON.stringify(locked.map((row: PostgresRow) => row['id'] as string))],\n transaction,\n );\n return { deletedDeliveries: deleted.length, deletedEvents: readCount(removed[0]!, 'count') };\n });\n }\n}\n\ninterface AppendPlan {\n /** First occurrence of every event id in the call, in entry order. */\n readonly events: readonly EventEnvelope[];\n readonly deliveries: readonly DeliveryRow[];\n /** One per entry: its event id, and whether an earlier entry of the call carried the same id. */\n readonly outcomes: ReadonlyArray<{ readonly eventId: string; readonly repeated: boolean }>;\n}\n\nfunction planAppend(entries: readonly AppendEntry[]): AppendPlan {\n const events: EventEnvelope[] = [];\n const deliveries: DeliveryRow[] = [];\n const outcomes: Array<{ eventId: string; repeated: boolean }> = [];\n const seenEventIds = new Set<string>();\n const seenDeliveries = new Set<string>();\n for (const { event, deliveries: newDeliveries } of entries) {\n const repeated = seenEventIds.has(event.id);\n seenEventIds.add(event.id);\n outcomes.push({ eventId: event.id, repeated });\n if (!repeated) {\n events.push(event);\n }\n for (const delivery of newDeliveries) {\n const identity = `${event.id}\\u0000${delivery.handler}`;\n if (!seenDeliveries.has(identity)) {\n seenDeliveries.add(identity);\n deliveries.push({\n id: delivery.id,\n event_id: event.id,\n handler: delivery.handler,\n available_at: delivery.availableAt.toISOString(),\n });\n }\n }\n }\n return { events, deliveries, outcomes };\n}\n\nfunction toEventRows(\n events: readonly EventEnvelope[],\n firstSequences: ReadonlyMap<string, bigint>,\n): EventRow[] {\n const nextSequences = new Map(firstSequences);\n return events.map((event) => {\n let sequence: string | null = null;\n if (event.key !== null) {\n const next = nextSequences.get(event.key)!;\n nextSequences.set(event.key, next + 1n);\n sequence = next.toString();\n }\n return {\n id: event.id,\n type: event.type,\n source: event.source,\n key: event.key,\n sequence,\n payload: event.payload,\n headers: event.headers,\n correlation_id: event.correlationId,\n causation_id: event.causationId,\n occurred_at: event.occurredAt.toISOString(),\n };\n });\n}\n"]}
package/dist/knex.cjs ADDED
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ // src/positional-sql.ts
4
+ function splitPositionalSql(sql) {
5
+ const parts = [];
6
+ let textStart = 0;
7
+ for (const match of sql.matchAll(/\$(\d+)/g)) {
8
+ parts.push(sql.slice(textStart, match.index), { parameterIndex: Number(match[1]) - 1 });
9
+ textStart = match.index + match[0].length;
10
+ }
11
+ parts.push(sql.slice(textStart));
12
+ return parts;
13
+ }
14
+
15
+ // src/knex/knex-executor.ts
16
+ function createKnexExecutor(knex) {
17
+ return {
18
+ transaction: (work) => knex.transaction(work),
19
+ async query(sql, parameters, transaction) {
20
+ const parts = splitPositionalSql(sql);
21
+ const knexSql = parts.map((part) => typeof part === "string" ? part : "?").join("");
22
+ const bindings = parts.flatMap(
23
+ (part) => typeof part === "string" ? [] : [parameters[part.parameterIndex]]
24
+ );
25
+ const result = await (transaction ?? knex).raw(knexSql, bindings);
26
+ return result.rows;
27
+ }
28
+ };
29
+ }
30
+
31
+ exports.createKnexExecutor = createKnexExecutor;
32
+ //# sourceMappingURL=knex.cjs.map
33
+ //# sourceMappingURL=knex.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/positional-sql.ts","../src/knex/knex-executor.ts"],"names":[],"mappings":";;;AASO,SAAS,mBAAmB,GAAA,EAAkC;AACnE,EAAA,MAAM,QAA6B,EAAC;AACpC,EAAA,IAAI,SAAA,GAAY,CAAA;AAChB,EAAA,KAAA,MAAW,KAAA,IAAS,GAAA,CAAI,QAAA,CAAS,UAAU,CAAA,EAAG;AAC5C,IAAA,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,KAAA,CAAM,SAAA,EAAW,MAAM,KAAK,CAAA,EAAG,EAAE,cAAA,EAAgB,OAAO,KAAA,CAAM,CAAC,CAAC,CAAA,GAAI,GAAG,CAAA;AACtF,IAAA,SAAA,GAAY,KAAA,CAAM,KAAA,GAAQ,KAAA,CAAM,CAAC,CAAA,CAAE,MAAA;AAAA,EACrC;AACA,EAAA,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,KAAA,CAAM,SAAS,CAAC,CAAA;AAC/B,EAAA,OAAO,KAAA;AACT;;;ACDO,SAAS,mBAAmB,IAAA,EAAiD;AAClF,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,CAAC,IAAA,KAAS,IAAA,CAAK,YAAY,IAAI,CAAA;AAAA,IAC5C,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,MAAM,KAAA,GAAQ,mBAAmB,GAAG,CAAA;AACpC,MAAA,MAAM,OAAA,GAAU,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,KAAU,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,GAAI,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA;AACpF,MAAA,MAAM,WAAW,KAAA,CAAM,OAAA;AAAA,QAAQ,CAAC,IAAA,KAC9B,OAAO,IAAA,KAAS,QAAA,GAAW,EAAC,GAAI,CAAC,UAAA,CAAW,IAAA,CAAK,cAAc,CAAC;AAAA,OAClE;AACA,MAAA,MAAM,SAAS,MAAA,CAAO,WAAA,IAAe,IAAA,EAAM,GAAA,CAAI,SAAS,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB;AAAA,GACF;AACF","file":"knex.cjs","sourcesContent":["/** A piece of SQL text, or a reference to the (zero-based) parameter that stands at this position. */\nexport type PositionalSqlPart = string | { readonly parameterIndex: number };\n\n/**\n * Splits SQL written with PostgreSQL `$1, $2, ...` placeholders into text and\n * parameter references, in order of appearance. A placeholder used twice\n * appears twice. Adapters for libraries with their own placeholder syntax\n * (Knex `?`, Drizzle parameter chunks) rebuild the statement from the parts.\n */\nexport function splitPositionalSql(sql: string): PositionalSqlPart[] {\n const parts: PositionalSqlPart[] = [];\n let textStart = 0;\n for (const match of sql.matchAll(/\\$(\\d+)/g)) {\n parts.push(sql.slice(textStart, match.index), { parameterIndex: Number(match[1]) - 1 });\n textStart = match.index + match[0].length;\n }\n parts.push(sql.slice(textStart));\n return parts;\n}\n","import type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\nimport { splitPositionalSql } from '../positional-sql.js';\n\n/** What a Knex instance and a Knex transaction have in common. */\nexport interface KnexQueryable {\n raw(sql: string, bindings: readonly unknown[]): PromiseLike<{ readonly rows: PostgresRow[] }>;\n}\n\n/** The part of a `Knex` instance the executor uses. */\nexport interface KnexLike extends KnexQueryable {\n transaction<T>(work: (transaction: KnexQueryable) => Promise<T>): Promise<T>;\n}\n\n/**\n * Executor for Knex with the `pg` client. The transaction handle is a Knex\n * transaction: pass `trx` from `knex.transaction(async (trx) => ...)`.\n */\nexport function createKnexExecutor(knex: KnexLike): PostgresExecutor<KnexQueryable> {\n return {\n transaction: (work) => knex.transaction(work),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n const parts = splitPositionalSql(sql);\n const knexSql = parts.map((part) => (typeof part === 'string' ? part : '?')).join('');\n const bindings = parts.flatMap((part) =>\n typeof part === 'string' ? [] : [parameters[part.parameterIndex]],\n );\n const result = await (transaction ?? knex).raw(knexSql, bindings);\n return result.rows;\n },\n };\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import { b as PostgresRow, P as PostgresExecutor } from './executor-CSM7ZOhz.cjs';
2
+
3
+ /** What a Knex instance and a Knex transaction have in common. */
4
+ interface KnexQueryable {
5
+ raw(sql: string, bindings: readonly unknown[]): PromiseLike<{
6
+ readonly rows: PostgresRow[];
7
+ }>;
8
+ }
9
+ /** The part of a `Knex` instance the executor uses. */
10
+ interface KnexLike extends KnexQueryable {
11
+ transaction<T>(work: (transaction: KnexQueryable) => Promise<T>): Promise<T>;
12
+ }
13
+ /**
14
+ * Executor for Knex with the `pg` client. The transaction handle is a Knex
15
+ * transaction: pass `trx` from `knex.transaction(async (trx) => ...)`.
16
+ */
17
+ declare function createKnexExecutor(knex: KnexLike): PostgresExecutor<KnexQueryable>;
18
+
19
+ export { type KnexLike, type KnexQueryable, createKnexExecutor };
package/dist/knex.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { b as PostgresRow, P as PostgresExecutor } from './executor-CSM7ZOhz.js';
2
+
3
+ /** What a Knex instance and a Knex transaction have in common. */
4
+ interface KnexQueryable {
5
+ raw(sql: string, bindings: readonly unknown[]): PromiseLike<{
6
+ readonly rows: PostgresRow[];
7
+ }>;
8
+ }
9
+ /** The part of a `Knex` instance the executor uses. */
10
+ interface KnexLike extends KnexQueryable {
11
+ transaction<T>(work: (transaction: KnexQueryable) => Promise<T>): Promise<T>;
12
+ }
13
+ /**
14
+ * Executor for Knex with the `pg` client. The transaction handle is a Knex
15
+ * transaction: pass `trx` from `knex.transaction(async (trx) => ...)`.
16
+ */
17
+ declare function createKnexExecutor(knex: KnexLike): PostgresExecutor<KnexQueryable>;
18
+
19
+ export { type KnexLike, type KnexQueryable, createKnexExecutor };
package/dist/knex.js ADDED
@@ -0,0 +1,21 @@
1
+ import { splitPositionalSql } from './chunk-UUFSUL2M.js';
2
+
3
+ // src/knex/knex-executor.ts
4
+ function createKnexExecutor(knex) {
5
+ return {
6
+ transaction: (work) => knex.transaction(work),
7
+ async query(sql, parameters, transaction) {
8
+ const parts = splitPositionalSql(sql);
9
+ const knexSql = parts.map((part) => typeof part === "string" ? part : "?").join("");
10
+ const bindings = parts.flatMap(
11
+ (part) => typeof part === "string" ? [] : [parameters[part.parameterIndex]]
12
+ );
13
+ const result = await (transaction ?? knex).raw(knexSql, bindings);
14
+ return result.rows;
15
+ }
16
+ };
17
+ }
18
+
19
+ export { createKnexExecutor };
20
+ //# sourceMappingURL=knex.js.map
21
+ //# sourceMappingURL=knex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/knex/knex-executor.ts"],"names":[],"mappings":";;;AAiBO,SAAS,mBAAmB,IAAA,EAAiD;AAClF,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,CAAC,IAAA,KAAS,IAAA,CAAK,YAAY,IAAI,CAAA;AAAA,IAC5C,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,MAAM,KAAA,GAAQ,mBAAmB,GAAG,CAAA;AACpC,MAAA,MAAM,OAAA,GAAU,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,KAAU,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,GAAI,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA;AACpF,MAAA,MAAM,WAAW,KAAA,CAAM,OAAA;AAAA,QAAQ,CAAC,IAAA,KAC9B,OAAO,IAAA,KAAS,QAAA,GAAW,EAAC,GAAI,CAAC,UAAA,CAAW,IAAA,CAAK,cAAc,CAAC;AAAA,OAClE;AACA,MAAA,MAAM,SAAS,MAAA,CAAO,WAAA,IAAe,IAAA,EAAM,GAAA,CAAI,SAAS,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB;AAAA,GACF;AACF","file":"knex.js","sourcesContent":["import type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\nimport { splitPositionalSql } from '../positional-sql.js';\n\n/** What a Knex instance and a Knex transaction have in common. */\nexport interface KnexQueryable {\n raw(sql: string, bindings: readonly unknown[]): PromiseLike<{ readonly rows: PostgresRow[] }>;\n}\n\n/** The part of a `Knex` instance the executor uses. */\nexport interface KnexLike extends KnexQueryable {\n transaction<T>(work: (transaction: KnexQueryable) => Promise<T>): Promise<T>;\n}\n\n/**\n * Executor for Knex with the `pg` client. The transaction handle is a Knex\n * transaction: pass `trx` from `knex.transaction(async (trx) => ...)`.\n */\nexport function createKnexExecutor(knex: KnexLike): PostgresExecutor<KnexQueryable> {\n return {\n transaction: (work) => knex.transaction(work),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n const parts = splitPositionalSql(sql);\n const knexSql = parts.map((part) => (typeof part === 'string' ? part : '?')).join('');\n const bindings = parts.flatMap((part) =>\n typeof part === 'string' ? [] : [parameters[part.parameterIndex]],\n );\n const result = await (transaction ?? knex).raw(knexSql, bindings);\n return result.rows;\n },\n };\n}\n"]}
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ var kysely = require('kysely');
4
+
5
+ // src/kysely/kysely-executor.ts
6
+ function createKyselyExecutor(database) {
7
+ return {
8
+ transaction: (work) => database.transaction().execute(work),
9
+ async query(sql, parameters, transaction) {
10
+ const result = await (transaction ?? database).executeQuery(
11
+ kysely.CompiledQuery.raw(sql, [...parameters])
12
+ );
13
+ return result.rows;
14
+ }
15
+ };
16
+ }
17
+
18
+ exports.createKyselyExecutor = createKyselyExecutor;
19
+ //# sourceMappingURL=kysely.cjs.map
20
+ //# sourceMappingURL=kysely.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/kysely/kysely-executor.ts"],"names":["CompiledQuery"],"mappings":";;;;;AAoBO,SAAS,qBAAqB,QAAA,EAAyD;AAC5F,EAAA,OAAO;AAAA,IACL,aAAa,CAAC,IAAA,KAAS,SAAS,WAAA,EAAY,CAAE,QAAQ,IAAI,CAAA;AAAA,IAC1D,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,MAAM,MAAA,GAAS,MAAA,CAAO,WAAA,IAAe,QAAA,EAAU,YAAA;AAAA,QAC7CA,qBAAc,GAAA,CAAI,GAAA,EAAK,CAAC,GAAG,UAAU,CAAC;AAAA,OACxC;AACA,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB;AAAA,GACF;AACF","file":"kysely.cjs","sourcesContent":["import { CompiledQuery } from 'kysely';\nimport type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\n\n/** What a Kysely instance and a Kysely transaction have in common. */\nexport interface KyselyQueryable {\n executeQuery<R>(query: CompiledQuery<R>): Promise<{ readonly rows: R[] }>;\n}\n\n/** The part of a `Kysely` instance the executor uses. */\nexport interface KyselyLike extends KyselyQueryable {\n transaction(): {\n execute<T>(work: (transaction: KyselyQueryable) => Promise<T>): Promise<T>;\n };\n}\n\n/**\n * Executor for Kysely. The transaction handle is a Kysely `Transaction`: pass\n * `trx` from `db.transaction().execute(async (trx) => ...)` as the\n * `transaction` option of `publish`.\n */\nexport function createKyselyExecutor(database: KyselyLike): PostgresExecutor<KyselyQueryable> {\n return {\n transaction: (work) => database.transaction().execute(work),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n const result = await (transaction ?? database).executeQuery<PostgresRow>(\n CompiledQuery.raw(sql, [...parameters]),\n );\n return result.rows;\n },\n };\n}\n"]}
@@ -0,0 +1,23 @@
1
+ import { CompiledQuery } from 'kysely';
2
+ import { P as PostgresExecutor } from './executor-CSM7ZOhz.cjs';
3
+
4
+ /** What a Kysely instance and a Kysely transaction have in common. */
5
+ interface KyselyQueryable {
6
+ executeQuery<R>(query: CompiledQuery<R>): Promise<{
7
+ readonly rows: R[];
8
+ }>;
9
+ }
10
+ /** The part of a `Kysely` instance the executor uses. */
11
+ interface KyselyLike extends KyselyQueryable {
12
+ transaction(): {
13
+ execute<T>(work: (transaction: KyselyQueryable) => Promise<T>): Promise<T>;
14
+ };
15
+ }
16
+ /**
17
+ * Executor for Kysely. The transaction handle is a Kysely `Transaction`: pass
18
+ * `trx` from `db.transaction().execute(async (trx) => ...)` as the
19
+ * `transaction` option of `publish`.
20
+ */
21
+ declare function createKyselyExecutor(database: KyselyLike): PostgresExecutor<KyselyQueryable>;
22
+
23
+ export { type KyselyLike, type KyselyQueryable, createKyselyExecutor };
@@ -0,0 +1,23 @@
1
+ import { CompiledQuery } from 'kysely';
2
+ import { P as PostgresExecutor } from './executor-CSM7ZOhz.js';
3
+
4
+ /** What a Kysely instance and a Kysely transaction have in common. */
5
+ interface KyselyQueryable {
6
+ executeQuery<R>(query: CompiledQuery<R>): Promise<{
7
+ readonly rows: R[];
8
+ }>;
9
+ }
10
+ /** The part of a `Kysely` instance the executor uses. */
11
+ interface KyselyLike extends KyselyQueryable {
12
+ transaction(): {
13
+ execute<T>(work: (transaction: KyselyQueryable) => Promise<T>): Promise<T>;
14
+ };
15
+ }
16
+ /**
17
+ * Executor for Kysely. The transaction handle is a Kysely `Transaction`: pass
18
+ * `trx` from `db.transaction().execute(async (trx) => ...)` as the
19
+ * `transaction` option of `publish`.
20
+ */
21
+ declare function createKyselyExecutor(database: KyselyLike): PostgresExecutor<KyselyQueryable>;
22
+
23
+ export { type KyselyLike, type KyselyQueryable, createKyselyExecutor };
package/dist/kysely.js ADDED
@@ -0,0 +1,18 @@
1
+ import { CompiledQuery } from 'kysely';
2
+
3
+ // src/kysely/kysely-executor.ts
4
+ function createKyselyExecutor(database) {
5
+ return {
6
+ transaction: (work) => database.transaction().execute(work),
7
+ async query(sql, parameters, transaction) {
8
+ const result = await (transaction ?? database).executeQuery(
9
+ CompiledQuery.raw(sql, [...parameters])
10
+ );
11
+ return result.rows;
12
+ }
13
+ };
14
+ }
15
+
16
+ export { createKyselyExecutor };
17
+ //# sourceMappingURL=kysely.js.map
18
+ //# sourceMappingURL=kysely.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/kysely/kysely-executor.ts"],"names":[],"mappings":";;;AAoBO,SAAS,qBAAqB,QAAA,EAAyD;AAC5F,EAAA,OAAO;AAAA,IACL,aAAa,CAAC,IAAA,KAAS,SAAS,WAAA,EAAY,CAAE,QAAQ,IAAI,CAAA;AAAA,IAC1D,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,MAAM,MAAA,GAAS,MAAA,CAAO,WAAA,IAAe,QAAA,EAAU,YAAA;AAAA,QAC7C,cAAc,GAAA,CAAI,GAAA,EAAK,CAAC,GAAG,UAAU,CAAC;AAAA,OACxC;AACA,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB;AAAA,GACF;AACF","file":"kysely.js","sourcesContent":["import { CompiledQuery } from 'kysely';\nimport type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\n\n/** What a Kysely instance and a Kysely transaction have in common. */\nexport interface KyselyQueryable {\n executeQuery<R>(query: CompiledQuery<R>): Promise<{ readonly rows: R[] }>;\n}\n\n/** The part of a `Kysely` instance the executor uses. */\nexport interface KyselyLike extends KyselyQueryable {\n transaction(): {\n execute<T>(work: (transaction: KyselyQueryable) => Promise<T>): Promise<T>;\n };\n}\n\n/**\n * Executor for Kysely. The transaction handle is a Kysely `Transaction`: pass\n * `trx` from `db.transaction().execute(async (trx) => ...)` as the\n * `transaction` option of `publish`.\n */\nexport function createKyselyExecutor(database: KyselyLike): PostgresExecutor<KyselyQueryable> {\n return {\n transaction: (work) => database.transaction().execute(work),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n const result = await (transaction ?? database).executeQuery<PostgresRow>(\n CompiledQuery.raw(sql, [...parameters]),\n );\n return result.rows;\n },\n };\n}\n"]}
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ // src/prisma/prisma-executor.ts
4
+ function createPrismaExecutor(client, transactionOptions = {}) {
5
+ return {
6
+ transaction: (work) => client.$transaction(work, transactionOptions),
7
+ async query(sql, parameters, transaction) {
8
+ return await (transaction ?? client).$queryRawUnsafe(sql, ...parameters);
9
+ }
10
+ };
11
+ }
12
+
13
+ exports.createPrismaExecutor = createPrismaExecutor;
14
+ //# sourceMappingURL=prisma.cjs.map
15
+ //# sourceMappingURL=prisma.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/prisma/prisma-executor.ts"],"names":[],"mappings":";;;AA6BO,SAAS,oBAAA,CACd,MAAA,EACA,kBAAA,GAA+C,EAAC,EACb;AACnC,EAAA,OAAO;AAAA,IACL,aAAa,CAAC,IAAA,KAAS,MAAA,CAAO,YAAA,CAAa,MAAM,kBAAkB,CAAA;AAAA,IACnE,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,OAAQ,OAAO,WAAA,IAAe,MAAA,EAAQ,eAAA,CAAgB,GAAA,EAAK,GAAG,UAAU,CAAA;AAAA,IAC1E;AAAA,GACF;AACF","file":"prisma.cjs","sourcesContent":["import type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\n\n/** What a `PrismaClient` and an interactive-transaction client have in common. */\nexport interface PrismaQueryable {\n $queryRawUnsafe(query: string, ...values: unknown[]): PromiseLike<unknown>;\n}\n\n/** The part of a `PrismaClient` the executor uses. */\nexport interface PrismaClientLike extends PrismaQueryable {\n $transaction<T>(\n work: (transaction: PrismaQueryable) => Promise<T>,\n options?: PrismaTransactionOptions,\n ): Promise<T>;\n}\n\n/** Prisma interactive transaction limits. Prisma's defaults (2 s wait, 5 s run) are short for handlers. */\nexport interface PrismaTransactionOptions {\n readonly maxWait?: number;\n readonly timeout?: number;\n}\n\n/**\n * Executor for Prisma, typed structurally so the package has no Prisma\n * dependency. The transaction handle is the client of an interactive\n * transaction: pass `tx` from `prisma.$transaction(async (tx) => ...)`.\n *\n * Not yet verified against a real Prisma client and database: it is covered by\n * unit tests with a structural fake only.\n */\nexport function createPrismaExecutor(\n client: PrismaClientLike,\n transactionOptions: PrismaTransactionOptions = {},\n): PostgresExecutor<PrismaQueryable> {\n return {\n transaction: (work) => client.$transaction(work, transactionOptions),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n return (await (transaction ?? client).$queryRawUnsafe(sql, ...parameters)) as PostgresRow[];\n },\n };\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import { P as PostgresExecutor } from './executor-CSM7ZOhz.cjs';
2
+
3
+ /** What a `PrismaClient` and an interactive-transaction client have in common. */
4
+ interface PrismaQueryable {
5
+ $queryRawUnsafe(query: string, ...values: unknown[]): PromiseLike<unknown>;
6
+ }
7
+ /** The part of a `PrismaClient` the executor uses. */
8
+ interface PrismaClientLike extends PrismaQueryable {
9
+ $transaction<T>(work: (transaction: PrismaQueryable) => Promise<T>, options?: PrismaTransactionOptions): Promise<T>;
10
+ }
11
+ /** Prisma interactive transaction limits. Prisma's defaults (2 s wait, 5 s run) are short for handlers. */
12
+ interface PrismaTransactionOptions {
13
+ readonly maxWait?: number;
14
+ readonly timeout?: number;
15
+ }
16
+ /**
17
+ * Executor for Prisma, typed structurally so the package has no Prisma
18
+ * dependency. The transaction handle is the client of an interactive
19
+ * transaction: pass `tx` from `prisma.$transaction(async (tx) => ...)`.
20
+ *
21
+ * Not yet verified against a real Prisma client and database: it is covered by
22
+ * unit tests with a structural fake only.
23
+ */
24
+ declare function createPrismaExecutor(client: PrismaClientLike, transactionOptions?: PrismaTransactionOptions): PostgresExecutor<PrismaQueryable>;
25
+
26
+ export { type PrismaClientLike, type PrismaQueryable, type PrismaTransactionOptions, createPrismaExecutor };
@@ -0,0 +1,26 @@
1
+ import { P as PostgresExecutor } from './executor-CSM7ZOhz.js';
2
+
3
+ /** What a `PrismaClient` and an interactive-transaction client have in common. */
4
+ interface PrismaQueryable {
5
+ $queryRawUnsafe(query: string, ...values: unknown[]): PromiseLike<unknown>;
6
+ }
7
+ /** The part of a `PrismaClient` the executor uses. */
8
+ interface PrismaClientLike extends PrismaQueryable {
9
+ $transaction<T>(work: (transaction: PrismaQueryable) => Promise<T>, options?: PrismaTransactionOptions): Promise<T>;
10
+ }
11
+ /** Prisma interactive transaction limits. Prisma's defaults (2 s wait, 5 s run) are short for handlers. */
12
+ interface PrismaTransactionOptions {
13
+ readonly maxWait?: number;
14
+ readonly timeout?: number;
15
+ }
16
+ /**
17
+ * Executor for Prisma, typed structurally so the package has no Prisma
18
+ * dependency. The transaction handle is the client of an interactive
19
+ * transaction: pass `tx` from `prisma.$transaction(async (tx) => ...)`.
20
+ *
21
+ * Not yet verified against a real Prisma client and database: it is covered by
22
+ * unit tests with a structural fake only.
23
+ */
24
+ declare function createPrismaExecutor(client: PrismaClientLike, transactionOptions?: PrismaTransactionOptions): PostgresExecutor<PrismaQueryable>;
25
+
26
+ export { type PrismaClientLike, type PrismaQueryable, type PrismaTransactionOptions, createPrismaExecutor };
package/dist/prisma.js ADDED
@@ -0,0 +1,13 @@
1
+ // src/prisma/prisma-executor.ts
2
+ function createPrismaExecutor(client, transactionOptions = {}) {
3
+ return {
4
+ transaction: (work) => client.$transaction(work, transactionOptions),
5
+ async query(sql, parameters, transaction) {
6
+ return await (transaction ?? client).$queryRawUnsafe(sql, ...parameters);
7
+ }
8
+ };
9
+ }
10
+
11
+ export { createPrismaExecutor };
12
+ //# sourceMappingURL=prisma.js.map
13
+ //# sourceMappingURL=prisma.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/prisma/prisma-executor.ts"],"names":[],"mappings":";AA6BO,SAAS,oBAAA,CACd,MAAA,EACA,kBAAA,GAA+C,EAAC,EACb;AACnC,EAAA,OAAO;AAAA,IACL,aAAa,CAAC,IAAA,KAAS,MAAA,CAAO,YAAA,CAAa,MAAM,kBAAkB,CAAA;AAAA,IACnE,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,OAAQ,OAAO,WAAA,IAAe,MAAA,EAAQ,eAAA,CAAgB,GAAA,EAAK,GAAG,UAAU,CAAA;AAAA,IAC1E;AAAA,GACF;AACF","file":"prisma.js","sourcesContent":["import type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\n\n/** What a `PrismaClient` and an interactive-transaction client have in common. */\nexport interface PrismaQueryable {\n $queryRawUnsafe(query: string, ...values: unknown[]): PromiseLike<unknown>;\n}\n\n/** The part of a `PrismaClient` the executor uses. */\nexport interface PrismaClientLike extends PrismaQueryable {\n $transaction<T>(\n work: (transaction: PrismaQueryable) => Promise<T>,\n options?: PrismaTransactionOptions,\n ): Promise<T>;\n}\n\n/** Prisma interactive transaction limits. Prisma's defaults (2 s wait, 5 s run) are short for handlers. */\nexport interface PrismaTransactionOptions {\n readonly maxWait?: number;\n readonly timeout?: number;\n}\n\n/**\n * Executor for Prisma, typed structurally so the package has no Prisma\n * dependency. The transaction handle is the client of an interactive\n * transaction: pass `tx` from `prisma.$transaction(async (tx) => ...)`.\n *\n * Not yet verified against a real Prisma client and database: it is covered by\n * unit tests with a structural fake only.\n */\nexport function createPrismaExecutor(\n client: PrismaClientLike,\n transactionOptions: PrismaTransactionOptions = {},\n): PostgresExecutor<PrismaQueryable> {\n return {\n transaction: (work) => client.$transaction(work, transactionOptions),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n return (await (transaction ?? client).$queryRawUnsafe(sql, ...parameters)) as PostgresRow[];\n },\n };\n}\n"]}
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ // src/typeorm/typeorm-executor.ts
4
+ function createTypeOrmExecutor(dataSource) {
5
+ return {
6
+ transaction: (work) => dataSource.transaction(work),
7
+ async query(sql, parameters, transaction) {
8
+ return await (transaction ?? dataSource).query(sql, [...parameters]);
9
+ }
10
+ };
11
+ }
12
+
13
+ exports.createTypeOrmExecutor = createTypeOrmExecutor;
14
+ //# sourceMappingURL=typeorm.cjs.map
15
+ //# sourceMappingURL=typeorm.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/typeorm/typeorm-executor.ts"],"names":[],"mappings":";;;AAkBO,SAAS,sBACd,UAAA,EACoC;AACpC,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,CAAC,IAAA,KAAS,UAAA,CAAW,YAAY,IAAI,CAAA;AAAA,IAClD,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,OAAQ,MAAA,CAAO,eAAe,UAAA,EAAY,KAAA,CAAM,KAAK,CAAC,GAAG,UAAU,CAAC,CAAA;AAAA,IACtE;AAAA,GACF;AACF","file":"typeorm.cjs","sourcesContent":["import type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\n\n/** What a TypeORM `DataSource` and an `EntityManager` have in common. */\nexport interface TypeOrmQueryable {\n query(query: string, parameters?: unknown[]): Promise<unknown>;\n}\n\n/** The part of a `DataSource` the executor uses. */\nexport interface TypeOrmDataSourceLike extends TypeOrmQueryable {\n transaction<T>(work: (manager: TypeOrmQueryable) => Promise<T>): Promise<T>;\n}\n\n/**\n * Executor for TypeORM. The transaction handle is the `EntityManager` of a\n * transaction: pass `manager` from `dataSource.transaction(async (manager) => ...)`\n * (or the manager your transaction decorator provides). Every statement the\n * store sends is a plain SELECT or INSERT, for which `query` returns the rows.\n */\nexport function createTypeOrmExecutor(\n dataSource: TypeOrmDataSourceLike,\n): PostgresExecutor<TypeOrmQueryable> {\n return {\n transaction: (work) => dataSource.transaction(work),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n return (await (transaction ?? dataSource).query(sql, [...parameters])) as PostgresRow[];\n },\n };\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import { P as PostgresExecutor } from './executor-CSM7ZOhz.cjs';
2
+
3
+ /** What a TypeORM `DataSource` and an `EntityManager` have in common. */
4
+ interface TypeOrmQueryable {
5
+ query(query: string, parameters?: unknown[]): Promise<unknown>;
6
+ }
7
+ /** The part of a `DataSource` the executor uses. */
8
+ interface TypeOrmDataSourceLike extends TypeOrmQueryable {
9
+ transaction<T>(work: (manager: TypeOrmQueryable) => Promise<T>): Promise<T>;
10
+ }
11
+ /**
12
+ * Executor for TypeORM. The transaction handle is the `EntityManager` of a
13
+ * transaction: pass `manager` from `dataSource.transaction(async (manager) => ...)`
14
+ * (or the manager your transaction decorator provides). Every statement the
15
+ * store sends is a plain SELECT or INSERT, for which `query` returns the rows.
16
+ */
17
+ declare function createTypeOrmExecutor(dataSource: TypeOrmDataSourceLike): PostgresExecutor<TypeOrmQueryable>;
18
+
19
+ export { type TypeOrmDataSourceLike, type TypeOrmQueryable, createTypeOrmExecutor };
@@ -0,0 +1,19 @@
1
+ import { P as PostgresExecutor } from './executor-CSM7ZOhz.js';
2
+
3
+ /** What a TypeORM `DataSource` and an `EntityManager` have in common. */
4
+ interface TypeOrmQueryable {
5
+ query(query: string, parameters?: unknown[]): Promise<unknown>;
6
+ }
7
+ /** The part of a `DataSource` the executor uses. */
8
+ interface TypeOrmDataSourceLike extends TypeOrmQueryable {
9
+ transaction<T>(work: (manager: TypeOrmQueryable) => Promise<T>): Promise<T>;
10
+ }
11
+ /**
12
+ * Executor for TypeORM. The transaction handle is the `EntityManager` of a
13
+ * transaction: pass `manager` from `dataSource.transaction(async (manager) => ...)`
14
+ * (or the manager your transaction decorator provides). Every statement the
15
+ * store sends is a plain SELECT or INSERT, for which `query` returns the rows.
16
+ */
17
+ declare function createTypeOrmExecutor(dataSource: TypeOrmDataSourceLike): PostgresExecutor<TypeOrmQueryable>;
18
+
19
+ export { type TypeOrmDataSourceLike, type TypeOrmQueryable, createTypeOrmExecutor };
@@ -0,0 +1,13 @@
1
+ // src/typeorm/typeorm-executor.ts
2
+ function createTypeOrmExecutor(dataSource) {
3
+ return {
4
+ transaction: (work) => dataSource.transaction(work),
5
+ async query(sql, parameters, transaction) {
6
+ return await (transaction ?? dataSource).query(sql, [...parameters]);
7
+ }
8
+ };
9
+ }
10
+
11
+ export { createTypeOrmExecutor };
12
+ //# sourceMappingURL=typeorm.js.map
13
+ //# sourceMappingURL=typeorm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/typeorm/typeorm-executor.ts"],"names":[],"mappings":";AAkBO,SAAS,sBACd,UAAA,EACoC;AACpC,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,CAAC,IAAA,KAAS,UAAA,CAAW,YAAY,IAAI,CAAA;AAAA,IAClD,MAAM,KAAA,CAAM,GAAA,EAAK,UAAA,EAA0C,WAAA,EAAa;AACtE,MAAA,OAAQ,MAAA,CAAO,eAAe,UAAA,EAAY,KAAA,CAAM,KAAK,CAAC,GAAG,UAAU,CAAC,CAAA;AAAA,IACtE;AAAA,GACF;AACF","file":"typeorm.js","sourcesContent":["import type { PostgresExecutor, PostgresParameter, PostgresRow } from '../executor.js';\n\n/** What a TypeORM `DataSource` and an `EntityManager` have in common. */\nexport interface TypeOrmQueryable {\n query(query: string, parameters?: unknown[]): Promise<unknown>;\n}\n\n/** The part of a `DataSource` the executor uses. */\nexport interface TypeOrmDataSourceLike extends TypeOrmQueryable {\n transaction<T>(work: (manager: TypeOrmQueryable) => Promise<T>): Promise<T>;\n}\n\n/**\n * Executor for TypeORM. The transaction handle is the `EntityManager` of a\n * transaction: pass `manager` from `dataSource.transaction(async (manager) => ...)`\n * (or the manager your transaction decorator provides). Every statement the\n * store sends is a plain SELECT or INSERT, for which `query` returns the rows.\n */\nexport function createTypeOrmExecutor(\n dataSource: TypeOrmDataSourceLike,\n): PostgresExecutor<TypeOrmQueryable> {\n return {\n transaction: (work) => dataSource.transaction(work),\n async query(sql, parameters: readonly PostgresParameter[], transaction) {\n return (await (transaction ?? dataSource).query(sql, [...parameters])) as PostgresRow[];\n },\n };\n}\n"]}