pg-codegen 5.11.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 +89 -59
- package/emit/barrel.js +7 -1
- package/emit/client.d.ts +5 -0
- package/emit/client.js +132 -0
- package/emit/record.js +46 -7
- 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/record.js +46 -7
- 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
package/esm/emit/record.js
CHANGED
|
@@ -59,8 +59,13 @@ const member = (object, key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
|
|
|
59
59
|
? t.memberExpression(t.identifier(object), t.identifier(key))
|
|
60
60
|
: t.memberExpression(t.identifier(object), t.stringLiteral(key), true);
|
|
61
61
|
const objectKey = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? t.identifier(name) : t.stringLiteral(name);
|
|
62
|
-
|
|
63
|
-
|
|
62
|
+
/**
|
|
63
|
+
* The decode call for one column, against an arbitrary value expression and an
|
|
64
|
+
* arbitrary label expression, so a whole-record decoder (`record.foo`, label
|
|
65
|
+
* `` `${label}.foo` ``) and a single-field decoder (`value`, label `label`)
|
|
66
|
+
* share one definition of what a column's runtime check is.
|
|
67
|
+
*/
|
|
68
|
+
const decodeExpression = (column, value, label, usage) => {
|
|
64
69
|
if (column.scalar === 'unknown') {
|
|
65
70
|
// No runtime shape to assert; the value passes through typed `unknown`.
|
|
66
71
|
return value;
|
|
@@ -78,7 +83,7 @@ const decodeExpression = (column, key, usage) => {
|
|
|
78
83
|
return t.callExpression(t.identifier('requireArrayOf'), [
|
|
79
84
|
value,
|
|
80
85
|
t.identifier(elementName),
|
|
81
|
-
|
|
86
|
+
label,
|
|
82
87
|
t.stringLiteral(`an array of ${enumTypeName(enumName)} values`)
|
|
83
88
|
]);
|
|
84
89
|
}
|
|
@@ -86,7 +91,7 @@ const decodeExpression = (column, key, usage) => {
|
|
|
86
91
|
usage.enumImports.add(fnName);
|
|
87
92
|
return column.nullable
|
|
88
93
|
? t.callExpression(t.identifier(fnName), [value])
|
|
89
|
-
: t.callExpression(t.identifier(fnName), [value,
|
|
94
|
+
: t.callExpression(t.identifier(fnName), [value, label]);
|
|
90
95
|
}
|
|
91
96
|
const coercer = COERCERS[column.scalar];
|
|
92
97
|
if (column.isArray) {
|
|
@@ -99,7 +104,7 @@ const decodeExpression = (column, key, usage) => {
|
|
|
99
104
|
return t.callExpression(t.identifier('requireArrayOf'), [
|
|
100
105
|
value,
|
|
101
106
|
t.identifier(coercer.as),
|
|
102
|
-
|
|
107
|
+
label,
|
|
103
108
|
t.stringLiteral(coercer.expectedArray)
|
|
104
109
|
]);
|
|
105
110
|
}
|
|
@@ -107,7 +112,34 @@ const decodeExpression = (column, key, usage) => {
|
|
|
107
112
|
usage.coerceImports.add(fnName);
|
|
108
113
|
return column.nullable
|
|
109
114
|
? t.callExpression(t.identifier(fnName), [value])
|
|
110
|
-
: t.callExpression(t.identifier(fnName), [value,
|
|
115
|
+
: t.callExpression(t.identifier(fnName), [value, label]);
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* `<TABLE>_FIELDS`: one decoder per column, for rows that are NOT a whole
|
|
119
|
+
* table row — a joined projection, an aliased column, a partial SELECT — where
|
|
120
|
+
* a record decoder would reject the absent columns.
|
|
121
|
+
*
|
|
122
|
+
* A nullable column's decoder is lenient (`T | null`, no label); a NOT NULL
|
|
123
|
+
* column's is strict and throws `CoerceError` naming the column, with the label
|
|
124
|
+
* overridable so a projection can name its own alias.
|
|
125
|
+
*/
|
|
126
|
+
const fieldsConstant = (table, name, usage) => {
|
|
127
|
+
const properties = table.columns.map(column => {
|
|
128
|
+
const valueParam = t.identifier('value');
|
|
129
|
+
valueParam.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
|
|
130
|
+
const params = [valueParam];
|
|
131
|
+
let label = t.stringLiteral(`${table.name}.${column.name}`);
|
|
132
|
+
if (!column.nullable && column.scalar !== 'unknown') {
|
|
133
|
+
params.push(t.assignmentPattern(t.identifier('label'), label));
|
|
134
|
+
label = t.identifier('label');
|
|
135
|
+
}
|
|
136
|
+
const fn = t.arrowFunctionExpression(params, decodeExpression(column, valueParam, label, usage));
|
|
137
|
+
fn.returnType = t.tsTypeAnnotation(columnTsType(column));
|
|
138
|
+
const property = t.objectProperty(objectKey(column.propertyName), fn);
|
|
139
|
+
t.addComment(property, 'leading', `* \`${column.name}\` (${column.pgType}) `, false);
|
|
140
|
+
return property;
|
|
141
|
+
});
|
|
142
|
+
return exportConst(name, asConst(t.objectExpression(properties)));
|
|
111
143
|
};
|
|
112
144
|
const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
|
|
113
145
|
usage.coerceImports.add('requireRecord');
|
|
@@ -117,7 +149,10 @@ const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
|
|
|
117
149
|
const recordDecl = t.variableDeclaration('const', [
|
|
118
150
|
t.variableDeclarator(t.identifier('record'), t.callExpression(t.identifier('requireRecord'), [t.identifier('value'), t.identifier('label')]))
|
|
119
151
|
]);
|
|
120
|
-
const resultObject = t.objectExpression(table.columns.map(column =>
|
|
152
|
+
const resultObject = t.objectExpression(table.columns.map(column => {
|
|
153
|
+
const key = keyFor(column);
|
|
154
|
+
return t.objectProperty(objectKey(key), decodeExpression(column, member('record', key), labelTemplate(key), usage));
|
|
155
|
+
}));
|
|
121
156
|
const fn = t.arrowFunctionExpression([valueParam, labelParam], t.blockStatement([recordDecl, t.returnStatement(resultObject)]));
|
|
122
157
|
fn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(returnTypeName)));
|
|
123
158
|
return exportConst(fnName, fn);
|
|
@@ -127,6 +162,7 @@ export const emitRecordModule = (table) => {
|
|
|
127
162
|
const pascal = toPascalCase(table.name);
|
|
128
163
|
const rowTypeName = `${pascal}Row`;
|
|
129
164
|
const metadataName = `${toConstantCase(table.name)}_TABLE`;
|
|
165
|
+
const fieldsName = `${toConstantCase(table.name)}_FIELDS`;
|
|
130
166
|
const qualified = `${table.schema}.${table.name}`;
|
|
131
167
|
const statements = [];
|
|
132
168
|
// Application (camelCase) interface.
|
|
@@ -148,6 +184,9 @@ export const emitRecordModule = (table) => {
|
|
|
148
184
|
])));
|
|
149
185
|
withJsDoc(metadata, `Column metadata for \`${qualified}\`.`);
|
|
150
186
|
statements.push(metadata);
|
|
187
|
+
// Per-column decoders, for projections a record decoder cannot describe.
|
|
188
|
+
const example = table.columns[0];
|
|
189
|
+
statements.push(withJsDoc(fieldsConstant(table, fieldsName, usage), `Per-column decoders for \`${qualified}\`, for a value that is not a whole\n * row: a joined projection, an aliased column, a partial SELECT.\n *\n * A NOT NULL column's decoder throws \`CoerceError\` and takes an overridable\n * label, so a projection can name its own alias; a nullable column's is\n * lenient and answers \`null\`.${example ? `\n *\n * \`\`\`ts\n * ${example.propertyName}: ${fieldsName}.${example.propertyName}(row.${example.name}),\n * \`\`\`` : ''}`));
|
|
151
190
|
// Decoders.
|
|
152
191
|
statements.push(withJsDoc(decoderFunction(table, `decode${pascal}`, pascal, column => column.propertyName, usage), `Decode an untrusted camelCase value (a wire envelope, a parsed body) into \`${pascal}\`.\n *\n * Throws \`CoerceError\` naming the offending field when a required column is\n * missing or of the wrong shape.`));
|
|
153
192
|
statements.push(withJsDoc(decoderFunction(table, `decode${pascal}Row`, rowTypeName, column => column.name, usage), `Decode an untrusted snake_case database row into \`${rowTypeName}\`.`));
|
|
@@ -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
|
+
}
|
|
@@ -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/generate.js
CHANGED
|
@@ -6,6 +6,7 @@ import { promises as fs } from 'fs';
|
|
|
6
6
|
import { introspect } from 'introspectron';
|
|
7
7
|
import path from 'path';
|
|
8
8
|
import { emitRootIndex, emitSchemaIndex, tableFileName } from './emit/barrel';
|
|
9
|
+
import { emitClientRuntime, emitSchemaDbModule } from './emit/client';
|
|
9
10
|
import { emitEnumsModule } from './emit/enums';
|
|
10
11
|
import { emitRecordModule } from './emit/record';
|
|
11
12
|
import { buildIr } from './ir';
|
|
@@ -19,8 +20,10 @@ export const emitFileTree = (ir) => {
|
|
|
19
20
|
for (const table of schema.tables) {
|
|
20
21
|
files[`${schema.name}/${tableFileName(table.name)}.ts`] = emitRecordModule(table);
|
|
21
22
|
}
|
|
23
|
+
files[`${schema.name}/db.ts`] = emitSchemaDbModule(schema);
|
|
22
24
|
files[`${schema.name}/index.ts`] = emitSchemaIndex(schema);
|
|
23
25
|
}
|
|
26
|
+
files['client.ts'] = emitClientRuntime();
|
|
24
27
|
files['index.ts'] = emitRootIndex(ir.schemas);
|
|
25
28
|
return files;
|
|
26
29
|
};
|