@forinda/kickjs-db 8.12.4 → 8.13.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/bin/kickjs-db.mjs +11 -27
- package/dist/{adapter-cVrkWrul.d.mts → adapter-HRQJb4xQ.d.mts} +2 -4
- package/dist/adapter-HRQJb4xQ.d.mts.map +1 -0
- package/dist/cli.d.mts +39 -9
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +4 -4
- package/dist/cli.mjs.map +1 -1
- package/dist/{create-NrvNUwZr.mjs → create-BGFj2wGn.mjs} +3 -3
- package/dist/create-BGFj2wGn.mjs.map +1 -0
- package/dist/{custom-type-CNmg8h4k.mjs → custom-type-CyQYFrA5.mjs} +2 -2
- package/dist/custom-type-CyQYFrA5.mjs.map +1 -0
- package/dist/devtools-events.d.mts +1 -3
- package/dist/devtools-events.d.mts.map +1 -1
- package/dist/devtools-events.mjs +1 -1
- package/dist/{index-Nf43jLx4.d.mts → index-AaU739CK.d.mts} +329 -135
- package/dist/index-AaU739CK.d.mts.map +1 -0
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +2 -2
- package/dist/mysql.d.mts +2 -8
- package/dist/mysql.d.mts.map +1 -1
- package/dist/mysql.mjs +2 -2
- package/dist/mysql.mjs.map +1 -1
- package/dist/{pg-lghOiA3k.mjs → pg-0Zp1q4gP.mjs} +3 -3
- package/dist/{pg-lghOiA3k.mjs.map → pg-0Zp1q4gP.mjs.map} +1 -1
- package/dist/pg.d.mts +4 -12
- package/dist/pg.d.mts.map +1 -1
- package/dist/pg.mjs +2 -2
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -3
- package/dist/pglite.d.mts.map +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/{schema-types-CdU4u-Ow.d.mts → schema-types-CsgTPOPi.d.mts} +9 -5
- package/dist/schema-types-CsgTPOPi.d.mts.map +1 -0
- package/dist/{schema-jLdsVhUe.d.mts → schema-v6Jgocab.d.mts} +3 -5
- package/dist/schema-v6Jgocab.d.mts.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +2 -2
- package/dist/schema.mjs.map +1 -1
- package/dist/{split-statements-cNBnqF81.mjs → split-statements-DHYNJs5X.mjs} +2 -2
- package/dist/{split-statements-cNBnqF81.mjs.map → split-statements-DHYNJs5X.mjs.map} +1 -1
- package/dist/sqlite.d.mts +1 -7
- package/dist/sqlite.d.mts.map +1 -1
- package/dist/sqlite.mjs +2 -2
- package/dist/sqlite.mjs.map +1 -1
- package/dist/{src-BkewQb59.mjs → src-CBTegE76.mjs} +4 -4
- package/dist/src-CBTegE76.mjs.map +1 -0
- package/dist/{table-BGk08X3C.d.mts → table-B8eYtdq_.d.mts} +7 -8
- package/dist/table-B8eYtdq_.d.mts.map +1 -0
- package/dist/testing.d.mts +2 -4
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +2 -2
- package/dist/testing.mjs.map +1 -1
- package/dist/{types-8xZUYm43.d.mts → types-Bmbj69hY.d.mts} +79 -17
- package/dist/types-Bmbj69hY.d.mts.map +1 -0
- package/dist/{types-DB_xyeQT.d.mts → types-D4x2u-EZ.d.mts} +22 -5
- package/dist/types-D4x2u-EZ.d.mts.map +1 -0
- package/package.json +11 -11
- package/dist/adapter-cVrkWrul.d.mts.map +0 -1
- package/dist/create-NrvNUwZr.mjs.map +0 -1
- package/dist/custom-type-CNmg8h4k.mjs.map +0 -1
- package/dist/index-Nf43jLx4.d.mts.map +0 -1
- package/dist/schema-jLdsVhUe.d.mts.map +0 -1
- package/dist/schema-types-CdU4u-Ow.d.mts.map +0 -1
- package/dist/src-BkewQb59.mjs.map +0 -1
- package/dist/table-BGk08X3C.d.mts.map +0 -1
- package/dist/types-8xZUYm43.d.mts.map +0 -1
- package/dist/types-DB_xyeQT.d.mts.map +0 -1
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { S as PolicySnapshot, m as TypedColumnRefs, n as ColumnBuilder, t as CheckSelfRefs, w as RoleSnapshot, x as IndexSnapshot } from "./types-
|
|
3
|
-
//#region src/dsl/rls.d.ts
|
|
2
|
+
import { S as PolicySnapshot, m as TypedColumnRefs, n as ColumnBuilder, t as CheckSelfRefs, w as RoleSnapshot, x as IndexSnapshot } from "./types-D4x2u-EZ.mjs";
|
|
4
3
|
/** A database role, for `policy().to(...)` — created by migrations unless `.existing()`. */
|
|
5
4
|
declare class RoleDecl {
|
|
6
5
|
readonly __isRole = true;
|
|
@@ -58,8 +57,6 @@ declare class PolicyDecl {
|
|
|
58
57
|
* A table with a policy has row-level security turned on.
|
|
59
58
|
*/
|
|
60
59
|
declare function policy(name: string): PolicyDecl;
|
|
61
|
-
//#endregion
|
|
62
|
-
//#region src/dsl/constraints.d.ts
|
|
63
60
|
interface ColRef {
|
|
64
61
|
__name: string;
|
|
65
62
|
}
|
|
@@ -148,8 +145,11 @@ declare function primaryKey(name?: string): {
|
|
|
148
145
|
* expression is SQL, passed through as written.
|
|
149
146
|
*/
|
|
150
147
|
declare function check(name: string, expression: string): CheckDecl;
|
|
151
|
-
|
|
152
|
-
|
|
148
|
+
/**
|
|
149
|
+
* A table declared with `table()`: its name, columns, indexes and constraints.
|
|
150
|
+
*
|
|
151
|
+
* @see https://kickjs.app/guide/database/schema
|
|
152
|
+
*/
|
|
153
153
|
interface TableDecl<TName extends string = string, C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>, TSchema extends string | undefined = string | undefined> {
|
|
154
154
|
__isTable: true;
|
|
155
155
|
__name: TName;
|
|
@@ -232,6 +232,5 @@ declare function buildTable<TName extends string, C extends Record<string, Colum
|
|
|
232
232
|
* the class is enough — no separate `export const users = User.table`.
|
|
233
233
|
*/
|
|
234
234
|
declare function unwrapTable(value: unknown): TableDecl | undefined;
|
|
235
|
-
//#endregion
|
|
236
235
|
export { PolicyDecl as _, qualifiedTableName as a, pgRole as b, CheckDecl as c, PrimaryKeyDecl as d, TableConstraint as f, unique as g, primaryKey as h, buildTable as i, IndexDecl as l, index as m, TableDecl as n, table as o, check as p, TableOptions as r, unwrapTable as s, QualifiedName as t, IndexKey as u, RoleDecl as v, policy as x, isRole as y };
|
|
237
|
-
//# sourceMappingURL=table-
|
|
236
|
+
//# sourceMappingURL=table-B8eYtdq_.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"table-B8eYtdq_.d.mts","names":[],"sources":["../src/dsl/rls.ts","../src/dsl/constraints.ts","../src/dsl/table.ts"],"mappings":";;;cAGa;WACF;WACA,QAAQ;;EAEjB;EAEA,YAAY,cAAc,UAAS,KAAK;;EAKxC;;;;;;;;;;;iBAec,OAAO,cAAc,UAAS,KAAK,wBAA6B;iBAIhE,OAAO,iBAAiB,SAAS;KAI5C,UAAU;;cAGF;WACF;WACA,UAAU;EAEnB,YAAY;;EAKZ,IAAI,SAAS;;EAMb,MAAM,OAAO,eAAe;;;;;EAS5B,GAAG;;EAMH,MAAM;;EAMN,UAAU;;;;;;;;;;;;;;;;;iBAqBI,OAAO,eAAe;UC9F5B;EACR;;;KAIU,WAAW;;;;;;;;;;cAeV;;WAEF,SAAS;EAElB,YAAY,cAAc,MAAM,YAAY;;EAK5C,MAAM;;EAMN,MAAM;;EAMN,WAAW,MAAM;;EAMjB,GAAG,KAAK,UAAU;;;;;;EAclB;;;;;;;;;;;iBAec,MAAM;EAElB,MAAE,MAAU,aAAa;;;;;;;;;iBAab,OAAO;EAEnB,MAAE,MAAU,aAAa;;;UAOZ;EACf;;EAEA;EACA;;;UAIe;EACf;EACA;;EAEA;;;KAIU,kBAAkB,YAAY,iBAAiB,YAAY;;;;;;;;;;iBAWvD,WAAW;EAEvB,MAAE,MAAU,WAAW;;;;;;iBAYX,MAAM,cAAc,qBAAqB;;;;;;UClIxC,UACf,+BACA,UAAU,eAAe,iBAAiB,eAAe,gBACzD;EAEA;EACA,QAAQ;EACR,WAAW;EACX,WAAW;;EAEX,eAAe;EACf,WAAW;;EAEX;;EAEA;IAAU;;EACV,aAAa;;;;;;;;;EASb,WAAW;;;;;WAKF,UAAU,SAAS;;;;;;;;;;KAWlB,cACV,sBACA,sCACE,4BAA4B,WAAW,UAAU;;iBAGrC,mBAAmB;EACjC;EACA;;KAKG,UACH,sBACA,UAAU,eAAe,gBACzB,kDACE,UAAU,OAAO,GAAG,WAAW,gBAAgB;KAE9C,kBAAkB,UAAU,eAAe,mBAC9C,MAAM,gBAAgB,OACnB,eAAe;;;;;KAMR,aAAa,UAAU,eAAe,kBAC9C,kBAAkB;EAEhB,cAAc,kBAAkB;EAChC;;;;;;;EAOA;IAAkB;;;;;;;;;iBASR,MAAM,sBAAsB,UAAU,eAAe,gBACnE,MAAM,OACN,SAAS,IAAI,cAAc,IAC3B,UAAU,aAAa,KACtB,UAAU,OAAO;;;;;iBAQJ,WACd,sBACA,UAAU,eAAe,gBACzB,oCAEA,MAAM,OACN,UAAU,GACV,SAAS,aAAa,gBACtB,QAAQ,UACP,UAAU,OAAO,GAAG;;;;;;;iBA6EP,YAAY,iBAAiB"}
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { r as KickDbClient, s as QueryEvent } from "./types-
|
|
3
|
-
import { t as SchemaToTypes } from "./schema-types-
|
|
4
|
-
//#region src/testing.d.ts
|
|
2
|
+
import { r as KickDbClient, s as QueryEvent } from "./types-Bmbj69hY.mjs";
|
|
3
|
+
import { t as SchemaToTypes } from "./schema-types-CsgTPOPi.mjs";
|
|
5
4
|
export interface TestDbOptions<S> {
|
|
6
5
|
schema: S;
|
|
7
6
|
/**
|
|
@@ -68,6 +67,5 @@ export declare function captureQueries<T>(db: Observable, fn: () => Promise<T>):
|
|
|
68
67
|
* await expectQueries(db, 2, () => postsWithAuthors()) // 1 + 1, not 1 + N
|
|
69
68
|
*/
|
|
70
69
|
export declare function expectQueries<T>(db: Observable, count: number, fn: () => Promise<T>): Promise<T>;
|
|
71
|
-
//#endregion
|
|
72
70
|
export {};
|
|
73
71
|
//# sourceMappingURL=testing.d.mts.map
|
package/dist/testing.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.d.mts","names":[],"sources":["../src/testing.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"testing.d.mts","names":[],"sources":["../src/testing.ts"],"mappings":";;;iBAeiB,cAAc;EAC7B,QAAQ;;;;;EAKR;;EAEA;;;;;;;;wBASoB,aAAa,GACjC,MAAM,cAAc,KACnB,QAAQ,aAAa,cAAc;iBA6BrB,SAAS;EACxB,IAAI,aAAa,cAAc;;EAE/B;;EAEA,QAAQ;;;;;;;;;;;wBAYY,eAAe,GACnC,MAAM,cAAc;;EAElB;IAED,QAAQ,SAAS;;;;;;;;;;wBA8EE,WAAW,GAE/B,IAAI,KAAK,mCACT,UAAU,QAAQ,KACjB,QAAQ;KAcN,aAAa,KAAK;;;;;;;;wBASD,eAAe,GACnC,IAAI,YACJ,UAAU,QAAQ,KACjB;EAAU,QAAQ;EAAG,SAAS;;;;;;;;wBAuBX,cAAc,GAClC,IAAI,YACJ,eACA,UAAU,QAAQ,KACjB,QAAQ"}
|
package/dist/testing.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v8.
|
|
2
|
+
* @forinda/kickjs-db v8.13.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{O as emitPg,Q as extractSnapshot,Y as diff,d as migrateLatest,t as createDbClient,y as emitSqlite,z as EVENTS_ENABLED}from"./create-
|
|
11
|
+
import{O as emitPg,Q as extractSnapshot,Y as diff,d as migrateLatest,t as createDbClient,y as emitSqlite,z as EVENTS_ENABLED}from"./create-BGFj2wGn.mjs";import{randomBytes}from"node:crypto";async function createTestDb(opts){let{default:Database}=await import(`better-sqlite3`),{sqliteAdapter,sqliteDialect}=await import(`./sqlite.mjs`),database=new Database(`:memory:`);if(database.pragma(`foreign_keys = ON`),opts.migrationsDir)await migrateLatest({adapter:sqliteAdapter({database}),migrationsDir:opts.migrationsDir,requireReviewed:!1,driftCheck:`ignore`});else{let empty={version:1,dialect:`sqlite`,tables:{}},target=extractSnapshot(opts.schema,`sqlite`,{casing:opts.casing});database.exec(emitSqlite(diff(empty,target),{from:empty,to:target}))}return createDbClient({schema:opts.schema,dialect:sqliteDialect({database}),casing:opts.casing,events:!0})}async function createPgTestDb(opts){let{default:pg}=await import(`pg`),{pgAdapter,pgDialect}=await import(`./pg.mjs`),name=`kick_test_${randomBytes(6).toString(`hex`)}`,admin=new pg.Client({connectionString:opts.connectionString});await admin.connect();try{await admin.query(`CREATE DATABASE "${name}"`)}finally{await admin.end()}let url=new URL(opts.connectionString);url.pathname=`/${name}`;let connectionString=url.toString(),pool=new pg.Pool({connectionString});pool.on(`error`,()=>{}),pool.on(`connect`,client=>client.on(`error`,()=>{})),opts.migrationsDir?await migrateLatest({adapter:pgAdapter({pool}),migrationsDir:opts.migrationsDir,requireReviewed:!1,driftCheck:`ignore`}):await pool.query(emitPg(diff({version:1,dialect:`postgres`,tables:{}},extractSnapshot(opts.schema,`postgres`,{casing:opts.casing}))));let db=createDbClient({schema:opts.schema,dialect:pgDialect({pool}),casing:opts.casing,events:!0});return{db,connectionString,async drop(){await db.destroy();let admin=new pg.Client({connectionString:opts.connectionString});await admin.connect();try{await admin.query(`DROP DATABASE IF EXISTS "${name}" WITH (FORCE)`)}finally{await admin.end()}}}}const ROLLBACK=Symbol(`kickjs-db rolled back`);async function rolledBack(db,fn){let result;return await db.transaction(async()=>{throw result=await fn(),ROLLBACK}).catch(err=>{if(err!==ROLLBACK)throw err}),result}async function captureQueries(db,fn){if(db[EVENTS_ENABLED]===!1)throw Error("captureQueries: this client was created without events, so no query is reported and every count would be 0. Create it with `events: true`.");let queries=[],listener=event=>void queries.push(event);db.on(`query`,listener);try{return{result:await fn(),queries}}finally{db.off(`query`,listener)}}async function expectQueries(db,count,fn){let{result,queries}=await captureQueries(db,fn);if(queries.length!==count){let list=queries.map((q,i)=>` ${i+1}. ${q.sql}`).join(`
|
|
12
12
|
`);throw Error(`Expected ${count} quer${count===1?`y`:`ies`}, ran ${queries.length}:\n${list||` (none)`}`)}return result}export{captureQueries,createPgTestDb,createTestDb,expectQueries,rolledBack};
|
|
13
13
|
//# sourceMappingURL=testing.mjs.map
|
package/dist/testing.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.mjs","names":[],"sources":["../src/testing.ts"],"sourcesContent":["// `@forinda/kickjs-db/testing` — test helpers (D.15): a throwaway database\n// per test file, and a transaction per test that never commits.\nimport { randomBytes } from 'node:crypto'\nimport { createDbClient } from './client/create'\nimport { EVENTS_ENABLED } from './client/events'\nimport type { QueryEvent } from './client/types'\nimport type { KickDbClient } from './client/types'\nimport type { SchemaToTypes } from './client/schema-types'\nimport { diff } from './diff/engine'\nimport { emitPg } from './emit/pg'\nimport { emitSqlite } from './emit/sqlite'\nimport { migrateLatest } from './migrate/runner'\nimport { extractSnapshot } from './snapshot/extract'\nimport type { SchemaSnapshot } from './snapshot/types'\n\nexport interface TestDbOptions<S> {\n schema: S\n /**\n * Apply these migrations instead of creating tables straight from the\n * schema — the SQL production runs. Unreviewed ones apply too.\n */\n migrationsDir?: string\n /** The `casing` your client and `kick.config.ts` use. */\n casing?: 'snake_case'\n}\n\n/**\n * A fresh in-memory SQLite database with your schema, foreign keys on —\n * milliseconds to create, one per test file. Needs `better-sqlite3`.\n *\n * const db = await createTestDb({ schema })\n */\nexport async function createTestDb<S>(\n opts: TestDbOptions<S>,\n): Promise<KickDbClient<SchemaToTypes<S>>> {\n const { default: Database } = await import('better-sqlite3')\n const { sqliteAdapter, sqliteDialect } = await import('./sqlite')\n const database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n\n if (opts.migrationsDir) {\n await migrateLatest({\n adapter: sqliteAdapter({ database }),\n migrationsDir: opts.migrationsDir,\n requireReviewed: false,\n driftCheck: 'ignore',\n })\n } else {\n const empty: SchemaSnapshot = { version: 1, dialect: 'sqlite', tables: {} }\n const target = extractSnapshot(opts.schema as Record<string, unknown>, 'sqlite', {\n casing: opts.casing,\n })\n database.exec(emitSqlite(diff(empty, target), { from: empty, to: target }))\n }\n return createDbClient({\n schema: opts.schema,\n dialect: sqliteDialect({ database }),\n casing: opts.casing,\n // On, so captureQueries / expectQueries can count.\n events: true,\n }) as never\n}\n\nexport interface PgTestDb<S> {\n db: KickDbClient<SchemaToTypes<S>>\n /** The throwaway database's connection string — for code that opens its own pool. */\n connectionString: string\n /** Close the client and drop the database. Call it in `afterAll`. */\n drop(): Promise<void>\n}\n\n/**\n * A throwaway database on an existing Postgres server — a CI service\n * container, a local Docker Postgres — with your schema or migrations\n * applied. Creating one takes well under a second, so each test file can\n * have its own without starting a container. Needs `pg`.\n *\n * const pg = await createPgTestDb({ schema, connectionString: process.env.TEST_DATABASE_URL! })\n * afterAll(() => pg.drop())\n */\nexport async function createPgTestDb<S>(\n opts: TestDbOptions<S> & {\n /** A database on the server to connect to first, with permission to CREATE DATABASE. */\n connectionString: string\n },\n): Promise<PgTestDb<S>> {\n const { default: pg } = await import('pg')\n const { pgAdapter, pgDialect } = await import('./pg')\n const name = `kick_test_${randomBytes(6).toString('hex')}`\n\n const admin = new pg.Client({ connectionString: opts.connectionString })\n await admin.connect()\n try {\n await admin.query(`CREATE DATABASE \"${name}\"`)\n } finally {\n await admin.end()\n }\n\n const url = new URL(opts.connectionString)\n url.pathname = `/${name}`\n const connectionString = url.toString()\n const pool = new pg.Pool({ connectionString })\n // Dropped connections at teardown aren't test failures. The client-level\n // listener matters: `pool.end()` resolves before a client's socket closes,\n // and the pool detaches its own listener first, so the FORCE drop's\n // termination would otherwise surface as an uncaught error.\n pool.on('error', () => {})\n pool.on('connect', (client) => client.on('error', () => {}))\n\n if (opts.migrationsDir) {\n await migrateLatest({\n adapter: pgAdapter({ pool }),\n migrationsDir: opts.migrationsDir,\n requireReviewed: false,\n driftCheck: 'ignore',\n })\n } else {\n const empty: SchemaSnapshot = { version: 1, dialect: 'postgres', tables: {} }\n await pool.query(\n emitPg(\n diff(\n empty,\n extractSnapshot(opts.schema as Record<string, unknown>, 'postgres', {\n casing: opts.casing,\n }),\n ),\n ),\n )\n }\n\n const db = createDbClient({\n schema: opts.schema,\n dialect: pgDialect({ pool }),\n casing: opts.casing,\n events: true,\n }) as never as KickDbClient<SchemaToTypes<S>>\n return {\n db,\n connectionString,\n async drop() {\n await db.destroy() // ends the pool\n const admin = new pg.Client({ connectionString: opts.connectionString })\n await admin.connect()\n try {\n await admin.query(`DROP DATABASE IF EXISTS \"${name}\" WITH (FORCE)`)\n } finally {\n await admin.end()\n }\n },\n }\n}\n\nconst ROLLBACK = Symbol('kickjs-db rolled back')\n\n/**\n * Run `fn` in a transaction that's always rolled back — every test starts\n * from the same data. Code that only holds the client (a service, a\n * repository) joins the transaction through the call chain, so nothing it\n * writes survives. `afterCommit` hooks don't run. A real failure in `fn`\n * still throws.\n *\n * it('creates a user', () => rolledBack(db, async () => { … }))\n */\nexport async function rolledBack<T>(\n // oxlint-disable-next-line no-explicit-any -- any schema's client\n db: Pick<KickDbClient<any>, 'transaction'>,\n fn: () => Promise<T>,\n): Promise<T> {\n let result!: T\n await db\n .transaction(async () => {\n result = await fn()\n throw ROLLBACK\n })\n .catch((err: unknown) => {\n if (err !== ROLLBACK) throw err\n })\n return result\n}\n\n// oxlint-disable-next-line no-explicit-any -- any schema's client\ntype Observable = Pick<KickDbClient<any>, 'on' | 'off'>\n\n/**\n * Run `fn` and return the queries it sent, in order. The client must have\n * events on — `createTestDb` / `createPgTestDb` clients do; your own needs\n * `createDbClient({ events: true })`.\n *\n * const { result, queries } = await captureQueries(db, () => repo.list())\n */\nexport async function captureQueries<T>(\n db: Observable,\n fn: () => Promise<T>,\n): Promise<{ result: T; queries: QueryEvent[] }> {\n if ((db as unknown as Record<symbol, unknown>)[EVENTS_ENABLED] === false) {\n throw new Error(\n 'captureQueries: this client was created without events, so no query is reported ' +\n 'and every count would be 0. Create it with `events: true`.',\n )\n }\n const queries: QueryEvent[] = []\n const listener = (event: QueryEvent) => void queries.push(event)\n db.on('query', listener)\n try {\n return { result: await fn(), queries }\n } finally {\n db.off('query', listener)\n }\n}\n\n/**\n * Assert `fn` sends exactly `count` queries — a guard against N+1 queries\n * that grows with the data. On a mismatch the error lists every query sent.\n *\n * await expectQueries(db, 2, () => postsWithAuthors()) // 1 + 1, not 1 + N\n */\nexport async function expectQueries<T>(\n db: Observable,\n count: number,\n fn: () => Promise<T>,\n): Promise<T> {\n const { result, queries } = await captureQueries(db, fn)\n if (queries.length !== count) {\n const list = queries.map((q, i) => ` ${i + 1}. ${q.sql}`).join('\\n')\n throw new Error(\n `Expected ${count} quer${count === 1 ? 'y' : 'ies'}, ran ${queries.length}:\\n${list || ' (none)'}`,\n )\n }\n return result\n}\n"],"mappings":";;;;;;;;;;8LAgCA,eAAsB,aACpB,KACyC,CACzC,GAAM,CAAE,QAAS,UAAa,MAAM,OAAO,kBACrC,CAAE,cAAe,eAAkB,MAAM,OAAO,gBAChD,SAAW,IAAI,SAAS,UAAU,EAGxC,GAFA,SAAS,OAAO,mBAAmB,EAE/B,KAAK,cACP,MAAM,cAAc,CAClB,QAAS,cAAc,CAAE,QAAS,CAAC,EACnC,cAAe,KAAK,cACpB,gBAAiB,GACjB,WAAY,QACd,CAAC,MACI,CACL,IAAM,MAAwB,CAAE,QAAS,EAAG,QAAS,SAAU,OAAQ,CAAC,CAAE,EACpE,OAAS,gBAAgB,KAAK,OAAmC,SAAU,CAC/E,OAAQ,KAAK,MACf,CAAC,EACD,SAAS,KAAK,WAAW,KAAK,MAAO,MAAM,EAAG,CAAE,KAAM,MAAO,GAAI,MAAO,CAAC,CAAC,CAC5E,CACA,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E,iBAAkB,KAAK,gBAAiB,CAAC,EACvE,MAAM,MAAM,QAAQ,EACpB,GAAI,CACF,MAAM,MAAM,MAAM,4BAA4B,KAAK,eAAe,CACpE,QAAU,CACR,MAAM,MAAM,IAAI,CAClB,CACF,CACF,CACF,CAEA,MAAM,SAAW,OAAO,uBAAuB,EAW/C,eAAsB,WAEpB,GACA,GACY,CACZ,IAAI,OASJ,OARA,MAAM,GACH,YAAY,SAAY,CAEvB,KADA,QAAS,MAAM,GAAG,EACZ,QACR,CAAC,CAAC,CACD,MAAO,KAAiB,CACvB,GAAI,MAAQ,SAAU,MAAM,GAC9B,CAAC,EACI,MACT,CAYA,eAAsB,eACpB,GACA,GAC+C,CAC/C,GAAK,GAA0C,kBAAoB,GACjE,MAAU,MACR,4IAEF,EAEF,IAAM,QAAwB,CAAC,EACzB,SAAY,OAAsB,KAAK,QAAQ,KAAK,KAAK,EAC/D,GAAG,GAAG,QAAS,QAAQ,EACvB,GAAI,CACF,MAAO,CAAE,OAAQ,MAAM,GAAG,EAAG,OAAQ,CACvC,QAAU,CACR,GAAG,IAAI,QAAS,QAAQ,CAC1B,CACF,CAQA,eAAsB,cACpB,GACA,MACA,GACY,CACZ,GAAM,CAAE,OAAQ,SAAY,MAAM,eAAe,GAAI,EAAE,EACvD,GAAI,QAAQ,SAAW,MAAO,CAC5B,IAAM,KAAO,QAAQ,KAAK,EAAG,IAAM,KAAK,EAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,KAAK;CAAI,EACpE,MAAU,MACR,YAAY,MAAM,OAAO,QAAU,EAAI,IAAM,MAAM,QAAQ,QAAQ,OAAO,KAAK,MAAQ,YACzF,CACF,CACA,OAAO,MACT"}
|
|
1
|
+
{"version":3,"file":"testing.mjs","names":[],"sources":["../src/testing.ts"],"sourcesContent":["// `@forinda/kickjs-db/testing` — test helpers (D.15): a throwaway database\n// per test file, and a transaction per test that never commits.\nimport { randomBytes } from 'node:crypto'\nimport { createDbClient } from './client/create'\nimport { EVENTS_ENABLED } from './client/events'\nimport type { QueryEvent } from './client/types'\nimport type { KickDbClient } from './client/types'\nimport type { SchemaToTypes } from './client/schema-types'\nimport { diff } from './diff/engine'\nimport { emitPg } from './emit/pg'\nimport { emitSqlite } from './emit/sqlite'\nimport { migrateLatest } from './migrate/runner'\nimport { extractSnapshot } from './snapshot/extract'\nimport type { SchemaSnapshot } from './snapshot/types'\n\nexport interface TestDbOptions<S> {\n schema: S\n /**\n * Apply these migrations instead of creating tables straight from the\n * schema — the SQL production runs. Unreviewed ones apply too.\n */\n migrationsDir?: string\n /** The `casing` your client and `kick.config.ts` use. */\n casing?: 'snake_case'\n}\n\n/**\n * A fresh in-memory SQLite database with your schema, foreign keys on —\n * milliseconds to create, one per test file. Needs `better-sqlite3`.\n *\n * const db = await createTestDb({ schema })\n */\nexport async function createTestDb<S>(\n opts: TestDbOptions<S>,\n): Promise<KickDbClient<SchemaToTypes<S>>> {\n const { default: Database } = await import('better-sqlite3')\n const { sqliteAdapter, sqliteDialect } = await import('./sqlite')\n const database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n\n if (opts.migrationsDir) {\n await migrateLatest({\n adapter: sqliteAdapter({ database }),\n migrationsDir: opts.migrationsDir,\n requireReviewed: false,\n driftCheck: 'ignore',\n })\n } else {\n const empty: SchemaSnapshot = { version: 1, dialect: 'sqlite', tables: {} }\n const target = extractSnapshot(opts.schema as Record<string, unknown>, 'sqlite', {\n casing: opts.casing,\n })\n database.exec(emitSqlite(diff(empty, target), { from: empty, to: target }))\n }\n return createDbClient({\n schema: opts.schema,\n dialect: sqliteDialect({ database }),\n casing: opts.casing,\n // On, so captureQueries / expectQueries can count.\n events: true,\n }) as never\n}\n\nexport interface PgTestDb<S> {\n db: KickDbClient<SchemaToTypes<S>>\n /** The throwaway database's connection string — for code that opens its own pool. */\n connectionString: string\n /** Close the client and drop the database. Call it in `afterAll`. */\n drop(): Promise<void>\n}\n\n/**\n * A throwaway database on an existing Postgres server — a CI service\n * container, a local Docker Postgres — with your schema or migrations\n * applied. Creating one takes well under a second, so each test file can\n * have its own without starting a container. Needs `pg`.\n *\n * const pg = await createPgTestDb({ schema, connectionString: process.env.TEST_DATABASE_URL! })\n * afterAll(() => pg.drop())\n */\nexport async function createPgTestDb<S>(\n opts: TestDbOptions<S> & {\n /** A database on the server to connect to first, with permission to CREATE DATABASE. */\n connectionString: string\n },\n): Promise<PgTestDb<S>> {\n const { default: pg } = await import('pg')\n const { pgAdapter, pgDialect } = await import('./pg')\n const name = `kick_test_${randomBytes(6).toString('hex')}`\n\n const admin = new pg.Client({ connectionString: opts.connectionString })\n await admin.connect()\n try {\n await admin.query(`CREATE DATABASE \"${name}\"`)\n } finally {\n await admin.end()\n }\n\n const url = new URL(opts.connectionString)\n url.pathname = `/${name}`\n const connectionString = url.toString()\n const pool = new pg.Pool({ connectionString })\n // Dropped connections at teardown aren't test failures. The client-level\n // listener matters: `pool.end()` resolves before a client's socket closes,\n // and the pool detaches its own listener first, so the FORCE drop's\n // termination would otherwise surface as an uncaught error.\n pool.on('error', () => {})\n pool.on('connect', (client) => client.on('error', () => {}))\n\n if (opts.migrationsDir) {\n await migrateLatest({\n adapter: pgAdapter({ pool }),\n migrationsDir: opts.migrationsDir,\n requireReviewed: false,\n driftCheck: 'ignore',\n })\n } else {\n const empty: SchemaSnapshot = { version: 1, dialect: 'postgres', tables: {} }\n await pool.query(\n emitPg(\n diff(\n empty,\n extractSnapshot(opts.schema as Record<string, unknown>, 'postgres', {\n casing: opts.casing,\n }),\n ),\n ),\n )\n }\n\n const db = createDbClient({\n schema: opts.schema,\n dialect: pgDialect({ pool }),\n casing: opts.casing,\n events: true,\n }) as never as KickDbClient<SchemaToTypes<S>>\n return {\n db,\n connectionString,\n async drop() {\n await db.destroy() // ends the pool\n const admin = new pg.Client({ connectionString: opts.connectionString })\n await admin.connect()\n try {\n await admin.query(`DROP DATABASE IF EXISTS \"${name}\" WITH (FORCE)`)\n } finally {\n await admin.end()\n }\n },\n }\n}\n\nconst ROLLBACK = Symbol('kickjs-db rolled back')\n\n/**\n * Run `fn` in a transaction that's always rolled back — every test starts\n * from the same data. Code that only holds the client (a service, a\n * repository) joins the transaction through the call chain, so nothing it\n * writes survives. `afterCommit` hooks don't run. A real failure in `fn`\n * still throws.\n *\n * it('creates a user', () => rolledBack(db, async () => { … }))\n */\nexport async function rolledBack<T>(\n // oxlint-disable-next-line no-explicit-any -- any schema's client\n db: Pick<KickDbClient<any>, 'transaction'>,\n fn: () => Promise<T>,\n): Promise<T> {\n let result!: T\n await db\n .transaction(async () => {\n result = await fn()\n throw ROLLBACK\n })\n .catch((err: unknown) => {\n if (err !== ROLLBACK) throw err\n })\n return result\n}\n\n// oxlint-disable-next-line no-explicit-any -- any schema's client\ntype Observable = Pick<KickDbClient<any>, 'on' | 'off'>\n\n/**\n * Run `fn` and return the queries it sent, in order. The client must have\n * events on — `createTestDb` / `createPgTestDb` clients do; your own needs\n * `createDbClient({ events: true })`.\n *\n * const { result, queries } = await captureQueries(db, () => repo.list())\n */\nexport async function captureQueries<T>(\n db: Observable,\n fn: () => Promise<T>,\n): Promise<{ result: T; queries: QueryEvent[] }> {\n if ((db as unknown as Record<symbol, unknown>)[EVENTS_ENABLED] === false) {\n throw new Error(\n 'captureQueries: this client was created without events, so no query is reported ' +\n 'and every count would be 0. Create it with `events: true`.',\n )\n }\n const queries: QueryEvent[] = []\n const listener = (event: QueryEvent) => void queries.push(event)\n db.on('query', listener)\n try {\n return { result: await fn(), queries }\n } finally {\n db.off('query', listener)\n }\n}\n\n/**\n * Assert `fn` sends exactly `count` queries — a guard against N+1 queries\n * that grows with the data. On a mismatch the error lists every query sent.\n *\n * await expectQueries(db, 2, () => postsWithAuthors()) // 1 + 1, not 1 + N\n */\nexport async function expectQueries<T>(\n db: Observable,\n count: number,\n fn: () => Promise<T>,\n): Promise<T> {\n const { result, queries } = await captureQueries(db, fn)\n if (queries.length !== count) {\n const list = queries.map((q, i) => ` ${i + 1}. ${q.sql}`).join('\\n')\n throw new Error(\n `Expected ${count} quer${count === 1 ? 'y' : 'ies'}, ran ${queries.length}:\\n${list || ' (none)'}`,\n )\n }\n return result\n}\n"],"mappings":";;;;;;;;;;A,8LAgCA,eAAsB,aACpB,KACyC,CACzC,GAAM,CAAE,QAAS,UAAa,MAAM,OAAO,kBACrC,CAAE,cAAe,eAAkB,MAAM,OAAO,gBAChD,SAAW,IAAI,SAAS,UAAU,EAGxC,GAFA,SAAS,OAAO,mBAAmB,EAE/B,KAAK,cACP,MAAM,cAAc,CAClB,QAAS,cAAc,CAAE,QAAS,CAAC,EACnC,cAAe,KAAK,cACpB,gBAAiB,GACjB,WAAY,QACd,CAAC,MACI,CACL,IAAM,MAAwB,CAAE,QAAS,EAAG,QAAS,SAAU,OAAQ,CAAC,CAAE,EACpE,OAAS,gBAAgB,KAAK,OAAmC,SAAU,CAC/E,OAAQ,KAAK,MACf,CAAC,EACD,SAAS,KAAK,WAAW,KAAK,MAAO,MAAM,EAAG,CAAE,KAAM,MAAO,GAAI,MAAO,CAAC,CAAC,CAC5E,CACA,OAAO,eAAe,CACpB,OAAQ,KAAK,OACb,QAAS,cAAc,CAAE,QAAS,CAAC,EACnC,OAAQ,KAAK,OAEb,OAAQ,EACV,CAAC,CACH,CAmBA,eAAsB,eACpB,KAIsB,CACtB,GAAM,CAAE,QAAS,IAAO,MAAM,OAAO,MAC/B,CAAE,UAAW,WAAc,MAAM,OAAO,YACxC,KAAO,aAAa,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,IAEjD,MAAQ,IAAI,GAAG,OAAO,CAAE,iBAAkB,KAAK,gBAAiB,CAAC,EACvE,MAAM,MAAM,QAAQ,EACpB,GAAI,CACF,MAAM,MAAM,MAAM,oBAAoB,KAAK,EAAE,CAC/C,QAAU,CACR,MAAM,MAAM,IAAI,CAClB,CAEA,IAAM,IAAM,IAAI,IAAI,KAAK,gBAAgB,EACzC,IAAI,SAAW,IAAI,OACnB,IAAM,iBAAmB,IAAI,SAAS,EAChC,KA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QAAS,QAAQ,EACvB,GAAI,CACF,MAAO,CAAE,OAAQ,MAAM,GAAG,EAAG,OAAQ,CACvC,QAAU,CACR,GAAG,IAAI,QAAS,QAAQ,CAC1B,CACF,CAQA,eAAsB,cACpB,GACA,MACA,GACY,CACZ,GAAM,CAAE,OAAQ,SAAY,MAAM,eAAe,GAAI,EAAE,EACvD,GAAI,QAAQ,SAAW,MAAO,CAC5B,IAAM,KAAO,QAAQ,KAAK,EAAG,IAAM,KAAK,EAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,KAAK;CAAI,EACpE,MAAU,MACR,YAAY,MAAM,OAAO,QAAU,EAAI,IAAM,MAAM,QAAQ,QAAQ,OAAO,KAAK,MAAQ,YACzF,CACF,CACA,OAAO,MACT,C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as ColumnBuilder, s as GeneratedBrand, u as NotNullBrand } from "./types-
|
|
2
|
+
import { n as ColumnBuilder, s as GeneratedBrand, u as NotNullBrand } from "./types-D4x2u-EZ.mjs";
|
|
3
3
|
import { CommonTableExpression, Dialect, Expression, ExpressionBuilder, Insertable, Kysely, KyselyPlugin, SelectQueryBuilder, SelectType, Selectable, SqlBool, UpdateObject } from "kysely";
|
|
4
|
-
|
|
4
|
+
/** Options for `db.insertMany()`: the parameter limit per statement, and atomicity. */
|
|
5
5
|
interface InsertManyOptions {
|
|
6
6
|
/**
|
|
7
7
|
* Bind parameters one statement may use. Default the dialect's limit; set it
|
|
@@ -15,8 +15,11 @@ interface InsertManyOptions {
|
|
|
15
15
|
*/
|
|
16
16
|
atomic?: boolean;
|
|
17
17
|
}
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Options for `db.upsert()`.
|
|
20
|
+
*
|
|
21
|
+
* @see https://kickjs.app/guide/database/queries#upsert-and-find-or-create
|
|
22
|
+
*/
|
|
20
23
|
interface UpsertOptions<DB, T extends keyof DB & string> extends InsertManyOptions {
|
|
21
24
|
/**
|
|
22
25
|
* The row — or rows — to insert. Many rows are split into statements that
|
|
@@ -48,6 +51,11 @@ interface UpsertOptions<DB, T extends keyof DB & string> extends InsertManyOptio
|
|
|
48
51
|
type PresentKeys<W> = { [K in keyof W]-?: {} extends Pick<W, K> ? never : K; }[keyof W];
|
|
49
52
|
/** What `create` adds to `where`: every required column `where` may leave out. */
|
|
50
53
|
type CreateRest<DB, T extends keyof DB, W> = Omit<Insertable<DB[T]>, PresentKeys<W>> & Partial<Insertable<DB[T]>>;
|
|
54
|
+
/**
|
|
55
|
+
* Options for `db.findOrCreate()`: the unique key to look up, and the rest of the row to create.
|
|
56
|
+
*
|
|
57
|
+
* @see https://kickjs.app/guide/database/queries#upsert-and-find-or-create
|
|
58
|
+
*/
|
|
51
59
|
type FindOrCreateOptions<DB, T extends keyof DB & string, W extends Partial<Selectable<DB[T]>> = Partial<Selectable<DB[T]>>> = {
|
|
52
60
|
/** Identifies the row — columns of a unique key. Also part of what's created. */
|
|
53
61
|
where: W & Record<Exclude<keyof W, keyof Selectable<DB[T]>>, never>;
|
|
@@ -56,8 +64,6 @@ type FindOrCreateOptions<DB, T extends keyof DB & string, W extends Partial<Sele
|
|
|
56
64
|
} : {
|
|
57
65
|
create: CreateRest<DB, T, W>;
|
|
58
66
|
});
|
|
59
|
-
//#endregion
|
|
60
|
-
//#region src/extend/types.d.ts
|
|
61
67
|
/**
|
|
62
68
|
* Method bag keyed by table name. Methods receive `this` as the
|
|
63
69
|
* extended client (the runtime calls them with `Function.prototype.call`
|
|
@@ -114,8 +120,6 @@ type ComputedFields<Bag> = Bag extends Record<string, {
|
|
|
114
120
|
* method bag from `model`.
|
|
115
121
|
*/
|
|
116
122
|
type ExtendedClient<DB, E extends ExtensionDefinition<DB>> = KickDbClient<E['result'] extends ResultExtensions<DB> ? DBWithResults<DB, NonNullable<E['result']>> : DB> & { [T in keyof NonNullable<E['model']> & keyof DB & string]: NonNullable<NonNullable<E['model']>[T]>; };
|
|
117
|
-
//#endregion
|
|
118
|
-
//#region src/tenancy.d.ts
|
|
119
123
|
/**
|
|
120
124
|
* How tenants' rows are kept apart:
|
|
121
125
|
*
|
|
@@ -132,6 +136,11 @@ type ExtendedClient<DB, E extends ExtensionDefinition<DB>> = KickDbClient<E['res
|
|
|
132
136
|
* central database.
|
|
133
137
|
*/
|
|
134
138
|
type TenancyStrategy = 'column' | 'rls' | 'schema' | 'database';
|
|
139
|
+
/**
|
|
140
|
+
* Options for `defineTenancy()`.
|
|
141
|
+
*
|
|
142
|
+
* @see https://kickjs.app/guide/database/tenancy
|
|
143
|
+
*/
|
|
135
144
|
interface TenancyOptions {
|
|
136
145
|
strategy: TenancyStrategy;
|
|
137
146
|
/**
|
|
@@ -195,18 +204,33 @@ interface TenancyOptions {
|
|
|
195
204
|
*/
|
|
196
205
|
roleCheck?: 'error' | 'warn' | 'off';
|
|
197
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* What `onBypass` receives for each `bypass()`: the reason, the strategy, and where it was called.
|
|
209
|
+
*
|
|
210
|
+
* @see https://kickjs.app/guide/database/tenancy#cross-tenant-work-bypass
|
|
211
|
+
*/
|
|
198
212
|
interface BypassInfo {
|
|
199
213
|
reason: string;
|
|
200
214
|
strategy: TenancyStrategy;
|
|
201
215
|
/** Where `bypass()` was called. */
|
|
202
216
|
stack: string | undefined;
|
|
203
217
|
}
|
|
218
|
+
/**
|
|
219
|
+
* Options for `tenancy.bypass()`.
|
|
220
|
+
*
|
|
221
|
+
* @see https://kickjs.app/guide/database/tenancy#cross-tenant-work-bypass
|
|
222
|
+
*/
|
|
204
223
|
interface BypassOptions {
|
|
205
224
|
/** Why — passed to `onBypass`, for the audit log. */
|
|
206
225
|
reason: string;
|
|
207
226
|
/** Allow it inside an HTTP request (refused there by default). */
|
|
208
227
|
allowInRequest?: boolean;
|
|
209
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* A tenancy made by `defineTenancy()`: pass it to `createDbClient({ tenancy })` and to `tenantKey()` columns.
|
|
231
|
+
*
|
|
232
|
+
* @see https://kickjs.app/guide/database/tenancy
|
|
233
|
+
*/
|
|
210
234
|
interface Tenancy extends Readonly<Required<Pick<TenancyOptions, 'strategy' | 'setting' | 'schemaFor' | 'binding' | 'roleCheck'>>> {
|
|
211
235
|
readonly bypassDialect?: Dialect;
|
|
212
236
|
readonly dialectFor?: (tenantId: string) => Dialect;
|
|
@@ -229,6 +253,17 @@ interface Tenancy extends Readonly<Required<Pick<TenancyOptions, 'strategy' | 's
|
|
|
229
253
|
declare class TenantRequiredError extends Error {
|
|
230
254
|
constructor(table: string);
|
|
231
255
|
}
|
|
256
|
+
/**
|
|
257
|
+
* One description of how tenants are separated, shared by the schema
|
|
258
|
+
* (`tenantKey(tenancy)`) and the client (`createDbClient({ tenancy })`).
|
|
259
|
+
*
|
|
260
|
+
* ```ts
|
|
261
|
+
* export const tenancy = defineTenancy({
|
|
262
|
+
* strategy: 'rls',
|
|
263
|
+
* current: () => getRequestValue('tenant')?.id,
|
|
264
|
+
* })
|
|
265
|
+
* ```
|
|
266
|
+
*/
|
|
232
267
|
declare function defineTenancy(options: TenancyOptions): Tenancy;
|
|
233
268
|
/**
|
|
234
269
|
* The tenant column of a tenanted table — what marks it tenanted. Filled
|
|
@@ -247,8 +282,6 @@ declare function defineTenancy(options: TenancyOptions): Tenancy;
|
|
|
247
282
|
* setting. Pass another column to change its type: `tenantKey(tenancy, uuid())`.
|
|
248
283
|
*/
|
|
249
284
|
declare function tenantKey<T = string>(tenancy: Tenancy, column?: ColumnBuilder<T>): ColumnBuilder<T> & NotNullBrand & GeneratedBrand;
|
|
250
|
-
//#endregion
|
|
251
|
-
//#region src/client/register.d.ts
|
|
252
285
|
/**
|
|
253
286
|
* Module-augmentable registry for the typed KickJS-DB surface. Adopters
|
|
254
287
|
* declare:
|
|
@@ -289,8 +322,6 @@ type RegisteredDB = KickDbRegister extends {
|
|
|
289
322
|
} ? D extends {
|
|
290
323
|
qb: import('kysely').Kysely<infer X>;
|
|
291
324
|
} ? X : unknown : unknown;
|
|
292
|
-
//#endregion
|
|
293
|
-
//#region src/query/types.d.ts
|
|
294
325
|
/**
|
|
295
326
|
* Adopter-augmented at typegen time, mirroring `KickDbRegister`. The
|
|
296
327
|
* augmentation slots a record keyed by table name; each value is a
|
|
@@ -517,8 +548,11 @@ interface TableQueryNamespace<DB, Table extends keyof DB & string> {
|
|
|
517
548
|
* without an explicit generic.
|
|
518
549
|
*/
|
|
519
550
|
type QueryNamespace<DB = RegisteredDB> = { [Table in keyof DB & string]: TableQueryNamespace<DB, Table>; };
|
|
520
|
-
|
|
521
|
-
|
|
551
|
+
/**
|
|
552
|
+
* Payload of the `query` event: a query that ran, with its duration.
|
|
553
|
+
*
|
|
554
|
+
* @see https://kickjs.app/guide/database/events-plugins#lifecycle-events
|
|
555
|
+
*/
|
|
522
556
|
interface QueryEvent {
|
|
523
557
|
sql: string;
|
|
524
558
|
parameters: readonly unknown[];
|
|
@@ -528,6 +562,11 @@ interface QueryEvent {
|
|
|
528
562
|
/** The transaction it ran in, when it ran in one (a savepoint shares its transaction's). */
|
|
529
563
|
txId?: string;
|
|
530
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* Payload of the `queryError` event: a query that failed.
|
|
567
|
+
*
|
|
568
|
+
* @see https://kickjs.app/guide/database/events-plugins#lifecycle-events
|
|
569
|
+
*/
|
|
531
570
|
interface QueryErrorEvent {
|
|
532
571
|
sql: string;
|
|
533
572
|
parameters: readonly unknown[];
|
|
@@ -537,6 +576,12 @@ interface QueryErrorEvent {
|
|
|
537
576
|
/** The transaction it ran in, when it ran in one (a savepoint shares its transaction's). */
|
|
538
577
|
txId?: string;
|
|
539
578
|
}
|
|
579
|
+
/**
|
|
580
|
+
* Payload of the `beforeQuery` event, fired before a query runs; listeners may
|
|
581
|
+
* rewrite `sql` and `parameters`.
|
|
582
|
+
*
|
|
583
|
+
* @see https://kickjs.app/guide/database/events-plugins#lifecycle-events
|
|
584
|
+
*/
|
|
540
585
|
interface BeforeQueryEvent {
|
|
541
586
|
/** Mutable — listeners may rewrite sql / parameters before execution. */
|
|
542
587
|
sql: string;
|
|
@@ -544,9 +589,11 @@ interface BeforeQueryEvent {
|
|
|
544
589
|
/** Kysely's id for this query, as `query` / `queryError` report it. Absent for statements kick/db sends itself. */
|
|
545
590
|
readonly queryId?: string;
|
|
546
591
|
}
|
|
592
|
+
/** Payload of the `transactionStart` and `transactionCommit` events. */
|
|
547
593
|
interface TransactionEvent {
|
|
548
594
|
isolation?: 'serializable' | 'repeatable read' | 'read committed' | 'read uncommitted';
|
|
549
595
|
}
|
|
596
|
+
/** Payload of the `transactionRollback` event: the error that rolled it back. */
|
|
550
597
|
interface TransactionRollbackEvent extends TransactionEvent {
|
|
551
598
|
error: unknown;
|
|
552
599
|
}
|
|
@@ -558,13 +605,13 @@ interface TransactionRetryEvent extends TransactionEvent {
|
|
|
558
605
|
error: unknown;
|
|
559
606
|
delayMs: number;
|
|
560
607
|
}
|
|
561
|
-
/** Options for `transaction(opts, fn)`. */
|
|
562
608
|
/** A transaction from `startTransaction()`: a client, and the way to finish it. */
|
|
563
609
|
type ManualTransaction<DB> = KickDbClient<DB> & {
|
|
564
610
|
/** Commit, then run its `afterCommit` hooks. */
|
|
565
611
|
commit(): Promise<void>;
|
|
566
612
|
rollback(): Promise<void>;
|
|
567
613
|
};
|
|
614
|
+
/** Options for `transaction(opts, fn)`. */
|
|
568
615
|
interface TransactionOptions extends TransactionEvent {
|
|
569
616
|
/**
|
|
570
617
|
* What to do when a transaction is already open on this call chain:
|
|
@@ -634,7 +681,18 @@ interface ReadRoute {
|
|
|
634
681
|
/** How many replicas there are: valid indexes are `0` to `replicas - 1`. */
|
|
635
682
|
replicas: number;
|
|
636
683
|
}
|
|
684
|
+
/**
|
|
685
|
+
* Picks where a read outside a transaction goes: `'primary'`, a replica's
|
|
686
|
+
* index, or `undefined` for the default (replicas in turn).
|
|
687
|
+
*
|
|
688
|
+
* @see https://kickjs.app/guide/database/pooling#read-replicas
|
|
689
|
+
*/
|
|
637
690
|
type ReadRouter = (read: ReadRoute) => 'primary' | number | undefined;
|
|
691
|
+
/**
|
|
692
|
+
* The client's lifecycle events by name, with their payloads: what `db.on(name, fn)` takes.
|
|
693
|
+
*
|
|
694
|
+
* @see https://kickjs.app/guide/database/events-plugins#lifecycle-events
|
|
695
|
+
*/
|
|
638
696
|
interface KickDbClientEvents {
|
|
639
697
|
beforeQuery: BeforeQueryEvent;
|
|
640
698
|
query: QueryEvent;
|
|
@@ -826,6 +884,11 @@ interface KickDbClient<DB = RegisteredDB> {
|
|
|
826
884
|
$extends<E extends ExtensionDefinition<DB>>(ext: E): ExtendedClient<DB, E>;
|
|
827
885
|
destroy(): Promise<void>;
|
|
828
886
|
}
|
|
887
|
+
/**
|
|
888
|
+
* Options for `createDbClient()`.
|
|
889
|
+
*
|
|
890
|
+
* @see https://kickjs.app/guide/database/
|
|
891
|
+
*/
|
|
829
892
|
interface CreateDbClientOptions<TSchema, _DB = unknown> {
|
|
830
893
|
/** Schema record — only used for type inference (M2-S1 tightens). */
|
|
831
894
|
schema: TSchema;
|
|
@@ -953,6 +1016,5 @@ interface CreateDbClientOptions<TSchema, _DB = unknown> {
|
|
|
953
1016
|
*/
|
|
954
1017
|
casing?: 'snake_case';
|
|
955
1018
|
}
|
|
956
|
-
//#endregion
|
|
957
1019
|
export { TenancyStrategy as A, WithClause as C, BypassOptions as D, BypassInfo as E, ExtensionDefinition as F, ModelExtensions as I, FindOrCreateOptions as L, defineTenancy as M, tenantKey as N, Tenancy as O, ExtendedClient as P, UpsertOptions as R, TableRelations as S, RegisteredDB as T, KickDbRelationsRegister as _, ManualTransaction as a, RelationMapEntry as b, ReadRoute as c, TransactionEvent as d, TransactionOptions as f, FindManyRow as g, FindManyOptions as h, KickDbClientEvents as i, TenantRequiredError as j, TenancyOptions as k, ReadRouter as l, TransactionRollbackEvent as m, CreateDbClientOptions as n, QueryErrorEvent as o, TransactionRetryEvent as p, KickDbClient as r, QueryEvent as s, BeforeQueryEvent as t, SlowQueryEvent as u, QueryNamespace as v, KickDbRegister as w, TableQueryNamespace as x, RegisteredRelations as y, InsertManyOptions as z };
|
|
958
|
-
//# sourceMappingURL=types-
|
|
1020
|
+
//# sourceMappingURL=types-Bmbj69hY.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-Bmbj69hY.d.mts","names":["_$__upsert0.UpsertOptions","_$__insert_many0.InsertManyOptions","_$__upsert0.FindOrCreateOptions","_$___extend_types0.ExtensionDefinition","_$___extend_types0.ExtendedClient","KyselyDialect","_$___tenancy0.Tenancy"],"sources":["../src/client/insert-many.ts","../src/client/upsert.ts","../src/extend/types.ts","../src/tenancy.ts","../src/client/register.ts","../src/query/types.ts","../src/client/types.ts"],"mappings":";;;;UAkBiB;;;;;EAKf;;;;;;EAMA;;;;;;;UCLe,cAAc,IAAI,gBAAgB,qBAAqB;;;;;EAKtE,QAAQ,WAAW,GAAG,MAAM,cAAc,WAAW,GAAG;;;;;;EAMxD,QAAQ,oBAAoB,GAAG;;;;;;;;EAQ/B,SAAS,oBAAoB,GAAG,eAAe,aAAa,IAAI;;;;;;EAMhE,SAAS,IAAI,kBAAkB,IAAI,OAAO,WAAW;;;KAIlD,YAAY,QAAQ,WAAW,iBAAiB,KAAK,GAAG,aAAa,WAAU;;KAG/E,WAAW,IAAI,gBAAgB,IAAI,KAAK,KAAK,WAAW,GAAG,KAAK,YAAY,MAC/E,QAAQ,WAAW,GAAG;;;;;;KAOZ,oBACV,IACA,gBAAgB,aAChB,UAAU,QAAQ,WAAW,GAAG,OAAO,QAAQ,WAAW,GAAG;;EAG7D,OAAO,IAAI,OAAO,cAAc,SAAS,WAAW,GAAG;gBACzC,WAAW,IAAI,GAAG;EAE5B,SAAS,WAAW,IAAI,GAAG;;EAC3B,QAAQ,WAAW,IAAI,GAAG;;;;;;;;;KC/BpB,gBAAgB,SACzB,eAAe,eAAe,mBAAmB;;;;;;;UASnC,gBAAgB;;EAE/B,O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G7E;;;;;WAMA,SAAS,aAAa;;;;;;;;;;;;;;;;;;;;;;;;EAyB/B,SAAS,UAAwDC,oBAAA,KAC/D,KAAK,IACyCC,eAAJ,IAAI;EAEhD,WAAW;;;;;;;UAQI,sBAAsB,SAAS;;EAE9C,QAAQ;;;;;EAKR,SAASC;;;;;;EAMT;;;;;EAKA,UAXSC;;;;;;;EAkBT,UAAUD,mBAAyBA;;;;;;;;;;;EAWnC,QAAQ;;;;;;;EAOR;;;;;;;EAOA;;;;;;;EAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4BA,iDAAiD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkCjD,UAAU;;;;;;EAMV"}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
|
|
2
|
-
|
|
2
|
+
/** The SQL dialect a schema snapshot is written for. */
|
|
3
3
|
type Dialect = 'postgres' | 'sqlite' | 'mysql';
|
|
4
4
|
/** The foreign-key actions, in the snapshot's spelling. */
|
|
5
5
|
declare const FK_ACTION_NAMES: readonly ['cascade', 'restrict', 'set_null', 'set_default', 'no_action'];
|
|
6
|
+
/** A foreign key's `ON DELETE` / `ON UPDATE` action, in the snapshot's spelling. */
|
|
6
7
|
type FkAction = (typeof FK_ACTION_NAMES)[number];
|
|
8
|
+
/** A column in a schema snapshot. */
|
|
7
9
|
interface ColumnSnapshot {
|
|
8
10
|
name: string;
|
|
9
11
|
type: string;
|
|
@@ -33,6 +35,7 @@ interface ColumnSnapshot {
|
|
|
33
35
|
*/
|
|
34
36
|
colName?: string;
|
|
35
37
|
}
|
|
38
|
+
/** An index in a schema snapshot. */
|
|
36
39
|
interface IndexSnapshot {
|
|
37
40
|
name: string;
|
|
38
41
|
/** Key parts in order: a column name, or an SQL expression wrapped in parentheses. */
|
|
@@ -49,6 +52,7 @@ interface IndexSnapshot {
|
|
|
49
52
|
/** Build and drop without locking writes (Postgres). Doesn't change the index itself. */
|
|
50
53
|
concurrently?: boolean;
|
|
51
54
|
}
|
|
55
|
+
/** A foreign-key constraint in a schema snapshot. */
|
|
52
56
|
interface ForeignKeySnapshot {
|
|
53
57
|
name: string;
|
|
54
58
|
columns: string[];
|
|
@@ -57,10 +61,12 @@ interface ForeignKeySnapshot {
|
|
|
57
61
|
onDelete: FkAction;
|
|
58
62
|
onUpdate: FkAction;
|
|
59
63
|
}
|
|
64
|
+
/** A `CHECK` constraint in a schema snapshot: its name and SQL expression. */
|
|
60
65
|
interface CheckSnapshot {
|
|
61
66
|
name: string;
|
|
62
67
|
expression: string;
|
|
63
68
|
}
|
|
69
|
+
/** A table in a schema snapshot: columns, indexes, constraints, comment and row-level security. */
|
|
64
70
|
interface TableSnapshot {
|
|
65
71
|
/**
|
|
66
72
|
* Bare table name, unqualified. The schema (when any) lives in
|
|
@@ -197,6 +203,12 @@ interface ViewSnapshot {
|
|
|
197
203
|
*/
|
|
198
204
|
columns?: Record<string, ColumnSnapshot>;
|
|
199
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* A JSON-serializable description of a whole schema. `diff()` compares two of
|
|
208
|
+
* them, and each migration stores the one it leaves the database in (`snapshot.json`).
|
|
209
|
+
*
|
|
210
|
+
* @see https://kickjs.app/guide/database/concepts
|
|
211
|
+
*/
|
|
200
212
|
interface SchemaSnapshot {
|
|
201
213
|
version: 1;
|
|
202
214
|
dialect: Dialect;
|
|
@@ -231,8 +243,6 @@ interface SchemaSnapshot {
|
|
|
231
243
|
*/
|
|
232
244
|
relations?: Record<string, Record<string, RelationSnapshot>>;
|
|
233
245
|
}
|
|
234
|
-
//#endregion
|
|
235
|
-
//#region src/dsl/columns/types.d.ts
|
|
236
246
|
/**
|
|
237
247
|
* Runtime + type representation of a column reference (e.g. `users.id`).
|
|
238
248
|
* Carries the parent table name, the column's own name, plus runtime
|
|
@@ -297,6 +307,9 @@ type ValueOf<B> = B extends ColumnBuilder<infer T> ? T : never;
|
|
|
297
307
|
* type this column can hold. A failing column reads as the reason.
|
|
298
308
|
*/
|
|
299
309
|
type CheckSelfRefs<C> = { [P in keyof C]: [SelfRefTarget<C[P]>] extends [never] ? C[P] : SelfRefTarget<C[P]> extends keyof C ? [ValueOf<C[SelfRefTarget<C[P]>]>] extends [ValueOf<C[P]>] ? C[P] : `selfRef('${SelfRefTarget<C[P]>}'): that column's type doesn't match this one` : `selfRef('${SelfRefTarget<C[P]>}'): this table has no such column`; };
|
|
310
|
+
/**
|
|
311
|
+
* A column's foreign key, from `.references()`: the referenced column (as a thunk) and the actions.
|
|
312
|
+
*/
|
|
300
313
|
interface FkSpec {
|
|
301
314
|
thunk: () => ColumnRef;
|
|
302
315
|
onDelete: FkAction;
|
|
@@ -313,6 +326,9 @@ interface FkSpec {
|
|
|
313
326
|
*/
|
|
314
327
|
name?: string;
|
|
315
328
|
}
|
|
329
|
+
/**
|
|
330
|
+
* What a column builder records about its column: type, nullability, default, keys and the rest.
|
|
331
|
+
*/
|
|
316
332
|
interface ColumnState {
|
|
317
333
|
type: string;
|
|
318
334
|
nullable: boolean;
|
|
@@ -364,6 +380,7 @@ interface ColumnState {
|
|
|
364
380
|
* Runtime is a no-op — the symbol never reaches a value.
|
|
365
381
|
*/
|
|
366
382
|
declare const KICK_GENERATED: unique symbol;
|
|
383
|
+
/** Type-only marker for a column that can be omitted on insert. See `KICK_GENERATED`. */
|
|
367
384
|
type GeneratedBrand = {
|
|
368
385
|
readonly [KICK_GENERATED]?: true;
|
|
369
386
|
};
|
|
@@ -388,6 +405,7 @@ type GeneratedAlwaysBrand = {
|
|
|
388
405
|
* `<TNullable>` would collapse the subclass back to the parent.
|
|
389
406
|
*/
|
|
390
407
|
declare const KICK_NOT_NULL: unique symbol;
|
|
408
|
+
/** Type-only marker for a `NOT NULL` column. See `KICK_NOT_NULL`. */
|
|
391
409
|
type NotNullBrand = {
|
|
392
410
|
readonly [KICK_NOT_NULL]?: true;
|
|
393
411
|
};
|
|
@@ -554,6 +572,5 @@ declare class ColumnBuilder<T = unknown> {
|
|
|
554
572
|
toJSON(name: string): ColumnSnapshot;
|
|
555
573
|
__state(): Readonly<ColumnState>;
|
|
556
574
|
}
|
|
557
|
-
//#endregion
|
|
558
575
|
export { RelationSnapshot as C, ViewSnapshot as D, TableSnapshot as E, PolicySnapshot as S, SchemaSnapshot as T, Dialect as _, FkSpec as a, ForeignKeySnapshot as b, KICK_GENERATED as c, SelfRef as d, SelfRefTo as f, ColumnSnapshot as g, CheckSnapshot as h, ColumnState as i, KICK_NOT_NULL as l, TypedColumnRefs as m, ColumnBuilder as n, GeneratedAlwaysBrand as o, TypedColumnRef as p, ColumnRef as r, GeneratedBrand as s, CheckSelfRefs as t, NotNullBrand as u, EnumSnapshot as v, RoleSnapshot as w, IndexSnapshot as x, FkAction as y };
|
|
559
|
-
//# sourceMappingURL=types-
|
|
576
|
+
//# sourceMappingURL=types-D4x2u-EZ.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-D4x2u-EZ.d.mts","names":[],"sources":["../src/snapshot/types.ts","../src/dsl/columns/types.ts"],"mappings":";;KACY;;cAGC;;KAQD,mBAAmB;;UAGd;EACf;EACA;EACA;EACA;;EAEA;;;;;;EAMA;EACA;;EAEA;IAAc;IAAoB;;;EAElC;;EAEA;;;;;EAKA;;;UAIe;EACf;;EAEA;EACA;;EAEA;;EAEA;;EAEA;;EAEA,YAAY;;EAEZ;;;UAIe;EACf;EACA;EACA;EACA;EACA,UAAU;EACV,UAAU;;;UAIK;EACf;EACA;;;UAIe;;;;;;EAMf;;;;;;EAMA;EACA,SAAS,eAAe;EACxB,SAAS;EACT,aAAa;EACb,QAAQ;;;;;;;EAOR;IAAe;IAAe;;;EAE9B;;EAEA;IAAQ;;;EAER,WAAW;;;;;;;UAQI;EACf;;EAEA;;;;;;;;;;;;;;UAee;EACf;;EAEA;;EAEA;;EAEA;;;;;EAKA;;;;;EAKA;IAAY;IAAe;IAAkC;;;;;;EAK7D;IAAU;IAAgB;;;;;;;EAM1B;IACE;IACA,SAAS;MAAgB;MAAe;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AC5B,aAAa,iBAAiB,6BAC9B,aAAa,uBAAuB,mCACpC,aAAa,gBAAgB,KAAK,UAAU;;;;;;;;;;cAWlC,cAAc;WAGR,MAAM;YAEb,OAAO;EAEjB,YAAY,cAAc,WAAU,QAAQ;;;;;;;EAkB5C,kBAAkB;;;;;;;;EAYlB,qBAAqB;;;;;;;;EAarB;;;;;;;EAWA,SAAS,qBAAqB,cAAc;;;;;;;;;;;;EAgB5C,WACE,cAAc,WACd;IAAQ,WAAW;IAAU,WAAW;IAAU;;;;;;;;;;;;;;;;;EA4CpD,QAAQ,mCAAmC,WAAW;;;;;;;;EAsBtD,WAAW,4BAA4B;;;;;;;EAYvC,WAAW,UAAU,WAAW;;;;;;EAUhC,UAAU,UAAU;;;;;;;;;EAapB;;;;;;;;;;;;;;;EAmBA;;;;;;;;EAYA,kBACE,oBACA;IAAW;aACH;;;;;EASV,oCAAoC,eAAe;;EAOnD,uCAAuC,eAAe;;;;;EAUtD,QAAQ;;;;;;EAUR,QAAQ;;EAMR,aAAa;EAIb,OAAO,eAAe;EAgBtB,WAAW,SAAS"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forinda/kickjs-db",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.13.0",
|
|
4
4
|
"description": "KickJS-native ORM — code-first schema, reversible migrations, multi-dialect SQL builder",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kickjs",
|
|
@@ -66,10 +66,10 @@
|
|
|
66
66
|
"bin"
|
|
67
67
|
],
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"commander": "^15.
|
|
69
|
+
"commander": "^15.1.0",
|
|
70
70
|
"jiti": "^2.7.0",
|
|
71
|
-
"kysely": "0.29.
|
|
72
|
-
"@forinda/kickjs-cli-kit": "0.1.
|
|
71
|
+
"kysely": "0.29.9",
|
|
72
|
+
"@forinda/kickjs-cli-kit": "0.1.4"
|
|
73
73
|
},
|
|
74
74
|
"peerDependencies": {
|
|
75
75
|
"@electric-sql/pglite": ">=0.5.5",
|
|
@@ -97,25 +97,25 @@
|
|
|
97
97
|
}
|
|
98
98
|
},
|
|
99
99
|
"devDependencies": {
|
|
100
|
-
"@electric-sql/pglite": "0.5.
|
|
100
|
+
"@electric-sql/pglite": "0.5.16",
|
|
101
101
|
"@libsql/client": "^0.18.0",
|
|
102
102
|
"@libsql/kysely-libsql": "^0.4.1",
|
|
103
103
|
"@testcontainers/mysql": "^12.2.1",
|
|
104
104
|
"@testcontainers/postgresql": "^12.2.1",
|
|
105
105
|
"@types/better-sqlite3": "^9.6.0",
|
|
106
|
-
"@types/node": "^26.6.
|
|
106
|
+
"@types/node": "^26.6.6",
|
|
107
107
|
"@types/pg": "^8.23.1",
|
|
108
|
-
"better-sqlite3": "^13.
|
|
109
|
-
"kysely": "^0.29.
|
|
108
|
+
"better-sqlite3": "^13.1.1",
|
|
109
|
+
"kysely": "^0.29.9",
|
|
110
110
|
"kysely-d1": "^0.4.0",
|
|
111
111
|
"miniflare": "^4.20260730.0",
|
|
112
112
|
"mysql2": "^3.24.6",
|
|
113
113
|
"pg": "^8.23.1",
|
|
114
114
|
"pg-cursor": "^2.22.1",
|
|
115
115
|
"typescript": "^7.0.2",
|
|
116
|
-
"@forinda/kickjs": "10.
|
|
117
|
-
"@forinda/kickjs-devtools-kit": "7.3.
|
|
118
|
-
"@forinda/kickjs-schema": "0.2.
|
|
116
|
+
"@forinda/kickjs": "10.15.0",
|
|
117
|
+
"@forinda/kickjs-devtools-kit": "7.3.1",
|
|
118
|
+
"@forinda/kickjs-schema": "0.2.5"
|
|
119
119
|
},
|
|
120
120
|
"publishConfig": {
|
|
121
121
|
"access": "public"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"adapter-cVrkWrul.d.mts","names":[],"sources":["../src/adapters/pg/adapter.ts"],"mappings":";;;;;;;UAsBiB;EACf,MAAM,aACJ,aACA,8BACC;IAAU,MAAM;IAAK;;EACxB;;;;;;;;;;;;;UAce;EACf,MAAM,aACJ,aACA,8BACC;IAAU,MAAM;IAAK;;EACxB,WAAW,QAAQ;EACnB,QAAQ;;UAGO;;;;;;EAMf;;;;;EAKA,MAAM;;EAEN;;;;;;;EAOA;;;;;;;;;;;;iBAec,UAAU,MAAM,mBAAmB"}
|