@forinda/kickjs-db 7.3.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.mts +10 -10
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/cli.mjs.map +1 -1
- package/dist/custom-type-CZdUgkPT.mjs +12 -0
- package/dist/custom-type-CZdUgkPT.mjs.map +1 -0
- package/dist/devtools-events.d.mts +2 -1
- package/dist/devtools-events.mjs +1 -1
- package/dist/{index-BJipaUa3.d.mts → index-BQQWKybR.d.mts} +138 -327
- package/dist/index-BQQWKybR.d.mts.map +1 -0
- package/dist/index.d.mts +4 -3
- package/dist/index.mjs +2 -2
- package/dist/mysql.d.mts +11 -12
- package/dist/mysql.d.mts.map +1 -1
- package/dist/mysql.mjs +2 -2
- package/dist/mysql.mjs.map +1 -1
- package/dist/pg-CwNv938J.mjs +12 -0
- package/dist/pg-CwNv938J.mjs.map +1 -0
- package/dist/pg.d.mts +22 -22
- package/dist/pg.d.mts.map +1 -1
- package/dist/pg.mjs +2 -2
- package/dist/pg.mjs.map +1 -1
- package/dist/schema-DDMkteEP.d.mts +416 -0
- package/dist/schema-DDMkteEP.d.mts.map +1 -0
- package/dist/schema.d.mts +3 -0
- package/dist/schema.mjs +12 -0
- package/dist/schema.mjs.map +1 -0
- package/dist/sqlite.d.mts +7 -8
- package/dist/sqlite.d.mts.map +1 -1
- package/dist/sqlite.mjs +2 -2
- package/dist/{src-DVdBmsLe.mjs → src-BEJ33yHI.mjs} +9 -9
- package/dist/src-BEJ33yHI.mjs.map +1 -0
- package/dist/{types-NkfgZHEN.d.mts → types-DtvYnaXL.d.mts} +3 -4
- package/dist/types-DtvYnaXL.d.mts.map +1 -0
- package/package.json +11 -6
- package/dist/index-BJipaUa3.d.mts.map +0 -1
- package/dist/src-DVdBmsLe.mjs.map +0 -1
- package/dist/types-NkfgZHEN.d.mts.map +0 -1
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/snapshot/types.d.ts
|
|
3
|
+
type Dialect = 'postgres' | 'sqlite' | 'mysql';
|
|
4
|
+
type FkAction = 'cascade' | 'restrict' | 'set_null' | 'set_default' | 'no_action';
|
|
5
|
+
interface ColumnSnapshot {
|
|
6
|
+
name: string;
|
|
7
|
+
type: string;
|
|
8
|
+
nullable: boolean;
|
|
9
|
+
default: string | null;
|
|
10
|
+
primaryKey: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface IndexSnapshot {
|
|
13
|
+
name: string;
|
|
14
|
+
columns: string[];
|
|
15
|
+
unique: boolean;
|
|
16
|
+
}
|
|
17
|
+
interface ForeignKeySnapshot {
|
|
18
|
+
name: string;
|
|
19
|
+
columns: string[];
|
|
20
|
+
refTable: string;
|
|
21
|
+
refColumns: string[];
|
|
22
|
+
onDelete: FkAction;
|
|
23
|
+
onUpdate: FkAction;
|
|
24
|
+
}
|
|
25
|
+
interface CheckSnapshot {
|
|
26
|
+
name: string;
|
|
27
|
+
expression: string;
|
|
28
|
+
}
|
|
29
|
+
interface TableSnapshot {
|
|
30
|
+
/**
|
|
31
|
+
* Bare table name, unqualified. The schema (when any) lives in
|
|
32
|
+
* {@link TableSnapshot.schema}; the map key on `SchemaSnapshot.tables` is
|
|
33
|
+
* the qualified form (`billing.invoices`).
|
|
34
|
+
*/
|
|
35
|
+
name: string;
|
|
36
|
+
/**
|
|
37
|
+
* Named SQL schema, from `pgSchema('x').table(...)`. Absent for tables in
|
|
38
|
+
* the connection's default search_path, which keeps pre-schema snapshots
|
|
39
|
+
* byte-identical (and their migration hashes valid).
|
|
40
|
+
*/
|
|
41
|
+
schema?: string;
|
|
42
|
+
columns: Record<string, ColumnSnapshot>;
|
|
43
|
+
indexes: IndexSnapshot[];
|
|
44
|
+
foreignKeys: ForeignKeySnapshot[];
|
|
45
|
+
checks: CheckSnapshot[];
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* PostgreSQL ENUM type declaration. Currently PG-only; the field is
|
|
49
|
+
* optional on `SchemaSnapshot` so other dialects don't have to carry
|
|
50
|
+
* a phantom `enums: {}`.
|
|
51
|
+
*/
|
|
52
|
+
interface EnumSnapshot {
|
|
53
|
+
name: string;
|
|
54
|
+
/** Allowed values, in declaration order. PG preserves the order. */
|
|
55
|
+
values: readonly string[];
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Resolved relation graph attached as a sidecar on the snapshot.
|
|
59
|
+
* Lives on `SchemaSnapshot.relations` (optional). Keyed
|
|
60
|
+
* sourceTable → relationName → resolved entry. Consumed by the
|
|
61
|
+
* relational-query compiler in `packages/db/src/query/`. The
|
|
62
|
+
* migration pipeline does not read this field — relations are
|
|
63
|
+
* query-time sugar, not DDL.
|
|
64
|
+
*
|
|
65
|
+
* Shaped this way (rather than re-using the runtime `RelationsDecl`)
|
|
66
|
+
* so the snapshot stays JSON-serializable: no function thunks, no
|
|
67
|
+
* back-references to table objects.
|
|
68
|
+
*/
|
|
69
|
+
interface RelationSnapshot {
|
|
70
|
+
kind: 'one' | 'many';
|
|
71
|
+
/** Target table name. */
|
|
72
|
+
target: string;
|
|
73
|
+
/** Columns on the source table that participate in the join. */
|
|
74
|
+
sourceColumns: readonly string[];
|
|
75
|
+
/** Columns on the target table that participate in the join. */
|
|
76
|
+
targetColumns: readonly string[];
|
|
77
|
+
/**
|
|
78
|
+
* Optional pairing tag from `relationName: 'foo'` on both sides of
|
|
79
|
+
* the relation. Disambiguates multi-FK schemas.
|
|
80
|
+
*/
|
|
81
|
+
relationName?: string;
|
|
82
|
+
}
|
|
83
|
+
interface SchemaSnapshot {
|
|
84
|
+
version: 1;
|
|
85
|
+
dialect: Dialect;
|
|
86
|
+
/**
|
|
87
|
+
* Keyed by QUALIFIED name — `billing.invoices` for a table declared through
|
|
88
|
+
* `pgSchema('billing')`, the bare name otherwise. Qualifying the key is what
|
|
89
|
+
* lets two schemas hold same-named tables without colliding, and it makes
|
|
90
|
+
* every `table: string` field on a diff `Change` already schema-correct:
|
|
91
|
+
* `quoteIdent` splits on `.`, rendering `"billing"."invoices"`.
|
|
92
|
+
*/
|
|
93
|
+
tables: Record<string, TableSnapshot>;
|
|
94
|
+
/**
|
|
95
|
+
* Named schemas the tables in this snapshot live in, sorted. Drives
|
|
96
|
+
* `CREATE SCHEMA IF NOT EXISTS` emission. PG-only; absent when no table
|
|
97
|
+
* declares a schema, so existing snapshots keep their exact shape.
|
|
98
|
+
*/
|
|
99
|
+
schemas?: readonly string[];
|
|
100
|
+
/** ENUM types declared via `pgEnum()`. PG-only; absent on other dialects. */
|
|
101
|
+
enums?: Record<string, EnumSnapshot>;
|
|
102
|
+
/**
|
|
103
|
+
* Optional relation sidecar populated when the schema includes
|
|
104
|
+
* `relations()` declarations. Absent when no relations are
|
|
105
|
+
* declared so M0/M1 callers see the same snapshot shape they
|
|
106
|
+
* always did.
|
|
107
|
+
*/
|
|
108
|
+
relations?: Record<string, Record<string, RelationSnapshot>>;
|
|
109
|
+
}
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/dsl/columns/types.d.ts
|
|
112
|
+
/**
|
|
113
|
+
* Runtime + type representation of a column reference (e.g. `users.id`).
|
|
114
|
+
* Carries the parent table name, the column's own name, plus runtime
|
|
115
|
+
* accessors used by FK thunks and constraint builders.
|
|
116
|
+
*
|
|
117
|
+
* Exported so adopters can annotate self-referencing thunks without
|
|
118
|
+
* spelling the shape inline:
|
|
119
|
+
*
|
|
120
|
+
* parentId: uuid().references((): ColumnRef => categories.id)
|
|
121
|
+
*
|
|
122
|
+
* Without the annotation the initializer of a self-referencing const
|
|
123
|
+
* trips TS7022 — TS needs to infer the const while the initializer
|
|
124
|
+
* already references it.
|
|
125
|
+
*/
|
|
126
|
+
interface ColumnRef {
|
|
127
|
+
__tableName: string;
|
|
128
|
+
__name: string;
|
|
129
|
+
__builder: ColumnBuilder;
|
|
130
|
+
__state: () => ReturnType<ColumnBuilder['__state']>;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Resolved FK spec — `table` / `column` are pulled by invoking `thunk()`
|
|
134
|
+
* lazily. The thunk pattern lets self-referencing tables work:
|
|
135
|
+
*
|
|
136
|
+
* const categories = table('categories', {
|
|
137
|
+
* id: uuid().primaryKey().defaultRandom(),
|
|
138
|
+
* parentId: uuid().references((): ColumnRef => categories.id),
|
|
139
|
+
* })
|
|
140
|
+
*
|
|
141
|
+
* If we resolved at `.references()` call time, `categories` would TDZ-fail
|
|
142
|
+
* inside its own initializer. Storing the thunk and resolving on read
|
|
143
|
+
* (extract / render / emit) defers until after the const binding lands.
|
|
144
|
+
*/
|
|
145
|
+
/**
|
|
146
|
+
* A column ref that knows its column's value type — what lets a foreign key
|
|
147
|
+
* be checked against the column it points at (`fk()`). Assignable to
|
|
148
|
+
* `ColumnRef`, so every existing ref-taking API keeps working.
|
|
149
|
+
*/
|
|
150
|
+
type TypedColumnRef<T> = ColumnRef & {
|
|
151
|
+
readonly __valueType?: T;
|
|
152
|
+
};
|
|
153
|
+
/** Typed refs for a column record — one per column. */
|
|
154
|
+
type TypedColumnRefs<C> = { [K in keyof C]: TypedColumnRef<C[K] extends ColumnBuilder<infer T> ? T : never>; };
|
|
155
|
+
interface FkSpec {
|
|
156
|
+
thunk: () => ColumnRef;
|
|
157
|
+
onDelete: FkAction;
|
|
158
|
+
onUpdate: FkAction;
|
|
159
|
+
/**
|
|
160
|
+
* The constraint's name in the database.
|
|
161
|
+
*
|
|
162
|
+
* Omitted for schemas written by hand — the name is then derived as
|
|
163
|
+
* `<table>_<column>_fk`. It is set when the schema was generated by
|
|
164
|
+
* `kick db introspect`, because a database names its constraints itself:
|
|
165
|
+
* Postgres' own default is `<table>_<column>_fkey`, and a DBA may have
|
|
166
|
+
* chosen anything. Dropping the real name would make the next diff want to
|
|
167
|
+
* rename every foreign key in the schema.
|
|
168
|
+
*/
|
|
169
|
+
name?: string;
|
|
170
|
+
}
|
|
171
|
+
interface ColumnState {
|
|
172
|
+
type: string;
|
|
173
|
+
nullable: boolean;
|
|
174
|
+
default: string | null;
|
|
175
|
+
primaryKey: boolean;
|
|
176
|
+
unique: boolean;
|
|
177
|
+
references: FkSpec | null;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Type-only brand attached to a column when it's auto-assigned by the
|
|
181
|
+
* database (serial / bigserial / smallserial), has a runtime default
|
|
182
|
+
* (`.default(...)`), or carries an expression default
|
|
183
|
+
* (`uuid().defaultRandom()`, `timestamp().defaultNow()`). `SchemaToTypes<S>`
|
|
184
|
+
* reads this marker and wraps the column type in Kysely's `Generated<T>` so
|
|
185
|
+
* adopters can omit the column on insert.
|
|
186
|
+
*
|
|
187
|
+
* Runtime is a no-op — the symbol never reaches a value.
|
|
188
|
+
*/
|
|
189
|
+
declare const KICK_GENERATED: unique symbol;
|
|
190
|
+
type GeneratedBrand = {
|
|
191
|
+
readonly [KICK_GENERATED]?: true;
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Type-only brand attached to a column when `.notNull()` or `.primaryKey()`
|
|
195
|
+
* is called. `SchemaToTypes<S>` reads this brand to decide whether the
|
|
196
|
+
* column type is `T` (NOT NULL) or `T | null` (default nullable).
|
|
197
|
+
*
|
|
198
|
+
* Why a brand instead of a class generic: chained methods (notNull,
|
|
199
|
+
* primaryKey) can return `this & NotNullBrand` to narrow nullability while
|
|
200
|
+
* preserving the subclass identity — so `uuid().primaryKey().defaultRandom()`
|
|
201
|
+
* still resolves `defaultRandom()` on `UuidBuilder`. A class generic
|
|
202
|
+
* `<TNullable>` would collapse the subclass back to the parent.
|
|
203
|
+
*/
|
|
204
|
+
declare const KICK_NOT_NULL: unique symbol;
|
|
205
|
+
type NotNullBrand = {
|
|
206
|
+
readonly [KICK_NOT_NULL]?: true;
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* Re-attach the nullability / generated brands after a transform that
|
|
210
|
+
* must return a *new* builder type (e.g. `.array()` widening `T` to
|
|
211
|
+
* `T[]`). Without this, `integer().notNull().array()` silently dropped
|
|
212
|
+
* `NotNullBrand` and the row type regressed to `number[] | null`.
|
|
213
|
+
*
|
|
214
|
+
* Uses the same `extends` checks as `SchemaToTypes` (client/schema-types.ts)
|
|
215
|
+
* so detection stays consistent in both directions.
|
|
216
|
+
*/
|
|
217
|
+
type PreserveBrands<Self, Out> = Out & (Self extends NotNullBrand ? NotNullBrand : unknown) & (Self extends GeneratedBrand ? GeneratedBrand : unknown);
|
|
218
|
+
/**
|
|
219
|
+
* Phantom-typed column builder. The `T` generic carries the column's TS
|
|
220
|
+
* value type (number / string / Date / etc.); nullability is tracked via
|
|
221
|
+
* the `NotNullBrand` intersection rather than a class generic so chain
|
|
222
|
+
* methods preserve subclass identity.
|
|
223
|
+
*
|
|
224
|
+
* Both `T` and the brand are erased at runtime; they exist purely so
|
|
225
|
+
* `SchemaToTypes<S>` can pull them out per column.
|
|
226
|
+
*/
|
|
227
|
+
declare class ColumnBuilder<T = unknown> {
|
|
228
|
+
readonly __t?: T;
|
|
229
|
+
protected state: ColumnState;
|
|
230
|
+
constructor(type: string, defaults?: Partial<ColumnState>);
|
|
231
|
+
notNull(): this & NotNullBrand;
|
|
232
|
+
primaryKey(): this & NotNullBrand;
|
|
233
|
+
unique(): this;
|
|
234
|
+
array(): PreserveBrands<this, ColumnBuilder<T[]>>;
|
|
235
|
+
references(target: () => ColumnRef, opts?: {
|
|
236
|
+
onDelete?: FkAction;
|
|
237
|
+
onUpdate?: FkAction;
|
|
238
|
+
name?: string;
|
|
239
|
+
}): this;
|
|
240
|
+
/**
|
|
241
|
+
* Mark the column as having a runtime / DB-assigned default. The
|
|
242
|
+
* `GeneratedBrand` flows into `SchemaToTypes<S>` so the column wraps
|
|
243
|
+
* in `Generated<T>` — adopters can `INSERT` without specifying it.
|
|
244
|
+
*
|
|
245
|
+
* Accepts the natural literal for the column type — `boolean().default(false)`,
|
|
246
|
+
* `integer().default(0)`, `varchar().default('active')`. Non-string
|
|
247
|
+
* literals are normalised to their SQL-literal text so the snapshot
|
|
248
|
+
* (`ColumnSnapshot.default: string | null`) and migration emitter stay
|
|
249
|
+
* string-only. For a quoted string default the text is the value
|
|
250
|
+
* itself (`'active'`); booleans/numbers emit bare (`false`, `0`).
|
|
251
|
+
*/
|
|
252
|
+
default(value: string | number | boolean): this & GeneratedBrand;
|
|
253
|
+
toJSON(name: string): ColumnSnapshot;
|
|
254
|
+
__state(): Readonly<ColumnState>;
|
|
255
|
+
}
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/dsl/constraints.d.ts
|
|
258
|
+
interface IndexDecl {
|
|
259
|
+
name: string;
|
|
260
|
+
columns: string[];
|
|
261
|
+
unique: boolean;
|
|
262
|
+
}
|
|
263
|
+
interface ColRef {
|
|
264
|
+
__name: string;
|
|
265
|
+
}
|
|
266
|
+
declare function index(name: string): {
|
|
267
|
+
on(...cols: ColRef[]): IndexDecl;
|
|
268
|
+
};
|
|
269
|
+
declare function unique(name: string): {
|
|
270
|
+
on(...cols: ColRef[]): IndexDecl;
|
|
271
|
+
};
|
|
272
|
+
//#endregion
|
|
273
|
+
//#region src/dsl/table.d.ts
|
|
274
|
+
interface TableDecl<TName extends string = string, C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>, TSchema extends string | undefined = string | undefined> {
|
|
275
|
+
__isTable: true;
|
|
276
|
+
__name: TName;
|
|
277
|
+
__columns: C;
|
|
278
|
+
__indexes: IndexDecl[];
|
|
279
|
+
/**
|
|
280
|
+
* Named SQL schema this table lives in, from `pgSchema('x').table(...)`.
|
|
281
|
+
* `undefined` means the connection's default search_path (`public` on PG),
|
|
282
|
+
* which is every table declared through the bare `table()` factory.
|
|
283
|
+
*
|
|
284
|
+
* PostgreSQL only — `assertSchemasSupported()` rejects a declared schema
|
|
285
|
+
* on MySQL/SQLite at snapshot time rather than emitting subtly wrong DDL.
|
|
286
|
+
*/
|
|
287
|
+
__schema?: TSchema;
|
|
288
|
+
/**
|
|
289
|
+
* Validation rules a table form declared (`@Rule`, `rules`, `.column(k, b, rule)`),
|
|
290
|
+
* applied by `insertSchema` / `selectSchema` / `updateSchema`. Not enumerable.
|
|
291
|
+
*/
|
|
292
|
+
readonly __rules?: Readonly<Record<string, unknown>>;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Fully-qualified name used as the snapshot key, the Kysely table key, and
|
|
296
|
+
* the emitted identifier. `quoteIdent` splits on `.`, so `billing.invoices`
|
|
297
|
+
* renders as `"billing"."invoices"` with no further work.
|
|
298
|
+
*
|
|
299
|
+
* Unqualified tables keep their bare name, so every pre-schema snapshot,
|
|
300
|
+
* migration hash, and `KickDbSchema` key is byte-identical to before.
|
|
301
|
+
*/
|
|
302
|
+
type QualifiedName<TName extends string, TSchema extends string | undefined> = TSchema extends string ? `${TSchema}.${TName}` : TName;
|
|
303
|
+
/** Runtime counterpart of {@link QualifiedName}. */
|
|
304
|
+
declare function qualifiedTableName(decl: {
|
|
305
|
+
__name: string;
|
|
306
|
+
__schema?: string | undefined;
|
|
307
|
+
}): string;
|
|
308
|
+
type TableRefs<TName extends string, C extends Record<string, ColumnBuilder>, TSchema extends string | undefined = undefined> = TableDecl<TName, C, TSchema> & TypedColumnRefs<C>;
|
|
309
|
+
type ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: TypedColumnRefs<C>) => Record<string, IndexDecl>;
|
|
310
|
+
/**
|
|
311
|
+
* Declare a typed table. The `TName extends string` generic narrows to the
|
|
312
|
+
* literal table name so `SchemaToTypes<S>` can index by it without losing
|
|
313
|
+
* the constant — `table('users', …)` widens to `TableDecl<'users', …>`,
|
|
314
|
+
* not `TableDecl<string, …>`.
|
|
315
|
+
*/
|
|
316
|
+
declare function table<TName extends string, C extends Record<string, ColumnBuilder>>(name: TName, columns: C, constraints?: ConstraintBuilder<C>): TableRefs<TName, C>;
|
|
317
|
+
/**
|
|
318
|
+
* Shared table constructor. `table()` passes `schema: undefined`;
|
|
319
|
+
* `pgSchema('x').table()` passes the schema name through.
|
|
320
|
+
*/
|
|
321
|
+
declare function buildTable<TName extends string, C extends Record<string, ColumnBuilder>, TSchema extends string | undefined>(name: TName, declared: C, constraints: ConstraintBuilder<C> | undefined, schema: TSchema): TableRefs<TName, C, TSchema>;
|
|
322
|
+
/**
|
|
323
|
+
* The table a schema-barrel export stands for: a table itself, or a class
|
|
324
|
+
* form carrying one as `static table` (`class User extends TableBase(...)`).
|
|
325
|
+
* Everything that scans a schema for tables goes through this, so exporting
|
|
326
|
+
* the class is enough — no separate `export const users = User.table`.
|
|
327
|
+
*/
|
|
328
|
+
declare function unwrapTable(value: unknown): TableDecl | undefined;
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region src/schema.d.ts
|
|
331
|
+
type ColumnsOf<T> = T extends TableDecl<string, infer C, string | undefined> ? C : never;
|
|
332
|
+
type ValueOf<C> = C extends ColumnBuilder<infer V> ? V : never;
|
|
333
|
+
type IsNotNull<C> = C extends NotNullBrand ? true : false;
|
|
334
|
+
/** A row as read from the table. */
|
|
335
|
+
type InferSelect<T extends TableDecl> = { [K in keyof ColumnsOf<T>]: IsNotNull<ColumnsOf<T>[K]> extends true ? ValueOf<ColumnsOf<T>[K]> : ValueOf<ColumnsOf<T>[K]> | null; };
|
|
336
|
+
type OptionalOnInsert<T> = { [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends GeneratedBrand ? K : IsNotNull<ColumnsOf<T>[K]> extends true ? never : K; }[keyof ColumnsOf<T>];
|
|
337
|
+
/** A row to insert: generated, defaulted and nullable columns may be left out. */
|
|
338
|
+
type InferInsert<T extends TableDecl> = Omit<InferSelect<T>, OptionalOnInsert<T>> & Partial<Pick<InferSelect<T>, OptionalOnInsert<T>>>;
|
|
339
|
+
/** Extra rules for one column — what a SQL type can't say. */
|
|
340
|
+
interface ColumnRule {
|
|
341
|
+
/** JSON Schema `format`; `email`, `uri`, `uuid` and `date-time` are also checked. */
|
|
342
|
+
format?: string;
|
|
343
|
+
minLength?: number;
|
|
344
|
+
maxLength?: number;
|
|
345
|
+
/** Checked against the whole string. */
|
|
346
|
+
pattern?: string;
|
|
347
|
+
minimum?: number;
|
|
348
|
+
maximum?: number;
|
|
349
|
+
}
|
|
350
|
+
/** Anything with `safeParse` + `toJsonSchema` — a `KickSchema` (e.g. `fromZod(...)`). */
|
|
351
|
+
interface SchemaLike {
|
|
352
|
+
safeParse(data: unknown): {
|
|
353
|
+
success: true;
|
|
354
|
+
data: unknown;
|
|
355
|
+
} | {
|
|
356
|
+
success: false;
|
|
357
|
+
issues: unknown[];
|
|
358
|
+
};
|
|
359
|
+
toJsonSchema(options?: JsonSchemaOptions): Record<string, unknown>;
|
|
360
|
+
}
|
|
361
|
+
interface TableSchemaOptions<T extends TableDecl> {
|
|
362
|
+
columns?: { [K in keyof ColumnsOf<T>]?: ColumnRule | SchemaLike; };
|
|
363
|
+
/** Columns left out of the schema entirely (e.g. `password` on a read). */
|
|
364
|
+
omit?: readonly (keyof ColumnsOf<T>)[];
|
|
365
|
+
}
|
|
366
|
+
interface JsonSchemaOptions {
|
|
367
|
+
readonly target?: 'draft-2020-12' | 'draft-07' | 'openapi-3.0';
|
|
368
|
+
}
|
|
369
|
+
interface SchemaIssue {
|
|
370
|
+
path: string[];
|
|
371
|
+
message: string;
|
|
372
|
+
code: string;
|
|
373
|
+
}
|
|
374
|
+
/** The schema these functions return — structurally a `KickSchema<TOutput>` and a Standard Schema. */
|
|
375
|
+
interface TableSchema<TOutput> {
|
|
376
|
+
safeParse(data: unknown): {
|
|
377
|
+
success: true;
|
|
378
|
+
data: TOutput;
|
|
379
|
+
} | {
|
|
380
|
+
success: false;
|
|
381
|
+
issues: SchemaIssue[];
|
|
382
|
+
};
|
|
383
|
+
toJsonSchema(options?: JsonSchemaOptions): Record<string, unknown>;
|
|
384
|
+
readonly '~standard': {
|
|
385
|
+
readonly version: 1;
|
|
386
|
+
readonly vendor: 'kickjs-db';
|
|
387
|
+
readonly validate: (value: unknown) => {
|
|
388
|
+
value: TOutput;
|
|
389
|
+
issues?: undefined;
|
|
390
|
+
} | {
|
|
391
|
+
issues: ReadonlyArray<{
|
|
392
|
+
message: string;
|
|
393
|
+
path: readonly string[];
|
|
394
|
+
}>;
|
|
395
|
+
};
|
|
396
|
+
readonly types?: {
|
|
397
|
+
readonly input: unknown;
|
|
398
|
+
readonly output: TOutput;
|
|
399
|
+
};
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
/** A row as read: every column present, nullable ones may be `null`. */
|
|
403
|
+
declare function selectSchema<T extends TableDecl, const O extends keyof ColumnsOf<T> = never>(table: T, options?: TableSchemaOptions<T> & {
|
|
404
|
+
omit?: readonly O[];
|
|
405
|
+
}): TableSchema<Omit<InferSelect<T>, O>>;
|
|
406
|
+
/** A row to insert: serial, defaulted and nullable columns are optional. */
|
|
407
|
+
declare function insertSchema<T extends TableDecl, const O extends keyof ColumnsOf<T> = never>(table: T, options?: TableSchemaOptions<T> & {
|
|
408
|
+
omit?: readonly O[];
|
|
409
|
+
}): TableSchema<Omit<InferInsert<T>, O>>;
|
|
410
|
+
/** A patch: every column optional. */
|
|
411
|
+
declare function updateSchema<T extends TableDecl, const O extends keyof ColumnsOf<T> = never>(table: T, options?: TableSchemaOptions<T> & {
|
|
412
|
+
omit?: readonly O[];
|
|
413
|
+
}): TableSchema<Partial<Omit<InferInsert<T>, O>>>;
|
|
414
|
+
//#endregion
|
|
415
|
+
export { TypedColumnRefs as A, TableSnapshot as B, ColumnState as C, KICK_NOT_NULL as D, KICK_GENERATED as E, FkAction as F, ForeignKeySnapshot as I, IndexSnapshot as L, ColumnSnapshot as M, Dialect as N, NotNullBrand as O, EnumSnapshot as P, RelationSnapshot as R, ColumnRef as S, GeneratedBrand as T, unwrapTable as _, SchemaIssue as a, unique as b, TableSchemaOptions as c, updateSchema as d, QualifiedName as f, table as g, qualifiedTableName as h, JsonSchemaOptions as i, CheckSnapshot as j, TypedColumnRef as k, insertSchema as l, buildTable as m, InferInsert as n, SchemaLike as o, TableDecl as p, InferSelect as r, TableSchema as s, ColumnRule as t, selectSchema as u, IndexDecl as v, FkSpec as w, ColumnBuilder as x, index as y, SchemaSnapshot as z };
|
|
416
|
+
//# sourceMappingURL=schema-DDMkteEP.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-DDMkteEP.d.mts","names":[],"sources":["../src/snapshot/types.ts","../src/dsl/columns/types.ts","../src/dsl/constraints.ts","../src/dsl/table.ts","../src/schema.ts"],"mappings":";;KAAY;KAEA;UAEK;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA,UAAU;EACV,UAAU;;UAGK;EACf;EACA;;UAGe;;;;;;EAMf;;;;;;EAMA;EACA,SAAS,eAAe;EACxB,SAAS;EACT,aAAa;EACb,QAAQ;;;;;;;UAQO;EACf;;EAEA;;;;;;;;;;;;;;UAee;EACf;;EAEA;;EAEA;;EAEA;;;;;EAKA;;UAGe;EACf;EACA,SAAS;;;;;;;;EAQT,QAAQ,eAAe;;;;;;EAMvB;;EAEA,QAAQ,eAAe;;;;;;;EAOvB,YAAY,eAAe,eAAe;;;;;;;;;;;;;;;;;;UClG3B;EACf;EACA;EACA,WAAW;EACX,eAAe,WAAW;;;;;;;;;;;;;;;;;;;;KAqBhB,eAAe,KAAK;WAAuB,cAAc;;;KAGzD,gBAAgB,QACzB,WAAW,IAAI,eAAe,EAAE,WAAW,oBAAoB,KAAK;UAGtD;EACf,aAAa;EACb,UAAU;EACV,UAAU;;;;;;;;;;;EAWV;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA,YAAY;;;;;;;;;;;;cAaD;KACD;YAA6B;;;;;;;;;;;;;cAa5B;KACD;YAA2B;;;;;;;;;;;KAW3B,eAAe,MAAM,OAAO,OACrC,aAAa,eAAe,2BAC5B,aAAa,iBAAiB;;;;;;;;;;cAWpB,cAAc;WAGR,MAAM;YAEb,OAAO;EAEjB,YAAY,cAAc,WAAU,QAAQ;EAW5C,kB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,GAAG,2BAErB,WACA,UAAU;;KAGN,YAAY,UAAU,aAAa,KAAK,YAAY,IAAI,iBAAiB,MACnF,QAAQ,KAAK,YAAY,IAAI,iBAAiB;;UAG/B;;EAEf;EACA;EACA;;EAEA;EACA;EACA;;;UAIe;EACf,UAAU;IAAkB;IAAe;;IAAoB;IAAgB;;EAC/E,aAAa,UAAU,oBAAoB;;UAG5B,mBAAmB,UAAU;EAC5C,aAAa,WAAW,UAAU,MAAM,aAAa;;EAErD,uBAAuB,UAAU;;UAGlB;WACN;;UAGM;EACf;EACA;EACA;;;UAIe,YAAY;EAC3B,UACE;IACG;IAAe,MAAM;;IAAc;IAAgB,QAAQ;;EAChE,aAAa,UAAU,oBAAoB;WAClC;aACE;aACA;aACA,WACP;MAEI,OAAO;MAAS;;MAChB,QAAQ;QAAgB;QAAiB;;;aACtC;eAAmB;eAAyB,QAAQ;;;;;iBAmXjD,aAAa,UAAU,iBAAiB,gBAAgB,UAAU,YAChF,OAAO,GACP,UAAU,mBAAmB;EAAO,gBAAgB;IACnD,YAAY,KAAK,YAAY,IAAI;;iBAKpB,aAAa,UAAU,iBAAiB,gBAAgB,UAAU,YAChF,OAAO,GACP,UAAU,mBAAmB;EAAO,gBAAgB;IACnD,YAAY,KAAK,YAAY,IAAI;;iBAKpB,aAAa,UAAU,iBAAiB,gBAAgB,UAAU,YAChF,OAAO,GACP,UAAU,mBAAmB;EAAO,gBAAgB;IACnD,YAAY,QAAQ,KAAK,YAAY,IAAI"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
|
|
2
|
+
import { a as SchemaIssue, c as TableSchemaOptions, d as updateSchema, i as JsonSchemaOptions, l as insertSchema, n as InferInsert, o as SchemaLike, r as InferSelect, s as TableSchema, t as ColumnRule, u as selectSchema } from "./schema-DDMkteEP.mjs";
|
|
3
|
+
export { ColumnRule, InferInsert, InferSelect, JsonSchemaOptions, SchemaIssue, SchemaLike, TableSchema, TableSchemaOptions, insertSchema, selectSchema, updateSchema };
|
package/dist/schema.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs-db v8.0.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{t as CustomColumnBuilder}from"./custom-type-CZdUgkPT.mjs";import{t as PgEnumColumnBuilder}from"./pg-CwNv938J.mjs";const ok=value=>({ok:!0,value}),fail=(message,code=`invalid_type`)=>({ok:!1,message,code}),INTEGER=/^-?\d+$/,DECIMAL=/^-?\d+(\.\d+)?$/,UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,EMAIL=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function integerSpec(minimum,maximum){return{json:{type:`integer`,minimum,maximum},parse:v=>typeof v!=`number`||!Number.isInteger(v)?fail(`Expected an integer`):v<minimum||v>maximum?fail(`Must be between ${minimum} and ${maximum}`,v<minimum?`too_small`:`too_big`):ok(v)}}const INT16=32767,INT32=2147483647,INT64=2n**63n;function stringSpec(json={},check){return{json:{type:`string`,...json},parse:v=>{if(typeof v!=`string`)return fail(`Expected a string`);let problem=check?.(v);return problem?fail(problem,`invalid_string`):ok(v)}}}function dateSpec(format){return{json:{type:`string`,format},parse:v=>{let date=v instanceof Date?v:typeof v==`string`?new Date(v):void 0;return date&&!Number.isNaN(date.getTime())?ok(date):fail(`Expected a ${format===`date`?`date`:`date-time`} string`)}}}function specFor(builder){if(builder instanceof PgEnumColumnBuilder){let values=builder.values;return{json:{type:`string`,enum:[...values]},parse:v=>typeof v==`string`&&values.includes(v)?ok(v):fail(`Expected one of ${values.join(`, `)}`,`invalid_enum_value`)}}if(builder instanceof CustomColumnBuilder)return anySpec();let type=builder.__state().type.toLowerCase();return type.endsWith(`[]`)?arraySpec(specForType(type.slice(0,-2))):specForType(type)}function anySpec(){return{json:{},parse:ok}}function arraySpec(item,length){return{json:{type:`array`,items:item.json,...length===void 0?{}:{minItems:length,maxItems:length}},parse:v=>{if(!Array.isArray(v))return fail(`Expected an array`);if(length!==void 0&&v.length!==length)return fail(`Expected ${length} items`,`invalid_length`);let out=[];for(let[i,element]of v.entries()){let parsed=item.parse(element);if(!parsed.ok)return fail(`[${i}]: ${parsed.message}`,parsed.code);out.push(parsed.value)}return ok(out)}}}function specForType(type){let base=type.replace(/\(.*$/,``).trim(),size=Number(/\((\d+)/.exec(type)?.[1]);switch(base){case`smallserial`:return integerSpec(1,INT16);case`serial`:return integerSpec(1,INT32);case`smallint`:return integerSpec(-32768,INT16);case`integer`:case`int`:return integerSpec(-2147483648,INT32);case`bigserial`:case`bigint`:return{json:{type:`string`,pattern:INTEGER.source},parse:v=>{if(!(typeof v==`number`&&Number.isInteger(v))&&!(typeof v==`string`&&INTEGER.test(v)))return fail(`Expected an integer or a string of digits`);let n=BigInt(v);return n<-INT64||n>=INT64?fail(`Out of range for a 64-bit integer`,`too_big`):ok(n)}};case`real`:case`double precision`:return{json:{type:`number`},parse:v=>typeof v==`number`&&Number.isFinite(v)?ok(v):fail(`Expected a number`)};case`decimal`:case`numeric`:case`money`:return{json:{type:`string`,pattern:DECIMAL.source},parse:v=>typeof v==`number`&&Number.isFinite(v)?ok(String(v)):typeof v==`string`&&DECIMAL.test(v)?ok(v):fail(`Expected a decimal number or string`)};case`varchar`:case`character varying`:case`char`:case`character`:return Number.isFinite(size)?stringSpec({maxLength:size},v=>v.length>size?`Must be at most ${size} characters`:null):stringSpec();case`boolean`:return{json:{type:`boolean`},parse:v=>typeof v==`boolean`?ok(v):fail(`Expected a boolean`)};case`timestamp`:case`timestamptz`:return dateSpec(`date-time`);case`date`:return dateSpec(`date`);case`uuid`:return stringSpec({format:`uuid`},v=>UUID.test(v)?null:`Expected a UUID`);case`vector`:return arraySpec({json:{type:`number`},parse:v=>typeof v==`number`?ok(v):fail(`Expected a number`)},Number.isFinite(size)?size:void 0);case`json`:case`jsonb`:return anySpec();default:return stringSpec()}}function isSchemaLike(value){return typeof value==`object`&&!!value&&typeof value.safeParse==`function`&&typeof value.toJsonSchema==`function`}function withRule(spec,rule){if(!rule)return spec;if(isSchemaLike(rule))return{json:rule.toJsonSchema(),jsonFor:options=>rule.toJsonSchema(options),parse:v=>{let result=rule.safeParse(v);if(result.success)return ok(result.data);let first=result.issues[0];return fail(first?.message??`Invalid value`,`custom`)}};let pattern=rule.pattern===void 0?void 0:RegExp(`^(?:${rule.pattern})$`);return{json:{...spec.json,...rule},parse:v=>{let parsed=spec.parse(v);if(!parsed.ok)return parsed;let value=parsed.value;if(typeof value==`string`){if(rule.minLength!==void 0&&value.length<rule.minLength)return fail(`Must be at least ${rule.minLength} characters`,`too_small`);if(rule.maxLength!==void 0&&value.length>rule.maxLength)return fail(`Must be at most ${rule.maxLength} characters`,`too_big`);if(pattern&&!pattern.test(value))return fail(`Invalid format`,`invalid_string`);let formatProblem=checkFormat(rule.format,value);if(formatProblem)return fail(formatProblem,`invalid_string`)}if(typeof value==`number`){if(rule.minimum!==void 0&&value<rule.minimum)return fail(`Must be at least ${rule.minimum}`,`too_small`);if(rule.maximum!==void 0&&value>rule.maximum)return fail(`Must be at most ${rule.maximum}`,`too_big`)}return parsed}}}function checkFormat(format,value){switch(format){case`email`:return EMAIL.test(value)?null:`Expected an email address`;case`uuid`:return UUID.test(value)?null:`Expected a UUID`;case`uri`:case`url`:return URL.canParse(value)?null:`Expected a URL`;case`date-time`:return Number.isNaN(Date.parse(value))?`Expected a date-time string`:null;default:return null}}function optionalOnInsert(builder){let state=builder.__state();return state.nullable||state.default!==null||/^(small|big)?serial$/.test(state.type)}function buildSchema(table,mode,options={}){let omitted=new Set(options.omit??[]),columns=Object.entries(table.__columns).filter(([name])=>!omitted.has(name)).map(([name,builder])=>({name,nullable:builder.__state().nullable,required:mode===`select`||mode===`insert`&&!optionalOnInsert(builder),spec:withRule(specFor(builder),options.columns?.[name]??table.__rules?.[name])})),safeParse=data=>{if(typeof data!=`object`||!data||Array.isArray(data))return{success:!1,issues:[{path:[],message:`Expected an object`,code:`invalid_type`}]};let input=data,out={},issues=[];for(let column of columns){let value=input[column.name];if(value===void 0){column.required&&issues.push({path:[column.name],message:`Required`,code:`invalid_type`});continue}if(value===null){column.nullable?out[column.name]=null:issues.push({path:[column.name],message:`Cannot be null`,code:`invalid_type`});continue}let parsed=column.spec.parse(value);parsed.ok?out[column.name]=parsed.value:issues.push({path:[column.name],message:parsed.message,code:parsed.code})}return issues.length>0?{success:!1,issues}:{success:!0,data:out}};return{safeParse,toJsonSchema:(jsonOptions={})=>{let openapi=jsonOptions.target===`openapi-3.0`,properties={};for(let column of columns){let json=column.spec.jsonFor?.(jsonOptions)??column.spec.json;properties[column.name]=column.nullable?openapi?{...json,nullable:!0}:{anyOf:[json,{type:`null`}]}:json}let required=columns.filter(c=>c.required).map(c=>c.name);return{type:`object`,properties,...required.length>0?{required}:{},additionalProperties:!1}},"~standard":{version:1,vendor:`kickjs-db`,validate:value=>{let result=safeParse(value);return result.success?{value:result.data}:{issues:result.issues}}}}}function selectSchema(table,options){return buildSchema(table,`select`,options)}function insertSchema(table,options){return buildSchema(table,`insert`,options)}function updateSchema(table,options){return buildSchema(table,`update`,options)}export{insertSchema,selectSchema,updateSchema};
|
|
12
|
+
//# sourceMappingURL=schema.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.mjs","names":[],"sources":["../src/schema.ts"],"sourcesContent":["/**\n * Request validators and JSON Schema from a kick/db table.\n *\n * import { insertSchema, selectSchema, updateSchema } from '@forinda/kickjs-db/schema'\n *\n * export const createUser = insertSchema(users, {\n * columns: { email: { format: 'email' }, name: { minLength: 1 } },\n * omit: ['id'],\n * })\n *\n * @Post('/', { body: createUser }) // validated + typed ctx.body + OpenAPI\n *\n * The result is a `KickSchema` (`safeParse` + `toJsonSchema`), so request\n * validation, the Swagger spec, `kick typegen` and the typed client take it\n * the way they take a wrapped Zod schema — and a Standard Schema\n * (`~standard`), for libraries that accept those. No schema library needed.\n *\n * Each column's rule comes from its SQL type and nullability. A table can't\n * say a column holds an email or a minimum length, and `json` / custom\n * columns have no runtime shape — `columns` adds those: a rule object, or a\n * whole schema (e.g. `fromZod(...)`) for the column.\n *\n * - `selectSchema` — a row as read: every column present, nullable ones may be null.\n * - `insertSchema` — a row to insert: columns the database fills (serial, a\n * default, nullable) are optional.\n * - `updateSchema` — a patch: every column optional.\n *\n * Unknown keys are dropped from the parsed value, like a Zod object.\n */\nimport { CustomColumnBuilder } from './custom-type'\nimport type { ColumnBuilder, GeneratedBrand, NotNullBrand } from './dsl/columns/types'\nimport { PgEnumColumnBuilder } from './dsl/columns/pg'\nimport type { TableDecl } from './dsl/table'\n\n// ── Types ───────────────────────────────────────────────────────────────\n\ntype ColumnsOf<T> = T extends TableDecl<string, infer C, string | undefined> ? C : never\ntype ValueOf<C> = C extends ColumnBuilder<infer V> ? V : never\ntype IsNotNull<C> = C extends NotNullBrand ? true : false\n\n/** A row as read from the table. */\nexport type InferSelect<T extends TableDecl> = {\n [K in keyof ColumnsOf<T>]: IsNotNull<ColumnsOf<T>[K]> extends true\n ? ValueOf<ColumnsOf<T>[K]>\n : ValueOf<ColumnsOf<T>[K]> | null\n}\n\ntype OptionalOnInsert<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends GeneratedBrand\n ? K\n : IsNotNull<ColumnsOf<T>[K]> extends true\n ? never\n : K\n}[keyof ColumnsOf<T>]\n\n/** A row to insert: generated, defaulted and nullable columns may be left out. */\nexport type InferInsert<T extends TableDecl> = Omit<InferSelect<T>, OptionalOnInsert<T>> &\n Partial<Pick<InferSelect<T>, OptionalOnInsert<T>>>\n\n/** Extra rules for one column — what a SQL type can't say. */\nexport interface ColumnRule {\n /** JSON Schema `format`; `email`, `uri`, `uuid` and `date-time` are also checked. */\n format?: string\n minLength?: number\n maxLength?: number\n /** Checked against the whole string. */\n pattern?: string\n minimum?: number\n maximum?: number\n}\n\n/** Anything with `safeParse` + `toJsonSchema` — a `KickSchema` (e.g. `fromZod(...)`). */\nexport interface SchemaLike {\n safeParse(data: unknown): { success: true; data: unknown } | { success: false; issues: unknown[] }\n toJsonSchema(options?: JsonSchemaOptions): Record<string, unknown>\n}\n\nexport interface TableSchemaOptions<T extends TableDecl> {\n columns?: { [K in keyof ColumnsOf<T>]?: ColumnRule | SchemaLike }\n /** Columns left out of the schema entirely (e.g. `password` on a read). */\n omit?: readonly (keyof ColumnsOf<T>)[]\n}\n\nexport interface JsonSchemaOptions {\n readonly target?: 'draft-2020-12' | 'draft-07' | 'openapi-3.0'\n}\n\nexport interface SchemaIssue {\n path: string[]\n message: string\n code: string\n}\n\n/** The schema these functions return — structurally a `KickSchema<TOutput>` and a Standard Schema. */\nexport interface TableSchema<TOutput> {\n safeParse(\n data: unknown,\n ): { success: true; data: TOutput } | { success: false; issues: SchemaIssue[] }\n toJsonSchema(options?: JsonSchemaOptions): Record<string, unknown>\n readonly '~standard': {\n readonly version: 1\n readonly vendor: 'kickjs-db'\n readonly validate: (\n value: unknown,\n ) =>\n | { value: TOutput; issues?: undefined }\n | { issues: ReadonlyArray<{ message: string; path: readonly string[] }> }\n readonly types?: { readonly input: unknown; readonly output: TOutput }\n }\n}\n\n// ── Column rules ────────────────────────────────────────────────────────\n\ntype Parsed = { ok: true; value: unknown } | { ok: false; message: string; code: string }\n\ninterface ColumnSpec {\n json: Record<string, unknown>\n /** For a whole-schema override: its JSON Schema in the caller's target. */\n jsonFor?: (options: JsonSchemaOptions) => Record<string, unknown>\n parse(value: unknown): Parsed\n}\n\nconst ok = (value: unknown): Parsed => ({ ok: true, value })\nconst fail = (message: string, code = 'invalid_type'): Parsed => ({ ok: false, message, code })\n\nconst INTEGER = /^-?\\d+$/\nconst DECIMAL = /^-?\\d+(\\.\\d+)?$/\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * An integer the column can store. Out of range, the database would reject\n * the insert with a server error; here it is a validation issue instead.\n */\nfunction integerSpec(minimum: number, maximum: number): ColumnSpec {\n return {\n json: { type: 'integer', minimum, maximum },\n parse: (v) =>\n typeof v !== 'number' || !Number.isInteger(v)\n ? fail('Expected an integer')\n : v < minimum || v > maximum\n ? fail(`Must be between ${minimum} and ${maximum}`, v < minimum ? 'too_small' : 'too_big')\n : ok(v),\n }\n}\n\nconst INT16 = 32_767\nconst INT32 = 2_147_483_647\nconst INT64 = 2n ** 63n\n\nfunction stringSpec(json: Record<string, unknown> = {}, check?: (v: string) => string | null) {\n return {\n json: { type: 'string', ...json },\n parse: (v: unknown): Parsed => {\n if (typeof v !== 'string') return fail('Expected a string')\n const problem = check?.(v)\n return problem ? fail(problem, 'invalid_string') : ok(v)\n },\n }\n}\n\nfunction dateSpec(format: 'date' | 'date-time'): ColumnSpec {\n return {\n json: { type: 'string', format },\n parse: (v) => {\n const date = v instanceof Date ? v : typeof v === 'string' ? new Date(v) : undefined\n return date && !Number.isNaN(date.getTime())\n ? ok(date)\n : fail(`Expected a ${format === 'date' ? 'date' : 'date-time'} string`)\n },\n }\n}\n\n/** The rule for one column, from its SQL type. */\nfunction specFor(builder: ColumnBuilder): ColumnSpec {\n if (builder instanceof PgEnumColumnBuilder) {\n const values = builder.values as readonly string[]\n return {\n json: { type: 'string', enum: [...values] },\n parse: (v) =>\n typeof v === 'string' && values.includes(v)\n ? ok(v)\n : fail(`Expected one of ${values.join(', ')}`, 'invalid_enum_value'),\n }\n }\n if (builder instanceof CustomColumnBuilder) return anySpec()\n\n const type = builder.__state().type.toLowerCase()\n if (type.endsWith('[]')) return arraySpec(specForType(type.slice(0, -2)))\n return specForType(type)\n}\n\nfunction anySpec(): ColumnSpec {\n return { json: {}, parse: ok }\n}\n\nfunction arraySpec(item: ColumnSpec, length?: number): ColumnSpec {\n return {\n json: {\n type: 'array',\n items: item.json,\n ...(length === undefined ? {} : { minItems: length, maxItems: length }),\n },\n parse: (v) => {\n if (!Array.isArray(v)) return fail('Expected an array')\n if (length !== undefined && v.length !== length) {\n return fail(`Expected ${length} items`, 'invalid_length')\n }\n const out: unknown[] = []\n for (const [i, element] of v.entries()) {\n const parsed = item.parse(element)\n if (!parsed.ok) return fail(`[${i}]: ${parsed.message}`, parsed.code)\n out.push(parsed.value)\n }\n return ok(out)\n },\n }\n}\n\nfunction specForType(type: string): ColumnSpec {\n const base = type.replace(/\\(.*$/, '').trim()\n const size = Number(/\\((\\d+)/.exec(type)?.[1])\n switch (base) {\n // serial values start at 1.\n case 'smallserial':\n return integerSpec(1, INT16)\n case 'serial':\n return integerSpec(1, INT32)\n case 'smallint':\n return integerSpec(-INT16 - 1, INT16)\n case 'integer':\n case 'int':\n return integerSpec(-INT32 - 1, INT32)\n case 'bigserial':\n case 'bigint':\n // JSON has no 64-bit integer: accept a number or a string of digits,\n // parse to the column's TS type, bigint.\n return {\n json: { type: 'string', pattern: INTEGER.source },\n parse: (v) => {\n if (\n !(typeof v === 'number' && Number.isInteger(v)) &&\n !(typeof v === 'string' && INTEGER.test(v))\n ) {\n return fail('Expected an integer or a string of digits')\n }\n const n = BigInt(v)\n return n < -INT64 || n >= INT64\n ? fail('Out of range for a 64-bit integer', 'too_big')\n : ok(n)\n },\n }\n case 'real':\n case 'double precision':\n return {\n json: { type: 'number' },\n parse: (v) =>\n typeof v === 'number' && Number.isFinite(v) ? ok(v) : fail('Expected a number'),\n }\n case 'decimal':\n case 'numeric':\n case 'money':\n // The column's TS type is string — exact decimals don't survive a float.\n return {\n json: { type: 'string', pattern: DECIMAL.source },\n parse: (v) =>\n typeof v === 'number' && Number.isFinite(v)\n ? ok(String(v))\n : typeof v === 'string' && DECIMAL.test(v)\n ? ok(v)\n : fail('Expected a decimal number or string'),\n }\n case 'varchar':\n case 'character varying':\n case 'char':\n case 'character':\n return Number.isFinite(size)\n ? stringSpec({ maxLength: size }, (v) =>\n v.length > size ? `Must be at most ${size} characters` : null,\n )\n : stringSpec()\n case 'boolean':\n return {\n json: { type: 'boolean' },\n parse: (v) => (typeof v === 'boolean' ? ok(v) : fail('Expected a boolean')),\n }\n case 'timestamp':\n case 'timestamptz':\n return dateSpec('date-time')\n case 'date':\n return dateSpec('date')\n case 'uuid':\n return stringSpec({ format: 'uuid' }, (v) => (UUID.test(v) ? null : 'Expected a UUID'))\n case 'vector':\n return arraySpec(\n {\n json: { type: 'number' },\n parse: (v) => (typeof v === 'number' ? ok(v) : fail('Expected a number')),\n },\n Number.isFinite(size) ? size : undefined,\n )\n case 'json':\n case 'jsonb':\n return anySpec()\n default:\n // text, citext, time, interval, inet, cidr, xml, tsvector, bytea (base64)\n return stringSpec()\n }\n}\n\nfunction isSchemaLike(value: unknown): value is SchemaLike {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as SchemaLike).safeParse === 'function' &&\n typeof (value as SchemaLike).toJsonSchema === 'function'\n )\n}\n\n/** Layer a column's extra rules over its type rule. */\nfunction withRule(spec: ColumnSpec, rule: ColumnRule | SchemaLike | undefined): ColumnSpec {\n if (!rule) return spec\n if (isSchemaLike(rule)) {\n return {\n json: rule.toJsonSchema(),\n jsonFor: (options) => rule.toJsonSchema(options),\n parse: (v) => {\n const result = rule.safeParse(v)\n if (result.success) return ok(result.data)\n const first = result.issues[0] as { message?: string } | undefined\n return fail(first?.message ?? 'Invalid value', 'custom')\n },\n }\n }\n const pattern = rule.pattern === undefined ? undefined : new RegExp(`^(?:${rule.pattern})$`)\n return {\n json: { ...spec.json, ...rule },\n parse: (v) => {\n const parsed = spec.parse(v)\n if (!parsed.ok) return parsed\n const value = parsed.value\n if (typeof value === 'string') {\n if (rule.minLength !== undefined && value.length < rule.minLength) {\n return fail(`Must be at least ${rule.minLength} characters`, 'too_small')\n }\n if (rule.maxLength !== undefined && value.length > rule.maxLength) {\n return fail(`Must be at most ${rule.maxLength} characters`, 'too_big')\n }\n if (pattern && !pattern.test(value)) return fail('Invalid format', 'invalid_string')\n const formatProblem = checkFormat(rule.format, value)\n if (formatProblem) return fail(formatProblem, 'invalid_string')\n }\n if (typeof value === 'number') {\n if (rule.minimum !== undefined && value < rule.minimum) {\n return fail(`Must be at least ${rule.minimum}`, 'too_small')\n }\n if (rule.maximum !== undefined && value > rule.maximum) {\n return fail(`Must be at most ${rule.maximum}`, 'too_big')\n }\n }\n return parsed\n },\n }\n}\n\nfunction checkFormat(format: string | undefined, value: string): string | null {\n switch (format) {\n case 'email':\n return EMAIL.test(value) ? null : 'Expected an email address'\n case 'uuid':\n return UUID.test(value) ? null : 'Expected a UUID'\n case 'uri':\n case 'url':\n return URL.canParse(value) ? null : 'Expected a URL'\n case 'date-time':\n return Number.isNaN(Date.parse(value)) ? 'Expected a date-time string' : null\n default:\n return null\n }\n}\n\n// ── Schemas ─────────────────────────────────────────────────────────────\n\ntype Mode = 'select' | 'insert' | 'update'\n\n/** Whether a column may be left out of an insert: the database fills it. */\nfunction optionalOnInsert(builder: ColumnBuilder): boolean {\n const state = builder.__state()\n return state.nullable || state.default !== null || /^(small|big)?serial$/.test(state.type)\n}\n\nfunction buildSchema<TOutput>(\n table: TableDecl,\n mode: Mode,\n options: TableSchemaOptions<TableDecl> = {},\n): TableSchema<TOutput> {\n const omitted = new Set<string>((options.omit ?? []) as string[])\n const columns = Object.entries(table.__columns)\n .filter(([name]) => !omitted.has(name))\n .map(([name, builder]) => ({\n name,\n nullable: builder.__state().nullable,\n required: mode === 'select' || (mode === 'insert' && !optionalOnInsert(builder)),\n // `columns` overrides a rule the table form declared.\n spec: withRule(\n specFor(builder),\n (options.columns as Record<string, ColumnRule | SchemaLike> | undefined)?.[name] ??\n (table.__rules?.[name] as ColumnRule | SchemaLike | undefined),\n ),\n }))\n\n const safeParse = (data: unknown) => {\n if (typeof data !== 'object' || data === null || Array.isArray(data)) {\n return {\n success: false as const,\n issues: [{ path: [], message: 'Expected an object', code: 'invalid_type' }],\n }\n }\n const input = data as Record<string, unknown>\n const out: Record<string, unknown> = {}\n const issues: SchemaIssue[] = []\n for (const column of columns) {\n const value = input[column.name]\n if (value === undefined) {\n if (column.required) {\n issues.push({ path: [column.name], message: 'Required', code: 'invalid_type' })\n }\n continue\n }\n if (value === null) {\n if (column.nullable) out[column.name] = null\n else issues.push({ path: [column.name], message: 'Cannot be null', code: 'invalid_type' })\n continue\n }\n const parsed = column.spec.parse(value)\n if (parsed.ok) out[column.name] = parsed.value\n else issues.push({ path: [column.name], message: parsed.message, code: parsed.code })\n }\n return issues.length > 0\n ? { success: false as const, issues }\n : { success: true as const, data: out as TOutput }\n }\n\n const toJsonSchema = (jsonOptions: JsonSchemaOptions = {}) => {\n const openapi = jsonOptions.target === 'openapi-3.0'\n const properties: Record<string, unknown> = {}\n for (const column of columns) {\n const json = column.spec.jsonFor?.(jsonOptions) ?? column.spec.json\n properties[column.name] = !column.nullable\n ? json\n : openapi\n ? { ...json, nullable: true }\n : { anyOf: [json, { type: 'null' }] }\n }\n const required = columns.filter((c) => c.required).map((c) => c.name)\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n }\n }\n\n return {\n safeParse,\n toJsonSchema,\n '~standard': {\n version: 1,\n vendor: 'kickjs-db',\n validate: (value: unknown) => {\n const result = safeParse(value)\n return result.success ? { value: result.data } : { issues: result.issues }\n },\n },\n }\n}\n\n/** A row as read: every column present, nullable ones may be `null`. */\nexport function selectSchema<T extends TableDecl, const O extends keyof ColumnsOf<T> = never>(\n table: T,\n options?: TableSchemaOptions<T> & { omit?: readonly O[] },\n): TableSchema<Omit<InferSelect<T>, O>> {\n return buildSchema(table, 'select', options as TableSchemaOptions<TableDecl>)\n}\n\n/** A row to insert: serial, defaulted and nullable columns are optional. */\nexport function insertSchema<T extends TableDecl, const O extends keyof ColumnsOf<T> = never>(\n table: T,\n options?: TableSchemaOptions<T> & { omit?: readonly O[] },\n): TableSchema<Omit<InferInsert<T>, O>> {\n return buildSchema(table, 'insert', options as TableSchemaOptions<TableDecl>)\n}\n\n/** A patch: every column optional. */\nexport function updateSchema<T extends TableDecl, const O extends keyof ColumnsOf<T> = never>(\n table: T,\n options?: TableSchemaOptions<T> & { omit?: readonly O[] },\n): TableSchema<Partial<Omit<InferInsert<T>, O>>> {\n return buildSchema(table, 'update', options as TableSchemaOptions<TableDecl>)\n}\n"],"mappings":";;;;;;;;;;yHA0HA,MAAM,GAAM,QAA4B,CAAE,GAAI,GAAM,KAAM,GACpD,MAAQ,QAAiB,KAAO,kBAA4B,CAAE,GAAI,GAAO,QAAS,IAAK,GAEvF,QAAU,UACV,QAAU,kBACV,KAAO,kEACP,MAAQ,6BAMd,SAAS,YAAY,QAAiB,QAA6B,CACjE,MAAO,CACL,KAAM,CAAE,KAAM,UAAW,QAAS,OAAQ,EAC1C,MAAQ,GACN,OAAO,GAAM,UAAY,CAAC,OAAO,UAAU,CAAC,EACxC,KAAK,qBAAqB,EAC1B,EAAI,SAAW,EAAI,QACjB,KAAK,mBAAmB,QAAQ,OAAO,UAAW,EAAI,QAAU,YAAc,SAAS,EACvF,GAAG,CAAC,CACd,CACF,CAEA,MAAM,MAAQ,MACR,MAAQ,WACR,MAAQ,IAAM,IAEpB,SAAS,WAAW,KAAgC,CAAC,EAAG,MAAsC,CAC5F,MAAO,CACL,KAAM,CAAE,KAAM,SAAU,GAAG,IAAK,EAChC,MAAQ,GAAuB,CAC7B,GAAI,OAAO,GAAM,SAAU,OAAO,KAAK,mBAAmB,EAC1D,IAAM,QAAU,QAAQ,CAAC,EACzB,OAAO,QAAU,KAAK,QAAS,gBAAgB,EAAI,GAAG,CAAC,CACzD,CACF,CACF,CAEA,SAAS,SAAS,OAA0C,CAC1D,MAAO,CACL,KAAM,CAAE,KAAM,SAAU,MAAO,EAC/B,MAAQ,GAAM,CACZ,IAAM,KAAO,aAAa,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-1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
2
|
+
import { on as MigrationAdapter } from "./index-BQQWKybR.mjs";
|
|
3
3
|
import { Dialect } from "kysely";
|
|
4
4
|
//#region src/adapters/sqlite/adapter.d.ts
|
|
5
5
|
/**
|
|
@@ -18,7 +18,7 @@ import { Dialect } from "kysely";
|
|
|
18
18
|
* (callers had to cast — same fix as `SqliteIntrospectDb`). Row typing
|
|
19
19
|
* happens at the call sites via assertions instead.
|
|
20
20
|
*/
|
|
21
|
-
interface SqliteStatement {
|
|
21
|
+
export interface SqliteStatement {
|
|
22
22
|
run(...params: readonly unknown[]): {
|
|
23
23
|
changes: number;
|
|
24
24
|
lastInsertRowid: number | bigint;
|
|
@@ -26,12 +26,12 @@ interface SqliteStatement {
|
|
|
26
26
|
all(...params: readonly unknown[]): unknown[];
|
|
27
27
|
get(...params: readonly unknown[]): unknown;
|
|
28
28
|
}
|
|
29
|
-
interface SqliteDatabaseLike {
|
|
29
|
+
export interface SqliteDatabaseLike {
|
|
30
30
|
prepare(sql: string): SqliteStatement;
|
|
31
31
|
exec(sql: string): unknown;
|
|
32
32
|
close(): unknown;
|
|
33
33
|
}
|
|
34
|
-
interface SqliteAdapterOptions {
|
|
34
|
+
export interface SqliteAdapterOptions {
|
|
35
35
|
/**
|
|
36
36
|
* better-sqlite3 (or compatible) Database handle. Caller-owned —
|
|
37
37
|
* the adapter's `close()` does NOT close the database because
|
|
@@ -53,10 +53,10 @@ interface SqliteAdapterOptions {
|
|
|
53
53
|
* vs the code-first DSL), so it powers `kick db introspect` rather than
|
|
54
54
|
* byte-exact drift detection.
|
|
55
55
|
*/
|
|
56
|
-
declare function sqliteAdapter(opts: SqliteAdapterOptions): MigrationAdapter;
|
|
56
|
+
export declare function sqliteAdapter(opts: SqliteAdapterOptions): MigrationAdapter;
|
|
57
57
|
//#endregion
|
|
58
58
|
//#region src/adapters/sqlite/dialect.d.ts
|
|
59
|
-
interface SqliteDialectOptions {
|
|
59
|
+
export interface SqliteDialectOptions {
|
|
60
60
|
/**
|
|
61
61
|
* better-sqlite3-compatible database handle. Both `new Database(...)`
|
|
62
62
|
* from `better-sqlite3` and bun's `bun:sqlite` `Database` match
|
|
@@ -84,7 +84,6 @@ interface SqliteDialectOptions {
|
|
|
84
84
|
* export const migrationAdapter = sqliteAdapter({ database })
|
|
85
85
|
* ```
|
|
86
86
|
*/
|
|
87
|
-
declare function sqliteDialect(opts: SqliteDialectOptions): Dialect;
|
|
87
|
+
export declare function sqliteDialect(opts: SqliteDialectOptions): Dialect;
|
|
88
88
|
//#endregion
|
|
89
|
-
export { SqliteAdapterOptions, SqliteDatabaseLike, SqliteDialectOptions, SqliteStatement, sqliteAdapter, sqliteDialect };
|
|
90
89
|
//# sourceMappingURL=sqlite.d.mts.map
|
package/dist/sqlite.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.d.mts","names":[],"sources":["../src/adapters/sqlite/adapter.ts","../src/adapters/sqlite/dialect.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"sqlite.d.mts","names":[],"sources":["../src/adapters/sqlite/adapter.ts","../src/adapters/sqlite/dialect.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;iBA0BiB;EACf,OAAO;IAA+B;IAAiB;;EACvD,OAAO;EACP,OAAO;;iBAGQ;EACf,QAAQ,cAAc;EACtB,KAAK;EACL;;iBAGe;;;;;;;EAOf,UAAU;;;;;;;;;;;;;;;wBAgBI,cAAc,MAAM,uBAAuB;;;iBCnD1C;;;;;;;EAOf,UAAU;;;;;;;;;;;;;;;;;;;;;wBAsBI,cAAc,MAAM,uBAAuB"}
|
package/dist/sqlite.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db
|
|
2
|
+
* @forinda/kickjs-db v8.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{
|
|
11
|
+
import{ht as migrationsTableDdl,lt as introspectSqlite,mt as lockTableDdl,q as markDialect}from"./src-BEJ33yHI.mjs";import{SqliteDialect}from"kysely";function sqliteAdapter(opts){let dialect=`sqlite`,{database}=opts,runBatch=sql=>database.exec(sql);return{dialect,async ensureMigrationTables(){runBatch(migrationsTableDdl(dialect)),runBatch(lockTableDdl(dialect))},async listApplied(){return database.prepare(`SELECT id, name, hash, batch, applied_at, direction
|
|
12
12
|
FROM kick_migrations
|
|
13
13
|
ORDER BY applied_at ASC, id ASC`).all().map(row=>({id:row.id,name:row.name,hash:row.hash,batch:Number(row.batch),appliedAt:row.applied_at,direction:row.direction}))},async recordApplied(row){database.prepare(`INSERT INTO kick_migrations (id, name, hash, batch, direction)
|
|
14
14
|
VALUES (?, ?, ?, ?, ?)`).run(row.id,row.name,row.hash,row.batch,row.direction)},async removeApplied(id){database.prepare(`DELETE FROM kick_migrations WHERE id = ?`).run(id)},async acquireLock(owner){return database.prepare(`UPDATE kick_migrations_lock
|