pg-codegen 5.12.0 → 5.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -2
- package/emit/barrel.js +7 -1
- package/emit/client.d.ts +5 -0
- package/emit/client.js +132 -0
- package/emit/templates/client.d.ts +135 -0
- package/emit/templates/client.js +214 -0
- package/emit/templates/client.ts +358 -0
- package/esm/emit/barrel.js +7 -1
- package/esm/emit/client.js +94 -0
- package/esm/emit/templates/client.js +209 -0
- package/esm/emit/templates/client.ts +358 -0
- package/esm/generate.js +3 -0
- package/generate.js +3 -0
- package/package.json +6 -4
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prisma-like table client over @constructive-io/query-builder.
|
|
3
|
+
*
|
|
4
|
+
* This is the RUNTIME code that gets copied to generated output. Generated
|
|
5
|
+
* per-schema `db` factories bind one TableClient per table, wiring the
|
|
6
|
+
* generated column metadata and field decoders in so call sites only see
|
|
7
|
+
* camelCase fields, `where` filters in the shared query-spec grammar, and
|
|
8
|
+
* decoded application values.
|
|
9
|
+
*
|
|
10
|
+
* NOTE: This file is read at codegen time and written to output.
|
|
11
|
+
* Any changes here will affect all generated clients.
|
|
12
|
+
*/
|
|
13
|
+
import type { Filter, SqlValue } from '@constructive-io/query-builder';
|
|
14
|
+
import { fn, lit, QueryBuilder } from '@constructive-io/query-builder';
|
|
15
|
+
|
|
16
|
+
/** Anything with pg's `query(text, values)` shape: Pool, PoolClient, Client. */
|
|
17
|
+
export interface Queryable {
|
|
18
|
+
query(text: string, values?: unknown[]): Promise<{ rows: unknown[]; rowCount?: number | null }>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One generated decoder per field, as emitted in the `<TABLE>_FIELDS` constant. */
|
|
22
|
+
export type FieldDecoders<App> = {
|
|
23
|
+
[K in keyof App]: (value: unknown, label?: string) => App[K];
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Table wiring supplied by the generated per-schema `db` factory. */
|
|
27
|
+
export interface TableSpec<App> {
|
|
28
|
+
schema: string;
|
|
29
|
+
table: string;
|
|
30
|
+
columnByField: Record<string, string>;
|
|
31
|
+
fields: FieldDecoders<App>;
|
|
32
|
+
/** camelCase fields backed by json/jsonb columns, serialized on writes. */
|
|
33
|
+
jsonFields?: readonly string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Select shape: `{ id: true, name: true }` — same as the GraphQL ORM. */
|
|
37
|
+
export type SelectShape<App> = { [K in keyof App]?: boolean };
|
|
38
|
+
|
|
39
|
+
type TrueKeys<App, S> = {
|
|
40
|
+
[K in keyof S]-?: S[K] extends true ? K & keyof App : never;
|
|
41
|
+
}[keyof S];
|
|
42
|
+
|
|
43
|
+
/** Rows narrow to the selected fields; no `select` returns the full record. */
|
|
44
|
+
export type SelectResult<App, S extends SelectShape<App> | undefined> =
|
|
45
|
+
S extends SelectShape<App>
|
|
46
|
+
? [TrueKeys<App, S>] extends [never]
|
|
47
|
+
? App
|
|
48
|
+
: Pick<App, TrueKeys<App, S>>
|
|
49
|
+
: App;
|
|
50
|
+
|
|
51
|
+
/** Per-field operators from the shared query-spec grammar. */
|
|
52
|
+
export interface FieldOps<V> {
|
|
53
|
+
equalTo?: V;
|
|
54
|
+
notEqualTo?: V;
|
|
55
|
+
distinctFrom?: V;
|
|
56
|
+
notDistinctFrom?: V;
|
|
57
|
+
lessThan?: V;
|
|
58
|
+
lessThanOrEqualTo?: V;
|
|
59
|
+
greaterThan?: V;
|
|
60
|
+
greaterThanOrEqualTo?: V;
|
|
61
|
+
in?: V[];
|
|
62
|
+
notIn?: V[];
|
|
63
|
+
like?: string;
|
|
64
|
+
notLike?: string;
|
|
65
|
+
likeInsensitive?: string;
|
|
66
|
+
notLikeInsensitive?: string;
|
|
67
|
+
includes?: string;
|
|
68
|
+
notIncludes?: string;
|
|
69
|
+
includesInsensitive?: string;
|
|
70
|
+
startsWith?: string;
|
|
71
|
+
endsWith?: string;
|
|
72
|
+
isNull?: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const FIELD_OP_NAMES: ReadonlySet<string> = new Set([
|
|
76
|
+
'equalTo',
|
|
77
|
+
'notEqualTo',
|
|
78
|
+
'distinctFrom',
|
|
79
|
+
'notDistinctFrom',
|
|
80
|
+
'lessThan',
|
|
81
|
+
'lessThanOrEqualTo',
|
|
82
|
+
'greaterThan',
|
|
83
|
+
'greaterThanOrEqualTo',
|
|
84
|
+
'in',
|
|
85
|
+
'notIn',
|
|
86
|
+
'like',
|
|
87
|
+
'notLike',
|
|
88
|
+
'likeInsensitive',
|
|
89
|
+
'notLikeInsensitive',
|
|
90
|
+
'includes',
|
|
91
|
+
'notIncludes',
|
|
92
|
+
'includesInsensitive',
|
|
93
|
+
'startsWith',
|
|
94
|
+
'endsWith',
|
|
95
|
+
'isNull'
|
|
96
|
+
]);
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Where filter keyed by camelCase field names. A bare value means `equalTo`
|
|
100
|
+
* (`null` means `isNull`). Extra string keys are physical column names —
|
|
101
|
+
* runtime-configured scope key columns qualify rows the same way any other
|
|
102
|
+
* condition does.
|
|
103
|
+
*/
|
|
104
|
+
export type Where<App> = {
|
|
105
|
+
[K in keyof App]?: App[K] | FieldOps<NonNullable<App[K]>>;
|
|
106
|
+
} & {
|
|
107
|
+
[column: string]: unknown;
|
|
108
|
+
} & {
|
|
109
|
+
and?: Where<App>[];
|
|
110
|
+
or?: Where<App>[];
|
|
111
|
+
not?: Where<App>;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Write data keyed by camelCase field names. Extra string keys are physical
|
|
116
|
+
* column names — runtime-configured scope key columns are stamped the same
|
|
117
|
+
* way any other value is.
|
|
118
|
+
*/
|
|
119
|
+
export type Data<App> = Partial<App> & { [column: string]: unknown };
|
|
120
|
+
|
|
121
|
+
export type OrderDirection = 'ASC' | 'DESC';
|
|
122
|
+
|
|
123
|
+
/** Order spec keyed by camelCase field names, e.g. `{ createdAt: 'DESC' }`. */
|
|
124
|
+
export type OrderBy<App> = { [K in keyof App]?: OrderDirection };
|
|
125
|
+
|
|
126
|
+
export interface FindManyArgs<App, S extends SelectShape<App> | undefined> {
|
|
127
|
+
where?: Where<App>;
|
|
128
|
+
select?: S;
|
|
129
|
+
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
130
|
+
limit?: number;
|
|
131
|
+
offset?: number;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface FindFirstArgs<App, S extends SelectShape<App> | undefined> {
|
|
135
|
+
where?: Where<App>;
|
|
136
|
+
select?: S;
|
|
137
|
+
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
|
|
141
|
+
data: Data<App>;
|
|
142
|
+
select?: S;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
|
|
146
|
+
where: Where<App>;
|
|
147
|
+
data: Data<App>;
|
|
148
|
+
select?: S;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface DeleteArgs<App, S extends SelectShape<App> | undefined> {
|
|
152
|
+
where: Where<App>;
|
|
153
|
+
select?: S;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Thrown by `findFirstOrThrow` / `updateOrThrow` when no row matches. */
|
|
157
|
+
export class RowNotFoundError extends Error {
|
|
158
|
+
constructor(
|
|
159
|
+
public readonly table: string,
|
|
160
|
+
public readonly operation: string
|
|
161
|
+
) {
|
|
162
|
+
super(`${table}.${operation}: no row matched the given where filter`);
|
|
163
|
+
this.name = 'RowNotFoundError';
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const encodeScalar = (value: unknown): SqlValue => {
|
|
168
|
+
if (value === null) return null;
|
|
169
|
+
if (value instanceof Date) return value.toISOString();
|
|
170
|
+
if (typeof value === 'object' && !Array.isArray(value)) return JSON.stringify(value);
|
|
171
|
+
return value as SqlValue;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
export class TableClient<App> {
|
|
175
|
+
constructor(
|
|
176
|
+
private readonly spec: TableSpec<App>,
|
|
177
|
+
private readonly db: Queryable
|
|
178
|
+
) {}
|
|
179
|
+
|
|
180
|
+
async findMany<S extends SelectShape<App> | undefined = undefined>(
|
|
181
|
+
args: FindManyArgs<App, S> = {}
|
|
182
|
+
): Promise<SelectResult<App, S>[]> {
|
|
183
|
+
const fields = this.selectedFields(args.select);
|
|
184
|
+
const query = this.baseQuery().select(fields.map(field => this.column(field)));
|
|
185
|
+
if (args.where) query.where(this.filter(args.where));
|
|
186
|
+
this.applyOrderBy(query, args.orderBy);
|
|
187
|
+
if (args.limit !== undefined) query.limit(args.limit);
|
|
188
|
+
if (args.offset !== undefined) query.offset(args.offset);
|
|
189
|
+
const { text, values } = query.build();
|
|
190
|
+
const { rows } = await this.db.query(text, values);
|
|
191
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async findFirst<S extends SelectShape<App> | undefined = undefined>(
|
|
195
|
+
args: FindFirstArgs<App, S> = {}
|
|
196
|
+
): Promise<SelectResult<App, S> | null> {
|
|
197
|
+
const rows = await this.findMany({ ...args, limit: 1 });
|
|
198
|
+
return rows.length > 0 ? rows[0] : null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async findFirstOrThrow<S extends SelectShape<App> | undefined = undefined>(
|
|
202
|
+
args: FindFirstArgs<App, S> = {}
|
|
203
|
+
): Promise<SelectResult<App, S>> {
|
|
204
|
+
const row = await this.findFirst(args);
|
|
205
|
+
if (row === null) throw new RowNotFoundError(this.spec.table, 'findFirstOrThrow');
|
|
206
|
+
return row;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async count(where?: Where<App>): Promise<number> {
|
|
210
|
+
const query = this.baseQuery().select([]).selectExpr('count', fn('count', [lit(1)]));
|
|
211
|
+
if (where) query.where(this.filter(where));
|
|
212
|
+
const { text, values } = query.build();
|
|
213
|
+
const { rows } = await this.db.query(text, values);
|
|
214
|
+
const row = rows[0] as { count: string | number };
|
|
215
|
+
return Number(row.count);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async create<S extends SelectShape<App> | undefined = undefined>(
|
|
219
|
+
args: CreateArgs<App, S>
|
|
220
|
+
): Promise<SelectResult<App, S>> {
|
|
221
|
+
const fields = this.selectedFields(args.select);
|
|
222
|
+
const query = this.baseQuery()
|
|
223
|
+
.insert(this.encodeData(args.data))
|
|
224
|
+
.returning(fields.map(field => this.column(field)));
|
|
225
|
+
const { text, values } = query.build();
|
|
226
|
+
const { rows } = await this.db.query(text, values);
|
|
227
|
+
return this.decodeRow(rows[0], fields);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async update<S extends SelectShape<App> | undefined = undefined>(
|
|
231
|
+
args: UpdateArgs<App, S>
|
|
232
|
+
): Promise<SelectResult<App, S>[]> {
|
|
233
|
+
const fields = this.selectedFields(args.select);
|
|
234
|
+
const query = this.baseQuery()
|
|
235
|
+
.update(this.encodeData(args.data))
|
|
236
|
+
.where(this.filter(args.where))
|
|
237
|
+
.returning(fields.map(field => this.column(field)));
|
|
238
|
+
const { text, values } = query.build();
|
|
239
|
+
const { rows } = await this.db.query(text, values);
|
|
240
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async updateOrThrow<S extends SelectShape<App> | undefined = undefined>(
|
|
244
|
+
args: UpdateArgs<App, S>
|
|
245
|
+
): Promise<SelectResult<App, S>> {
|
|
246
|
+
const rows = await this.update(args);
|
|
247
|
+
if (rows.length === 0) throw new RowNotFoundError(this.spec.table, 'updateOrThrow');
|
|
248
|
+
return rows[0];
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async delete<S extends SelectShape<App> | undefined = undefined>(
|
|
252
|
+
args: DeleteArgs<App, S>
|
|
253
|
+
): Promise<SelectResult<App, S>[]> {
|
|
254
|
+
const fields = this.selectedFields(args.select);
|
|
255
|
+
const query = this.baseQuery()
|
|
256
|
+
.delete()
|
|
257
|
+
.where(this.filter(args.where))
|
|
258
|
+
.returning(fields.map(field => this.column(field)));
|
|
259
|
+
const { text, values } = query.build();
|
|
260
|
+
const { rows } = await this.db.query(text, values);
|
|
261
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Rebind to another connection (e.g. a transaction's PoolClient). */
|
|
265
|
+
$with(db: Queryable): TableClient<App> {
|
|
266
|
+
return new TableClient(this.spec, db);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private baseQuery(): QueryBuilder {
|
|
270
|
+
return new QueryBuilder().schema(this.spec.schema).table(this.spec.table);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private column(field: string): string {
|
|
274
|
+
return this.spec.columnByField[field] ?? field;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
private selectedFields(select: SelectShape<App> | undefined): (keyof App & string)[] {
|
|
278
|
+
const all = Object.keys(this.spec.columnByField) as (keyof App & string)[];
|
|
279
|
+
if (!select) return all;
|
|
280
|
+
const picked = all.filter(field => select[field] === true);
|
|
281
|
+
return picked.length > 0 ? picked : all;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private decodeRow<S extends SelectShape<App> | undefined>(
|
|
285
|
+
row: unknown,
|
|
286
|
+
fields: (keyof App & string)[]
|
|
287
|
+
): SelectResult<App, S> {
|
|
288
|
+
const raw = row as Record<string, unknown>;
|
|
289
|
+
const decoded: Record<string, unknown> = {};
|
|
290
|
+
for (const field of fields) {
|
|
291
|
+
decoded[field] = this.spec.fields[field](raw[this.column(field)]);
|
|
292
|
+
}
|
|
293
|
+
return decoded as SelectResult<App, S>;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
private filter(where: Where<App>): Filter {
|
|
297
|
+
const filter: Filter = {};
|
|
298
|
+
for (const [key, value] of Object.entries(where)) {
|
|
299
|
+
if (value === undefined) continue;
|
|
300
|
+
if (key === 'and' || key === 'or') {
|
|
301
|
+
filter[key] = (value as Where<App>[]).map(nested => this.filter(nested));
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (key === 'not') {
|
|
305
|
+
filter.not = this.filter(value as Where<App>);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
filter[this.column(key)] = this.fieldFilter(value);
|
|
309
|
+
}
|
|
310
|
+
return filter;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private fieldFilter(value: unknown): Filter[string] {
|
|
314
|
+
if (value === null) return { isNull: true };
|
|
315
|
+
if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)) {
|
|
316
|
+
const entries = Object.entries(value as Record<string, unknown>);
|
|
317
|
+
if (entries.length > 0 && entries.every(([op]) => FIELD_OP_NAMES.has(op))) {
|
|
318
|
+
const ops: Record<string, unknown> = {};
|
|
319
|
+
for (const [op, operand] of entries) {
|
|
320
|
+
if (operand === undefined) continue;
|
|
321
|
+
ops[op] = Array.isArray(operand)
|
|
322
|
+
? operand.map(encodeScalar)
|
|
323
|
+
: op === 'isNull'
|
|
324
|
+
? operand
|
|
325
|
+
: encodeScalar(operand);
|
|
326
|
+
}
|
|
327
|
+
return ops as Filter[string];
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return { equalTo: encodeScalar(value) };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private applyOrderBy(query: QueryBuilder, orderBy: OrderBy<App> | OrderBy<App>[] | undefined): void {
|
|
334
|
+
if (!orderBy) return;
|
|
335
|
+
for (const spec of Array.isArray(orderBy) ? orderBy : [orderBy]) {
|
|
336
|
+
for (const [field, direction] of Object.entries(spec)) {
|
|
337
|
+
if (!direction) continue;
|
|
338
|
+
query.orderBy(this.column(field), direction as OrderDirection);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private encodeData(data: Data<App>): Record<string, SqlValue> {
|
|
344
|
+
const encoded: Record<string, SqlValue> = {};
|
|
345
|
+
for (const [field, value] of Object.entries(data)) {
|
|
346
|
+
if (value === undefined) continue;
|
|
347
|
+
if (value !== null && this.spec.jsonFields?.includes(field)) {
|
|
348
|
+
encoded[this.column(field)] = JSON.stringify(value);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
// pg serializes JS arrays into PostgreSQL array literals.
|
|
352
|
+
encoded[this.column(field)] = Array.isArray(value)
|
|
353
|
+
? (value.map(encodeScalar) as unknown as SqlValue)
|
|
354
|
+
: encodeScalar(value);
|
|
355
|
+
}
|
|
356
|
+
return encoded;
|
|
357
|
+
}
|
|
358
|
+
}
|
package/esm/emit/barrel.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
/** Emits the per-schema and root index modules. */
|
|
2
2
|
import { toCamelCase, toKebabCase } from 'inflekt';
|
|
3
3
|
import { generateCode, t } from './babel';
|
|
4
|
-
|
|
4
|
+
/** File names the schema directory reserves for its own modules. */
|
|
5
|
+
const RESERVED_FILE_NAMES = new Set(['index', 'db', 'enums']);
|
|
6
|
+
export const tableFileName = (tableName) => {
|
|
7
|
+
const name = toKebabCase(tableName);
|
|
8
|
+
return RESERVED_FILE_NAMES.has(name) ? `${name}-table` : name;
|
|
9
|
+
};
|
|
5
10
|
export const emitSchemaIndex = (schema) => {
|
|
6
11
|
const statements = [];
|
|
7
12
|
if (schema.enums.length > 0) {
|
|
@@ -10,6 +15,7 @@ export const emitSchemaIndex = (schema) => {
|
|
|
10
15
|
for (const table of schema.tables) {
|
|
11
16
|
statements.push(t.exportAllDeclaration(t.stringLiteral(`./${tableFileName(table.name)}`)));
|
|
12
17
|
}
|
|
18
|
+
statements.push(t.exportAllDeclaration(t.stringLiteral('./db')));
|
|
13
19
|
return generateCode(statements);
|
|
14
20
|
};
|
|
15
21
|
export const emitRootIndex = (schemas) => {
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits the Prisma-like database client: the shared `client.ts` runtime
|
|
3
|
+
* (copied from a typechecked template) and one `db.ts` per schema binding a
|
|
4
|
+
* TableClient per table over the generated metadata and field decoders.
|
|
5
|
+
*/
|
|
6
|
+
import * as fs from 'fs';
|
|
7
|
+
import { toCamelCase, toConstantCase, toPascalCase } from 'inflekt';
|
|
8
|
+
import * as path from 'path';
|
|
9
|
+
import { exportConst, generateCode, namedImport, t, withJsDoc } from './babel';
|
|
10
|
+
import { tableFileName } from './barrel';
|
|
11
|
+
const findTemplateFile = (templateName) => {
|
|
12
|
+
const templatePath = path.join(__dirname, 'templates', templateName);
|
|
13
|
+
if (fs.existsSync(templatePath))
|
|
14
|
+
return templatePath;
|
|
15
|
+
throw new Error(`Could not find template file: ${templateName}. Searched in: ${templatePath}`);
|
|
16
|
+
};
|
|
17
|
+
/** The shared runtime, copied verbatim with the template note replaced. */
|
|
18
|
+
export const emitClientRuntime = () => {
|
|
19
|
+
const content = fs.readFileSync(findTemplateFile('client.ts'), 'utf8');
|
|
20
|
+
return content.replace(/ \* NOTE: This file is read at codegen time and written to output\.\n \* Any changes here will affect all generated clients\.\n \*\/\n/, ' * Generated by pg-codegen. DO NOT EDIT.\n */\n/* eslint-disable */\n');
|
|
21
|
+
};
|
|
22
|
+
const typeImport = (names, source) => {
|
|
23
|
+
const declaration = namedImport(names, source);
|
|
24
|
+
declaration.importKind = 'type';
|
|
25
|
+
return declaration;
|
|
26
|
+
};
|
|
27
|
+
const modelKey = (table) => toCamelCase(table.name);
|
|
28
|
+
/** The per-schema `db.ts`: a `create<Schema>Db` factory of bound TableClients. */
|
|
29
|
+
export const emitSchemaDbModule = (schema) => {
|
|
30
|
+
const pascal = toPascalCase(schema.name);
|
|
31
|
+
const dbTypeName = `${pascal}Db`;
|
|
32
|
+
const optionsName = `${pascal}DbOptions`;
|
|
33
|
+
const factoryName = `create${pascal}Db`;
|
|
34
|
+
const statements = [
|
|
35
|
+
namedImport(['TableClient'], '../client'),
|
|
36
|
+
typeImport(['Queryable'], '../client')
|
|
37
|
+
];
|
|
38
|
+
for (const table of schema.tables) {
|
|
39
|
+
const appType = toPascalCase(table.name);
|
|
40
|
+
const constant = toConstantCase(table.name);
|
|
41
|
+
const file = `./${tableFileName(table.name)}`;
|
|
42
|
+
statements.push(typeImport([appType], file));
|
|
43
|
+
statements.push(namedImport([`${constant}_FIELDS`, `${constant}_TABLE`], file));
|
|
44
|
+
}
|
|
45
|
+
const tableNameProps = schema.tables.map(table => {
|
|
46
|
+
const prop = t.tsPropertySignature(t.identifier(modelKey(table)), t.tsTypeAnnotation(t.tsStringKeyword()));
|
|
47
|
+
prop.optional = true;
|
|
48
|
+
return prop;
|
|
49
|
+
});
|
|
50
|
+
const schemaProp = t.tsPropertySignature(t.identifier('schema'), t.tsTypeAnnotation(t.tsStringKeyword()));
|
|
51
|
+
schemaProp.optional = true;
|
|
52
|
+
const tablesProp = t.tsPropertySignature(t.identifier('tables'), t.tsTypeAnnotation(t.tsTypeLiteral(tableNameProps)));
|
|
53
|
+
tablesProp.optional = true;
|
|
54
|
+
statements.push(withJsDoc(t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(optionsName), null, null, t.tsInterfaceBody([schemaProp, tablesProp]))), 'Runtime overrides for the physical schema and per-table names, for tables provisioned into per-tenant schemas.'));
|
|
55
|
+
const dbMembers = schema.tables.map(table => t.tsPropertySignature(t.identifier(modelKey(table)), t.tsTypeAnnotation(t.tsTypeReference(t.identifier('TableClient'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(toPascalCase(table.name)))])))));
|
|
56
|
+
const withParam = t.identifier('db');
|
|
57
|
+
withParam.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Queryable')));
|
|
58
|
+
const withMember = t.tsMethodSignature(t.identifier('$with'), null, [withParam], t.tsTypeAnnotation(t.tsTypeReference(t.identifier(dbTypeName))));
|
|
59
|
+
t.addComment(withMember, 'leading', "* Rebind every table client to another connection (e.g. a transaction's PoolClient). ", false);
|
|
60
|
+
dbMembers.push(withMember);
|
|
61
|
+
statements.push(t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(dbTypeName), null, null, t.tsInterfaceBody(dbMembers))));
|
|
62
|
+
const clientProperties = schema.tables.map(table => {
|
|
63
|
+
const constant = toConstantCase(table.name);
|
|
64
|
+
const spec = t.objectExpression([
|
|
65
|
+
t.objectProperty(t.identifier('schema'), t.logicalExpression('??', t.optionalMemberExpression(t.identifier('options'), t.identifier('schema'), false, true), t.memberExpression(t.identifier(`${constant}_TABLE`), t.identifier('schema')))),
|
|
66
|
+
t.objectProperty(t.identifier('table'), t.logicalExpression('??', t.optionalMemberExpression(t.optionalMemberExpression(t.identifier('options'), t.identifier('tables'), false, true), t.identifier(modelKey(table)), false, true), t.memberExpression(t.identifier(`${constant}_TABLE`), t.identifier('name')))),
|
|
67
|
+
t.objectProperty(t.identifier('columnByField'), t.memberExpression(t.identifier(`${constant}_TABLE`), t.identifier('columnByField'))),
|
|
68
|
+
t.objectProperty(t.identifier('fields'), t.identifier(`${constant}_FIELDS`))
|
|
69
|
+
]);
|
|
70
|
+
const jsonFields = table.columns.filter(column => column.scalar === 'json');
|
|
71
|
+
if (jsonFields.length > 0) {
|
|
72
|
+
spec.properties.push(t.objectProperty(t.identifier('jsonFields'), t.arrayExpression(jsonFields.map(column => t.stringLiteral(column.propertyName)))));
|
|
73
|
+
}
|
|
74
|
+
const client = t.newExpression(t.identifier('TableClient'), [spec, t.identifier('db')]);
|
|
75
|
+
client.typeParameters = t.tsTypeParameterInstantiation([
|
|
76
|
+
t.tsTypeReference(t.identifier(toPascalCase(table.name)))
|
|
77
|
+
]);
|
|
78
|
+
return t.objectProperty(t.identifier(modelKey(table)), client);
|
|
79
|
+
});
|
|
80
|
+
const nextParam = t.identifier('next');
|
|
81
|
+
nextParam.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Queryable')));
|
|
82
|
+
clientProperties.push(t.objectProperty(t.identifier('$with'), t.arrowFunctionExpression([nextParam], t.callExpression(t.identifier(factoryName), [t.identifier('next'), t.identifier('options')]))));
|
|
83
|
+
const dbParam = t.identifier('db');
|
|
84
|
+
dbParam.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Queryable')));
|
|
85
|
+
const optionsParam = t.assignmentPattern((() => {
|
|
86
|
+
const id = t.identifier('options');
|
|
87
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(optionsName)));
|
|
88
|
+
return id;
|
|
89
|
+
})(), t.objectExpression([]));
|
|
90
|
+
const factory = t.arrowFunctionExpression([dbParam, optionsParam], t.objectExpression(clientProperties));
|
|
91
|
+
factory.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(dbTypeName)));
|
|
92
|
+
statements.push(withJsDoc(exportConst(factoryName, factory), `One Prisma-like client per table over any pg Pool/Client, decoding rows into the generated ${pascal} application types.`));
|
|
93
|
+
return generateCode(statements);
|
|
94
|
+
};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { fn, lit, QueryBuilder } from '@constructive-io/query-builder';
|
|
2
|
+
const FIELD_OP_NAMES = new Set([
|
|
3
|
+
'equalTo',
|
|
4
|
+
'notEqualTo',
|
|
5
|
+
'distinctFrom',
|
|
6
|
+
'notDistinctFrom',
|
|
7
|
+
'lessThan',
|
|
8
|
+
'lessThanOrEqualTo',
|
|
9
|
+
'greaterThan',
|
|
10
|
+
'greaterThanOrEqualTo',
|
|
11
|
+
'in',
|
|
12
|
+
'notIn',
|
|
13
|
+
'like',
|
|
14
|
+
'notLike',
|
|
15
|
+
'likeInsensitive',
|
|
16
|
+
'notLikeInsensitive',
|
|
17
|
+
'includes',
|
|
18
|
+
'notIncludes',
|
|
19
|
+
'includesInsensitive',
|
|
20
|
+
'startsWith',
|
|
21
|
+
'endsWith',
|
|
22
|
+
'isNull'
|
|
23
|
+
]);
|
|
24
|
+
/** Thrown by `findFirstOrThrow` / `updateOrThrow` when no row matches. */
|
|
25
|
+
export class RowNotFoundError extends Error {
|
|
26
|
+
table;
|
|
27
|
+
operation;
|
|
28
|
+
constructor(table, operation) {
|
|
29
|
+
super(`${table}.${operation}: no row matched the given where filter`);
|
|
30
|
+
this.table = table;
|
|
31
|
+
this.operation = operation;
|
|
32
|
+
this.name = 'RowNotFoundError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const encodeScalar = (value) => {
|
|
36
|
+
if (value === null)
|
|
37
|
+
return null;
|
|
38
|
+
if (value instanceof Date)
|
|
39
|
+
return value.toISOString();
|
|
40
|
+
if (typeof value === 'object' && !Array.isArray(value))
|
|
41
|
+
return JSON.stringify(value);
|
|
42
|
+
return value;
|
|
43
|
+
};
|
|
44
|
+
export class TableClient {
|
|
45
|
+
spec;
|
|
46
|
+
db;
|
|
47
|
+
constructor(spec, db) {
|
|
48
|
+
this.spec = spec;
|
|
49
|
+
this.db = db;
|
|
50
|
+
}
|
|
51
|
+
async findMany(args = {}) {
|
|
52
|
+
const fields = this.selectedFields(args.select);
|
|
53
|
+
const query = this.baseQuery().select(fields.map(field => this.column(field)));
|
|
54
|
+
if (args.where)
|
|
55
|
+
query.where(this.filter(args.where));
|
|
56
|
+
this.applyOrderBy(query, args.orderBy);
|
|
57
|
+
if (args.limit !== undefined)
|
|
58
|
+
query.limit(args.limit);
|
|
59
|
+
if (args.offset !== undefined)
|
|
60
|
+
query.offset(args.offset);
|
|
61
|
+
const { text, values } = query.build();
|
|
62
|
+
const { rows } = await this.db.query(text, values);
|
|
63
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
64
|
+
}
|
|
65
|
+
async findFirst(args = {}) {
|
|
66
|
+
const rows = await this.findMany({ ...args, limit: 1 });
|
|
67
|
+
return rows.length > 0 ? rows[0] : null;
|
|
68
|
+
}
|
|
69
|
+
async findFirstOrThrow(args = {}) {
|
|
70
|
+
const row = await this.findFirst(args);
|
|
71
|
+
if (row === null)
|
|
72
|
+
throw new RowNotFoundError(this.spec.table, 'findFirstOrThrow');
|
|
73
|
+
return row;
|
|
74
|
+
}
|
|
75
|
+
async count(where) {
|
|
76
|
+
const query = this.baseQuery().select([]).selectExpr('count', fn('count', [lit(1)]));
|
|
77
|
+
if (where)
|
|
78
|
+
query.where(this.filter(where));
|
|
79
|
+
const { text, values } = query.build();
|
|
80
|
+
const { rows } = await this.db.query(text, values);
|
|
81
|
+
const row = rows[0];
|
|
82
|
+
return Number(row.count);
|
|
83
|
+
}
|
|
84
|
+
async create(args) {
|
|
85
|
+
const fields = this.selectedFields(args.select);
|
|
86
|
+
const query = this.baseQuery()
|
|
87
|
+
.insert(this.encodeData(args.data))
|
|
88
|
+
.returning(fields.map(field => this.column(field)));
|
|
89
|
+
const { text, values } = query.build();
|
|
90
|
+
const { rows } = await this.db.query(text, values);
|
|
91
|
+
return this.decodeRow(rows[0], fields);
|
|
92
|
+
}
|
|
93
|
+
async update(args) {
|
|
94
|
+
const fields = this.selectedFields(args.select);
|
|
95
|
+
const query = this.baseQuery()
|
|
96
|
+
.update(this.encodeData(args.data))
|
|
97
|
+
.where(this.filter(args.where))
|
|
98
|
+
.returning(fields.map(field => this.column(field)));
|
|
99
|
+
const { text, values } = query.build();
|
|
100
|
+
const { rows } = await this.db.query(text, values);
|
|
101
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
102
|
+
}
|
|
103
|
+
async updateOrThrow(args) {
|
|
104
|
+
const rows = await this.update(args);
|
|
105
|
+
if (rows.length === 0)
|
|
106
|
+
throw new RowNotFoundError(this.spec.table, 'updateOrThrow');
|
|
107
|
+
return rows[0];
|
|
108
|
+
}
|
|
109
|
+
async delete(args) {
|
|
110
|
+
const fields = this.selectedFields(args.select);
|
|
111
|
+
const query = this.baseQuery()
|
|
112
|
+
.delete()
|
|
113
|
+
.where(this.filter(args.where))
|
|
114
|
+
.returning(fields.map(field => this.column(field)));
|
|
115
|
+
const { text, values } = query.build();
|
|
116
|
+
const { rows } = await this.db.query(text, values);
|
|
117
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
118
|
+
}
|
|
119
|
+
/** Rebind to another connection (e.g. a transaction's PoolClient). */
|
|
120
|
+
$with(db) {
|
|
121
|
+
return new TableClient(this.spec, db);
|
|
122
|
+
}
|
|
123
|
+
baseQuery() {
|
|
124
|
+
return new QueryBuilder().schema(this.spec.schema).table(this.spec.table);
|
|
125
|
+
}
|
|
126
|
+
column(field) {
|
|
127
|
+
return this.spec.columnByField[field] ?? field;
|
|
128
|
+
}
|
|
129
|
+
selectedFields(select) {
|
|
130
|
+
const all = Object.keys(this.spec.columnByField);
|
|
131
|
+
if (!select)
|
|
132
|
+
return all;
|
|
133
|
+
const picked = all.filter(field => select[field] === true);
|
|
134
|
+
return picked.length > 0 ? picked : all;
|
|
135
|
+
}
|
|
136
|
+
decodeRow(row, fields) {
|
|
137
|
+
const raw = row;
|
|
138
|
+
const decoded = {};
|
|
139
|
+
for (const field of fields) {
|
|
140
|
+
decoded[field] = this.spec.fields[field](raw[this.column(field)]);
|
|
141
|
+
}
|
|
142
|
+
return decoded;
|
|
143
|
+
}
|
|
144
|
+
filter(where) {
|
|
145
|
+
const filter = {};
|
|
146
|
+
for (const [key, value] of Object.entries(where)) {
|
|
147
|
+
if (value === undefined)
|
|
148
|
+
continue;
|
|
149
|
+
if (key === 'and' || key === 'or') {
|
|
150
|
+
filter[key] = value.map(nested => this.filter(nested));
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (key === 'not') {
|
|
154
|
+
filter.not = this.filter(value);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
filter[this.column(key)] = this.fieldFilter(value);
|
|
158
|
+
}
|
|
159
|
+
return filter;
|
|
160
|
+
}
|
|
161
|
+
fieldFilter(value) {
|
|
162
|
+
if (value === null)
|
|
163
|
+
return { isNull: true };
|
|
164
|
+
if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)) {
|
|
165
|
+
const entries = Object.entries(value);
|
|
166
|
+
if (entries.length > 0 && entries.every(([op]) => FIELD_OP_NAMES.has(op))) {
|
|
167
|
+
const ops = {};
|
|
168
|
+
for (const [op, operand] of entries) {
|
|
169
|
+
if (operand === undefined)
|
|
170
|
+
continue;
|
|
171
|
+
ops[op] = Array.isArray(operand)
|
|
172
|
+
? operand.map(encodeScalar)
|
|
173
|
+
: op === 'isNull'
|
|
174
|
+
? operand
|
|
175
|
+
: encodeScalar(operand);
|
|
176
|
+
}
|
|
177
|
+
return ops;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { equalTo: encodeScalar(value) };
|
|
181
|
+
}
|
|
182
|
+
applyOrderBy(query, orderBy) {
|
|
183
|
+
if (!orderBy)
|
|
184
|
+
return;
|
|
185
|
+
for (const spec of Array.isArray(orderBy) ? orderBy : [orderBy]) {
|
|
186
|
+
for (const [field, direction] of Object.entries(spec)) {
|
|
187
|
+
if (!direction)
|
|
188
|
+
continue;
|
|
189
|
+
query.orderBy(this.column(field), direction);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
encodeData(data) {
|
|
194
|
+
const encoded = {};
|
|
195
|
+
for (const [field, value] of Object.entries(data)) {
|
|
196
|
+
if (value === undefined)
|
|
197
|
+
continue;
|
|
198
|
+
if (value !== null && this.spec.jsonFields?.includes(field)) {
|
|
199
|
+
encoded[this.column(field)] = JSON.stringify(value);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
// pg serializes JS arrays into PostgreSQL array literals.
|
|
203
|
+
encoded[this.column(field)] = Array.isArray(value)
|
|
204
|
+
? value.map(encodeScalar)
|
|
205
|
+
: encodeScalar(value);
|
|
206
|
+
}
|
|
207
|
+
return encoded;
|
|
208
|
+
}
|
|
209
|
+
}
|