@forinda/kickjs-db 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +16 -45
  2. package/dist/cli.d.mts +16 -2
  3. package/dist/cli.d.mts.map +1 -1
  4. package/dist/cli.mjs +4 -3
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/create-CwuC1odW.mjs +29 -0
  7. package/dist/create-CwuC1odW.mjs.map +1 -0
  8. package/dist/custom-type-DeGuRFuz.mjs +12 -0
  9. package/dist/custom-type-DeGuRFuz.mjs.map +1 -0
  10. package/dist/devtools-events.d.mts +1 -1
  11. package/dist/devtools-events.mjs +1 -1
  12. package/dist/{index-BQQWKybR.d.mts → index-2fEnHqpn.d.mts} +702 -167
  13. package/dist/index-2fEnHqpn.d.mts.map +1 -0
  14. package/dist/index.d.mts +6 -4
  15. package/dist/index.mjs +2 -2
  16. package/dist/mysql.d.mts +41 -37
  17. package/dist/mysql.d.mts.map +1 -1
  18. package/dist/mysql.mjs +8 -8
  19. package/dist/mysql.mjs.map +1 -1
  20. package/dist/pg-CsmRByEZ.mjs +12 -0
  21. package/dist/pg-CsmRByEZ.mjs.map +1 -0
  22. package/dist/pg.d.mts +74 -8
  23. package/dist/pg.d.mts.map +1 -1
  24. package/dist/pg.mjs +8 -7
  25. package/dist/pg.mjs.map +1 -1
  26. package/dist/schema-BjGAg-s1.d.mts +95 -0
  27. package/dist/schema-BjGAg-s1.d.mts.map +1 -0
  28. package/dist/schema-types-DH-d43Pf.d.mts +51 -0
  29. package/dist/schema-types-DH-d43Pf.d.mts.map +1 -0
  30. package/dist/schema.d.mts +1 -1
  31. package/dist/schema.mjs +2 -2
  32. package/dist/schema.mjs.map +1 -1
  33. package/dist/split-statements-BPCw9cII.mjs +14 -0
  34. package/dist/split-statements-BPCw9cII.mjs.map +1 -0
  35. package/dist/sqlite.d.mts +86 -6
  36. package/dist/sqlite.d.mts.map +1 -1
  37. package/dist/sqlite.mjs +13 -7
  38. package/dist/sqlite.mjs.map +1 -1
  39. package/dist/src-DUtVGG2c.mjs +199 -0
  40. package/dist/src-DUtVGG2c.mjs.map +1 -0
  41. package/dist/table-CGPsm5i7.d.mts +221 -0
  42. package/dist/table-CGPsm5i7.d.mts.map +1 -0
  43. package/dist/testing.d.mts +53 -0
  44. package/dist/testing.d.mts.map +1 -0
  45. package/dist/testing.mjs +12 -0
  46. package/dist/testing.mjs.map +1 -0
  47. package/dist/{types-DtvYnaXL.d.mts → types-BZoTujcR.d.mts} +346 -9
  48. package/dist/types-BZoTujcR.d.mts.map +1 -0
  49. package/dist/{schema-DDMkteEP.d.mts → types-DNAKmwPO.d.mts} +174 -159
  50. package/dist/types-DNAKmwPO.d.mts.map +1 -0
  51. package/package.json +15 -5
  52. package/dist/custom-type-CZdUgkPT.mjs +0 -12
  53. package/dist/custom-type-CZdUgkPT.mjs.map +0 -1
  54. package/dist/index-BQQWKybR.d.mts.map +0 -1
  55. package/dist/pg-CwNv938J.mjs +0 -12
  56. package/dist/pg-CwNv938J.mjs.map +0 -1
  57. package/dist/schema-DDMkteEP.d.mts.map +0 -1
  58. package/dist/src-BEJ33yHI.mjs +0 -166
  59. package/dist/src-BEJ33yHI.mjs.map +0 -1
  60. package/dist/types-DtvYnaXL.d.mts.map +0 -1
@@ -0,0 +1,221 @@
1
+
2
+ import { d as TypedColumnRefs, t as ColumnBuilder, v as IndexSnapshot, x as RoleSnapshot, y as PolicySnapshot } from "./types-DNAKmwPO.mjs";
3
+ //#region src/dsl/rls.d.ts
4
+ /** A database role, for `policy().to(...)` — created by migrations unless `.existing()`. */
5
+ declare class RoleDecl {
6
+ readonly __isRole = true;
7
+ readonly __role: RoleSnapshot;
8
+ /** Managed outside these migrations: referenced by policies, never created. */
9
+ __existing: boolean;
10
+ constructor(name: string, options?: Omit<RoleSnapshot, 'name'>);
11
+ /** The role already exists (created by your DBA or another app): never create it. */
12
+ existing(): this;
13
+ }
14
+ /**
15
+ * A Postgres role, declared with the schema:
16
+ * `export const appUser = pgRole('app_user', { login: true })`.
17
+ *
18
+ * Roles belong to the whole server, not one database, so migrations create
19
+ * one only if it's missing and never drop it — remove it yourself when no
20
+ * database uses it. Passwords stay out of the schema: set them with
21
+ * `ALTER ROLE … PASSWORD` outside migrations.
22
+ */
23
+ declare function pgRole(name: string, options?: Omit<RoleSnapshot, 'name'>): RoleDecl;
24
+ declare function isRole(value: unknown): value is RoleDecl;
25
+ type Command = PolicySnapshot['command'];
26
+ /** A row-level security policy, returned from a table's constraints. */
27
+ declare class PolicyDecl {
28
+ readonly kind = "policy";
29
+ readonly __policy: PolicySnapshot;
30
+ constructor(name: string);
31
+ /** Which statements it applies to. Default `'all'`. */
32
+ for(command: Command): this;
33
+ /** The roles it applies to, by name or `pgRole()`. Default `public` (everyone). */
34
+ to(...roles: Array<string | RoleDecl>): this;
35
+ /**
36
+ * `'permissive'` (default): a row passes if any permissive policy allows it.
37
+ * `'restrictive'`: every restrictive policy must allow it as well.
38
+ */
39
+ as(kind: 'permissive' | 'restrictive'): this;
40
+ /** Which existing rows are visible / updatable / deletable — a SQL boolean expression. */
41
+ using(expression: string): this;
42
+ /** Which new rows may be written (insert, update) — a SQL boolean expression. */
43
+ withCheck(expression: string): this;
44
+ }
45
+ /**
46
+ * A row-level security policy (Postgres):
47
+ *
48
+ * ```ts
49
+ * table('docs', columns, {
50
+ * constraints: (t) => ({
51
+ * ownDocs: policy('docs_owner')
52
+ * .to(appUser)
53
+ * .using(`owner_id = current_setting('app.user_id')::int`),
54
+ * }),
55
+ * })
56
+ * ```
57
+ *
58
+ * A table with a policy has row-level security turned on.
59
+ */
60
+ declare function policy(name: string): PolicyDecl;
61
+ //#endregion
62
+ //#region src/dsl/constraints.d.ts
63
+ interface ColRef {
64
+ __name: string;
65
+ }
66
+ /** An index key part: a column, or an SQL expression such as `'lower(email)'`. */
67
+ type IndexKey = ColRef | string;
68
+ /**
69
+ * An index declared in a table's constraint builder. Chain the options;
70
+ * each returns the same declaration:
71
+ *
72
+ * index('users_active_email').on(t.email).where('"deletedAt" IS NULL')
73
+ * index('users_email_lower').on('lower(email)')
74
+ * index('docs_embedding').on(t.embedding).using('hnsw').op(t.embedding, 'vector_cosine_ops')
75
+ * index('orders_customer').on(t.customerId).include(t.total).concurrently()
76
+ */
77
+ declare class IndexDecl {
78
+ /** The index as recorded in the snapshot. */
79
+ readonly __index: IndexSnapshot;
80
+ constructor(name: string, keys: IndexKey[], unique: boolean);
81
+ /** Make it a partial index over the rows matching `predicate` (Postgres, SQLite). */
82
+ where(predicate: string): this;
83
+ /** The index method: `gin`, `gist`, `brin`, `hash`, `hnsw`, `ivfflat` … (MySQL: `btree` / `hash`). */
84
+ using(method: string): this;
85
+ /** Store these columns in the index without making them part of the key (Postgres). */
86
+ include(...cols: ColRef[]): this;
87
+ /** The operator class for one key part, e.g. `vector_cosine_ops` or `gin_trgm_ops` (Postgres). */
88
+ op(key: IndexKey, opclass: string): this;
89
+ /**
90
+ * Build and drop it with `CONCURRENTLY`, without blocking writes (Postgres).
91
+ * `kick db generate` puts each such change in a migration of its own that
92
+ * runs outside a transaction, as `CONCURRENTLY` requires.
93
+ */
94
+ concurrently(): this;
95
+ }
96
+ declare function index(name: string): {
97
+ on(...keys: IndexKey[]): IndexDecl;
98
+ };
99
+ declare function unique(name: string): {
100
+ on(...keys: IndexKey[]): IndexDecl;
101
+ };
102
+ /** A table's primary key, declared on its own — required for a composite or named key. */
103
+ interface PrimaryKeyDecl {
104
+ kind: 'primaryKey';
105
+ /** Constraint name; Postgres otherwise names it `<table>_pkey`. MySQL and SQLite ignore it. */
106
+ name?: string;
107
+ columns: string[];
108
+ }
109
+ /** A CHECK constraint. */
110
+ interface CheckDecl {
111
+ kind: 'check';
112
+ name: string;
113
+ /** SQL boolean expression, written for the target dialect. */
114
+ expression: string;
115
+ }
116
+ /** Anything a table's constraint builder may return. */
117
+ type TableConstraint = IndexDecl | PrimaryKeyDecl | CheckDecl | PolicyDecl;
118
+ /**
119
+ * The table's primary key, over one or more columns, in key order:
120
+ *
121
+ * table('memberships', { teamId: integer(), userId: integer() }, (t) => ({
122
+ * pk: primaryKey('memberships_pk').on(t.teamId, t.userId),
123
+ * }))
124
+ *
125
+ * Use this or a column's `.primaryKey()`, not both.
126
+ */
127
+ declare function primaryKey(name?: string): {
128
+ on(...cols: ColRef[]): PrimaryKeyDecl;
129
+ };
130
+ /**
131
+ * A CHECK constraint — `check('price_positive', 'price > 0')`. The
132
+ * expression is SQL, passed through as written.
133
+ */
134
+ declare function check(name: string, expression: string): CheckDecl;
135
+ //#endregion
136
+ //#region src/dsl/table.d.ts
137
+ interface TableDecl<TName extends string = string, C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>, TSchema extends string | undefined = string | undefined> {
138
+ __isTable: true;
139
+ __name: TName;
140
+ __columns: C;
141
+ __indexes: IndexSnapshot[];
142
+ /** Declared with `primaryKey(...)` — absent when columns carry `.primaryKey()`. */
143
+ __primaryKey?: PrimaryKeyDecl;
144
+ __checks?: CheckDecl[];
145
+ /** `table(name, columns, { comment })`: stored in the database (Postgres, MySQL). */
146
+ __comment?: string;
147
+ /** `table(name, columns, { rls })`, or set by declaring a policy (Postgres). */
148
+ __rls?: {
149
+ force?: true;
150
+ };
151
+ __policies?: PolicySnapshot[];
152
+ /**
153
+ * Named SQL schema this table lives in, from `pgSchema('x').table(...)`.
154
+ * `undefined` means the connection's default search_path (`public` on PG),
155
+ * which is every table declared through the bare `table()` factory.
156
+ *
157
+ * PostgreSQL only — `assertSchemasSupported()` rejects a declared schema
158
+ * on MySQL/SQLite at snapshot time rather than emitting subtly wrong DDL.
159
+ */
160
+ __schema?: TSchema;
161
+ /**
162
+ * Validation rules a table form declared (`@Rule`, `rules`, `.column(k, b, rule)`),
163
+ * applied by `insertSchema` / `selectSchema` / `updateSchema`. Not enumerable.
164
+ */
165
+ readonly __rules?: Readonly<Record<string, unknown>>;
166
+ }
167
+ /**
168
+ * Fully-qualified name used as the snapshot key, the Kysely table key, and
169
+ * the emitted identifier. `quoteIdent` splits on `.`, so `billing.invoices`
170
+ * renders as `"billing"."invoices"` with no further work.
171
+ *
172
+ * Unqualified tables keep their bare name, so every pre-schema snapshot,
173
+ * migration hash, and `KickDbSchema` key is byte-identical to before.
174
+ */
175
+ type QualifiedName<TName extends string, TSchema extends string | undefined> = TSchema extends string ? `${TSchema}.${TName}` : TName;
176
+ /** Runtime counterpart of {@link QualifiedName}. */
177
+ declare function qualifiedTableName(decl: {
178
+ __name: string;
179
+ __schema?: string | undefined;
180
+ }): string;
181
+ type TableRefs<TName extends string, C extends Record<string, ColumnBuilder>, TSchema extends string | undefined = undefined> = TableDecl<TName, C, TSchema> & TypedColumnRefs<C>;
182
+ type ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: TypedColumnRefs<C>) => Record<string, TableConstraint>;
183
+ /**
184
+ * `table()`'s third argument: the constraints callback, or options holding it
185
+ * and the table's comment — `table('users', columns, { comment: 'People who sign in' })`.
186
+ */
187
+ type TableOptions<C extends Record<string, ColumnBuilder>> = ConstraintBuilder<C> | {
188
+ constraints?: ConstraintBuilder<C>;
189
+ comment?: string;
190
+ /**
191
+ * Turn on row-level security (Postgres) — implied by declaring a
192
+ * policy. `{ force: true }` applies it to the table's owner too, which
193
+ * is usually the account the app connects as. With it on and no
194
+ * policy, no row is visible.
195
+ */
196
+ rls?: boolean | {
197
+ force?: boolean;
198
+ };
199
+ };
200
+ /**
201
+ * Declare a typed table. The `TName extends string` generic narrows to the
202
+ * literal table name so `SchemaToTypes<S>` can index by it without losing
203
+ * the constant — `table('users', …)` widens to `TableDecl<'users', …>`,
204
+ * not `TableDecl<string, …>`.
205
+ */
206
+ declare function table<TName extends string, C extends Record<string, ColumnBuilder>>(name: TName, columns: C, options?: TableOptions<C>): TableRefs<TName, C>;
207
+ /**
208
+ * Shared table constructor. `table()` passes `schema: undefined`;
209
+ * `pgSchema('x').table()` passes the schema name through.
210
+ */
211
+ declare function buildTable<TName extends string, C extends Record<string, ColumnBuilder>, TSchema extends string | undefined>(name: TName, declared: C, options: TableOptions<C> | undefined, schema: TSchema): TableRefs<TName, C, TSchema>;
212
+ /**
213
+ * The table a schema-barrel export stands for: a table itself, or a class
214
+ * form carrying one as `static table` (`class User extends TableBase(...)`).
215
+ * Everything that scans a schema for tables goes through this, so exporting
216
+ * the class is enough — no separate `export const users = User.table`.
217
+ */
218
+ declare function unwrapTable(value: unknown): TableDecl | undefined;
219
+ //#endregion
220
+ 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 };
221
+ //# sourceMappingURL=table-CGPsm5i7.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"table-CGPsm5i7.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;;iBAMc,MAAM;EAElB,MAAE,MAAU,aAAa;;iBAMb,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;;;UCxHxC,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,GACT,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"}
@@ -0,0 +1,53 @@
1
+
2
+ import { r as KickDbClient } from "./types-BZoTujcR.mjs";
3
+ import { t as SchemaToTypes } from "./schema-types-DH-d43Pf.mjs";
4
+ //#region src/testing.d.ts
5
+ export interface TestDbOptions<S> {
6
+ schema: S;
7
+ /**
8
+ * Apply these migrations instead of creating tables straight from the
9
+ * schema — the SQL production runs. Unreviewed ones apply too.
10
+ */
11
+ migrationsDir?: string;
12
+ /** The `casing` your client and `kick.config.ts` use. */
13
+ casing?: 'snake_case';
14
+ }
15
+ /**
16
+ * A fresh in-memory SQLite database with your schema, foreign keys on —
17
+ * milliseconds to create, one per test file. Needs `better-sqlite3`.
18
+ *
19
+ * const db = await createTestDb({ schema })
20
+ */
21
+ export declare function createTestDb<S>(opts: TestDbOptions<S>): Promise<KickDbClient<SchemaToTypes<S>>>;
22
+ export interface PgTestDb<S> {
23
+ db: KickDbClient<SchemaToTypes<S>>;
24
+ /** The throwaway database's connection string — for code that opens its own pool. */
25
+ connectionString: string;
26
+ /** Close the client and drop the database. Call it in `afterAll`. */
27
+ drop(): Promise<void>;
28
+ }
29
+ /**
30
+ * A throwaway database on an existing Postgres server — a CI service
31
+ * container, a local Docker Postgres — with your schema or migrations
32
+ * applied. Creating one takes well under a second, so each test file can
33
+ * have its own without starting a container. Needs `pg`.
34
+ *
35
+ * const pg = await createPgTestDb({ schema, connectionString: process.env.TEST_DATABASE_URL! })
36
+ * afterAll(() => pg.drop())
37
+ */
38
+ export declare function createPgTestDb<S>(opts: TestDbOptions<S> & {
39
+ /** A database on the server to connect to first, with permission to CREATE DATABASE. */
40
+ connectionString: string;
41
+ }): Promise<PgTestDb<S>>;
42
+ /**
43
+ * Run `fn` in a transaction that's always rolled back — every test starts
44
+ * from the same data. Code that only holds the client (a service, a
45
+ * repository) joins the transaction through the call chain, so nothing it
46
+ * writes survives. `afterCommit` hooks don't run. A real failure in `fn`
47
+ * still throws.
48
+ *
49
+ * it('creates a user', () => rolledBack(db, async () => { … }))
50
+ */
51
+ export declare function rolledBack<T>(db: Pick<KickDbClient<any>, 'transaction'>, fn: () => Promise<T>): Promise<T>;
52
+ //#endregion
53
+ //# sourceMappingURL=testing.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.mts","names":[],"sources":["../src/testing.ts"],"mappings":";;;;iBAaiB,cAAc;EAC7B,QAAQ;;;;;EAKR;;EAEA;;;;;;;;wBASoB,aAAa,GACjC,MAAM,cAAc,KACnB,QAAQ,aAAa,cAAc;iBA2BrB,SAAS;EACxB,IAAI,aAAa,cAAc;;EAE/B;;EAEA,QAAQ;;;;;;;;;;;wBAYY,eAAe,GACnC,MAAM,cAAc;;EAElB;IAED,QAAQ,SAAS;;;;;;;;;;wBA6EE,WAAW,GAE/B,IAAI,KAAK,mCACT,UAAU,QAAQ,KACjB,QAAQ"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs-db v8.1.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{E as emitPg,W as diff,d as migrateLatest,q as extractSnapshot,t as createDbClient,v as emitSqlite}from"./create-CwuC1odW.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})}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});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}export{createPgTestDb,createTestDb,rolledBack};
12
+ //# sourceMappingURL=testing.mjs.map
@@ -0,0 +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 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 }) 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 }) 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"],"mappings":";;;;;;;;;;0KA8BA,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,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