functype-kysely 2.3.0 → 2.4.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.
package/dist/KyselyDb.js CHANGED
@@ -1,2 +1,2 @@
1
- import{IO as e,Option as t,Tag as n}from"functype";import{sql as r}from"kysely";import{toDbError as i}from"./DbError.js";import{QUERY_FAILED as a,RELEASED_THEN_GIVEN_UP as o,SAVEPOINT_ROLLBACK_FAILED as s,childHandle as c,lockedQuery as l,markFailed as u,scopeOf as d,withLock as f}from"./Scope.js";import{widen as p}from"./widen.js";const m=e=>e,h=(e,t,n)=>r`${r.raw(t)} ${r.id(n)}`.execute(e),g=t=>e.tryAsync(t,i),_=(t,n=()=>void 0)=>e.async(t).map(()=>void 0).recoverWith(()=>e.sync(n)),v=e=>({_tag:`DbError`,code:t.none(),message:e,cause:void 0}),y=()=>v(a),b=(t,n)=>e.sync(()=>t.failed.value).flatMap(t=>t.fold(()=>g(n).map(()=>void 0),t=>e.fail(v(t)))),x=()=>`functype_sp_${Math.random().toString(36).slice(2,10)}`,S=(r=`Db`)=>{let v=n(`functype-kysely:${r}`),y=(t,n)=>e.service(v).flatMap(r=>{let a=n??(e=>i(e));return r.isTransaction?l(d(r),e=>t(r,e),a):e.tryAsync(e=>t(r,e),a)}),S=(e,n)=>y(e,n).map(e=>t(e??void 0)),C=(t,n)=>e.bracketExit(p()(g(()=>t.startTransaction().execute()).map(e=>m(e))),e=>p()(n.provideService(v,e).flatMap(t=>f(d(e),b(d(e),()=>e.commit().execute())).map(()=>t))),t=>p()(t.isCommitted||t.isRolledBack?e.succeed(void 0):f(d(t),_(()=>t.rollback().execute())))),w=(t,n)=>{let r=d(t),i=c(t),l=d(i),m=x(),y={value:!1},S=()=>f(l,_(()=>h(i,`rollback to savepoint`,m),()=>u(r,s)));return f(r,e.bracketExit(p()(g(()=>h(t,`savepoint`,m)).mapError(e=>(u(r,a),e)).map(()=>i)),e=>p()(n.provideService(v,e).flatMap(t=>f(l,b(l,()=>h(e,`release savepoint`,m).then(()=>{y.value=!0}))).map(()=>t))),(t,n)=>{let i=()=>y.value?e.sync(()=>u(r,o)):S();return p()(n.fold(i,()=>e.succeed(void 0),i,i))}))};return{tag:v,query:y,queryOption:S,transaction:t=>p()(e.service(v).flatMap(e=>e.isTransaction?w(e,t):C(e,t)))}};export{S as KyselyDb,y as recoveredQueryError};
1
+ import{IO as e,Option as t,Tag as n}from"functype";import{sql as r}from"kysely";import{toDbError as i}from"./DbError.js";import{QUERY_FAILED as a,RELEASED_THEN_GIVEN_UP as o,SAVEPOINT_ROLLBACK_FAILED as s,childHandle as c,lockedQuery as l,markFailed as u,scopeOf as d,withLock as f}from"./Scope.js";const p=e=>e,m=(e,t,n)=>r`${r.raw(t)} ${r.id(n)}`.execute(e),h=t=>e.tryAsync(t,i),g=(t,n=()=>void 0)=>e.async(t).map(()=>void 0).recoverWith(()=>e.sync(n)),_=e=>({_tag:`DbError`,code:t.none(),message:e,cause:void 0}),v=()=>_(a),y=(t,n)=>e.sync(()=>t.failed.value).flatMap(t=>t.fold(()=>h(n).map(()=>void 0),t=>e.fail(_(t)))),b=()=>`functype_sp_${Math.random().toString(36).slice(2,10)}`,x=(r=`Db`)=>{let _=n(`functype-kysely:${r}`),v=(t,n)=>e.service(_).flatMap(r=>{let a=n??(e=>i(e));return r.isTransaction?l(d(r),e=>t(r,e),a):e.tryAsync(e=>t(r,e),a)}),x=(e,n)=>v(e,n).map(e=>t(e??void 0)),S=(t,n)=>e.bracketExit(h(()=>t.startTransaction().execute()).map(e=>p(e)),e=>n.provideService(_,e).flatMap(t=>f(d(e),y(d(e),()=>e.commit().execute())).map(()=>t)),t=>t.isCommitted||t.isRolledBack?e.succeed(void 0):f(d(t),g(()=>t.rollback().execute()))),C=(t,n)=>{let r=d(t),i=c(t),l=d(i),p=b(),v={value:!1},x=()=>f(l,g(()=>m(i,`rollback to savepoint`,p),()=>u(r,s)));return f(r,e.bracketExit(h(()=>m(t,`savepoint`,p)).mapError(e=>(u(r,a),e)).map(()=>i),e=>n.provideService(_,e).flatMap(t=>f(l,y(l,()=>m(e,`release savepoint`,p).then(()=>{v.value=!0}))).map(()=>t)),(t,n)=>{let i=()=>v.value?e.sync(()=>u(r,o)):x();return n.fold(i,()=>e.succeed(void 0),i,i)}))};return{tag:_,query:v,queryOption:x,transaction:t=>e.service(_).flatMap(e=>e.isTransaction?C(e,t):S(e,t))}};export{x as KyselyDb,v as recoveredQueryError};
2
2
  //# sourceMappingURL=KyselyDb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"KyselyDb.js","names":["IO","Option","Tag","sql","toDbError","QUERY_FAILED","RELEASED_THEN_GIVEN_UP","SAVEPOINT_ROLLBACK_FAILED","childHandle","lockedQuery","markFailed","scopeOf","withLock","widen","controlled","trx","savepointSql","command","name","step","f","rollbackQuietly","onFailure","refused","message","recoveredQueryError","finish","scope","failed","reason","savepointName","KyselyDb","tag","query","toError","db","mapError","signal","queryOption","a","inTopLevel","program","t","inSavepoint","parent","parentScope","inner","innerScope","savepoint","released","rollback","handle","_handle","exit","undo"],"sources":["../src/KyselyDb.ts"],"sourcesContent":["import type { IOType, TagType } from \"functype\"\nimport { IO, Option, Tag } from \"functype\"\nimport type { ControlledTransaction, Kysely } from \"kysely\"\nimport { sql } from \"kysely\"\n\nimport type { DbError } from \"./DbError\"\nimport { toDbError } from \"./DbError\"\nimport type { Scope } from \"./Scope\"\nimport {\n childHandle,\n lockedQuery,\n markFailed,\n QUERY_FAILED,\n RELEASED_THEN_GIVEN_UP,\n SAVEPOINT_ROLLBACK_FAILED,\n scopeOf,\n withLock,\n} from \"./Scope\"\nimport { widen } from \"./widen\"\n\n/**\n * A Kysely database as a functype service: a {@link TagType | Tag} to provide it under, queries\n * that return IO, and transactions that wrap an IO program.\n *\n * Make one per database with {@link KyselyDb}, and provide the `Kysely` instance once, at the edge:\n * `program.provideService(Db.tag, db).run()`.\n */\nexport type KyselyDb<DB> = {\n /** The service tag. Provide a `Kysely<DB>` under it. */\n readonly tag: TagType<Kysely<DB>>\n\n /**\n * Runs one Kysely call as an IO. A throw becomes a typed {@link DbError}, or `toError`'s value.\n *\n * `f` gets the current database, which is the open transaction inside\n * {@link KyselyDb.transaction}, and the run's abort signal. Pass the signal to `execute` so a\n * cancelled run stops waiting for the query; Kysely's `inflightQueryAbortStrategy` decides\n * whether the server cancels it too.\n *\n * @example\n * ```ts\n * const findUser = (id: string) =>\n * Db.query((db, signal) => db.selectFrom(\"user\").selectAll().where(\"id\", \"=\", id).executeTakeFirst({ signal }))\n * ```\n */\n readonly query: {\n <A>(f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>): IOType<Kysely<DB>, DbError, A>\n <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError: (error: unknown) => E,\n ): IOType<Kysely<DB>, E, A>\n }\n\n /**\n * Runs a Kysely call that may find no row, such as `executeTakeFirst`, as an IO of an `Option`:\n * `Some` for a row, `None` for `undefined` or `null`. Otherwise it is {@link KyselyDb.query}.\n *\n * Prefer it to `executeTakeFirstOrThrow` inside a transaction. A missing row is then `None`, not\n * a rejected query, so the program can handle it and the transaction still commits.\n *\n * @example\n * ```ts\n * const findUser = (id: string) =>\n * Db.queryOption((db, signal) => db.selectFrom(\"user\").selectAll().where(\"id\", \"=\", id).executeTakeFirst({ signal }))\n * // IO<Kysely<Database>, DbError, Option<User>>\n * ```\n */\n readonly queryOption: {\n <A>(f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>): IOType<Kysely<DB>, DbError, Option<NonNullable<A>>>\n <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError: (error: unknown) => E,\n ): IOType<Kysely<DB>, E, Option<NonNullable<A>>>\n }\n\n /**\n * Runs `program` in a transaction. It commits when `program` succeeds. It rolls back when\n * `program` fails with its own error, dies, or is cancelled, and that outcome passes through\n * unchanged. A failure to begin or commit is a {@link DbError}.\n *\n * Inside, every `Db.query` and `IO.service(Db.tag)` sees the transaction, so the steps are\n * ordinary IO: compose them with `flatMap` and `IO.gen`, and fail with your own typed errors;\n * nothing needs to throw to roll back.\n *\n * **A failed or abandoned query can't be recovered in place.** Postgres aborts a transaction on\n * any failed statement, and its COMMIT then rolls back without an error; a write a `timeout` gave\n * up on may still land. So when a `Db.query` fails, or a timeout or cancel gives up on it, and the\n * program carries on, the commit fails with a {@link DbError} rather than report a commit that\n * didn't happen. Run a query you may need to recover from in a nested `transaction`.\n *\n * **Steps run one at a time.** The transaction is one connection: its queries, nested\n * transactions and commit wait for each other, even under `IO.all`.\n *\n * Both rules cover `Db.query` and `Db.queryOption` only. Any rejection of their function counts\n * as a failed query, Kysely's `NoResultError` included, so read a row that may be missing with\n * `Db.queryOption` and `executeTakeFirst`, not `executeTakeFirstOrThrow`. A function that catches\n * a failed statement and resolves isn't a failed query, so on Postgres its COMMIT rolls back\n * silently. A statement run on the handle directly, or on one derived from it with `withSchema`\n * or `withPlugin`, isn't serialized or checked.\n *\n * **Nesting uses a savepoint.** A `transaction` inside another one opens a savepoint, not a\n * second transaction. When the inner program fails, its writes roll back to the savepoint and the\n * outer transaction stays usable, so an outer `recover` can carry on. This needs a dialect with\n * `SAVEPOINT` (Postgres, MySQL, SQLite; not MSSQL).\n *\n * **A cancel waits for the query in flight.** A cancelled run stops before its next step and rolls\n * back once the current query settles. A nested transaction that a `timeout`, `race`, `IO.all` or\n * `interruptOn` gave up on still finishes its rollback before the outer transaction's next step;\n * if it was given up on after its savepoint was released, the outer commit is refused instead. A\n * commit that has already started when the run is cancelled still commits, though the run\n * reports the cancel.\n *\n * The provided service can also be a transaction you opened with Kysely itself, such as the\n * `trx` in `db.transaction().execute(callback)`. Then `transaction` opens a savepoint in it, but\n * Kysely owns the commit, so neither the one-at-a-time lock nor the refused commit covers it.\n *\n * Inside a nested transaction, don't re-provide an outer handle captured earlier: the nested\n * transaction holds the outer one's lock, so a query on it waits forever.\n *\n * @example\n * ```ts\n * const transfer = (from: string, to: string, amount: number) =>\n * Db.transaction(\n * IO.gen(function* () {\n * const balance = yield* balanceOf(from)\n * if (balance < amount) return yield* IO.fail(insufficientFunds(from))\n * yield* debit(from, amount)\n * yield* credit(to, amount)\n * }),\n * )\n * // IO<Kysely<Database>, DbError | InsufficientFunds, void>\n * ```\n */\n readonly transaction: <R, E, A>(program: IOType<R, E, A>) => IOType<R | Kysely<DB>, E | DbError, A>\n}\n\n/** The parts of a controlled transaction this module calls. */\ntype Controlled<DB> = Kysely<DB> & {\n readonly isCommitted: boolean\n readonly isRolledBack: boolean\n readonly commit: () => { readonly execute: () => Promise<void> }\n readonly rollback: () => { readonly execute: () => Promise<void> }\n}\n\nconst controlled = <DB>(trx: ControlledTransaction<DB>): Controlled<DB> => trx as unknown as Controlled<DB>\n\n/**\n * Savepoints are issued as SQL rather than through Kysely's `savepoint()`, which only a controlled\n * transaction has and some drivers (PGlite's) don't implement. Postgres, MySQL and SQLite share\n * this syntax.\n */\nconst savepointSql = <DB>(\n trx: Kysely<DB>,\n command: \"savepoint\" | \"release savepoint\" | \"rollback to savepoint\",\n name: string,\n) => sql`${sql.raw(command)} ${sql.id(name)}`.execute(trx)\n\nconst step = <A>(f: () => Promise<A>): IOType<never, DbError, A> => IO.tryAsync(f, toDbError)\n\n/**\n * A rollback after the program already failed. Its own failure is dropped so the program's outcome\n * stands; Kysely frees the connection either way. `onFailure` notes the lost rollback.\n */\nconst rollbackQuietly = (\n f: () => Promise<unknown>,\n onFailure: () => void = () => undefined,\n): IOType<never, never, void> =>\n IO.async(f)\n .map(() => undefined)\n .recoverWith(() => IO.sync(onFailure))\n\nconst refused = (message: string): DbError => ({ _tag: \"DbError\", code: Option.none(), message, cause: undefined })\n\n/** What a commit fails with when a query in its scope failed, or was given up on, and the program carried on. */\nexport const recoveredQueryError = (): DbError => refused(QUERY_FAILED)\n\n/** Commits, or releases a savepoint, unless something on the scope went wrong. */\nconst finish = (scope: Scope, f: () => Promise<unknown>): IOType<never, DbError, void> =>\n IO.sync(() => scope.failed.value).flatMap((failed) =>\n failed.fold(\n () => step(f).map(() => undefined),\n (reason) => IO.fail(refused(reason)),\n ),\n )\n\nconst savepointName = (): string => `functype_sp_${Math.random().toString(36).slice(2, 10)}`\n\n/**\n * Makes the {@link KyselyDb} service for one database.\n *\n * @param name - names the service, `\"Db\"` by default. Its tag's id is `functype-kysely:<name>`,\n * so two databases need two names.\n *\n * @example\n * ```ts\n * import { KyselyDb } from \"functype-kysely\"\n *\n * export const Db = KyselyDb<Database>()\n *\n * const program = Db.transaction(createOrder(input))\n * const result = await program.provideService(Db.tag, db).run()\n * ```\n */\nexport const KyselyDb = <DB>(name = \"Db\"): KyselyDb<DB> => {\n const tag = Tag<Kysely<DB>>(`functype-kysely:${name}`)\n\n const query = <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError?: (error: unknown) => E,\n ): IOType<Kysely<DB>, E | DbError, A> =>\n IO.service(tag).flatMap((db) => {\n const mapError = toError ?? ((e: unknown): E | DbError => toDbError(e))\n if (!db.isTransaction) return IO.tryAsync((signal) => f(db, signal), mapError)\n return lockedQuery(scopeOf(db), (signal) => f(db, signal), mapError)\n })\n\n const queryOption = <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError?: (error: unknown) => E,\n ): IOType<Kysely<DB>, E | DbError, Option<NonNullable<A>>> => query(f, toError).map((a) => Option(a ?? undefined))\n\n const inTopLevel = <R, E, A>(db: Kysely<DB>, program: IOType<R, E, A>): IOType<R, E | DbError, A> =>\n IO.bracketExit(\n widen<R, E | DbError>()(step(() => db.startTransaction().execute()).map((t) => controlled<DB>(t))),\n (trx) =>\n widen<R, E | DbError>()(\n program.provideService(tag, trx).flatMap((a) =>\n withLock(\n scopeOf(trx),\n finish(scopeOf(trx), () => trx.commit().execute()),\n ).map(() => a),\n ),\n ),\n (trx) =>\n widen<R, never>()(\n trx.isCommitted || trx.isRolledBack\n ? IO.succeed(undefined)\n : withLock(\n scopeOf(trx),\n rollbackQuietly(() => trx.rollback().execute()),\n ),\n ),\n )\n\n const inSavepoint = <R, E, A>(parent: Kysely<DB>, program: IOType<R, E, A>): IOType<R, E | DbError, A> => {\n const parentScope = scopeOf(parent)\n const inner = childHandle(parent)\n const innerScope = scopeOf(inner)\n const savepoint = savepointName()\n // Set once RELEASE SAVEPOINT succeeds. A cancel can still land after it, and then there is no\n // savepoint left to roll back to: its writes are already the parent's.\n const released = { value: false }\n // Release and rollback take the savepoint's own lock, so they wait for a query in it that a\n // timeout gave up on: its write lands before the rollback, which then undoes it.\n const rollback = (): IOType<never, never, void> =>\n withLock(\n innerScope,\n rollbackQuietly(\n () => savepointSql(inner, \"rollback to savepoint\", savepoint),\n () => markFailed(parentScope, SAVEPOINT_ROLLBACK_FAILED),\n ),\n )\n // The savepoint holds its parent's lock for its whole life, so no sibling statement lands\n // between its open and its release or rollback.\n return withLock(\n parentScope,\n IO.bracketExit(\n widen<R, E | DbError>()(\n step(() => savepointSql(parent, \"savepoint\", savepoint))\n .mapError((e) => {\n markFailed(parentScope, QUERY_FAILED)\n return e\n })\n .map(() => inner),\n ),\n (handle) =>\n widen<R, E | DbError>()(\n program.provideService(tag, handle).flatMap((a) =>\n withLock(\n innerScope,\n finish(innerScope, () =>\n savepointSql(handle, \"release savepoint\", savepoint).then(() => {\n released.value = true\n }),\n ),\n ).map(() => a),\n ),\n ),\n (_handle, exit) => {\n const undo = (): IOType<never, never, void> =>\n released.value ? IO.sync(() => markFailed(parentScope, RELEASED_THEN_GIVEN_UP)) : rollback()\n return widen<R, never>()(exit.fold(undo, () => IO.succeed(undefined), undo, undo))\n },\n ),\n )\n }\n\n const transaction = <R, E, A>(program: IOType<R, E, A>): IOType<R | Kysely<DB>, E | DbError, A> =>\n widen<R | Kysely<DB>, E | DbError>()(\n IO.service(tag).flatMap((db) => (db.isTransaction ? inSavepoint(db, program) : inTopLevel(db, program))),\n )\n\n return { tag, query, queryOption, transaction } as KyselyDb<DB>\n}\n"],"mappings":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CAAC,CAAC,SAAW,CAC9DC,EAAS,MAAQ,EACnB,CAAC,CACH,CACF,CAAC,CAAC,QAAUV,CAAC,CACf,CACF,GACDa,EAASC,IAAS,CACjB,IAAMC,MACJL,EAAS,MAAQjD,EAAG,SAAWU,EAAWmC,EAAavC,CAAsB,CAAC,EAAI4C,EAAS,EAC7F,OAAOrC,EAAgB,CAAC,CAACwC,EAAK,KAAKC,MAAYtD,EAAG,QAAQ,IAAA,EAAS,EAAGsD,EAAMA,CAAI,CAAC,CACnF,CACF,CACF,CACF,EAOA,MAAO,CAAEtB,MAAKC,QAAOK,cAAa,YALJG,GAC5B5B,EAAmC,CAAC,CAClCb,EAAG,QAAQgC,CAAG,CAAC,CAAC,QAASG,GAAQA,EAAG,cAAgBQ,EAAYR,EAAIM,CAAO,EAAID,EAAWL,EAAIM,CAAO,CAAE,CACzG,CAE4C,CAChD,E"}
1
+ {"version":3,"file":"KyselyDb.js","names":["IO","Option","Tag","sql","toDbError","QUERY_FAILED","RELEASED_THEN_GIVEN_UP","SAVEPOINT_ROLLBACK_FAILED","childHandle","lockedQuery","markFailed","scopeOf","withLock","controlled","trx","savepointSql","command","name","step","f","rollbackQuietly","onFailure","refused","message","recoveredQueryError","finish","scope","failed","reason","savepointName","KyselyDb","tag","query","toError","db","mapError","signal","queryOption","a","inTopLevel","program","t","inSavepoint","parent","parentScope","inner","innerScope","savepoint","released","rollback","handle","_handle","exit","undo"],"sources":["../src/KyselyDb.ts"],"sourcesContent":["import type { IOType, TagType } from \"functype\"\nimport { IO, Option, Tag } from \"functype\"\nimport type { ControlledTransaction, Kysely } from \"kysely\"\nimport { sql } from \"kysely\"\n\nimport type { DbError } from \"./DbError\"\nimport { toDbError } from \"./DbError\"\nimport type { Scope } from \"./Scope\"\nimport {\n childHandle,\n lockedQuery,\n markFailed,\n QUERY_FAILED,\n RELEASED_THEN_GIVEN_UP,\n SAVEPOINT_ROLLBACK_FAILED,\n scopeOf,\n withLock,\n} from \"./Scope\"\n\n/**\n * A Kysely database as a functype service: a {@link TagType | Tag} to provide it under, queries\n * that return IO, and transactions that wrap an IO program.\n *\n * Make one per database with {@link KyselyDb}, and provide the `Kysely` instance once, at the edge:\n * `program.provideService(Db.tag, db).run()`.\n */\nexport type KyselyDb<DB> = {\n /** The service tag. Provide a `Kysely<DB>` under it. */\n readonly tag: TagType<Kysely<DB>>\n\n /**\n * Runs one Kysely call as an IO. A throw becomes a typed {@link DbError}, or `toError`'s value.\n *\n * `f` gets the current database, which is the open transaction inside\n * {@link KyselyDb.transaction}, and the run's abort signal. Pass the signal to `execute` so a\n * cancelled run stops waiting for the query; Kysely's `inflightQueryAbortStrategy` decides\n * whether the server cancels it too.\n *\n * @example\n * ```ts\n * const findUser = (id: string) =>\n * Db.query((db, signal) => db.selectFrom(\"user\").selectAll().where(\"id\", \"=\", id).executeTakeFirst({ signal }))\n * ```\n */\n readonly query: {\n <A>(f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>): IOType<Kysely<DB>, DbError, A>\n <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError: (error: unknown) => E,\n ): IOType<Kysely<DB>, E, A>\n }\n\n /**\n * Runs a Kysely call that may find no row, such as `executeTakeFirst`, as an IO of an `Option`:\n * `Some` for a row, `None` for `undefined` or `null`. Otherwise it is {@link KyselyDb.query}.\n *\n * Prefer it to `executeTakeFirstOrThrow` inside a transaction. A missing row is then `None`, not\n * a rejected query, so the program can handle it and the transaction still commits.\n *\n * @example\n * ```ts\n * const findUser = (id: string) =>\n * Db.queryOption((db, signal) => db.selectFrom(\"user\").selectAll().where(\"id\", \"=\", id).executeTakeFirst({ signal }))\n * // IO<Kysely<Database>, DbError, Option<User>>\n * ```\n */\n readonly queryOption: {\n <A>(f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>): IOType<Kysely<DB>, DbError, Option<NonNullable<A>>>\n <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError: (error: unknown) => E,\n ): IOType<Kysely<DB>, E, Option<NonNullable<A>>>\n }\n\n /**\n * Runs `program` in a transaction. It commits when `program` succeeds. It rolls back when\n * `program` fails with its own error, dies, or is cancelled, and that outcome passes through\n * unchanged. A failure to begin or commit is a {@link DbError}.\n *\n * Inside, every `Db.query` and `IO.service(Db.tag)` sees the transaction, so the steps are\n * ordinary IO: compose them with `flatMap` and `IO.gen`, and fail with your own typed errors;\n * nothing needs to throw to roll back.\n *\n * **A failed or abandoned query can't be recovered in place.** Postgres aborts a transaction on\n * any failed statement, and its COMMIT then rolls back without an error; a write a `timeout` gave\n * up on may still land. So when a `Db.query` fails, or a timeout or cancel gives up on it, and the\n * program carries on, the commit fails with a {@link DbError} rather than report a commit that\n * didn't happen. Run a query you may need to recover from in a nested `transaction`.\n *\n * **Steps run one at a time.** The transaction is one connection: its queries, nested\n * transactions and commit wait for each other, even under `IO.all`.\n *\n * Both rules cover `Db.query` and `Db.queryOption` only. Any rejection of their function counts\n * as a failed query, Kysely's `NoResultError` included, so read a row that may be missing with\n * `Db.queryOption` and `executeTakeFirst`, not `executeTakeFirstOrThrow`. A function that catches\n * a failed statement and resolves isn't a failed query, so on Postgres its COMMIT rolls back\n * silently. A statement run on the handle directly, or on one derived from it with `withSchema`\n * or `withPlugin`, isn't serialized or checked.\n *\n * **Nesting uses a savepoint.** A `transaction` inside another one opens a savepoint, not a\n * second transaction. When the inner program fails, its writes roll back to the savepoint and the\n * outer transaction stays usable, so an outer `recover` can carry on. This needs a dialect with\n * `SAVEPOINT` (Postgres, MySQL, SQLite; not MSSQL).\n *\n * **A cancel waits for the query in flight.** A cancelled run stops before its next step and rolls\n * back once the current query settles. A nested transaction that a `timeout`, `race`, `IO.all` or\n * `interruptOn` gave up on still finishes its rollback before the outer transaction's next step;\n * if it was given up on after its savepoint was released, the outer commit is refused instead. A\n * commit that has already started when the run is cancelled still commits, though the run\n * reports the cancel.\n *\n * The provided service can also be a transaction you opened with Kysely itself, such as the\n * `trx` in `db.transaction().execute(callback)`. Then `transaction` opens a savepoint in it, but\n * Kysely owns the commit, so neither the one-at-a-time lock nor the refused commit covers it.\n *\n * Inside a nested transaction, don't re-provide an outer handle captured earlier: the nested\n * transaction holds the outer one's lock, so a query on it waits forever.\n *\n * @example\n * ```ts\n * const transfer = (from: string, to: string, amount: number) =>\n * Db.transaction(\n * IO.gen(function* () {\n * const balance = yield* balanceOf(from)\n * if (balance < amount) return yield* IO.fail(insufficientFunds(from))\n * yield* debit(from, amount)\n * yield* credit(to, amount)\n * }),\n * )\n * // IO<Kysely<Database>, DbError | InsufficientFunds, void>\n * ```\n */\n readonly transaction: <R, E, A>(program: IOType<R, E, A>) => IOType<R | Kysely<DB>, E | DbError, A>\n}\n\n/** The parts of a controlled transaction this module calls. */\ntype Controlled<DB> = Kysely<DB> & {\n readonly isCommitted: boolean\n readonly isRolledBack: boolean\n readonly commit: () => { readonly execute: () => Promise<void> }\n readonly rollback: () => { readonly execute: () => Promise<void> }\n}\n\nconst controlled = <DB>(trx: ControlledTransaction<DB>): Controlled<DB> => trx as unknown as Controlled<DB>\n\n/**\n * Savepoints are issued as SQL rather than through Kysely's `savepoint()`, which only a controlled\n * transaction has and some drivers (PGlite's) don't implement. Postgres, MySQL and SQLite share\n * this syntax.\n */\nconst savepointSql = <DB>(\n trx: Kysely<DB>,\n command: \"savepoint\" | \"release savepoint\" | \"rollback to savepoint\",\n name: string,\n) => sql`${sql.raw(command)} ${sql.id(name)}`.execute(trx)\n\nconst step = <A>(f: () => Promise<A>): IOType<never, DbError, A> => IO.tryAsync(f, toDbError)\n\n/**\n * A rollback after the program already failed. Its own failure is dropped so the program's outcome\n * stands; Kysely frees the connection either way. `onFailure` notes the lost rollback.\n */\nconst rollbackQuietly = (\n f: () => Promise<unknown>,\n onFailure: () => void = () => undefined,\n): IOType<never, never, void> =>\n IO.async(f)\n .map(() => undefined)\n .recoverWith(() => IO.sync(onFailure))\n\nconst refused = (message: string): DbError => ({ _tag: \"DbError\", code: Option.none(), message, cause: undefined })\n\n/** What a commit fails with when a query in its scope failed, or was given up on, and the program carried on. */\nexport const recoveredQueryError = (): DbError => refused(QUERY_FAILED)\n\n/** Commits, or releases a savepoint, unless something on the scope went wrong. */\nconst finish = (scope: Scope, f: () => Promise<unknown>): IOType<never, DbError, void> =>\n IO.sync(() => scope.failed.value).flatMap((failed) =>\n failed.fold(\n () => step(f).map(() => undefined),\n (reason) => IO.fail(refused(reason)),\n ),\n )\n\nconst savepointName = (): string => `functype_sp_${Math.random().toString(36).slice(2, 10)}`\n\n/**\n * Makes the {@link KyselyDb} service for one database.\n *\n * @param name - names the service, `\"Db\"` by default. Its tag's id is `functype-kysely:<name>`,\n * so two databases need two names.\n *\n * @example\n * ```ts\n * import { KyselyDb } from \"functype-kysely\"\n *\n * export const Db = KyselyDb<Database>()\n *\n * const program = Db.transaction(createOrder(input))\n * const result = await program.provideService(Db.tag, db).run()\n * ```\n */\nexport const KyselyDb = <DB>(name = \"Db\"): KyselyDb<DB> => {\n const tag = Tag<Kysely<DB>>(`functype-kysely:${name}`)\n\n const query = <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError?: (error: unknown) => E,\n ): IOType<Kysely<DB>, E | DbError, A> =>\n IO.service(tag).flatMap((db) => {\n const mapError = toError ?? ((e: unknown): E | DbError => toDbError(e))\n if (!db.isTransaction) return IO.tryAsync((signal) => f(db, signal), mapError)\n return lockedQuery(scopeOf(db), (signal) => f(db, signal), mapError)\n })\n\n const queryOption = <A, E>(\n f: (db: Kysely<DB>, signal?: AbortSignal) => Promise<A>,\n toError?: (error: unknown) => E,\n ): IOType<Kysely<DB>, E | DbError, Option<NonNullable<A>>> => query(f, toError).map((a) => Option(a ?? undefined))\n\n const inTopLevel = <R, E, A>(db: Kysely<DB>, program: IOType<R, E, A>): IOType<R, E | DbError, A> =>\n IO.bracketExit(\n step(() => db.startTransaction().execute()).map((t) => controlled<DB>(t)),\n (trx) =>\n program.provideService(tag, trx).flatMap((a) =>\n withLock(\n scopeOf(trx),\n finish(scopeOf(trx), () => trx.commit().execute()),\n ).map(() => a),\n ),\n (trx) =>\n trx.isCommitted || trx.isRolledBack\n ? IO.succeed(undefined)\n : withLock(\n scopeOf(trx),\n rollbackQuietly(() => trx.rollback().execute()),\n ),\n )\n\n const inSavepoint = <R, E, A>(parent: Kysely<DB>, program: IOType<R, E, A>): IOType<R, E | DbError, A> => {\n const parentScope = scopeOf(parent)\n const inner = childHandle(parent)\n const innerScope = scopeOf(inner)\n const savepoint = savepointName()\n // Set once RELEASE SAVEPOINT succeeds. A cancel can still land after it, and then there is no\n // savepoint left to roll back to: its writes are already the parent's.\n const released = { value: false }\n // Release and rollback take the savepoint's own lock, so they wait for a query in it that a\n // timeout gave up on: its write lands before the rollback, which then undoes it.\n const rollback = (): IOType<never, never, void> =>\n withLock(\n innerScope,\n rollbackQuietly(\n () => savepointSql(inner, \"rollback to savepoint\", savepoint),\n () => markFailed(parentScope, SAVEPOINT_ROLLBACK_FAILED),\n ),\n )\n // The savepoint holds its parent's lock for its whole life, so no sibling statement lands\n // between its open and its release or rollback.\n return withLock(\n parentScope,\n IO.bracketExit(\n step(() => savepointSql(parent, \"savepoint\", savepoint))\n .mapError((e) => {\n markFailed(parentScope, QUERY_FAILED)\n return e\n })\n .map(() => inner),\n (handle) =>\n program.provideService(tag, handle).flatMap((a) =>\n withLock(\n innerScope,\n finish(innerScope, () =>\n savepointSql(handle, \"release savepoint\", savepoint).then(() => {\n released.value = true\n }),\n ),\n ).map(() => a),\n ),\n (_handle, exit) => {\n const undo = (): IOType<never, never, void> =>\n released.value ? IO.sync(() => markFailed(parentScope, RELEASED_THEN_GIVEN_UP)) : rollback()\n return exit.fold(undo, () => IO.succeed(undefined), undo, undo)\n },\n ),\n )\n }\n\n const transaction = <R, E, A>(program: IOType<R, E, A>): IOType<R | Kysely<DB>, E | DbError, A> =>\n IO.service(tag).flatMap((db) => (db.isTransaction ? inSavepoint(db, program) : inTopLevel(db, program)))\n\n return { t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,CAAC,CACf,GACDa,EAASC,IAAS,CACjB,IAAMC,MACJL,EAAS,MAAQhD,EAAG,SAAWU,EAAWkC,EAAatC,CAAsB,CAAC,EAAI2C,EAAS,EAC7F,OAAOG,EAAK,KAAKC,MAAYrD,EAAG,QAAQ,IAAA,EAAS,EAAGqD,EAAMA,CAAI,CAChE,CACF,CACF,CACF,EAKA,MAAO,CAAEtB,MAAKC,QAAOK,cAAa,YAHJG,GAC5BxC,EAAG,QAAQ+B,CAAG,CAAC,CAAC,QAASG,GAAQA,EAAG,cAAgBQ,EAAYR,EAAIM,CAAO,EAAID,EAAWL,EAAIM,CAAO,CAAE,CAE3D,CAChD,E"}
package/dist/Scope.js CHANGED
@@ -1,2 +1,2 @@
1
- import{IO as e,Option as t}from"functype";import{widen as n}from"./widen.js";const r=()=>{let e=Promise.resolve();return{acquire:()=>{let t=()=>void 0,n=new Promise(e=>{t=e}),r=e.then(()=>t);return e=e.then(()=>n),r}}},i=/* @__PURE__ */ new WeakMap,a=e=>{let n=i.get(e);if(n!==void 0)return n;let a={lock:r(),failed:{value:t.none()}};return i.set(e,a),a},o=t=>e.async(()=>t.lock.acquire()).recoverWith(t=>e.die(t)),s=(t,r)=>e.bracket(n()(o(t)),()=>r,t=>n()(e.sync(t))),c=(e,n)=>{e.failed.value.isNone()&&(e.failed.value=t(n))},l=`A query in this transaction failed, or a timeout or cancel gave up on it, and the program carried on, so the transaction can't commit: Postgres may already have aborted it, and a write given up on may still have landed. Run a query you may need to recover from in a nested Db.transaction.`,u=`A timeout or cancel gave up on a nested Db.transaction after its savepoint was released, so its writes are already part of this transaction, which can't commit.`,d=`A nested Db.transaction in this transaction failed to roll back to its savepoint, so the transaction can't commit.`,f=(r,i,a)=>e.sync(()=>({started:!1,signal:t.none()})).flatMap(s=>e.bracketExit(n()(o(r)),()=>e.tryAsync(e=>(s.started=!0,s.signal=t(e),i(e)),a),(t,n)=>e.sync(()=>{let e=()=>{s.started&&c(r,l)};n.fold(e,()=>{s.signal.exists(e=>e.aborted)&&e()},e,e),t()}))),p={transformQuery:({node:e})=>e,transformResult:({result:e})=>Promise.resolve(e)},m=e=>e.withPlugin(p);export{l as QUERY_FAILED,u as RELEASED_THEN_GIVEN_UP,d as SAVEPOINT_ROLLBACK_FAILED,m as childHandle,f as lockedQuery,c as markFailed,a as scopeOf,s as withLock};
1
+ import{IO as e,Option as t}from"functype";const n=()=>{let e=Promise.resolve();return{acquire:()=>{let t=()=>void 0,n=new Promise(e=>{t=e}),r=e.then(()=>t);return e=e.then(()=>n),r}}},r=/* @__PURE__ */ new WeakMap,i=e=>{let i=r.get(e);if(i!==void 0)return i;let a={lock:n(),failed:{value:t.none()}};return r.set(e,a),a},a=t=>e.async(()=>t.lock.acquire()).recoverWith(t=>e.die(t)),o=(t,n)=>e.bracket(a(t),()=>n,t=>e.sync(t)),s=(e,n)=>{e.failed.value.isNone()&&(e.failed.value=t(n))},c=`A query in this transaction failed, or a timeout or cancel gave up on it, and the program carried on, so the transaction can't commit: Postgres may already have aborted it, and a write given up on may still have landed. Run a query you may need to recover from in a nested Db.transaction.`,l=`A timeout or cancel gave up on a nested Db.transaction after its savepoint was released, so its writes are already part of this transaction, which can't commit.`,u=`A nested Db.transaction in this transaction failed to roll back to its savepoint, so the transaction can't commit.`,d=(n,r,i)=>e.sync(()=>({started:!1,signal:t.none()})).flatMap(o=>e.bracketExit(a(n),()=>e.tryAsync(e=>(o.started=!0,o.signal=t(e),r(e)),i),(t,r)=>e.sync(()=>{let e=()=>{o.started&&s(n,c)};r.fold(e,()=>{o.signal.exists(e=>e.aborted)&&e()},e,e),t()}))),f={transformQuery:({node:e})=>e,transformResult:({result:e})=>Promise.resolve(e)},p=e=>e.withPlugin(f);export{c as QUERY_FAILED,l as RELEASED_THEN_GIVEN_UP,u as SAVEPOINT_ROLLBACK_FAILED,p as childHandle,d as lockedQuery,s as markFailed,i as scopeOf,o as withLock};
2
2
  //# sourceMappingURL=Scope.js.map
package/dist/Scope.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Scope.js","names":["IO","Option","widen","createLock","tail","unlock","held","resolve","ready","scopes","scopeOf","trx","existing","scope","acquire","e","withLock","io","markFailed","reason","QUERY_FAILED","RELEASED_THEN_GIVEN_UP","SAVEPOINT_ROLLBACK_FAILED","lockedQuery","run","mapError","call","signal","exit","mark","NO_OP","node","result","childHandle"],"sources":["../src/Scope.ts"],"sourcesContent":["import type { IOType } from \"functype\"\nimport { IO, Option } from \"functype\"\nimport type { Kysely, KyselyPlugin } from \"kysely\"\n\nimport { widen } from \"./widen\"\n\n/**\n * One transaction or savepoint: the connection-level state that IO's own types can't carry.\n *\n * - `lock` serializes everything that runs on the scope: its queries, its nested savepoints and its\n * commit or rollback. One transaction is one connection, so statements on it run one at a time\n * anyway; the lock also keeps a savepoint's whole life (open, body, release or rollback) from\n * interleaving with a sibling's, and makes a commit wait for a nested scope still running after a\n * `timeout` or `race` gave up on it.\n * - `failed` holds why the scope can't commit, once something on it went wrong: a query that\n * started and didn't succeed (it failed, or a timeout or cancel gave up on it), a nested\n * savepoint whose rollback failed, or one a timeout gave up on after its release. Postgres aborts\n * a transaction on any failed statement, and its COMMIT then rolls back without an error; a write\n * given up on may still land. So such a scope refuses to commit. A nested `Db.transaction` is how\n * a program recovers from a failed query.\n * - Any rejection of a query's callback counts, Kysely's `NoResultError` included: a callback can\n * run several statements, and a not-found error could hide one that failed and aborted the\n * transaction.\n */\nexport type Scope = {\n readonly lock: Lock\n readonly failed: { value: Option<string> }\n}\n\ntype Lock = {\n /** Resolves with the unlock function once every earlier holder has unlocked. */\n readonly acquire: () => Promise<() => void>\n}\n\nconst createLock = (): Lock => {\n // eslint-disable-next-line functype/no-let -- the queue's tail, replaced on each acquire\n let tail: Promise<void> = Promise.resolve()\n return {\n acquire: () => {\n // eslint-disable-next-line functype/no-let -- set by the executor below, before anyone reads it\n let unlock: () => void = () => undefined\n const held = new Promise<void>((resolve) => {\n unlock = resolve\n })\n const ready = tail.then(() => unlock)\n tail = tail.then(() => held)\n return ready\n },\n }\n}\n\nconst scopes = new WeakMap<object, Scope>()\n\n/** The scope of a transaction object, made on first use. */\nexport const scopeOf = (trx: object): Scope => {\n const existing = scopes.get(trx)\n if (existing !== undefined) return existing\n const scope: Scope = { lock: createLock(), failed: { value: Option.none() } }\n scopes.set(trx, scope)\n return scope\n}\n\nconst acquire = (scope: Scope): IOType<never, never, () => void> =>\n IO.async(() => scope.lock.acquire()).recoverWith((e) => IO.die(e))\n\n/** Runs `io` while holding `scope`'s lock, and unlocks on every outcome. */\nexport const withLock = <R, E, A>(scope: Scope, io: IOType<R, E, A>): IOType<R, E, A> =>\n IO.bracket(\n widen<R, E>()(acquire(scope)),\n () => io,\n (unlock) => widen<R, never>()(IO.sync(unlock)),\n )\n\n/** Records why the scope can't commit. The first reason stands. */\nexport const markFailed = (scope: Scope, reason: string): void => {\n if (scope.failed.value.isNone()) scope.failed.value = Option(reason)\n}\n\nexport const QUERY_FAILED =\n \"A query in this transaction failed, or a timeout or cancel gave up on it, and the program carried on, so the transaction can't commit: Postgres may already have aborted it, and a write given up on may still have landed. Run a query you may need to recover from in a nested Db.transaction.\"\n\nexport const RELEASED_THEN_GIVEN_UP =\n \"A timeout or cancel gave up on a nested Db.transaction after its savepoint was released, so its writes are already part of this transaction, which can't commit.\"\n\nexport const SAVEPOINT_ROLLBACK_FAILED =\n \"A nested Db.transaction in this transaction failed to roll back to its savepoint, so the transaction can't commit.\"\n\n/**\n * Runs one query on a transaction's scope, holding its lock. A query that started and didn't\n * succeed marks the scope, whether it failed, or a timeout or cancel gave up on it, even if it then\n * succeeded. The mark is set in the bracket's release, which runs even in a cancelled region, where\n * error handlers don't.\n */\nexport const lockedQuery = <E, A>(\n scope: Scope,\n run: (signal?: AbortSignal) => Promise<A>,\n mapError: (error: unknown) => E,\n): IOType<never, E, A> =>\n IO.sync((): { started: boolean; signal: Option<AbortSignal> } => ({ started: false, signal: Option.none() })).flatMap(\n (call) =>\n IO.bracketExit(\n widen<never, E>()(acquire(scope)),\n () =>\n IO.tryAsync((signal) => {\n call.started = true\n call.signal = Option(signal)\n return run(signal)\n }, mapError),\n (unlock, exit) =>\n IO.sync(() => {\n const mark = (): void => {\n if (call.started) markFailed(scope, QUERY_FAILED)\n }\n // A query that settles after its region was cancelled still succeeds here, though the\n // program has moved on without it.\n const markIfGivenUp = (): void => {\n if (call.signal.exists((signal) => signal.aborted)) mark()\n }\n exit.fold(mark, markIfGivenUp, mark, mark)\n unlock()\n }),\n ),\n )\n\nconst NO_OP: KyselyPlugin = {\n transformQuery: ({ node }) => node,\n transformResult: ({ result }) => Promise.resolve(result),\n}\n\n/**\n * A second handle on the same transaction and connection, with the same plugins, so a savepoint\n * gets a scope of its own.\n */\nexport const childHandle = <DB>(trx: Kysely<DB>): Kysely<DB> => trx.withPlugin(NO_OP)\n"],"mappings":"A,6EAkCA,MAAMG,MAAyB,CAE7B,IAAIC,EAAsB,QAAQ,QAAQ,EAC1C,MAAO,CACL,YAAe,CAEb,IAAIC,MAA2B,IAAA,GACzBC,EAAO,IAAI,QAAeC,GAAY,CAC1CF,EAASE,CACX,CAAC,EACKC,EAAQJ,EAAK,SAAWC,CAAM,EAEpC,MADAD,GAAOA,EAAK,SAAWE,CAAI,EACpBE,CACT,CACF,CACF,EAEMC,kBAAS,IAAI,QAGNC,EAAWC,GAAuB,CAC7C,IAAMC,EAAWH,EAAO,IAAIE,CAAG,EAC/B,GAAIC,IAAa,IAAA,GAAW,OAAOA,EACnC,IAAMC,EAAe,CAAE,KAAMV,EAAW,EAAG,OAAQ,CAAE,MAAOF,EAAO,KAAK,CAAE,CAAE,EAE5E,OADAQ,EAAO,IAAIE,EAAKE,CAAK,EACdA,CACT,EAEMC,EAAWD,GACfb,EAAG,UAAYa,EAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAaE,GAAMf,EAAG,IAAIe,CAAC,CAAC,EAGtDC,GAAqBH,EAAcI,IAC9CjB,EAAG,QACDE,EAAY,CAAC,CAACY,EAAQD,CAAK,CAAC,MACtBI,EACLZ,GAAWH,EAAgB,CAAC,CAACF,EAAG,KAAKK,CAAM,CAAC,CAC/C,EAGWa,GAAcL,EAAcM,IAAyB,CAC5DN,EAAM,OAAO,MAAM,OAAO,IAAGA,EAAM,OAAO,MAAQZ,EAAOkB,CAAM,EACrE,EAEaC,EACX,mSAEWC,EACX,mKAEWC,EACX,qHAQWC,GACXV,EACAW,EACAC,IAEAzB,EAAG,UAA+D,CAAE,QAAS,GAAO,OAAQC,EAAO,KAAK,CAAE,EAAE,CAAC,CAAC,QAC3GyB,GACC1B,EAAG,YACDE,EAAgB,CAAC,CAACY,EAAQD,CAAK,CAAC,MAE9Bb,EAAG,SAAU2B,IACXD,EAAK,QAAU,GACfA,EAAK,OAASzB,EAAO0B,CAAM,EACpBH,EAAIG,CAAM,GAChBF,CAAQ,GACZpB,EAAQuB,IACP5B,EAAG,SAAW,CACZ,IAAM6B,MAAmB,CACnBH,EAAK,SAASR,EAAWL,EAAOO,CAAY,CAClD,EAMAQ,EAAK,KAAKC,MAHwB,CAC5BH,EAAK,OAAO,OAAQC,GAAWA,EAAO,OAAO,GAAGE,EAAK,CAC3D,EAC+BA,EAAMA,CAAI,EACzCxB,EAAO,CACT,CAAC,CACL,CACJ,EAEIyB,EAAsB,CAC1B,gBAAiB,CAAEC,UAAWA,EAC9B,iBAAkB,CAAEC,YAAa,QAAQ,QAAQA,CAAM,CACzD,EAMaC,EAAmBtB,GAAgCA,EAAI,WAAWmB,CAAK,E"}
1
+ {"version":3,"file":"Scope.js","names":["IO","Option","createLock","tail","unlock","held","resolve","ready","scopes","scopeOf","trx","existing","scope","acquire","e","withLock","io","markFailed","reason","QUERY_FAILED","RELEASED_THEN_GIVEN_UP","SAVEPOINT_ROLLBACK_FAILED","lockedQuery","run","mapError","call","signal","exit","mark","NO_OP","node","result","childHandle"],"sources":["../src/Scope.ts"],"sourcesContent":["import type { IOType } from \"functype\"\nimport { IO, Option } from \"functype\"\nimport type { Kysely, KyselyPlugin } from \"kysely\"\n\n/**\n * One transaction or savepoint: the connection-level state that IO's own types can't carry.\n *\n * - `lock` serializes everything that runs on the scope: its queries, its nested savepoints and its\n * commit or rollback. One transaction is one connection, so statements on it run one at a time\n * anyway; the lock also keeps a savepoint's whole life (open, body, release or rollback) from\n * interleaving with a sibling's, and makes a commit wait for a nested scope still running after a\n * `timeout` or `race` gave up on it.\n * - `failed` holds why the scope can't commit, once something on it went wrong: a query that\n * started and didn't succeed (it failed, or a timeout or cancel gave up on it), a nested\n * savepoint whose rollback failed, or one a timeout gave up on after its release. Postgres aborts\n * a transaction on any failed statement, and its COMMIT then rolls back without an error; a write\n * given up on may still land. So such a scope refuses to commit. A nested `Db.transaction` is how\n * a program recovers from a failed query.\n * - Any rejection of a query's callback counts, Kysely's `NoResultError` included: a callback can\n * run several statements, and a not-found error could hide one that failed and aborted the\n * transaction.\n */\nexport type Scope = {\n readonly lock: Lock\n readonly failed: { value: Option<string> }\n}\n\ntype Lock = {\n /** Resolves with the unlock function once every earlier holder has unlocked. */\n readonly acquire: () => Promise<() => void>\n}\n\nconst createLock = (): Lock => {\n // eslint-disable-next-line functype/no-let -- the queue's tail, replaced on each acquire\n let tail: Promise<void> = Promise.resolve()\n return {\n acquire: () => {\n // eslint-disable-next-line functype/no-let -- set by the executor below, before anyone reads it\n let unlock: () => void = () => undefined\n const held = new Promise<void>((resolve) => {\n unlock = resolve\n })\n const ready = tail.then(() => unlock)\n tail = tail.then(() => held)\n return ready\n },\n }\n}\n\nconst scopes = new WeakMap<object, Scope>()\n\n/** The scope of a transaction object, made on first use. */\nexport const scopeOf = (trx: object): Scope => {\n const existing = scopes.get(trx)\n if (existing !== undefined) return existing\n const scope: Scope = { lock: createLock(), failed: { value: Option.none() } }\n scopes.set(trx, scope)\n return scope\n}\n\nconst acquire = (scope: Scope): IOType<never, never, () => void> =>\n IO.async(() => scope.lock.acquire()).recoverWith((e) => IO.die(e))\n\n/** Runs `io` while holding `scope`'s lock, and unlocks on every outcome. */\nexport const withLock = <R, E, A>(scope: Scope, io: IOType<R, E, A>): IOType<R, E, A> =>\n IO.bracket(\n acquire(scope),\n () => io,\n (unlock) => IO.sync(unlock),\n )\n\n/** Records why the scope can't commit. The first reason stands. */\nexport const markFailed = (scope: Scope, reason: string): void => {\n if (scope.failed.value.isNone()) scope.failed.value = Option(reason)\n}\n\nexport const QUERY_FAILED =\n \"A query in this transaction failed, or a timeout or cancel gave up on it, and the program carried on, so the transaction can't commit: Postgres may already have aborted it, and a write given up on may still have landed. Run a query you may need to recover from in a nested Db.transaction.\"\n\nexport const RELEASED_THEN_GIVEN_UP =\n \"A timeout or cancel gave up on a nested Db.transaction after its savepoint was released, so its writes are already part of this transaction, which can't commit.\"\n\nexport const SAVEPOINT_ROLLBACK_FAILED =\n \"A nested Db.transaction in this transaction failed to roll back to its savepoint, so the transaction can't commit.\"\n\n/**\n * Runs one query on a transaction's scope, holding its lock. A query that started and didn't\n * succeed marks the scope, whether it failed, or a timeout or cancel gave up on it, even if it then\n * succeeded. The mark is set in the bracket's release, which runs even in a cancelled region, where\n * error handlers don't.\n */\nexport const lockedQuery = <E, A>(\n scope: Scope,\n run: (signal?: AbortSignal) => Promise<A>,\n mapError: (error: unknown) => E,\n): IOType<never, E, A> =>\n IO.sync((): { started: boolean; signal: Option<AbortSignal> } => ({ started: false, signal: Option.none() })).flatMap(\n (call) =>\n IO.bracketExit(\n acquire(scope),\n () =>\n IO.tryAsync((signal) => {\n call.started = true\n call.signal = Option(signal)\n return run(signal)\n }, mapError),\n (unlock, exit) =>\n IO.sync(() => {\n const mark = (): void => {\n if (call.started) markFailed(scope, QUERY_FAILED)\n }\n // A query that settles after its region was cancelled still succeeds here, though the\n // program has moved on without it.\n const markIfGivenUp = (): void => {\n if (call.signal.exists((signal) => signal.aborted)) mark()\n }\n exit.fold(mark, markIfGivenUp, mark, mark)\n unlock()\n }),\n ),\n )\n\nconst NO_OP: KyselyPlugin = {\n transformQuery: ({ node }) => node,\n transformResult: ({ result }) => Promise.resolve(result),\n}\n\n/**\n * A second handle on the same transaction and connection, with the same plugins, so a savepoint\n * gets a scope of its own.\n */\nexport const childHandle = <DB>(trx: Kysely<DB>): Kysely<DB> => trx.withPlugin(NO_OP)\n"],"mappings":"A,0CAgCA,MAAME,MAAyB,CAE7B,IAAIC,EAAsB,QAAQ,QAAQ,EAC1C,MAAO,CACL,YAAe,CAEb,IAAIC,MAA2B,IAAA,GACzBC,EAAO,IAAI,QAAeC,GAAY,CAC1CF,EAASE,CACX,CAAC,EACKC,EAAQJ,EAAK,SAAWC,CAAM,EAEpC,MADAD,GAAOA,EAAK,SAAWE,CAAI,EACpBE,CACT,CACF,CACF,EAEMC,kBAAS,IAAI,QAGNC,EAAWC,GAAuB,CAC7C,IAAMC,EAAWH,EAAO,IAAIE,CAAG,EAC/B,GAAIC,IAAa,IAAA,GAAW,OAAOA,EACnC,IAAMC,EAAe,CAAE,KAAMV,EAAW,EAAG,OAAQ,CAAE,MAAOD,EAAO,KAAK,CAAE,CAAE,EAE5E,OADAO,EAAO,IAAIE,EAAKE,CAAK,EACdA,CACT,EAEMC,EAAWD,GACfZ,EAAG,UAAYY,EAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAaE,GAAMd,EAAG,IAAIc,CAAC,CAAC,EAGtDC,GAAqBH,EAAcI,IAC9ChB,EAAG,QACDa,EAAQD,CAAK,MACPI,EACLZ,GAAWJ,EAAG,KAAKI,CAAM,CAC5B,EAGWa,GAAcL,EAAcM,IAAyB,CAC5DN,EAAM,OAAO,MAAM,OAAO,IAAGA,EAAM,OAAO,MAAQX,EAAOiB,CAAM,EACrE,EAEaC,EACX,mSAEWC,EACX,mKAEWC,EACX,qHAQWC,GACXV,EACAW,EACAC,IAEAxB,EAAG,UAA+D,CAAE,QAAS,GAAO,OAAQC,EAAO,KAAK,CAAE,EAAE,CAAC,CAAC,QAC3GwB,GACCzB,EAAG,YACDa,EAAQD,CAAK,MAEXZ,EAAG,SAAU0B,IACXD,EAAK,QAAU,GACfA,EAAK,OAASxB,EAAOyB,CAAM,EACpBH,EAAIG,CAAM,GAChBF,CAAQ,GACZpB,EAAQuB,IACP3B,EAAG,SAAW,CACZ,IAAM4B,MAAmB,CACnBH,EAAK,SAASR,EAAWL,EAAOO,CAAY,CAClD,EAMAQ,EAAK,KAAKC,MAHwB,CAC5BH,EAAK,OAAO,OAAQC,GAAWA,EAAO,OAAO,GAAGE,EAAK,CAC3D,EAC+BA,EAAMA,CAAI,EACzCxB,EAAO,CACT,CAAC,CACL,CACJ,EAEIyB,EAAsB,CAC1B,gBAAiB,CAAEC,UAAWA,EAC9B,iBAAkB,CAAEC,YAAa,QAAQ,QAAQA,CAAM,CACzD,EAMaC,EAAmBtB,GAAgCA,EAAI,WAAWmB,CAAK,E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "functype-kysely",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "Kysely for functype — queries as typed IO, and transactions that roll back on a typed failure, a defect or a cancel",
5
5
  "keywords": [
6
6
  "functype",
@@ -30,7 +30,7 @@
30
30
  "@electric-sql/pglite": "0.5.17",
31
31
  "@types/node": "^24.19.2",
32
32
  "eslint-config-prettier": "^10.1.8",
33
- "functype": "^2.3.0",
33
+ "functype": "^2.4.0",
34
34
  "kysely": "0.29.9",
35
35
  "kysely-pglite-dialect": "1.4.0",
36
36
  "ts-builds": "^5.0.0",
package/dist/widen.d.ts DELETED
@@ -1,13 +0,0 @@
1
- import { IOType } from "functype";
2
- /**
3
- * Widens an IO to services `R` and errors `E`, which must contain its own.
4
- *
5
- * IO's type parameters are invariant, so an IO that needs fewer services or fails in fewer ways
6
- * doesn't widen on its own. Widening is sound: such an IO fits anywhere the wider one does. The
7
- * bounds keep everything else checked: an error or service outside the target, or a value that
8
- * isn't an IO, is a compile error.
9
- *
10
- * Curried so the target is written and the IO's own types are inferred:
11
- * `widen<R, E | DbError>()(step)`.
12
- */
13
- export declare const widen: <R, E>() => <R0 extends R, E0 extends E, A>(io: IOType<R0, E0, A>) => IOType<R, E, A>;
package/dist/widen.js DELETED
@@ -1,2 +0,0 @@
1
- const e=()=>e=>e;export{e as widen};
2
- //# sourceMappingURL=widen.js.map
package/dist/widen.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"widen.js","names":["widen","io"],"sources":["../src/widen.ts"],"sourcesContent":["import type { IOType } from \"functype\"\n\n/**\n * Widens an IO to services `R` and errors `E`, which must contain its own.\n *\n * IO's type parameters are invariant, so an IO that needs fewer services or fails in fewer ways\n * doesn't widen on its own. Widening is sound: such an IO fits anywhere the wider one does. The\n * bounds keep everything else checked: an error or service outside the target, or a value that\n * isn't an IO, is a compile error.\n *\n * Curried so the target is written and the IO's own types are inferred:\n * `widen<R, E | DbError>()(step)`.\n */\nexport const widen =\n <R, E>() =>\n <R0 extends R, E0 extends E, A>(io: IOType<R0, E0, A>): IOType<R, E, A> =>\n io as unknown as IOType<R, E, A>\n"],"mappings":"AAaA,MAAaA,MAEqBC,GAC9BA,E"}