@kern-orm/orchid-interop 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @kern-orm/orchid-interop
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run existing Orchid ORM queries and new [kern-orm](https://github.com/IlyaSemenov/kern-orm) queries on one connection pool and in the same transactions, to move an application from Orchid ORM to kern-orm one function at a time.
4
+
5
+ The adapter is experimental: it supports Orchid ORM 1.x (1.78.61 or later) and postgres.js 4, and not every feature of Orchid ORM.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @kern-orm/orchid-interop kern-orm orchid-orm postgres@4
11
+ ```
12
+
13
+ To only run kern-db code in transactions of an existing Orchid instance, install `kern-db` instead of `kern-orm`.
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { bindSchema } from "kern-orm"
19
+ import { createOrchidInterop } from "@kern-orm/orchid-interop"
20
+
21
+ import { UserTable } from "./legacy/user.table"
22
+ import { schema } from "./schema"
23
+
24
+ export const { database, orchid } = await createOrchidInterop(
25
+ { connection: { databaseURL: process.env.DATABASE_URL! } },
26
+ { user: UserTable },
27
+ )
28
+ export const db = bindSchema(schema, database)
29
+
30
+ await db.$transaction(async () => {
31
+ const user = await orchid.user.create({ email })
32
+ await db.profile.insert({ userId: user.id, name })
33
+ })
34
+ ```
35
+
36
+ To run kern-orm code, such as migrations, in the transactions of an Orchid instance that you keep as it is, including its test transactions, call `runInOrchidTransaction`.
37
+
38
+ See [the documentation](https://ilyasemenov.github.io/kern-orm/orm/orchid-interop) for transactions, tests, and limitations, and [running kern-orm code in transactions of Orchid](https://ilyasemenov.github.io/kern-orm/orm/orchid-interop#run-kern-orm-code-in-transactions-of-orchid).
@@ -0,0 +1,52 @@
1
+ import { Database, DatabaseOptions } from "kern-db";
2
+ import { PostgresJsAdapterOptions } from "orchid-orm/postgres-js";
3
+ import { Adapter as Adapter$1, OrchidORM, OrchidORMSetupOptions, OrmTableThunks } from "orchid-orm";
4
+ /** Connection options of Orchid's postgres.js adapter that the shared pool does not support, with their replacements where they have one. */
5
+ declare const unsupportedConnectionOptions: {
6
+ schema: string;
7
+ setConfig: string;
8
+ connectRetry: string;
9
+ types: string;
10
+ };
11
+ /** Shared database and Orchid instance; close either one to close their single pool. */
12
+ interface OrchidInterop<T extends OrmTableThunks, V extends OrmTableThunks = {}> {
13
+ /** Kern database to bind schemas to and use for transactions and test helpers. */
14
+ database: Database;
15
+ /** Orchid instance using the same database for queries and transactions. */
16
+ orchid: OrchidORM<T, V>;
17
+ }
18
+ /** Connection, database lifecycle, and Orchid query options of the shared database. */
19
+ interface OrchidInteropOptions<V extends OrmTableThunks = {}> {
20
+ /** postgres.js connection options, configured with Orchid's codecs. */
21
+ connection: Omit<PostgresJsAdapterOptions, keyof typeof unsupportedConnectionOptions>;
22
+ /** Kern lifecycle options, including `test: true` for its transaction test helpers. */
23
+ database?: Omit<DatabaseOptions, "driver">;
24
+ /** Orchid schema, logging, table, and view options. */
25
+ orchid?: OrchidORMSetupOptions<V> & {
26
+ db?: never;
27
+ };
28
+ }
29
+ /**
30
+ * Opens one postgres.js pool for Kern and existing Orchid tables, with transactions owned by Kern.
31
+ * Initializes database-defined codecs before returning, unless `fetch_types` of the connection is `false`; close `database` or `orchid` when finished.
32
+ * A failed initialization closes the pool; if closing fails too, it rejects with a `SuppressedError` whose `error` is the error of closing and `suppressed` the error of the initialization.
33
+ */
34
+ export declare function createOrchidInterop<T extends OrmTableThunks, V extends OrmTableThunks = {}>(options: OrchidInteropOptions<V>, tables: T): Promise<OrchidInterop<T, V>>;
35
+ /** Orchid ORM instance whose current transaction `runInOrchidTransaction` joins, such as of `createDb` or `orchidORM` of `orchid-orm/postgres-js`. */
36
+ interface OrchidTransactionSource {
37
+ /** Returns the adapter of the current transaction of Orchid, or the adapter of the pool outside one. */
38
+ $getAdapter(): Adapter$1;
39
+ }
40
+ /**
41
+ * Runs `callback` in an external transaction of `database` over the current transaction of the native Orchid ORM instance `orchid` on postgres.js, so that the statements of kern-db in it commit or roll back with that transaction, which Orchid keeps owning.
42
+ *
43
+ * It joins the innermost transaction, savepoint, or test transaction of `orchid` that is running, such as of `$transaction` of an instance of `orchidORM`, `transaction` of an instance of `createDb`, or `testTransaction` of `orchid-orm`; `orchid` must be the instance that started it, such as the one passed to `testTransaction.start`.
44
+ * The statements of `database` run on the postgres.js client of the current scope of Orchid, read for each statement, and those of Orchid in the callback keep running through Orchid.
45
+ * After a statement of `database` failed on the client of the scope that runs the call, that scope can only roll back, also when the callback caught the error or a nested transaction of `database` rolled the statement back: postgres.js then rolls it back when it ends.
46
+ * When the callback of an outermost `$transaction` of Orchid resolves, Orchid resolves that transaction without an error although postgres.js rolled it back.
47
+ * So it rejects after a callback that resolved although such a statement failed, once the statements that the callback sent have settled; a callback that rejects keeps its error.
48
+ * A failed statement in a nested `$transaction` of Orchid that started in the callback rolls back only that nested transaction, which rejects, provided that its callback awaited the statement: a statement that fails after that callback resolved fails the enclosing scope without a rejection.
49
+ * It rejects outside a transaction of Orchid with `TypeError`, and for an instance of `createOrchidInterop`, another driver of Orchid, or a version of Orchid whose private transaction state it does not recognize, with an `Error` that names the tested versions.
50
+ */
51
+ export declare function runInOrchidTransaction<T>(orchid: OrchidTransactionSource, database: Database, callback: () => PromiseLike<T>): Promise<T>;
52
+ export type { OrchidInterop, OrchidInteropOptions, OrchidTransactionSource };
package/dist/index.mjs ADDED
@@ -0,0 +1,421 @@
1
+ import { QueryError, createDatabase } from "kern-db";
2
+ import { Adapter } from "orchid-orm/postgres-js";
3
+ import { postgresJsConnection, postgresJsDriver } from "kern-db/postgres-js";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
+ import { orchidORMWithAdapter } from "orchid-orm";
6
+ // src/postgres-js.ts
7
+ /** Key of the JavaScript values of the parameters of an Orchid statement, which postgres.js serializes. */
8
+ const orchidValues = Symbol("orchidValues");
9
+ /**
10
+ * Creates a Kern driver over a postgres.js client that runs both the text statements of Kern and the statements of the executor.
11
+ *
12
+ * postgres.js serializes the values of an Orchid statement as when Orchid runs it on the client: by the types that PostgreSQL resolves for its parameters on the connection that runs it.
13
+ * Closing the driver ends the client.
14
+ */
15
+ function createOrchidPostgresJsDriver(client) {
16
+ return postgresJsDriver(client, { getNativeParameters: (statement) => statement[orchidValues] });
17
+ }
18
+ /**
19
+ * Creates a statement executor that decodes results with the parsers of a configured Orchid postgres.js 4 client.
20
+ *
21
+ * The database must run on the driver of `createOrchidPostgresJsDriver` over the same client.
22
+ * The caller must initialize the client's database-defined types before passing it, and neither resource is closed here.
23
+ */
24
+ function createPostgresJsExecutor(database, client) {
25
+ const { parsers, transform } = client.options;
26
+ if (transform.column.from || transform.row.from || transform.value.from) throw new TypeError("The Orchid executor does not support postgres.js result transforms");
27
+ function execute(text, values = []) {
28
+ const statement = {
29
+ text,
30
+ parameters: [],
31
+ [orchidValues]: values
32
+ };
33
+ return database.execute(statement);
34
+ }
35
+ return {
36
+ async query(text, values) {
37
+ return decodeResult(await execute(text, values), parsers, false);
38
+ },
39
+ async arrays(text, values) {
40
+ return decodeResult(await execute(text, values), parsers, true);
41
+ }
42
+ };
43
+ }
44
+ function decodeResult(result, registry, arrays) {
45
+ const fields = [];
46
+ const parsers = [];
47
+ for (const column of result.columns) {
48
+ fields.push({ name: column.name });
49
+ parsers.push(registry[column.type]);
50
+ }
51
+ const rows = [];
52
+ for (const source of result.rows) {
53
+ const row = arrays ? [] : {};
54
+ for (let index = 0; index < fields.length; index++) {
55
+ const value = source[index];
56
+ const decoded = value === null ? null : parsers[index](value);
57
+ if (arrays) row.push(decoded);
58
+ else {
59
+ const name = fields[index].name;
60
+ if (name === "__proto__") Object.defineProperty(row, name, {
61
+ value: decoded,
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true
65
+ });
66
+ else row[name] = decoded;
67
+ }
68
+ }
69
+ rows.push(row);
70
+ }
71
+ return {
72
+ rowCount: getRowCount(result),
73
+ rows,
74
+ fields
75
+ };
76
+ }
77
+ /** Restores postgres.js's null for commands whose PostgreSQL tag has no count; Kern represents it as zero. */
78
+ function getRowCount(result) {
79
+ if (result.count !== 0) return result.count;
80
+ switch (result.command) {
81
+ case "SELECT":
82
+ case "INSERT":
83
+ case "UPDATE":
84
+ case "DELETE":
85
+ case "MERGE":
86
+ case "COPY":
87
+ case "FETCH":
88
+ case "MOVE": return 0;
89
+ default: return null;
90
+ }
91
+ }
92
+ // src/adapter.ts
93
+ /** Rejects a feature whose transaction semantics this adapter cannot preserve. */
94
+ function rejectUnsupported(feature) {
95
+ throw new TypeError(`The Kern Orchid adapter does not support ${feature}`);
96
+ }
97
+ /** Rejects session settings before a query or transaction can apply only part of them. */
98
+ function assertSessionOptions(options) {
99
+ if (options?.role !== void 0 || options?.setConfig !== void 0) rejectUnsupported("role or setConfig options");
100
+ }
101
+ /** First keyword of a statement that begins or ends a transaction or a savepoint, apart from `PREPARE TRANSACTION`. */
102
+ const transactionCommand = /(?:abort|begin|commit|end|release|rollback|savepoint|start)(?![\w$\u0080-\uffff])/iy;
103
+ const prepareKeyword = /prepare(?![\w$\u0080-\uffff])/iy;
104
+ const transactionKeyword = /transaction(?![\w$\u0080-\uffff])/iy;
105
+ const asKeyword = /as(?![\w$\u0080-\uffff])/iy;
106
+ /**
107
+ * Rejects direct transaction and savepoint commands, such as `COMMIT` of `$query`, so that they cannot end a transaction of Kern.
108
+ * The driver runs one statement per text with the extended protocol, and every such statement of PostgreSQL starts with its keywords, so the leading keywords after whitespace, comments, and empty statements recognize it.
109
+ * Statements that change settings, such as `SET TRANSACTION`, are allowed, as decisions/transactions/orchid-transaction-control.md explains.
110
+ */
111
+ function assertNoTransactionControl(text) {
112
+ let index = skipWhitespaceAndComments(text, 0);
113
+ while (text[index] === ";") index = skipWhitespaceAndComments(text, index + 1);
114
+ if (matchesAt(transactionCommand, text, index) || isPrepareTransaction(text, index)) rejectUnsupported("transaction control statements; use orchid.$transaction or database.transaction");
115
+ }
116
+ /**
117
+ * Whether the statement at `index` is `PREPARE TRANSACTION`, which a string constant follows.
118
+ * `PREPARE` of a statement named `transaction` is followed by `AS` or the list of its parameter types instead.
119
+ */
120
+ function isPrepareTransaction(text, index) {
121
+ if (!matchesAt(prepareKeyword, text, index)) return false;
122
+ index = skipWhitespaceAndComments(text, prepareKeyword.lastIndex);
123
+ if (!matchesAt(transactionKeyword, text, index)) return false;
124
+ index = skipWhitespaceAndComments(text, transactionKeyword.lastIndex);
125
+ return text[index] !== "(" && !matchesAt(asKeyword, text, index);
126
+ }
127
+ /** Whether the sticky `pattern` matches at `index`; on a match, its `lastIndex` is the end of the match. */
128
+ function matchesAt(pattern, text, index) {
129
+ pattern.lastIndex = index;
130
+ return pattern.test(text);
131
+ }
132
+ /** Index of the first character at or after `index` outside the whitespace and comments of PostgreSQL, whose block comments nest. */
133
+ function skipWhitespaceAndComments(text, index) {
134
+ while (index < text.length) {
135
+ const char = text[index];
136
+ if (char === " " || char === " " || char === "\n" || char === "\r" || char === "\f" || char === "\v") index++;
137
+ else if (text.startsWith("--", index)) {
138
+ index += 2;
139
+ while (index < text.length && text[index] !== "\n" && text[index] !== "\r") index++;
140
+ } else if (text.startsWith("/*", index)) {
141
+ index += 2;
142
+ for (let depth = 1; depth > 0 && index < text.length;) if (text.startsWith("/*", index)) {
143
+ depth++;
144
+ index += 2;
145
+ } else if (text.startsWith("*/", index)) {
146
+ depth--;
147
+ index += 2;
148
+ } else index++;
149
+ } else break;
150
+ }
151
+ return index;
152
+ }
153
+ /** Creates Orchid's execution facade; every transaction belongs to the supplied Kern database. */
154
+ function createAdapter(database, client) {
155
+ const executor = createPostgresJsExecutor(database, client);
156
+ const adapter = {
157
+ errorClass: QueryError,
158
+ driverAdapter: {
159
+ ...Adapter,
160
+ configure: () => rejectUnsupported("creating another connection pool"),
161
+ borrow: () => rejectUnsupported("borrowing native connections"),
162
+ release: () => rejectUnsupported("releasing native connections"),
163
+ queryClient: () => rejectUnsupported("native query execution"),
164
+ begin: () => rejectUnsupported("native transactions"),
165
+ savepoint: () => rejectUnsupported("native savepoints"),
166
+ hackySavepoint: () => rejectUnsupported("manually controlled savepoints"),
167
+ close: () => rejectUnsupported("closing native connections")
168
+ },
169
+ isInTransaction() {
170
+ return database.isInTransactionBlock();
171
+ },
172
+ assignError(to, from) {
173
+ const source = from.cause ?? from;
174
+ const target = to;
175
+ for (const key in Adapter.errorFields) {
176
+ const names = Adapter.errorFields[key];
177
+ if (typeof names === "string") target[key] = source[names];
178
+ else for (const name of names) if (source[name] !== void 0) {
179
+ target[key] = source[name];
180
+ break;
181
+ }
182
+ }
183
+ to.message = from.message;
184
+ to.code = from.code;
185
+ to.constraint = from.constraint;
186
+ },
187
+ async query(text, values, state) {
188
+ assertSessionOptions(state);
189
+ assertNoTransactionControl(text);
190
+ return await executor.query(text, values);
191
+ },
192
+ async arrays(text, values, state) {
193
+ assertSessionOptions(state);
194
+ assertNoTransactionControl(text);
195
+ return await executor.arrays(text, values);
196
+ },
197
+ transaction(storage, options, callback) {
198
+ assertSessionOptions(options);
199
+ if (options?.readOnly !== void 0 || options?.deferrable !== void 0) rejectUnsupported("readOnly or deferrable transaction options");
200
+ const isolation = options?.level?.toLowerCase();
201
+ if (isolation !== void 0 && isolation !== "read committed" && isolation !== "repeatable read" && isolation !== "serializable") rejectUnsupported(`transaction isolation ${options.level}`);
202
+ return database.transaction(() => {
203
+ if (!storage) return callback(adapter);
204
+ const state = storage.getStore();
205
+ return storage.run({
206
+ ...state,
207
+ log: options?.log ?? state?.log,
208
+ schema: options?.schema ?? state?.schema
209
+ }, () => Promise.resolve(callback(adapter)));
210
+ }, { isolation });
211
+ },
212
+ savepoint: (_name, _log, callback) => database.transaction(callback),
213
+ hackySavepoint: () => rejectUnsupported("recoverable writes of .none() that select relations; run the write without recovery in a transaction of its own and catch the error outside it"),
214
+ close: () => database.close(),
215
+ getDatabase: () => client.options.database ?? adapter.getUser(),
216
+ getUser: () => typeof client.options.user === "string" ? client.options.user : rejectUnsupported("reading dynamic user metadata"),
217
+ getHost: () => client.options.host.join(","),
218
+ getSearchPath: () => client.options.connection.search_path?.toString(),
219
+ getSchema: () => void 0,
220
+ clone: () => rejectUnsupported("cloning adapters or Orchid testTransaction; use Kern test helpers")
221
+ };
222
+ return adapter;
223
+ }
224
+ // src/orchid.ts
225
+ const commitHooks = [
226
+ "afterCreateCommit",
227
+ "afterUpdateCommit",
228
+ "afterDeleteCommit",
229
+ "afterSaveCommit"
230
+ ];
231
+ /**
232
+ * Creates an Orchid instance whose statements and callback transactions run through the supplied Kern database.
233
+ * The postgres.js client must have Orchid's codecs initialized against the same database; it supplies codecs and connection metadata only.
234
+ * Closing the Orchid instance closes the shared Kern database.
235
+ */
236
+ function createOrchidDb(database, client, tables, options = {}) {
237
+ if ("db" in options) rejectUnsupported("the db option of Orchid");
238
+ const adapter = createAdapter(database, client);
239
+ const orchid = orchidORMWithAdapter({
240
+ ...options,
241
+ adapter
242
+ }, tables);
243
+ installStorage(orchid.$qb, database, adapter);
244
+ const bases = /* @__PURE__ */ new Set([orchid.$qb]);
245
+ for (const key in tables) bases.add(orchid[key].baseQuery);
246
+ for (const key in orchid.$views) bases.add(orchid.$views[key].baseQuery);
247
+ for (const base of bases) installQuery(base, database);
248
+ return orchid;
249
+ }
250
+ /** Projects Kern's current transaction into Orchid without creating another transaction owner. */
251
+ function installStorage(query, database, adapter) {
252
+ const storage = query.internal.asyncStorage;
253
+ const getStore = storage.getStore.bind(storage);
254
+ const run = storage.run.bind(storage);
255
+ const transaction = Object.freeze({
256
+ transactionAdapter: adapter,
257
+ transactionId: 0
258
+ });
259
+ storage.getStore = () => {
260
+ const state = getStore();
261
+ if (!database.isInTransaction()) return state;
262
+ return state ? {
263
+ ...state,
264
+ ...transaction
265
+ } : transaction;
266
+ };
267
+ storage.run = (state, callback) => {
268
+ assertSessionOptions(state);
269
+ if (state?.transactionAdapter) {
270
+ state = { ...state };
271
+ delete state.transactionAdapter;
272
+ delete state.transactionId;
273
+ }
274
+ return run(state, callback);
275
+ };
276
+ Object.defineProperty(storage, "fallback", {
277
+ get: () => void 0,
278
+ set() {
279
+ rejectUnsupported("Orchid testTransaction; use Kern test helpers");
280
+ }
281
+ });
282
+ }
283
+ /** Installs per-instance behavior inherited by Orchid's cloned and related queries. */
284
+ function installQuery(base, database) {
285
+ for (const hook of commitHooks) {
286
+ if (base.q[hook]?.length) rejectUnsupported(`${hook} hooks`);
287
+ Object.defineProperty(base, hook, { value: () => rejectUnsupported(`${hook} hooks`) });
288
+ }
289
+ Object.defineProperties(base, {
290
+ afterCommit: { value: () => rejectUnsupported("afterCommit hooks") },
291
+ ensureTransaction: { value: (callback) => database.ensureTransaction(callback) },
292
+ isInTransaction: { value: () => database.isInTransaction() }
293
+ });
294
+ const prototype = Object.getPrototypeOf(base);
295
+ const transaction = base.transaction;
296
+ Object.defineProperty(base, "transaction", { value(...args) {
297
+ for (const symbol of Object.getOwnPropertySymbols(this.internal)) if (symbol.description === "trxForTest" && this.internal[symbol].levels.length) return new Promise(() => rejectUnsupported("Orchid testTransaction; use Kern test helpers"));
298
+ return transaction.apply(this, args);
299
+ } });
300
+ Object.defineProperty(base, "then", {
301
+ configurable: true,
302
+ get() {
303
+ const then = Reflect.get(prototype, "then", this);
304
+ const resume = AsyncLocalStorage.snapshot();
305
+ return (resolve, reject) => resume(() => this.q.catch ? executeRecoverable(this, database).then(resolve, reject) : then.call(this, resolve, reject));
306
+ },
307
+ set(value) {
308
+ Object.defineProperty(this, "then", { value });
309
+ }
310
+ });
311
+ }
312
+ /**
313
+ * Executes a query marked by `.catch()`, `.catchUniqueError()`, or `.recoverable()` so that its failure leaves the enclosing transaction usable.
314
+ * A `ConnectionError` still ends the enclosing transaction, as Kern ends it for every failure of the connection.
315
+ * Orchid wraps such a query in a savepoint of its own; a nested Kern transaction gives every statement of the query the same savepoint without Orchid's native savepoint protocol.
316
+ * Outside a transaction, a failed statement leaves nothing to recover, so the query runs as usual.
317
+ */
318
+ function executeRecoverable(query, database) {
319
+ const plain = query.clone();
320
+ plain.q.catch = void 0;
321
+ const execute = () => plain.then();
322
+ return database.isInTransactionBlock() ? database.transaction(execute) : execute();
323
+ }
324
+ // src/interop.ts
325
+ /** Connection options of Orchid's postgres.js adapter that the shared pool does not support, with their replacements where they have one. */
326
+ const unsupportedConnectionOptions = {
327
+ schema: "connection.schema; use orchid.schema",
328
+ setConfig: "connection.setConfig; set the settings in connection.connection",
329
+ connectRetry: "connection.connectRetry",
330
+ types: "connection.types"
331
+ };
332
+ /**
333
+ * Opens one postgres.js pool for Kern and existing Orchid tables, with transactions owned by Kern.
334
+ * Initializes database-defined codecs before returning, unless `fetch_types` of the connection is `false`; close `database` or `orchid` when finished.
335
+ * A failed initialization closes the pool; if closing fails too, it rejects with a `SuppressedError` whose `error` is the error of closing and `suppressed` the error of the initialization.
336
+ */
337
+ async function createOrchidInterop(options, tables) {
338
+ for (const key in unsupportedConnectionOptions) if (options.connection[key] !== void 0) rejectUnsupported(unsupportedConnectionOptions[key]);
339
+ const client = Adapter.configure(options.connection);
340
+ let database;
341
+ try {
342
+ database = createDatabase({
343
+ ...options.database,
344
+ driver: createOrchidPostgresJsDriver(client)
345
+ });
346
+ await client.unsafe("SELECT 1").execute();
347
+ const orchid = createOrchidDb(database, client, tables, options.orchid);
348
+ return {
349
+ database,
350
+ orchid
351
+ };
352
+ } catch (error) {
353
+ try {
354
+ await (database ? database.close() : client.end());
355
+ } catch (cleanup) {
356
+ throw new SuppressedError(cleanup, error, "Could not close the connection pool after initialization failed");
357
+ }
358
+ throw error;
359
+ }
360
+ }
361
+ // src/orchid-transaction.ts
362
+ /** Versions whose private transaction state `readTransactionClient` was tested with. */
363
+ const testedVersions = "Orchid ORM 1.78.61 (pqb 0.73.50) on postgres.js 4";
364
+ /**
365
+ * Runs `callback` in an external transaction of `database` over the current transaction of the native Orchid ORM instance `orchid` on postgres.js, so that the statements of kern-db in it commit or roll back with that transaction, which Orchid keeps owning.
366
+ *
367
+ * It joins the innermost transaction, savepoint, or test transaction of `orchid` that is running, such as of `$transaction` of an instance of `orchidORM`, `transaction` of an instance of `createDb`, or `testTransaction` of `orchid-orm`; `orchid` must be the instance that started it, such as the one passed to `testTransaction.start`.
368
+ * The statements of `database` run on the postgres.js client of the current scope of Orchid, read for each statement, and those of Orchid in the callback keep running through Orchid.
369
+ * After a statement of `database` failed on the client of the scope that runs the call, that scope can only roll back, also when the callback caught the error or a nested transaction of `database` rolled the statement back: postgres.js then rolls it back when it ends.
370
+ * When the callback of an outermost `$transaction` of Orchid resolves, Orchid resolves that transaction without an error although postgres.js rolled it back.
371
+ * So it rejects after a callback that resolved although such a statement failed, once the statements that the callback sent have settled; a callback that rejects keeps its error.
372
+ * A failed statement in a nested `$transaction` of Orchid that started in the callback rolls back only that nested transaction, which rejects, provided that its callback awaited the statement: a statement that fails after that callback resolved fails the enclosing scope without a rejection.
373
+ * It rejects outside a transaction of Orchid with `TypeError`, and for an instance of `createOrchidInterop`, another driver of Orchid, or a version of Orchid whose private transaction state it does not recognize, with an `Error` that names the tested versions.
374
+ */
375
+ async function runInOrchidTransaction(orchid, database, callback) {
376
+ const scope = readTransactionClient(orchid);
377
+ let failure;
378
+ let currentClient = scope;
379
+ let currentConnection = postgresJsConnection(scope);
380
+ /** Statements sent on the connection that have not settled. */
381
+ const pending = /* @__PURE__ */ new Set();
382
+ /** Runs `run` on the connection of the current client of Orchid's transaction, and records its failure on the client of the scope. */
383
+ async function runStatement(run) {
384
+ const client = readTransactionClient(orchid);
385
+ if (client !== currentClient) {
386
+ currentClient = client;
387
+ currentConnection = postgresJsConnection(client);
388
+ }
389
+ const result = run(currentConnection);
390
+ pending.add(result);
391
+ try {
392
+ return await result;
393
+ } catch (error) {
394
+ if (client === scope) failure ??= { error };
395
+ throw error;
396
+ } finally {
397
+ pending.delete(result);
398
+ }
399
+ }
400
+ const result = await database.externalTransaction({
401
+ execute: (statement) => runStatement((connection) => connection.execute(statement)),
402
+ executeScript: (text) => runStatement((connection) => connection.executeScript(text))
403
+ }, callback);
404
+ await Promise.allSettled(pending);
405
+ if (failure) throw new Error("runInOrchidTransaction(): a statement failed in the transaction or savepoint of Orchid ORM that runs the call, which can therefore only roll back, also after a nested transaction rolled the statement back", { cause: failure.error });
406
+ return result;
407
+ }
408
+ /** Returns the postgres.js client of the innermost scope of the current transaction of Orchid, read from private fields of Orchid that have no public accessor. */
409
+ function readTransactionClient(orchid) {
410
+ let adapter = orchid.$getAdapter();
411
+ if (!adapter.isInTransaction()) throw new TypeError("runInOrchidTransaction() must run in a transaction of Orchid ORM, such as in the callback of $transaction or in a test transaction");
412
+ while (isObject(adapter) && !("client" in adapter) && "trx" in adapter) adapter = adapter.adapter;
413
+ const client = isObject(adapter) ? adapter.client : void 0;
414
+ if (typeof client !== "function" || typeof client.savepoint !== "function") throw new Error(`runInOrchidTransaction() did not recognize the postgres.js client in the transaction of Orchid ORM: it requires a native instance of Orchid ORM on postgres.js, not an instance of createOrchidInterop, whose transactions belong to kern-db, and was tested with ${testedVersions}`);
415
+ return client;
416
+ }
417
+ /** Tells whether `value` is an object whose properties can be read. */
418
+ function isObject(value) {
419
+ return typeof value === "object" && value !== null;
420
+ }
421
+ export { createOrchidInterop, runInOrchidTransaction };
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@kern-orm/orchid-interop",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Run Orchid ORM and kern-orm queries in the same transactions while moving an application to kern-orm",
5
+ "keywords": [
6
+ "kern-db",
7
+ "kern-orm",
8
+ "orchid-orm",
9
+ "postgres",
10
+ "transactions"
11
+ ],
12
+ "homepage": "https://ilyasemenov.github.io/kern-orm/orm/orchid-interop",
13
+ "bugs": "https://github.com/IlyaSemenov/kern-orm/issues",
14
+ "license": "MIT",
15
+ "author": "Ilya Semenov",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/IlyaSemenov/kern-orm.git",
19
+ "directory": "packages/orchid-interop"
20
+ },
21
+ "files": [
22
+ "README.md",
23
+ "dist"
24
+ ],
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "types": "./dist/index.d.mts",
28
+ "exports": {
29
+ ".": "./dist/index.mjs",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown",
37
+ "prepublishOnly": "bun run build"
38
+ },
39
+ "devDependencies": {
40
+ "@kern-orm/test-harness": "workspace:*",
41
+ "kern-db": "workspace:*",
42
+ "kern-migrations": "workspace:*",
43
+ "kern-orm": "workspace:*",
44
+ "orchid-orm": "1.78.61",
45
+ "postgres": "catalog:"
46
+ },
47
+ "peerDependencies": {
48
+ "kern-db": "^0.8.0",
49
+ "orchid-orm": "^1.78.61",
50
+ "postgres": "^4.0.0"
51
+ },
52
+ "engines": {
53
+ "bun": ">=1.4",
54
+ "node": ">=24"
55
+ }
56
+ }