@geekmidas/testkit 10.0.0-alpha.89 → 10.0.0-alpha.90

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.
@@ -24,6 +24,12 @@ let kysely = require("kysely");
24
24
  * too, so a failure — a duplicate key two concurrent requests raced to insert —
25
25
  * fails that statement alone, as it would deployed, rather than every request
26
26
  * the test makes after it.
27
+ *
28
+ * A savepoint the test or the code opens by name — `savepoint refused`, a
29
+ * statement expected to fail, `rollback to savepoint refused` — is its own
30
+ * transaction control, and passes through untouched. While one is open,
31
+ * statements run in it as they would inside a `begin`: unwrapped, so a failure
32
+ * aborts the transaction until the matching `rollback to savepoint`.
27
33
  */
28
34
  /**
29
35
  * The connection settings for a database URL.
@@ -54,11 +60,12 @@ async function openBoundTransaction(url, config = {}) {
54
60
  await client.connect();
55
61
  await client.query("BEGIN");
56
62
  const inTurn = turns();
63
+ const named = [];
57
64
  return {
58
65
  db: new kysely.Kysely({
59
66
  ...config,
60
67
  dialect: new kysely.PostgresDialect({ pool: {
61
- connect: async () => savepointing(client, inTurn),
68
+ connect: async () => savepointing(client, inTurn, named),
62
69
  end: async () => {}
63
70
  } })
64
71
  }),
@@ -78,10 +85,16 @@ async function openBoundTransaction(url, config = {}) {
78
85
  * one place they can be caught. A depth counter names the savepoints, so
79
86
  * nested transactions nest.
80
87
  */
81
- function savepointing(client, inTurn) {
88
+ function savepointing(client, inTurn, named) {
82
89
  let depth = 0;
83
90
  const query = client.query.bind(client);
84
91
  const wrapped = Object.create(client);
92
+ const closeTransaction = (level) => {
93
+ for (let i = named.length - 1; i >= 0; i--) {
94
+ const savepoint = named[i];
95
+ if (savepoint.checkout === wrapped && savepoint.depth >= level) named.splice(i, 1);
96
+ }
97
+ };
85
98
  Object.assign(wrapped, {
86
99
  query: (text, ...rest) => {
87
100
  if (typeof text !== "string" || typeof rest.at(-1) === "function") return query(text, ...rest);
@@ -91,20 +104,70 @@ function savepointing(client, inTurn) {
91
104
  return inTurn(() => query(`SAVEPOINT ${savepoint}`));
92
105
  }
93
106
  if (statement === "commit") {
94
- const savepoint = `test_sp_${depth--}`;
95
- return inTurn(() => query(`RELEASE SAVEPOINT ${savepoint}`));
107
+ const level = depth--;
108
+ closeTransaction(level);
109
+ return inTurn(() => query(`RELEASE SAVEPOINT test_sp_${level}`));
96
110
  }
97
111
  if (statement === "rollback") {
98
- const savepoint = `test_sp_${depth--}`;
99
- return inTurn(() => query(`ROLLBACK TO SAVEPOINT ${savepoint}`));
112
+ const level = depth--;
113
+ closeTransaction(level);
114
+ return inTurn(() => query(`ROLLBACK TO SAVEPOINT test_sp_${level}`));
100
115
  }
101
- if (depth > 0) return inTurn(() => query(text, ...rest));
116
+ const control = savepointControl(text);
117
+ if (control) return inTurn(async () => {
118
+ const result = await query(text, ...rest);
119
+ track(named, control, {
120
+ checkout: wrapped,
121
+ depth
122
+ });
123
+ return result;
124
+ });
125
+ if (depth > 0 || named.length > 0) return inTurn(() => query(text, ...rest));
102
126
  return inTurn(() => autocommitted(query, text, rest));
103
127
  },
104
128
  release: () => {}
105
129
  });
106
130
  return wrapped;
107
131
  }
132
+ const IDENTIFIER = String.raw`("(?:[^"]|"")+"|[^\s;"]+)`;
133
+ const SAVEPOINT_CONTROL = [
134
+ ["savepoint", new RegExp(String.raw`^savepoint\s+${IDENTIFIER}\s*;?$`, "i")],
135
+ ["release", new RegExp(String.raw`^release\s+(?:savepoint\s+)?${IDENTIFIER}\s*;?$`, "i")],
136
+ ["rollback to", new RegExp(String.raw`^rollback\s+(?:(?:work|transaction)\s+)?to\s+(?:savepoint\s+)?${IDENTIFIER}\s*;?$`, "i")]
137
+ ];
138
+ /**
139
+ * The savepoint a statement opens, releases or rolls back to, named as
140
+ * Postgres names it: an unquoted name folded to lower case, a quoted one as
141
+ * written.
142
+ */
143
+ function savepointControl(text) {
144
+ const statement = text.trim();
145
+ for (const [action, pattern] of SAVEPOINT_CONTROL) {
146
+ const match = pattern.exec(statement);
147
+ if (!match) continue;
148
+ const identifier = match[1];
149
+ return {
150
+ action,
151
+ name: identifier.startsWith("\"") ? identifier.slice(1, -1).replaceAll("\"\"", "\"") : identifier.toLowerCase()
152
+ };
153
+ }
154
+ }
155
+ /**
156
+ * Keep the named savepoints as Postgres does: `RELEASE x` ends x and every
157
+ * savepoint after it; `ROLLBACK TO x` ends those after it and keeps x open.
158
+ */
159
+ function track(named, control, at) {
160
+ if (control.action === "savepoint") {
161
+ named.push({
162
+ name: control.name,
163
+ ...at
164
+ });
165
+ return;
166
+ }
167
+ const index = named.findLastIndex((s) => s.name === control.name);
168
+ if (index === -1) return;
169
+ named.splice(control.action === "release" ? index : index + 1);
170
+ }
108
171
  /**
109
172
  * One statement at a time on a connection, in the order they were asked for.
110
173
  *
@@ -1 +1 @@
1
- {"version":3,"file":"transactions.cjs","names":["Kysely","PostgresDialect"],"sources":["../src/transactions.ts"],"sourcesContent":["/**\n * A transaction per database, per test — as each runs deployed.\n *\n * An app's database and a schema tenant such as the auth server's are separate\n * databases to the code using them: separate connections, credentials, roles\n * and search paths. A test keeps them that way. Each gets its own connection,\n * opened into a transaction the first time the test touches it, and every one\n * is rolled back when the test ends.\n *\n * Code under test must be free to use transactions itself, and better-auth\n * does — it also calls `db.connection()`, which Kysely refuses on a\n * `Transaction`. So what a test hands over is not a `Transaction` but a Kysely\n * over the one connection already inside the test's transaction, on which a\n * `BEGIN` becomes a savepoint and a `COMMIT` releases it. Nothing the code does\n * can end the transaction the test will roll back.\n *\n * A statement the code runs outside a transaction of its own gets a savepoint\n * too, so a failure — a duplicate key two concurrent requests raced to insert —\n * fails that statement alone, as it would deployed, rather than every request\n * the test makes after it.\n */\n\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport pg from 'pg';\n\n/** How to reach one database: a URL, and its search path as a startup option. */\nexport interface ConnectionConfig {\n\tconnectionString: string;\n\toptions?: string;\n}\n\n/**\n * The connection settings for a database URL.\n *\n * `?search_path=` is not a libpq parameter: a URL carrying it connects and then\n * resolves every name against `public`. Postgres takes it as a startup option,\n * which is what a schema tenant's URL needs to reach its own tables.\n */\nexport function connectionConfig(url: string): ConnectionConfig {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tif (!searchPath) return { connectionString: url };\n\n\tparsed.searchParams.delete('search_path');\n\treturn {\n\t\tconnectionString: parsed.toString(),\n\t\toptions: `-c search_path=${searchPath}`,\n\t};\n}\n\n/** One database's connection, inside a transaction the test will roll back. */\nexport interface BoundTransaction {\n\t/** Everything queried through this runs inside the test's transaction. */\n\treadonly db: Kysely<any>;\n\t/** Undo everything, and let the connection go. */\n\trollback(): Promise<void>;\n}\n\n/**\n * Open a connection to `url` and begin the transaction a test will roll back.\n *\n * `config` is what the database's own clients are built with — its plugins\n * above all. The code under test is handed this Kysely in place of its own, so\n * one built without them runs different queries than production does.\n */\nexport async function openBoundTransaction(\n\turl: string,\n\tconfig: Omit<KyselyConfig, 'dialect'> = {},\n): Promise<BoundTransaction> {\n\tconst client = new pg.Client(connectionConfig(url));\n\tawait client.connect();\n\tawait client.query('BEGIN');\n\t// Shared by every checkout of the connection: concurrent requests in one\n\t// test each check it out, and all of them take turns on it.\n\tconst inTurn = turns();\n\n\treturn {\n\t\tdb: new Kysely({\n\t\t\t...config,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\t// A \"pool\" of the one connection. Released never, ended never: the\n\t\t\t\t// test owns it, and it closes in `rollback`.\n\t\t\t\tpool: {\n\t\t\t\t\tconnect: async () => savepointing(client, inTurn),\n\t\t\t\t\tend: async () => {},\n\t\t\t\t} as unknown as pg.Pool,\n\t\t\t}),\n\t\t}),\n\t\tasync rollback() {\n\t\t\ttry {\n\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The client, with transaction control turned into savepoints.\n *\n * Kysely issues `begin`/`commit`/`rollback` as plain statements; this is the\n * one place they can be caught. A depth counter names the savepoints, so\n * nested transactions nest.\n */\nfunction savepointing(client: pg.Client, inTurn: Turns): pg.PoolClient {\n\tlet depth = 0;\n\tconst query = client.query.bind(client) as (\n\t\t...args: unknown[]\n\t) => Promise<unknown>;\n\n\tconst wrapped = Object.create(client) as pg.PoolClient;\n\tObject.assign(wrapped, {\n\t\tquery: (text: unknown, ...rest: unknown[]) => {\n\t\t\t// A cursor, a query config, a callback: not what Kysely sends for a\n\t\t\t// statement, and nothing to wrap.\n\t\t\tif (typeof text !== 'string' || typeof rest.at(-1) === 'function') {\n\t\t\t\treturn query(text, ...rest);\n\t\t\t}\n\t\t\tconst statement = text.trim().toLowerCase();\n\n\t\t\tif (statement === 'begin' || statement.startsWith('start transaction')) {\n\t\t\t\tconst savepoint = `test_sp_${++depth}`;\n\t\t\t\treturn inTurn(() => query(`SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (statement === 'commit') {\n\t\t\t\tconst savepoint = `test_sp_${depth--}`;\n\t\t\t\treturn inTurn(() => query(`RELEASE SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (statement === 'rollback') {\n\t\t\t\tconst savepoint = `test_sp_${depth--}`;\n\t\t\t\treturn inTurn(() => query(`ROLLBACK TO SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (depth > 0) return inTurn(() => query(text, ...rest));\n\t\t\treturn inTurn(() => autocommitted(query, text, rest));\n\t\t},\n\t\trelease: () => {},\n\t});\n\treturn wrapped;\n}\n\n/** Runs work in the order it was asked for, each after the last has settled. */\ntype Turns = <T>(work: () => Promise<T>) => Promise<T>;\n\n/**\n * One statement at a time on a connection, in the order they were asked for.\n *\n * The connection runs them one at a time anyway; this keeps a statement and\n * the savepoint around it together, so nothing another request sends lands\n * between them — a `RELEASE` also ends every savepoint opened after its own.\n */\nfunction turns(): Turns {\n\tlet queue: Promise<unknown> = Promise.resolve();\n\treturn (work) => {\n\t\tconst turn = queue.then(work, work);\n\t\tqueue = turn.catch(() => {});\n\t\treturn turn;\n\t};\n}\n\n/**\n * A statement run outside any transaction the code opened, failing the way\n * it would deployed: on its own.\n *\n * Deployed, such a statement is its own transaction, so one that fails — a\n * duplicate key two concurrent requests both tried to insert — fails alone,\n * and code written for that (Better Auth's rate limiter reads the row the\n * other request inserted, and carries on) does carry on. Inside the test's\n * transaction a failed statement would abort everything after it, every\n * request of the test included. A savepoint around it puts back what\n * deployed would have.\n */\nasync function autocommitted(\n\tquery: (...args: unknown[]) => Promise<unknown>,\n\ttext: string,\n\trest: unknown[],\n): Promise<unknown> {\n\tawait query('SAVEPOINT test_statement');\n\ttry {\n\t\tconst result = await query(text, ...rest);\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\treturn result;\n\t} catch (error) {\n\t\tawait query('ROLLBACK TO SAVEPOINT test_statement');\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\tthrow error;\n\t}\n}\n\n/**\n * The transactions one test has opened, by database.\n *\n * `get` opens a database's transaction the first time it is asked for and\n * hands back the same one after that — including to a caller that asks while\n * it is still opening. `rollbackAll` ends every one of them.\n */\nexport class TransactionRegistry<TKey = string> {\n\tprivate readonly open = new Map<TKey, Promise<BoundTransaction>>();\n\n\tget(\n\t\tkey: TKey,\n\t\turl: string,\n\t\tconfig?: Omit<KyselyConfig, 'dialect'>,\n\t): Promise<Kysely<any>> {\n\t\tlet transaction = this.open.get(key);\n\t\tif (!transaction) {\n\t\t\ttransaction = openBoundTransaction(url, config);\n\t\t\tthis.open.set(key, transaction);\n\t\t}\n\t\treturn transaction.then(({ db }) => db);\n\t}\n\n\tasync rollbackAll(): Promise<void> {\n\t\tconst transactions = [...this.open.values()];\n\t\tthis.open.clear();\n\n\t\tconst results = await Promise.allSettled(\n\t\t\ttransactions.map(async (transaction) => (await transaction).rollback()),\n\t\t);\n\t\tconst failed = results.find(\n\t\t\t(result): result is PromiseRejectedResult => result.status === 'rejected',\n\t\t);\n\t\tif (failed) throw failed.reason;\n\t}\n}\n"],"mappings":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AM;EAKhB,MAAM,UAAS,MAHO,QAAQ,WAC7B,aAAa,IAAI,OAAO,iBAAiB,MAAM,YAAA,CAAa,SAAS,CAAC,CACvE,EAAA,CACuB,MACrB,WAA4C,OAAO,WAAW,UAChE;EACA,IAAI,QAAQ,MAAM,OAAO;CAC1B;AACD"}
1
+ {"version":3,"file":"transactions.cjs","names":["Kysely","PostgresDialect"],"sources":["../src/transactions.ts"],"sourcesContent":["/**\n * A transaction per database, per test — as each runs deployed.\n *\n * An app's database and a schema tenant such as the auth server's are separate\n * databases to the code using them: separate connections, credentials, roles\n * and search paths. A test keeps them that way. Each gets its own connection,\n * opened into a transaction the first time the test touches it, and every one\n * is rolled back when the test ends.\n *\n * Code under test must be free to use transactions itself, and better-auth\n * does — it also calls `db.connection()`, which Kysely refuses on a\n * `Transaction`. So what a test hands over is not a `Transaction` but a Kysely\n * over the one connection already inside the test's transaction, on which a\n * `BEGIN` becomes a savepoint and a `COMMIT` releases it. Nothing the code does\n * can end the transaction the test will roll back.\n *\n * A statement the code runs outside a transaction of its own gets a savepoint\n * too, so a failure — a duplicate key two concurrent requests raced to insert —\n * fails that statement alone, as it would deployed, rather than every request\n * the test makes after it.\n *\n * A savepoint the test or the code opens by name — `savepoint refused`, a\n * statement expected to fail, `rollback to savepoint refused` — is its own\n * transaction control, and passes through untouched. While one is open,\n * statements run in it as they would inside a `begin`: unwrapped, so a failure\n * aborts the transaction until the matching `rollback to savepoint`.\n */\n\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport pg from 'pg';\n\n/** How to reach one database: a URL, and its search path as a startup option. */\nexport interface ConnectionConfig {\n\tconnectionString: string;\n\toptions?: string;\n}\n\n/**\n * The connection settings for a database URL.\n *\n * `?search_path=` is not a libpq parameter: a URL carrying it connects and then\n * resolves every name against `public`. Postgres takes it as a startup option,\n * which is what a schema tenant's URL needs to reach its own tables.\n */\nexport function connectionConfig(url: string): ConnectionConfig {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tif (!searchPath) return { connectionString: url };\n\n\tparsed.searchParams.delete('search_path');\n\treturn {\n\t\tconnectionString: parsed.toString(),\n\t\toptions: `-c search_path=${searchPath}`,\n\t};\n}\n\n/** One database's connection, inside a transaction the test will roll back. */\nexport interface BoundTransaction {\n\t/** Everything queried through this runs inside the test's transaction. */\n\treadonly db: Kysely<any>;\n\t/** Undo everything, and let the connection go. */\n\trollback(): Promise<void>;\n}\n\n/**\n * Open a connection to `url` and begin the transaction a test will roll back.\n *\n * `config` is what the database's own clients are built with — its plugins\n * above all. The code under test is handed this Kysely in place of its own, so\n * one built without them runs different queries than production does.\n */\nexport async function openBoundTransaction(\n\turl: string,\n\tconfig: Omit<KyselyConfig, 'dialect'> = {},\n): Promise<BoundTransaction> {\n\tconst client = new pg.Client(connectionConfig(url));\n\tawait client.connect();\n\tawait client.query('BEGIN');\n\t// Shared by every checkout of the connection: concurrent requests in one\n\t// test each check it out, and all of them take turns on it.\n\tconst inTurn = turns();\n\t// The savepoints opened by name, shared by every checkout as the\n\t// connection's transaction is.\n\tconst named: NamedSavepoint[] = [];\n\n\treturn {\n\t\tdb: new Kysely({\n\t\t\t...config,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\t// A \"pool\" of the one connection. Released never, ended never: the\n\t\t\t\t// test owns it, and it closes in `rollback`.\n\t\t\t\tpool: {\n\t\t\t\t\tconnect: async () => savepointing(client, inTurn, named),\n\t\t\t\t\tend: async () => {},\n\t\t\t\t} as unknown as pg.Pool,\n\t\t\t}),\n\t\t}),\n\t\tasync rollback() {\n\t\t\ttry {\n\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The client, with transaction control turned into savepoints.\n *\n * Kysely issues `begin`/`commit`/`rollback` as plain statements; this is the\n * one place they can be caught. A depth counter names the savepoints, so\n * nested transactions nest.\n */\nfunction savepointing(\n\tclient: pg.Client,\n\tinTurn: Turns,\n\tnamed: NamedSavepoint[],\n): pg.PoolClient {\n\tlet depth = 0;\n\tconst query = client.query.bind(client) as (\n\t\t...args: unknown[]\n\t) => Promise<unknown>;\n\tconst wrapped = Object.create(client) as pg.PoolClient;\n\n\t// Ending one of the code's transactions ends every savepoint opened in it.\n\tconst closeTransaction = (level: number) => {\n\t\tfor (let i = named.length - 1; i >= 0; i--) {\n\t\t\tconst savepoint = named[i]!;\n\t\t\tif (savepoint.checkout === wrapped && savepoint.depth >= level) {\n\t\t\t\tnamed.splice(i, 1);\n\t\t\t}\n\t\t}\n\t};\n\n\tObject.assign(wrapped, {\n\t\tquery: (text: unknown, ...rest: unknown[]) => {\n\t\t\t// A cursor, a query config, a callback: not what Kysely sends for a\n\t\t\t// statement, and nothing to wrap.\n\t\t\tif (typeof text !== 'string' || typeof rest.at(-1) === 'function') {\n\t\t\t\treturn query(text, ...rest);\n\t\t\t}\n\t\t\tconst statement = text.trim().toLowerCase();\n\n\t\t\tif (statement === 'begin' || statement.startsWith('start transaction')) {\n\t\t\t\tconst savepoint = `test_sp_${++depth}`;\n\t\t\t\treturn inTurn(() => query(`SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (statement === 'commit') {\n\t\t\t\tconst level = depth--;\n\t\t\t\tcloseTransaction(level);\n\t\t\t\treturn inTurn(() => query(`RELEASE SAVEPOINT test_sp_${level}`));\n\t\t\t}\n\t\t\tif (statement === 'rollback') {\n\t\t\t\tconst level = depth--;\n\t\t\t\tcloseTransaction(level);\n\t\t\t\treturn inTurn(() => query(`ROLLBACK TO SAVEPOINT test_sp_${level}`));\n\t\t\t}\n\n\t\t\tconst control = savepointControl(text);\n\t\t\tif (control) {\n\t\t\t\treturn inTurn(async () => {\n\t\t\t\t\tconst result = await query(text, ...rest);\n\t\t\t\t\ttrack(named, control, { checkout: wrapped, depth });\n\t\t\t\t\treturn result;\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (depth > 0 || named.length > 0) {\n\t\t\t\treturn inTurn(() => query(text, ...rest));\n\t\t\t}\n\t\t\treturn inTurn(() => autocommitted(query, text, rest));\n\t\t},\n\t\trelease: () => {},\n\t});\n\treturn wrapped;\n}\n\n/** A savepoint the test or the code opened by name, and where it opened it. */\ninterface NamedSavepoint {\n\tname: string;\n\t/** The checkout, and its transaction depth, the savepoint was opened at. */\n\tcheckout: pg.PoolClient;\n\tdepth: number;\n}\n\n/** `SAVEPOINT x`, `RELEASE [SAVEPOINT] x`, `ROLLBACK [WORK] TO [SAVEPOINT] x`. */\ninterface SavepointControl {\n\taction: 'savepoint' | 'release' | 'rollback to';\n\tname: string;\n}\n\nconst IDENTIFIER = String.raw`(\"(?:[^\"]|\"\")+\"|[^\\s;\"]+)`;\nconst SAVEPOINT_CONTROL: [SavepointControl['action'], RegExp][] = [\n\t['savepoint', new RegExp(String.raw`^savepoint\\s+${IDENTIFIER}\\s*;?$`, 'i')],\n\t[\n\t\t'release',\n\t\tnew RegExp(\n\t\t\tString.raw`^release\\s+(?:savepoint\\s+)?${IDENTIFIER}\\s*;?$`,\n\t\t\t'i',\n\t\t),\n\t],\n\t[\n\t\t'rollback to',\n\t\tnew RegExp(\n\t\t\tString.raw`^rollback\\s+(?:(?:work|transaction)\\s+)?to\\s+(?:savepoint\\s+)?${IDENTIFIER}\\s*;?$`,\n\t\t\t'i',\n\t\t),\n\t],\n];\n\n/**\n * The savepoint a statement opens, releases or rolls back to, named as\n * Postgres names it: an unquoted name folded to lower case, a quoted one as\n * written.\n */\nfunction savepointControl(text: string): SavepointControl | undefined {\n\tconst statement = text.trim();\n\tfor (const [action, pattern] of SAVEPOINT_CONTROL) {\n\t\tconst match = pattern.exec(statement);\n\t\tif (!match) continue;\n\t\tconst identifier = match[1]!;\n\t\tconst name = identifier.startsWith('\"')\n\t\t\t? identifier.slice(1, -1).replaceAll('\"\"', '\"')\n\t\t\t: identifier.toLowerCase();\n\t\treturn { action, name };\n\t}\n\treturn undefined;\n}\n\n/**\n * Keep the named savepoints as Postgres does: `RELEASE x` ends x and every\n * savepoint after it; `ROLLBACK TO x` ends those after it and keeps x open.\n */\nfunction track(\n\tnamed: NamedSavepoint[],\n\tcontrol: SavepointControl,\n\tat: Omit<NamedSavepoint, 'name'>,\n): void {\n\tif (control.action === 'savepoint') {\n\t\tnamed.push({ name: control.name, ...at });\n\t\treturn;\n\t}\n\tconst index = named.findLastIndex((s) => s.name === control.name);\n\t// One opened before this connection was handed over, or by a name the\n\t// wrapper uses itself: nothing tracked to end.\n\tif (index === -1) return;\n\tnamed.splice(control.action === 'release' ? index : index + 1);\n}\n\n/** Runs work in the order it was asked for, each after the last has settled. */\ntype Turns = <T>(work: () => Promise<T>) => Promise<T>;\n\n/**\n * One statement at a time on a connection, in the order they were asked for.\n *\n * The connection runs them one at a time anyway; this keeps a statement and\n * the savepoint around it together, so nothing another request sends lands\n * between them — a `RELEASE` also ends every savepoint opened after its own.\n */\nfunction turns(): Turns {\n\tlet queue: Promise<unknown> = Promise.resolve();\n\treturn (work) => {\n\t\tconst turn = queue.then(work, work);\n\t\tqueue = turn.catch(() => {});\n\t\treturn turn;\n\t};\n}\n\n/**\n * A statement run outside any transaction the code opened, failing the way\n * it would deployed: on its own.\n *\n * Deployed, such a statement is its own transaction, so one that fails — a\n * duplicate key two concurrent requests both tried to insert — fails alone,\n * and code written for that (Better Auth's rate limiter reads the row the\n * other request inserted, and carries on) does carry on. Inside the test's\n * transaction a failed statement would abort everything after it, every\n * request of the test included. A savepoint around it puts back what\n * deployed would have.\n */\nasync function autocommitted(\n\tquery: (...args: unknown[]) => Promise<unknown>,\n\ttext: string,\n\trest: unknown[],\n): Promise<unknown> {\n\tawait query('SAVEPOINT test_statement');\n\ttry {\n\t\tconst result = await query(text, ...rest);\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\treturn result;\n\t} catch (error) {\n\t\tawait query('ROLLBACK TO SAVEPOINT test_statement');\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\tthrow error;\n\t}\n}\n\n/**\n * The transactions one test has opened, by database.\n *\n * `get` opens a database's transaction the first time it is asked for and\n * hands back the same one after that — including to a caller that asks while\n * it is still opening. `rollbackAll` ends every one of them.\n */\nexport class TransactionRegistry<TKey = string> {\n\tprivate readonly open = new Map<TKey, Promise<BoundTransaction>>();\n\n\tget(\n\t\tkey: TKey,\n\t\turl: string,\n\t\tconfig?: Omit<KyselyConfig, 'dialect'>,\n\t): Promise<Kysely<any>> {\n\t\tlet transaction = this.open.get(key);\n\t\tif (!transaction) {\n\t\t\ttransaction = openBoundTransaction(url, config);\n\t\t\tthis.open.set(key, transaction);\n\t\t}\n\t\treturn transaction.then(({ db }) => db);\n\t}\n\n\tasync rollbackAll(): Promise<void> {\n\t\tconst transactions = [...this.open.values()];\n\t\tthis.open.clear();\n\n\t\tconst results = await Promise.allSettled(\n\t\t\ttransactions.map(async (transaction) => (await transaction).rollback()),\n\t\t);\n\t\tconst failed = results.find(\n\t\t\t(result): result is PromiseRejectedResult => result.status === 'rejected',\n\t\t);\n\t\tif (failed) throw failed.reason;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,iBAAiB,KAA+B;CAC/D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,IAAI,CAAC,YAAY,OAAO,EAAE,kBAAkB,IAAI;CAEhD,OAAO,aAAa,OAAO,aAAa;CACxC,OAAO;EACN,kBAAkB,OAAO,SAAS;EAClC,SAAS,kBAAkB;CAC5B;AACD;;;;;;;;AAiBA,eAAsB,qBACrB,KACA,SAAwC,CAAC,GACb;CAC5B,MAAM,SAAS,IAAI,GAAA,QAAG,OAAO,iBAAiB,GAAG,CAAC;CAClD,MAAM,OAAO,QAAQ;CACrB,MAAM,OAAO,MAAM,OAAO;CAG1B,MAAM,SAAS,MAAM;CAGrB,MAAM,QAA0B,CAAC;CAEjC,OAAO;EACN,IAAI,IAAIA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;;;;;;;;qBAgIE,oBAAoB;mBACf;EAEjB,IACC,KAAK,MACL,aACA,SAAS,KAAK,2BACZ,QAAQ;EASL,eAAe"}
1
+ {"version":3,"file":"transactions.d.cts","names":[],"sources":["../src/transactions.ts"],"mappings":";;;iBAgCiB;EAChB;EACA;;;;;;;;;wBAUe,iBAAiB,cAAc;;iBAa9B;;WAEP,IAAI;;EAEb,YAAY;;;;;;;;;wBAUS,qBACrB,aACA,SAAQ,KAAK,2BACX,QAAQ;;;;;;;;qBAsOE,oBAAoB;mBACf;EAEjB,IACC,KAAK,MACL,aACA,SAAS,KAAK,2BACZ,QAAQ;EASL,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"transactions.d.mts","names":[],"sources":["../src/transactions.ts"],"mappings":";;;iBA0BiB;EAChB;EACA;;;;;;;;;wBAUe,iBAAiB,cAAc;;iBAa9B;;WAEP,IAAI;;EAEb,YAAY;;;;;;;;;wBAUS,qBACrB,aACA,SAAQ,KAAK,2BACX,QAAQ;;;;;;;;qBAgIE,oBAAoB;mBACf;EAEjB,IACC,KAAK,MACL,aACA,SAAS,KAAK,2BACZ,QAAQ;EASL,eAAe"}
1
+ {"version":3,"file":"transactions.d.mts","names":[],"sources":["../src/transactions.ts"],"mappings":";;;iBAgCiB;EAChB;EACA;;;;;;;;;wBAUe,iBAAiB,cAAc;;iBAa9B;;WAEP,IAAI;;EAEb,YAAY;;;;;;;;;wBAUS,qBACrB,aACA,SAAQ,KAAK,2BACX,QAAQ;;;;;;;;qBAsOE,oBAAoB;mBACf;EAEjB,IACC,KAAK,MACL,aACA,SAAS,KAAK,2BACZ,QAAQ;EASL,eAAe"}
@@ -21,6 +21,12 @@ import { Kysely, PostgresDialect } from "kysely";
21
21
  * too, so a failure — a duplicate key two concurrent requests raced to insert —
22
22
  * fails that statement alone, as it would deployed, rather than every request
23
23
  * the test makes after it.
24
+ *
25
+ * A savepoint the test or the code opens by name — `savepoint refused`, a
26
+ * statement expected to fail, `rollback to savepoint refused` — is its own
27
+ * transaction control, and passes through untouched. While one is open,
28
+ * statements run in it as they would inside a `begin`: unwrapped, so a failure
29
+ * aborts the transaction until the matching `rollback to savepoint`.
24
30
  */
25
31
  /**
26
32
  * The connection settings for a database URL.
@@ -51,11 +57,12 @@ async function openBoundTransaction(url, config = {}) {
51
57
  await client.connect();
52
58
  await client.query("BEGIN");
53
59
  const inTurn = turns();
60
+ const named = [];
54
61
  return {
55
62
  db: new Kysely({
56
63
  ...config,
57
64
  dialect: new PostgresDialect({ pool: {
58
- connect: async () => savepointing(client, inTurn),
65
+ connect: async () => savepointing(client, inTurn, named),
59
66
  end: async () => {}
60
67
  } })
61
68
  }),
@@ -75,10 +82,16 @@ async function openBoundTransaction(url, config = {}) {
75
82
  * one place they can be caught. A depth counter names the savepoints, so
76
83
  * nested transactions nest.
77
84
  */
78
- function savepointing(client, inTurn) {
85
+ function savepointing(client, inTurn, named) {
79
86
  let depth = 0;
80
87
  const query = client.query.bind(client);
81
88
  const wrapped = Object.create(client);
89
+ const closeTransaction = (level) => {
90
+ for (let i = named.length - 1; i >= 0; i--) {
91
+ const savepoint = named[i];
92
+ if (savepoint.checkout === wrapped && savepoint.depth >= level) named.splice(i, 1);
93
+ }
94
+ };
82
95
  Object.assign(wrapped, {
83
96
  query: (text, ...rest) => {
84
97
  if (typeof text !== "string" || typeof rest.at(-1) === "function") return query(text, ...rest);
@@ -88,20 +101,70 @@ function savepointing(client, inTurn) {
88
101
  return inTurn(() => query(`SAVEPOINT ${savepoint}`));
89
102
  }
90
103
  if (statement === "commit") {
91
- const savepoint = `test_sp_${depth--}`;
92
- return inTurn(() => query(`RELEASE SAVEPOINT ${savepoint}`));
104
+ const level = depth--;
105
+ closeTransaction(level);
106
+ return inTurn(() => query(`RELEASE SAVEPOINT test_sp_${level}`));
93
107
  }
94
108
  if (statement === "rollback") {
95
- const savepoint = `test_sp_${depth--}`;
96
- return inTurn(() => query(`ROLLBACK TO SAVEPOINT ${savepoint}`));
109
+ const level = depth--;
110
+ closeTransaction(level);
111
+ return inTurn(() => query(`ROLLBACK TO SAVEPOINT test_sp_${level}`));
97
112
  }
98
- if (depth > 0) return inTurn(() => query(text, ...rest));
113
+ const control = savepointControl(text);
114
+ if (control) return inTurn(async () => {
115
+ const result = await query(text, ...rest);
116
+ track(named, control, {
117
+ checkout: wrapped,
118
+ depth
119
+ });
120
+ return result;
121
+ });
122
+ if (depth > 0 || named.length > 0) return inTurn(() => query(text, ...rest));
99
123
  return inTurn(() => autocommitted(query, text, rest));
100
124
  },
101
125
  release: () => {}
102
126
  });
103
127
  return wrapped;
104
128
  }
129
+ const IDENTIFIER = String.raw`("(?:[^"]|"")+"|[^\s;"]+)`;
130
+ const SAVEPOINT_CONTROL = [
131
+ ["savepoint", new RegExp(String.raw`^savepoint\s+${IDENTIFIER}\s*;?$`, "i")],
132
+ ["release", new RegExp(String.raw`^release\s+(?:savepoint\s+)?${IDENTIFIER}\s*;?$`, "i")],
133
+ ["rollback to", new RegExp(String.raw`^rollback\s+(?:(?:work|transaction)\s+)?to\s+(?:savepoint\s+)?${IDENTIFIER}\s*;?$`, "i")]
134
+ ];
135
+ /**
136
+ * The savepoint a statement opens, releases or rolls back to, named as
137
+ * Postgres names it: an unquoted name folded to lower case, a quoted one as
138
+ * written.
139
+ */
140
+ function savepointControl(text) {
141
+ const statement = text.trim();
142
+ for (const [action, pattern] of SAVEPOINT_CONTROL) {
143
+ const match = pattern.exec(statement);
144
+ if (!match) continue;
145
+ const identifier = match[1];
146
+ return {
147
+ action,
148
+ name: identifier.startsWith("\"") ? identifier.slice(1, -1).replaceAll("\"\"", "\"") : identifier.toLowerCase()
149
+ };
150
+ }
151
+ }
152
+ /**
153
+ * Keep the named savepoints as Postgres does: `RELEASE x` ends x and every
154
+ * savepoint after it; `ROLLBACK TO x` ends those after it and keeps x open.
155
+ */
156
+ function track(named, control, at) {
157
+ if (control.action === "savepoint") {
158
+ named.push({
159
+ name: control.name,
160
+ ...at
161
+ });
162
+ return;
163
+ }
164
+ const index = named.findLastIndex((s) => s.name === control.name);
165
+ if (index === -1) return;
166
+ named.splice(control.action === "release" ? index : index + 1);
167
+ }
105
168
  /**
106
169
  * One statement at a time on a connection, in the order they were asked for.
107
170
  *
@@ -1 +1 @@
1
- {"version":3,"file":"transactions.mjs","names":[],"sources":["../src/transactions.ts"],"sourcesContent":["/**\n * A transaction per database, per test — as each runs deployed.\n *\n * An app's database and a schema tenant such as the auth server's are separate\n * databases to the code using them: separate connections, credentials, roles\n * and search paths. A test keeps them that way. Each gets its own connection,\n * opened into a transaction the first time the test touches it, and every one\n * is rolled back when the test ends.\n *\n * Code under test must be free to use transactions itself, and better-auth\n * does — it also calls `db.connection()`, which Kysely refuses on a\n * `Transaction`. So what a test hands over is not a `Transaction` but a Kysely\n * over the one connection already inside the test's transaction, on which a\n * `BEGIN` becomes a savepoint and a `COMMIT` releases it. Nothing the code does\n * can end the transaction the test will roll back.\n *\n * A statement the code runs outside a transaction of its own gets a savepoint\n * too, so a failure — a duplicate key two concurrent requests raced to insert —\n * fails that statement alone, as it would deployed, rather than every request\n * the test makes after it.\n */\n\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport pg from 'pg';\n\n/** How to reach one database: a URL, and its search path as a startup option. */\nexport interface ConnectionConfig {\n\tconnectionString: string;\n\toptions?: string;\n}\n\n/**\n * The connection settings for a database URL.\n *\n * `?search_path=` is not a libpq parameter: a URL carrying it connects and then\n * resolves every name against `public`. Postgres takes it as a startup option,\n * which is what a schema tenant's URL needs to reach its own tables.\n */\nexport function connectionConfig(url: string): ConnectionConfig {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tif (!searchPath) return { connectionString: url };\n\n\tparsed.searchParams.delete('search_path');\n\treturn {\n\t\tconnectionString: parsed.toString(),\n\t\toptions: `-c search_path=${searchPath}`,\n\t};\n}\n\n/** One database's connection, inside a transaction the test will roll back. */\nexport interface BoundTransaction {\n\t/** Everything queried through this runs inside the test's transaction. */\n\treadonly db: Kysely<any>;\n\t/** Undo everything, and let the connection go. */\n\trollback(): Promise<void>;\n}\n\n/**\n * Open a connection to `url` and begin the transaction a test will roll back.\n *\n * `config` is what the database's own clients are built with — its plugins\n * above all. The code under test is handed this Kysely in place of its own, so\n * one built without them runs different queries than production does.\n */\nexport async function openBoundTransaction(\n\turl: string,\n\tconfig: Omit<KyselyConfig, 'dialect'> = {},\n): Promise<BoundTransaction> {\n\tconst client = new pg.Client(connectionConfig(url));\n\tawait client.connect();\n\tawait client.query('BEGIN');\n\t// Shared by every checkout of the connection: concurrent requests in one\n\t// test each check it out, and all of them take turns on it.\n\tconst inTurn = turns();\n\n\treturn {\n\t\tdb: new Kysely({\n\t\t\t...config,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\t// A \"pool\" of the one connection. Released never, ended never: the\n\t\t\t\t// test owns it, and it closes in `rollback`.\n\t\t\t\tpool: {\n\t\t\t\t\tconnect: async () => savepointing(client, inTurn),\n\t\t\t\t\tend: async () => {},\n\t\t\t\t} as unknown as pg.Pool,\n\t\t\t}),\n\t\t}),\n\t\tasync rollback() {\n\t\t\ttry {\n\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The client, with transaction control turned into savepoints.\n *\n * Kysely issues `begin`/`commit`/`rollback` as plain statements; this is the\n * one place they can be caught. A depth counter names the savepoints, so\n * nested transactions nest.\n */\nfunction savepointing(client: pg.Client, inTurn: Turns): pg.PoolClient {\n\tlet depth = 0;\n\tconst query = client.query.bind(client) as (\n\t\t...args: unknown[]\n\t) => Promise<unknown>;\n\n\tconst wrapped = Object.create(client) as pg.PoolClient;\n\tObject.assign(wrapped, {\n\t\tquery: (text: unknown, ...rest: unknown[]) => {\n\t\t\t// A cursor, a query config, a callback: not what Kysely sends for a\n\t\t\t// statement, and nothing to wrap.\n\t\t\tif (typeof text !== 'string' || typeof rest.at(-1) === 'function') {\n\t\t\t\treturn query(text, ...rest);\n\t\t\t}\n\t\t\tconst statement = text.trim().toLowerCase();\n\n\t\t\tif (statement === 'begin' || statement.startsWith('start transaction')) {\n\t\t\t\tconst savepoint = `test_sp_${++depth}`;\n\t\t\t\treturn inTurn(() => query(`SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (statement === 'commit') {\n\t\t\t\tconst savepoint = `test_sp_${depth--}`;\n\t\t\t\treturn inTurn(() => query(`RELEASE SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (statement === 'rollback') {\n\t\t\t\tconst savepoint = `test_sp_${depth--}`;\n\t\t\t\treturn inTurn(() => query(`ROLLBACK TO SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (depth > 0) return inTurn(() => query(text, ...rest));\n\t\t\treturn inTurn(() => autocommitted(query, text, rest));\n\t\t},\n\t\trelease: () => {},\n\t});\n\treturn wrapped;\n}\n\n/** Runs work in the order it was asked for, each after the last has settled. */\ntype Turns = <T>(work: () => Promise<T>) => Promise<T>;\n\n/**\n * One statement at a time on a connection, in the order they were asked for.\n *\n * The connection runs them one at a time anyway; this keeps a statement and\n * the savepoint around it together, so nothing another request sends lands\n * between them — a `RELEASE` also ends every savepoint opened after its own.\n */\nfunction turns(): Turns {\n\tlet queue: Promise<unknown> = Promise.resolve();\n\treturn (work) => {\n\t\tconst turn = queue.then(work, work);\n\t\tqueue = turn.catch(() => {});\n\t\treturn turn;\n\t};\n}\n\n/**\n * A statement run outside any transaction the code opened, failing the way\n * it would deployed: on its own.\n *\n * Deployed, such a statement is its own transaction, so one that fails — a\n * duplicate key two concurrent requests both tried to insert — fails alone,\n * and code written for that (Better Auth's rate limiter reads the row the\n * other request inserted, and carries on) does carry on. Inside the test's\n * transaction a failed statement would abort everything after it, every\n * request of the test included. A savepoint around it puts back what\n * deployed would have.\n */\nasync function autocommitted(\n\tquery: (...args: unknown[]) => Promise<unknown>,\n\ttext: string,\n\trest: unknown[],\n): Promise<unknown> {\n\tawait query('SAVEPOINT test_statement');\n\ttry {\n\t\tconst result = await query(text, ...rest);\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\treturn result;\n\t} catch (error) {\n\t\tawait query('ROLLBACK TO SAVEPOINT test_statement');\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\tthrow error;\n\t}\n}\n\n/**\n * The transactions one test has opened, by database.\n *\n * `get` opens a database's transaction the first time it is asked for and\n * hands back the same one after that — including to a caller that asks while\n * it is still opening. `rollbackAll` ends every one of them.\n */\nexport class TransactionRegistry<TKey = string> {\n\tprivate readonly open = new Map<TKey, Promise<BoundTransaction>>();\n\n\tget(\n\t\tkey: TKey,\n\t\turl: string,\n\t\tconfig?: Omit<KyselyConfig, 'dialect'>,\n\t): Promise<Kysely<any>> {\n\t\tlet transaction = this.open.get(key);\n\t\tif (!transaction) {\n\t\t\ttransaction = openBoundTransaction(url, config);\n\t\t\tthis.open.set(key, transaction);\n\t\t}\n\t\treturn transaction.then(({ db }) => db);\n\t}\n\n\tasync rollbackAll(): Promise<void> {\n\t\tconst transactions = [...this.open.values()];\n\t\tthis.open.clear();\n\n\t\tconst results = await Promise.allSettled(\n\t\t\ttransactions.map(async (transaction) => (await transaction).rollback()),\n\t\t);\n\t\tconst failed = results.find(\n\t\t\t(result): result is PromiseRejectedResult => result.status === 'rejected',\n\t\t);\n\t\tif (failed) throw failed.reason;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,iBAAiB,KAA+B;CAC/D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,IAAI,CAAC,YAAY,OAAO,EAAE,kBAAkB,IAAI;CAEhD,OAAO,aAAa,OAAO,aAAa;CACxC,OAAO;EACN,kBAAkB,OAAO,SAAS;EAClC,SAAS,kBAAkB;CAC5B;AACD;;;;;;;;AAiBA,eAAsB,qBACrB,KACA,SAAwC,CAAC,G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,CAAC;CACjB,CAAC;CACD,OAAO;AACR;;;;;;;;AAYA,SAAS,QAAe;CACvB,IAAI,QAA0B,QAAQ,QAAQ;CAC9C,QAAQ,SAAS;EAChB,MAAM,OAAO,MAAM,KAAK,MAAM,IAAI;EAClC,QAAQ,KAAK,YAAY,CAAC,CAAC;EAC3B,OAAO;CACR;AACD;;;;;;;;;;;;;AAcA,eAAe,cACd,OACA,MACA,MACmB;CACnB,MAAM,MAAM,0BAA0B;CACtC,IAAI;EACH,MAAM,SAAS,MAAM,MAAM,MAAM,GAAG,IAAI;EACxC,MAAM,MAAM,kCAAkC;EAC9C,OAAO;CACR,SAAS,OAAO;EACf,MAAM,MAAM,sCAAsC;EAClD,MAAM,MAAM,kCAAkC;EAC9C,MAAM;CACP;AACD;;;;;;;;AASA,IAAa,sBAAb,MAAgD;CAC/C,uBAAwB,IAAI,IAAqC;CAEjE,IACC,KACA,KACA,QACuB;EACvB,IAAI,cAAc,KAAK,KAAK,IAAI,GAAG;EACnC,IAAI,CAAC,aAAa;GACjB,cAAc,qBAAqB,KAAK,MAAM;GAC9C,KAAK,KAAK,IAAI,KAAK,WAAW;EAC/B;EACA,OAAO,YAAY,MAAM,EAAE,SAAS,EAAE;CACvC;CAEA,MAAM,cAA6B;EAClC,MAAM,eAAe,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC;EAC3C,KAAK,KAAK,MAAM;EAKhB,MAAM,UAAS,MAHO,QAAQ,WAC7B,aAAa,IAAI,OAAO,iBAAiB,MAAM,YAAA,CAAa,SAAS,CAAC,CACvE,EAAA,CACuB,MACrB,WAA4C,OAAO,WAAW,UAChE;EACA,IAAI,QAAQ,MAAM,OAAO;CAC1B;AACD"}
1
+ {"version":3,"file":"transactions.mjs","names":[],"sources":["../src/transactions.ts"],"sourcesContent":["/**\n * A transaction per database, per test — as each runs deployed.\n *\n * An app's database and a schema tenant such as the auth server's are separate\n * databases to the code using them: separate connections, credentials, roles\n * and search paths. A test keeps them that way. Each gets its own connection,\n * opened into a transaction the first time the test touches it, and every one\n * is rolled back when the test ends.\n *\n * Code under test must be free to use transactions itself, and better-auth\n * does — it also calls `db.connection()`, which Kysely refuses on a\n * `Transaction`. So what a test hands over is not a `Transaction` but a Kysely\n * over the one connection already inside the test's transaction, on which a\n * `BEGIN` becomes a savepoint and a `COMMIT` releases it. Nothing the code does\n * can end the transaction the test will roll back.\n *\n * A statement the code runs outside a transaction of its own gets a savepoint\n * too, so a failure — a duplicate key two concurrent requests raced to insert —\n * fails that statement alone, as it would deployed, rather than every request\n * the test makes after it.\n *\n * A savepoint the test or the code opens by name — `savepoint refused`, a\n * statement expected to fail, `rollback to savepoint refused` — is its own\n * transaction control, and passes through untouched. While one is open,\n * statements run in it as they would inside a `begin`: unwrapped, so a failure\n * aborts the transaction until the matching `rollback to savepoint`.\n */\n\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport pg from 'pg';\n\n/** How to reach one database: a URL, and its search path as a startup option. */\nexport interface ConnectionConfig {\n\tconnectionString: string;\n\toptions?: string;\n}\n\n/**\n * The connection settings for a database URL.\n *\n * `?search_path=` is not a libpq parameter: a URL carrying it connects and then\n * resolves every name against `public`. Postgres takes it as a startup option,\n * which is what a schema tenant's URL needs to reach its own tables.\n */\nexport function connectionConfig(url: string): ConnectionConfig {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tif (!searchPath) return { connectionString: url };\n\n\tparsed.searchParams.delete('search_path');\n\treturn {\n\t\tconnectionString: parsed.toString(),\n\t\toptions: `-c search_path=${searchPath}`,\n\t};\n}\n\n/** One database's connection, inside a transaction the test will roll back. */\nexport interface BoundTransaction {\n\t/** Everything queried through this runs inside the test's transaction. */\n\treadonly db: Kysely<any>;\n\t/** Undo everything, and let the connection go. */\n\trollback(): Promise<void>;\n}\n\n/**\n * Open a connection to `url` and begin the transaction a test will roll back.\n *\n * `config` is what the database's own clients are built with — its plugins\n * above all. The code under test is handed this Kysely in place of its own, so\n * one built without them runs different queries than production does.\n */\nexport async function openBoundTransaction(\n\turl: string,\n\tconfig: Omit<KyselyConfig, 'dialect'> = {},\n): Promise<BoundTransaction> {\n\tconst client = new pg.Client(connectionConfig(url));\n\tawait client.connect();\n\tawait client.query('BEGIN');\n\t// Shared by every checkout of the connection: concurrent requests in one\n\t// test each check it out, and all of them take turns on it.\n\tconst inTurn = turns();\n\t// The savepoints opened by name, shared by every checkout as the\n\t// connection's transaction is.\n\tconst named: NamedSavepoint[] = [];\n\n\treturn {\n\t\tdb: new Kysely({\n\t\t\t...config,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\t// A \"pool\" of the one connection. Released never, ended never: the\n\t\t\t\t// test owns it, and it closes in `rollback`.\n\t\t\t\tpool: {\n\t\t\t\t\tconnect: async () => savepointing(client, inTurn, named),\n\t\t\t\t\tend: async () => {},\n\t\t\t\t} as unknown as pg.Pool,\n\t\t\t}),\n\t\t}),\n\t\tasync rollback() {\n\t\t\ttry {\n\t\t\t\tawait client.query('ROLLBACK');\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The client, with transaction control turned into savepoints.\n *\n * Kysely issues `begin`/`commit`/`rollback` as plain statements; this is the\n * one place they can be caught. A depth counter names the savepoints, so\n * nested transactions nest.\n */\nfunction savepointing(\n\tclient: pg.Client,\n\tinTurn: Turns,\n\tnamed: NamedSavepoint[],\n): pg.PoolClient {\n\tlet depth = 0;\n\tconst query = client.query.bind(client) as (\n\t\t...args: unknown[]\n\t) => Promise<unknown>;\n\tconst wrapped = Object.create(client) as pg.PoolClient;\n\n\t// Ending one of the code's transactions ends every savepoint opened in it.\n\tconst closeTransaction = (level: number) => {\n\t\tfor (let i = named.length - 1; i >= 0; i--) {\n\t\t\tconst savepoint = named[i]!;\n\t\t\tif (savepoint.checkout === wrapped && savepoint.depth >= level) {\n\t\t\t\tnamed.splice(i, 1);\n\t\t\t}\n\t\t}\n\t};\n\n\tObject.assign(wrapped, {\n\t\tquery: (text: unknown, ...rest: unknown[]) => {\n\t\t\t// A cursor, a query config, a callback: not what Kysely sends for a\n\t\t\t// statement, and nothing to wrap.\n\t\t\tif (typeof text !== 'string' || typeof rest.at(-1) === 'function') {\n\t\t\t\treturn query(text, ...rest);\n\t\t\t}\n\t\t\tconst statement = text.trim().toLowerCase();\n\n\t\t\tif (statement === 'begin' || statement.startsWith('start transaction')) {\n\t\t\t\tconst savepoint = `test_sp_${++depth}`;\n\t\t\t\treturn inTurn(() => query(`SAVEPOINT ${savepoint}`));\n\t\t\t}\n\t\t\tif (statement === 'commit') {\n\t\t\t\tconst level = depth--;\n\t\t\t\tcloseTransaction(level);\n\t\t\t\treturn inTurn(() => query(`RELEASE SAVEPOINT test_sp_${level}`));\n\t\t\t}\n\t\t\tif (statement === 'rollback') {\n\t\t\t\tconst level = depth--;\n\t\t\t\tcloseTransaction(level);\n\t\t\t\treturn inTurn(() => query(`ROLLBACK TO SAVEPOINT test_sp_${level}`));\n\t\t\t}\n\n\t\t\tconst control = savepointControl(text);\n\t\t\tif (control) {\n\t\t\t\treturn inTurn(async () => {\n\t\t\t\t\tconst result = await query(text, ...rest);\n\t\t\t\t\ttrack(named, control, { checkout: wrapped, depth });\n\t\t\t\t\treturn result;\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (depth > 0 || named.length > 0) {\n\t\t\t\treturn inTurn(() => query(text, ...rest));\n\t\t\t}\n\t\t\treturn inTurn(() => autocommitted(query, text, rest));\n\t\t},\n\t\trelease: () => {},\n\t});\n\treturn wrapped;\n}\n\n/** A savepoint the test or the code opened by name, and where it opened it. */\ninterface NamedSavepoint {\n\tname: string;\n\t/** The checkout, and its transaction depth, the savepoint was opened at. */\n\tcheckout: pg.PoolClient;\n\tdepth: number;\n}\n\n/** `SAVEPOINT x`, `RELEASE [SAVEPOINT] x`, `ROLLBACK [WORK] TO [SAVEPOINT] x`. */\ninterface SavepointControl {\n\taction: 'savepoint' | 'release' | 'rollback to';\n\tname: string;\n}\n\nconst IDENTIFIER = String.raw`(\"(?:[^\"]|\"\")+\"|[^\\s;\"]+)`;\nconst SAVEPOINT_CONTROL: [SavepointControl['action'], RegExp][] = [\n\t['savepoint', new RegExp(String.raw`^savepoint\\s+${IDENTIFIER}\\s*;?$`, 'i')],\n\t[\n\t\t'release',\n\t\tnew RegExp(\n\t\t\tString.raw`^release\\s+(?:savepoint\\s+)?${IDENTIFIER}\\s*;?$`,\n\t\t\t'i',\n\t\t),\n\t],\n\t[\n\t\t'rollback to',\n\t\tnew RegExp(\n\t\t\tString.raw`^rollback\\s+(?:(?:work|transaction)\\s+)?to\\s+(?:savepoint\\s+)?${IDENTIFIER}\\s*;?$`,\n\t\t\t'i',\n\t\t),\n\t],\n];\n\n/**\n * The savepoint a statement opens, releases or rolls back to, named as\n * Postgres names it: an unquoted name folded to lower case, a quoted one as\n * written.\n */\nfunction savepointControl(text: string): SavepointControl | undefined {\n\tconst statement = text.trim();\n\tfor (const [action, pattern] of SAVEPOINT_CONTROL) {\n\t\tconst match = pattern.exec(statement);\n\t\tif (!match) continue;\n\t\tconst identifier = match[1]!;\n\t\tconst name = identifier.startsWith('\"')\n\t\t\t? identifier.slice(1, -1).replaceAll('\"\"', '\"')\n\t\t\t: identifier.toLowerCase();\n\t\treturn { action, name };\n\t}\n\treturn undefined;\n}\n\n/**\n * Keep the named savepoints as Postgres does: `RELEASE x` ends x and every\n * savepoint after it; `ROLLBACK TO x` ends those after it and keeps x open.\n */\nfunction track(\n\tnamed: NamedSavepoint[],\n\tcontrol: SavepointControl,\n\tat: Omit<NamedSavepoint, 'name'>,\n): void {\n\tif (control.action === 'savepoint') {\n\t\tnamed.push({ name: control.name, ...at });\n\t\treturn;\n\t}\n\tconst index = named.findLastIndex((s) => s.name === control.name);\n\t// One opened before this connection was handed over, or by a name the\n\t// wrapper uses itself: nothing tracked to end.\n\tif (index === -1) return;\n\tnamed.splice(control.action === 'release' ? index : index + 1);\n}\n\n/** Runs work in the order it was asked for, each after the last has settled. */\ntype Turns = <T>(work: () => Promise<T>) => Promise<T>;\n\n/**\n * One statement at a time on a connection, in the order they were asked for.\n *\n * The connection runs them one at a time anyway; this keeps a statement and\n * the savepoint around it together, so nothing another request sends lands\n * between them — a `RELEASE` also ends every savepoint opened after its own.\n */\nfunction turns(): Turns {\n\tlet queue: Promise<unknown> = Promise.resolve();\n\treturn (work) => {\n\t\tconst turn = queue.then(work, work);\n\t\tqueue = turn.catch(() => {});\n\t\treturn turn;\n\t};\n}\n\n/**\n * A statement run outside any transaction the code opened, failing the way\n * it would deployed: on its own.\n *\n * Deployed, such a statement is its own transaction, so one that fails — a\n * duplicate key two concurrent requests both tried to insert — fails alone,\n * and code written for that (Better Auth's rate limiter reads the row the\n * other request inserted, and carries on) does carry on. Inside the test's\n * transaction a failed statement would abort everything after it, every\n * request of the test included. A savepoint around it puts back what\n * deployed would have.\n */\nasync function autocommitted(\n\tquery: (...args: unknown[]) => Promise<unknown>,\n\ttext: string,\n\trest: unknown[],\n): Promise<unknown> {\n\tawait query('SAVEPOINT test_statement');\n\ttry {\n\t\tconst result = await query(text, ...rest);\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\treturn result;\n\t} catch (error) {\n\t\tawait query('ROLLBACK TO SAVEPOINT test_statement');\n\t\tawait query('RELEASE SAVEPOINT test_statement');\n\t\tthrow error;\n\t}\n}\n\n/**\n * The transactions one test has opened, by database.\n *\n * `get` opens a database's transaction the first time it is asked for and\n * hands back the same one after that — including to a caller that asks while\n * it is still opening. `rollbackAll` ends every one of them.\n */\nexport class TransactionRegistry<TKey = string> {\n\tprivate readonly open = new Map<TKey, Promise<BoundTransaction>>();\n\n\tget(\n\t\tkey: TKey,\n\t\turl: string,\n\t\tconfig?: Omit<KyselyConfig, 'dialect'>,\n\t): Promise<Kysely<any>> {\n\t\tlet transaction = this.open.get(key);\n\t\tif (!transaction) {\n\t\t\ttransaction = openBoundTransaction(url, config);\n\t\t\tthis.open.set(key, transaction);\n\t\t}\n\t\treturn transaction.then(({ db }) => db);\n\t}\n\n\tasync rollbackAll(): Promise<void> {\n\t\tconst transactions = [...this.open.values()];\n\t\tthis.open.clear();\n\n\t\tconst results = await Promise.allSettled(\n\t\t\ttransactions.map(async (transaction) => (await transaction).rollback()),\n\t\t);\n\t\tconst failed = results.find(\n\t\t\t(result): result is PromiseRejectedResult => result.status === 'rejected',\n\t\t);\n\t\tif (failed) throw failed.reason;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,iBAAiB,KAA+B;CAC/D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,IAAI,CAAC,YAAY,OAAO,EAAE,kBAAkB,IAAI;CAEhD,OAAO,aAAa,OAAO,aAAa;CACxC,OAAO;EACN,kBAAkB,OAAO,SAAS;EAClC,SAAS,kBAAkB;CAC5B;AACD;;;;;;;;AAiBA,eAAsB,qBACrB,KACA,SAAwC,CAAC,GACb;CAC5B,MAAM,SAAS,IAAI,GAAG,OAAO,iBAAiB,GAAG,CAAC;CAClD,MAAM,OAAO,QAAQ;CACrB,MAAM,OAAO,MAAM,OAAO;CAG1B,MAAM,SAAS,MAAM;CAGrB,MAAM,QAA0B,CAAC;CAEjC,OAAO;EACN,IAAI,IAAI,OAAO;GACd,GAAG;GACH,SAAS,IAAI,gBAAgB,EAG5B,MAAM;IACL,SAAS,YAAY,aAAa,QAAQ,QAAQ,KAAK;IACvD,KAAK,YAAY,CAAC;GACnB,EACD,CAAC;EACF,CAAC;EACD,MAAM,WAAW;GAChB,IAAI;IACH,MAAM,OAAO,MAAM,UAAU;GAC9B,UAAU;IACT,MAAM,OAAO,IAAI;GAClB;EACD;CACD;AACD;;;;;;;;AASA,SAAS,aACR,QACA,QACA,OACgB;CAChB,IAAI,QAAQ;CACZ,MAAM,QAAQ,OAAO,MAAM,KAAK,MAAM;CAGtC,MAAM,UAAU,OAAO,OAAO,MA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CAAkC;EAC9C,MAAM;CACP;AACD;;;;;;;;AASA,IAAa,sBAAb,MAAgD;CAC/C,uBAAwB,IAAI,IAAqC;CAEjE,IACC,KACA,KACA,QACuB;EACvB,IAAI,cAAc,KAAK,KAAK,IAAI,GAAG;EACnC,IAAI,CAAC,aAAa;GACjB,cAAc,qBAAqB,KAAK,MAAM;GAC9C,KAAK,KAAK,IAAI,KAAK,WAAW;EAC/B;EACA,OAAO,YAAY,MAAM,EAAE,SAAS,EAAE;CACvC;CAEA,MAAM,cAA6B;EAClC,MAAM,eAAe,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC;EAC3C,KAAK,KAAK,MAAM;EAKhB,MAAM,UAAS,MAHO,QAAQ,WAC7B,aAAa,IAAI,OAAO,iBAAiB,MAAM,YAAA,CAAa,SAAS,CAAC,CACvE,EAAA,CACuB,MACrB,WAA4C,OAAO,WAAW,UAChE;EACA,IAAI,QAAQ,MAAM,OAAO;CAC1B;AACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/testkit",
3
- "version": "10.0.0-alpha.89",
3
+ "version": "10.0.0-alpha.90",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -161,17 +161,17 @@
161
161
  "dependencies": {
162
162
  "@faker-js/faker": "~10.6.0",
163
163
  "tough-cookie": "~6.0.2",
164
- "@geekmidas/envkit": "^10.0.0-alpha.89",
165
- "@geekmidas/logger": "^10.0.0-alpha.89",
166
- "@geekmidas/services": "^10.0.0-alpha.89"
164
+ "@geekmidas/envkit": "^10.0.0-alpha.90",
165
+ "@geekmidas/services": "^10.0.0-alpha.90",
166
+ "@geekmidas/logger": "^10.0.0-alpha.90"
167
167
  },
168
168
  "devDependencies": {
169
169
  "@better-auth/test-utils": "~1.7.6",
170
170
  "@types/pg": "~8.23.1",
171
171
  "better-auth": "~1.7.6",
172
- "@geekmidas/envkit": "^10.0.0-alpha.89",
173
- "@geekmidas/logger": "^10.0.0-alpha.89",
174
- "@geekmidas/services": "^10.0.0-alpha.89"
172
+ "@geekmidas/envkit": "^10.0.0-alpha.90",
173
+ "@geekmidas/logger": "^10.0.0-alpha.90",
174
+ "@geekmidas/services": "^10.0.0-alpha.90"
175
175
  },
176
176
  "repository": {
177
177
  "type": "git",