pg-codegen 5.12.0 → 5.14.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/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 +160 -0
- package/emit/templates/client.js +239 -0
- package/emit/templates/client.ts +405 -0
- package/esm/emit/barrel.js +7 -1
- package/esm/emit/client.js +94 -0
- package/esm/emit/templates/client.js +234 -0
- package/esm/emit/templates/client.ts +405 -0
- package/esm/generate.js +3 -0
- package/generate.js +3 -0
- package/package.json +6 -4
|
@@ -0,0 +1,234 @@
|
|
|
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
|
+
const predicate = this.predicate(args.where);
|
|
55
|
+
if (predicate)
|
|
56
|
+
query.where(predicate);
|
|
57
|
+
this.applyOrderBy(query, args.orderBy);
|
|
58
|
+
if (args.limit !== undefined)
|
|
59
|
+
query.limit(args.limit);
|
|
60
|
+
if (args.offset !== undefined)
|
|
61
|
+
query.offset(args.offset);
|
|
62
|
+
const { text, values } = query.build();
|
|
63
|
+
const { rows } = await this.db.query(text, values);
|
|
64
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
65
|
+
}
|
|
66
|
+
async findFirst(args = {}) {
|
|
67
|
+
const rows = await this.findMany({ ...args, limit: 1 });
|
|
68
|
+
return rows.length > 0 ? rows[0] : null;
|
|
69
|
+
}
|
|
70
|
+
async findFirstOrThrow(args = {}) {
|
|
71
|
+
const row = await this.findFirst(args);
|
|
72
|
+
if (row === null)
|
|
73
|
+
throw new RowNotFoundError(this.spec.table, 'findFirstOrThrow');
|
|
74
|
+
return row;
|
|
75
|
+
}
|
|
76
|
+
async count(where) {
|
|
77
|
+
const query = this.baseQuery().select([]).selectExpr('count', fn('count', [lit(1)]));
|
|
78
|
+
const predicate = this.predicate(where);
|
|
79
|
+
if (predicate)
|
|
80
|
+
query.where(predicate);
|
|
81
|
+
const { text, values } = query.build();
|
|
82
|
+
const { rows } = await this.db.query(text, values);
|
|
83
|
+
const row = rows[0];
|
|
84
|
+
return Number(row.count);
|
|
85
|
+
}
|
|
86
|
+
async create(args) {
|
|
87
|
+
const fields = this.selectedFields(args.select);
|
|
88
|
+
const query = this.baseQuery()
|
|
89
|
+
.insert(this.encodeData(args.data))
|
|
90
|
+
.returning(fields.map(field => this.column(field)));
|
|
91
|
+
const { text, values } = query.build();
|
|
92
|
+
const { rows } = await this.db.query(text, values);
|
|
93
|
+
return this.decodeRow(rows[0], fields);
|
|
94
|
+
}
|
|
95
|
+
async update(args) {
|
|
96
|
+
const fields = this.selectedFields(args.select);
|
|
97
|
+
const query = this.baseQuery()
|
|
98
|
+
.update(this.encodeData(args.data))
|
|
99
|
+
.where(this.required(args.where, 'update'))
|
|
100
|
+
.returning(fields.map(field => this.column(field)));
|
|
101
|
+
const { text, values } = query.build();
|
|
102
|
+
const { rows } = await this.db.query(text, values);
|
|
103
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
104
|
+
}
|
|
105
|
+
async updateOrThrow(args) {
|
|
106
|
+
const rows = await this.update(args);
|
|
107
|
+
if (rows.length === 0)
|
|
108
|
+
throw new RowNotFoundError(this.spec.table, 'updateOrThrow');
|
|
109
|
+
return rows[0];
|
|
110
|
+
}
|
|
111
|
+
async delete(args) {
|
|
112
|
+
const fields = this.selectedFields(args.select);
|
|
113
|
+
const query = this.baseQuery()
|
|
114
|
+
.delete()
|
|
115
|
+
.where(this.required(args.where, 'delete'))
|
|
116
|
+
.returning(fields.map(field => this.column(field)));
|
|
117
|
+
const { text, values } = query.build();
|
|
118
|
+
const { rows } = await this.db.query(text, values);
|
|
119
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
120
|
+
}
|
|
121
|
+
/** Rebind to another connection (e.g. a transaction's PoolClient). */
|
|
122
|
+
$with(db) {
|
|
123
|
+
return new TableClient(this.spec, db);
|
|
124
|
+
}
|
|
125
|
+
baseQuery() {
|
|
126
|
+
return new QueryBuilder().schema(this.spec.schema).table(this.spec.table);
|
|
127
|
+
}
|
|
128
|
+
column(field) {
|
|
129
|
+
return this.spec.columnByField[field] ?? field;
|
|
130
|
+
}
|
|
131
|
+
selectedFields(select) {
|
|
132
|
+
const all = Object.keys(this.spec.columnByField);
|
|
133
|
+
if (!select)
|
|
134
|
+
return all;
|
|
135
|
+
const picked = all.filter(field => select[field] === true);
|
|
136
|
+
if (picked.length > 0)
|
|
137
|
+
return picked;
|
|
138
|
+
// Nothing picked: the select either excludes fields or says nothing at all,
|
|
139
|
+
// and both read what is left.
|
|
140
|
+
return all.filter(field => select[field] !== false);
|
|
141
|
+
}
|
|
142
|
+
decodeRow(row, fields) {
|
|
143
|
+
const raw = row;
|
|
144
|
+
const decoded = {};
|
|
145
|
+
for (const field of fields) {
|
|
146
|
+
decoded[field] = this.spec.fields[field](raw[this.column(field)]);
|
|
147
|
+
}
|
|
148
|
+
return decoded;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The predicate to apply, or nothing to apply: a caller that spreads a
|
|
152
|
+
* conditional key column (a scope that records none) states an empty filter,
|
|
153
|
+
* and an unqualified read is what it asked for.
|
|
154
|
+
*/
|
|
155
|
+
predicate(where) {
|
|
156
|
+
if (!where)
|
|
157
|
+
return undefined;
|
|
158
|
+
const filter = this.filter(where);
|
|
159
|
+
return Object.keys(filter).length > 0 ? filter : undefined;
|
|
160
|
+
}
|
|
161
|
+
/** A write says which rows: an empty filter would mean the whole table. */
|
|
162
|
+
required(where, operation) {
|
|
163
|
+
const predicate = this.predicate(where);
|
|
164
|
+
if (!predicate) {
|
|
165
|
+
throw new Error(`${this.spec.table}.${operation}: refusing an empty where filter, which would match every row`);
|
|
166
|
+
}
|
|
167
|
+
return predicate;
|
|
168
|
+
}
|
|
169
|
+
filter(where) {
|
|
170
|
+
const filter = {};
|
|
171
|
+
for (const [key, value] of Object.entries(where)) {
|
|
172
|
+
if (value === undefined)
|
|
173
|
+
continue;
|
|
174
|
+
if (key === 'and' || key === 'or') {
|
|
175
|
+
filter[key] = value.map(nested => this.filter(nested));
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (key === 'not') {
|
|
179
|
+
filter.not = this.filter(value);
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
filter[this.column(key)] = this.fieldFilter(value);
|
|
183
|
+
}
|
|
184
|
+
return filter;
|
|
185
|
+
}
|
|
186
|
+
fieldFilter(value) {
|
|
187
|
+
if (value === null)
|
|
188
|
+
return { isNull: true };
|
|
189
|
+
if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)) {
|
|
190
|
+
const entries = Object.entries(value);
|
|
191
|
+
if (entries.length > 0 && entries.every(([op]) => FIELD_OP_NAMES.has(op))) {
|
|
192
|
+
const ops = {};
|
|
193
|
+
for (const [op, operand] of entries) {
|
|
194
|
+
if (operand === undefined)
|
|
195
|
+
continue;
|
|
196
|
+
ops[op] = Array.isArray(operand)
|
|
197
|
+
? operand.map(encodeScalar)
|
|
198
|
+
: op === 'isNull'
|
|
199
|
+
? operand
|
|
200
|
+
: encodeScalar(operand);
|
|
201
|
+
}
|
|
202
|
+
return ops;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return { equalTo: encodeScalar(value) };
|
|
206
|
+
}
|
|
207
|
+
applyOrderBy(query, orderBy) {
|
|
208
|
+
if (!orderBy)
|
|
209
|
+
return;
|
|
210
|
+
for (const spec of Array.isArray(orderBy) ? orderBy : [orderBy]) {
|
|
211
|
+
for (const [field, direction] of Object.entries(spec)) {
|
|
212
|
+
if (!direction)
|
|
213
|
+
continue;
|
|
214
|
+
query.orderBy(this.column(field), direction);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
encodeData(data) {
|
|
219
|
+
const encoded = {};
|
|
220
|
+
for (const [field, value] of Object.entries(data)) {
|
|
221
|
+
if (value === undefined)
|
|
222
|
+
continue;
|
|
223
|
+
if (value !== null && this.spec.jsonFields?.includes(field)) {
|
|
224
|
+
encoded[this.column(field)] = JSON.stringify(value);
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
// pg serializes JS arrays into PostgreSQL array literals.
|
|
228
|
+
encoded[this.column(field)] = Array.isArray(value)
|
|
229
|
+
? value.map(encodeScalar)
|
|
230
|
+
: encodeScalar(value);
|
|
231
|
+
}
|
|
232
|
+
return encoded;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
@@ -0,0 +1,405 @@
|
|
|
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
|
+
/**
|
|
37
|
+
* Select shape — same as the GraphQL ORM, stated either way round:
|
|
38
|
+
*
|
|
39
|
+
* - `{ id: true, name: true }` reads those fields and nothing else;
|
|
40
|
+
* - `{ databaseId: false }` reads every field except that one, for the field a
|
|
41
|
+
* record has in general but this binding's table does not (a scope's copy of
|
|
42
|
+
* a table without the scope key column) or that a caller must not carry (a
|
|
43
|
+
* secret's id, row bookkeeping).
|
|
44
|
+
*
|
|
45
|
+
* Naming a field `true` is a projection and wins outright: the excluded ones
|
|
46
|
+
* are simply not in it.
|
|
47
|
+
*/
|
|
48
|
+
export type SelectShape<App> = { [K in keyof App]?: boolean };
|
|
49
|
+
|
|
50
|
+
type TrueKeys<App, S> = {
|
|
51
|
+
[K in keyof S]-?: S[K] extends true ? K & keyof App : never;
|
|
52
|
+
}[keyof S];
|
|
53
|
+
|
|
54
|
+
type FalseKeys<App, S> = {
|
|
55
|
+
[K in keyof S]-?: S[K] extends false ? K & keyof App : never;
|
|
56
|
+
}[keyof S];
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Rows narrow to what the select states: the picked fields, else the record
|
|
60
|
+
* minus the excluded ones. No `select` returns the full record.
|
|
61
|
+
*/
|
|
62
|
+
export type SelectResult<App, S extends SelectShape<App> | undefined> =
|
|
63
|
+
S extends SelectShape<App>
|
|
64
|
+
? [TrueKeys<App, S>] extends [never]
|
|
65
|
+
? [FalseKeys<App, S>] extends [never]
|
|
66
|
+
? App
|
|
67
|
+
: Omit<App, FalseKeys<App, S>>
|
|
68
|
+
: Pick<App, TrueKeys<App, S>>
|
|
69
|
+
: App;
|
|
70
|
+
|
|
71
|
+
/** Per-field operators from the shared query-spec grammar. */
|
|
72
|
+
export interface FieldOps<V> {
|
|
73
|
+
equalTo?: V;
|
|
74
|
+
notEqualTo?: V;
|
|
75
|
+
distinctFrom?: V;
|
|
76
|
+
notDistinctFrom?: V;
|
|
77
|
+
lessThan?: V;
|
|
78
|
+
lessThanOrEqualTo?: V;
|
|
79
|
+
greaterThan?: V;
|
|
80
|
+
greaterThanOrEqualTo?: V;
|
|
81
|
+
in?: V[];
|
|
82
|
+
notIn?: V[];
|
|
83
|
+
like?: string;
|
|
84
|
+
notLike?: string;
|
|
85
|
+
likeInsensitive?: string;
|
|
86
|
+
notLikeInsensitive?: string;
|
|
87
|
+
includes?: string;
|
|
88
|
+
notIncludes?: string;
|
|
89
|
+
includesInsensitive?: string;
|
|
90
|
+
startsWith?: string;
|
|
91
|
+
endsWith?: string;
|
|
92
|
+
isNull?: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const FIELD_OP_NAMES: ReadonlySet<string> = new Set([
|
|
96
|
+
'equalTo',
|
|
97
|
+
'notEqualTo',
|
|
98
|
+
'distinctFrom',
|
|
99
|
+
'notDistinctFrom',
|
|
100
|
+
'lessThan',
|
|
101
|
+
'lessThanOrEqualTo',
|
|
102
|
+
'greaterThan',
|
|
103
|
+
'greaterThanOrEqualTo',
|
|
104
|
+
'in',
|
|
105
|
+
'notIn',
|
|
106
|
+
'like',
|
|
107
|
+
'notLike',
|
|
108
|
+
'likeInsensitive',
|
|
109
|
+
'notLikeInsensitive',
|
|
110
|
+
'includes',
|
|
111
|
+
'notIncludes',
|
|
112
|
+
'includesInsensitive',
|
|
113
|
+
'startsWith',
|
|
114
|
+
'endsWith',
|
|
115
|
+
'isNull'
|
|
116
|
+
]);
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Where filter keyed by camelCase field names. A bare value means `equalTo`
|
|
120
|
+
* (`null` means `isNull`). Extra string keys are physical column names —
|
|
121
|
+
* runtime-configured scope key columns qualify rows the same way any other
|
|
122
|
+
* condition does.
|
|
123
|
+
*/
|
|
124
|
+
export type Where<App> = {
|
|
125
|
+
[K in keyof App]?: App[K] | FieldOps<NonNullable<App[K]>>;
|
|
126
|
+
} & {
|
|
127
|
+
[column: string]: unknown;
|
|
128
|
+
} & {
|
|
129
|
+
and?: Where<App>[];
|
|
130
|
+
or?: Where<App>[];
|
|
131
|
+
not?: Where<App>;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Write data keyed by camelCase field names. Extra string keys are physical
|
|
136
|
+
* column names — runtime-configured scope key columns are stamped the same
|
|
137
|
+
* way any other value is.
|
|
138
|
+
*/
|
|
139
|
+
export type Data<App> = Partial<App> & { [column: string]: unknown };
|
|
140
|
+
|
|
141
|
+
export type OrderDirection = 'ASC' | 'DESC';
|
|
142
|
+
|
|
143
|
+
/** Order spec keyed by camelCase field names, e.g. `{ createdAt: 'DESC' }`. */
|
|
144
|
+
export type OrderBy<App> = { [K in keyof App]?: OrderDirection };
|
|
145
|
+
|
|
146
|
+
export interface FindManyArgs<App, S extends SelectShape<App> | undefined> {
|
|
147
|
+
where?: Where<App>;
|
|
148
|
+
select?: S;
|
|
149
|
+
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
150
|
+
limit?: number;
|
|
151
|
+
offset?: number;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface FindFirstArgs<App, S extends SelectShape<App> | undefined> {
|
|
155
|
+
where?: Where<App>;
|
|
156
|
+
select?: S;
|
|
157
|
+
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
|
|
161
|
+
data: Data<App>;
|
|
162
|
+
select?: S;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
|
|
166
|
+
where: Where<App>;
|
|
167
|
+
data: Data<App>;
|
|
168
|
+
select?: S;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export interface DeleteArgs<App, S extends SelectShape<App> | undefined> {
|
|
172
|
+
where: Where<App>;
|
|
173
|
+
select?: S;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Thrown by `findFirstOrThrow` / `updateOrThrow` when no row matches. */
|
|
177
|
+
export class RowNotFoundError extends Error {
|
|
178
|
+
constructor(
|
|
179
|
+
public readonly table: string,
|
|
180
|
+
public readonly operation: string
|
|
181
|
+
) {
|
|
182
|
+
super(`${table}.${operation}: no row matched the given where filter`);
|
|
183
|
+
this.name = 'RowNotFoundError';
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const encodeScalar = (value: unknown): SqlValue => {
|
|
188
|
+
if (value === null) return null;
|
|
189
|
+
if (value instanceof Date) return value.toISOString();
|
|
190
|
+
if (typeof value === 'object' && !Array.isArray(value)) return JSON.stringify(value);
|
|
191
|
+
return value as SqlValue;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
export class TableClient<App> {
|
|
195
|
+
constructor(
|
|
196
|
+
private readonly spec: TableSpec<App>,
|
|
197
|
+
private readonly db: Queryable
|
|
198
|
+
) {}
|
|
199
|
+
|
|
200
|
+
async findMany<S extends SelectShape<App> | undefined = undefined>(
|
|
201
|
+
args: FindManyArgs<App, S> = {}
|
|
202
|
+
): Promise<SelectResult<App, S>[]> {
|
|
203
|
+
const fields = this.selectedFields(args.select);
|
|
204
|
+
const query = this.baseQuery().select(fields.map(field => this.column(field)));
|
|
205
|
+
const predicate = this.predicate(args.where);
|
|
206
|
+
if (predicate) query.where(predicate);
|
|
207
|
+
this.applyOrderBy(query, args.orderBy);
|
|
208
|
+
if (args.limit !== undefined) query.limit(args.limit);
|
|
209
|
+
if (args.offset !== undefined) query.offset(args.offset);
|
|
210
|
+
const { text, values } = query.build();
|
|
211
|
+
const { rows } = await this.db.query(text, values);
|
|
212
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async findFirst<S extends SelectShape<App> | undefined = undefined>(
|
|
216
|
+
args: FindFirstArgs<App, S> = {}
|
|
217
|
+
): Promise<SelectResult<App, S> | null> {
|
|
218
|
+
const rows = await this.findMany({ ...args, limit: 1 });
|
|
219
|
+
return rows.length > 0 ? rows[0] : null;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async findFirstOrThrow<S extends SelectShape<App> | undefined = undefined>(
|
|
223
|
+
args: FindFirstArgs<App, S> = {}
|
|
224
|
+
): Promise<SelectResult<App, S>> {
|
|
225
|
+
const row = await this.findFirst(args);
|
|
226
|
+
if (row === null) throw new RowNotFoundError(this.spec.table, 'findFirstOrThrow');
|
|
227
|
+
return row;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async count(where?: Where<App>): Promise<number> {
|
|
231
|
+
const query = this.baseQuery().select([]).selectExpr('count', fn('count', [lit(1)]));
|
|
232
|
+
const predicate = this.predicate(where);
|
|
233
|
+
if (predicate) query.where(predicate);
|
|
234
|
+
const { text, values } = query.build();
|
|
235
|
+
const { rows } = await this.db.query(text, values);
|
|
236
|
+
const row = rows[0] as { count: string | number };
|
|
237
|
+
return Number(row.count);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async create<S extends SelectShape<App> | undefined = undefined>(
|
|
241
|
+
args: CreateArgs<App, S>
|
|
242
|
+
): Promise<SelectResult<App, S>> {
|
|
243
|
+
const fields = this.selectedFields(args.select);
|
|
244
|
+
const query = this.baseQuery()
|
|
245
|
+
.insert(this.encodeData(args.data))
|
|
246
|
+
.returning(fields.map(field => this.column(field)));
|
|
247
|
+
const { text, values } = query.build();
|
|
248
|
+
const { rows } = await this.db.query(text, values);
|
|
249
|
+
return this.decodeRow(rows[0], fields);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async update<S extends SelectShape<App> | undefined = undefined>(
|
|
253
|
+
args: UpdateArgs<App, S>
|
|
254
|
+
): Promise<SelectResult<App, S>[]> {
|
|
255
|
+
const fields = this.selectedFields(args.select);
|
|
256
|
+
const query = this.baseQuery()
|
|
257
|
+
.update(this.encodeData(args.data))
|
|
258
|
+
.where(this.required(args.where, 'update'))
|
|
259
|
+
.returning(fields.map(field => this.column(field)));
|
|
260
|
+
const { text, values } = query.build();
|
|
261
|
+
const { rows } = await this.db.query(text, values);
|
|
262
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async updateOrThrow<S extends SelectShape<App> | undefined = undefined>(
|
|
266
|
+
args: UpdateArgs<App, S>
|
|
267
|
+
): Promise<SelectResult<App, S>> {
|
|
268
|
+
const rows = await this.update(args);
|
|
269
|
+
if (rows.length === 0) throw new RowNotFoundError(this.spec.table, 'updateOrThrow');
|
|
270
|
+
return rows[0];
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async delete<S extends SelectShape<App> | undefined = undefined>(
|
|
274
|
+
args: DeleteArgs<App, S>
|
|
275
|
+
): Promise<SelectResult<App, S>[]> {
|
|
276
|
+
const fields = this.selectedFields(args.select);
|
|
277
|
+
const query = this.baseQuery()
|
|
278
|
+
.delete()
|
|
279
|
+
.where(this.required(args.where, 'delete'))
|
|
280
|
+
.returning(fields.map(field => this.column(field)));
|
|
281
|
+
const { text, values } = query.build();
|
|
282
|
+
const { rows } = await this.db.query(text, values);
|
|
283
|
+
return rows.map(row => this.decodeRow(row, fields));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Rebind to another connection (e.g. a transaction's PoolClient). */
|
|
287
|
+
$with(db: Queryable): TableClient<App> {
|
|
288
|
+
return new TableClient(this.spec, db);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
private baseQuery(): QueryBuilder {
|
|
292
|
+
return new QueryBuilder().schema(this.spec.schema).table(this.spec.table);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private column(field: string): string {
|
|
296
|
+
return this.spec.columnByField[field] ?? field;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private selectedFields(select: SelectShape<App> | undefined): (keyof App & string)[] {
|
|
300
|
+
const all = Object.keys(this.spec.columnByField) as (keyof App & string)[];
|
|
301
|
+
if (!select) return all;
|
|
302
|
+
const picked = all.filter(field => select[field] === true);
|
|
303
|
+
if (picked.length > 0) return picked;
|
|
304
|
+
// Nothing picked: the select either excludes fields or says nothing at all,
|
|
305
|
+
// and both read what is left.
|
|
306
|
+
return all.filter(field => select[field] !== false);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private decodeRow<S extends SelectShape<App> | undefined>(
|
|
310
|
+
row: unknown,
|
|
311
|
+
fields: (keyof App & string)[]
|
|
312
|
+
): SelectResult<App, S> {
|
|
313
|
+
const raw = row as Record<string, unknown>;
|
|
314
|
+
const decoded: Record<string, unknown> = {};
|
|
315
|
+
for (const field of fields) {
|
|
316
|
+
decoded[field] = this.spec.fields[field](raw[this.column(field)]);
|
|
317
|
+
}
|
|
318
|
+
return decoded as SelectResult<App, S>;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* The predicate to apply, or nothing to apply: a caller that spreads a
|
|
323
|
+
* conditional key column (a scope that records none) states an empty filter,
|
|
324
|
+
* and an unqualified read is what it asked for.
|
|
325
|
+
*/
|
|
326
|
+
private predicate(where: Where<App> | undefined): Filter | undefined {
|
|
327
|
+
if (!where) return undefined;
|
|
328
|
+
const filter = this.filter(where);
|
|
329
|
+
return Object.keys(filter).length > 0 ? filter : undefined;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** A write says which rows: an empty filter would mean the whole table. */
|
|
333
|
+
private required(where: Where<App>, operation: string): Filter {
|
|
334
|
+
const predicate = this.predicate(where);
|
|
335
|
+
if (!predicate) {
|
|
336
|
+
throw new Error(
|
|
337
|
+
`${this.spec.table}.${operation}: refusing an empty where filter, which would match every row`
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
return predicate;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private filter(where: Where<App>): Filter {
|
|
344
|
+
const filter: Filter = {};
|
|
345
|
+
for (const [key, value] of Object.entries(where)) {
|
|
346
|
+
if (value === undefined) continue;
|
|
347
|
+
if (key === 'and' || key === 'or') {
|
|
348
|
+
filter[key] = (value as Where<App>[]).map(nested => this.filter(nested));
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
if (key === 'not') {
|
|
352
|
+
filter.not = this.filter(value as Where<App>);
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
filter[this.column(key)] = this.fieldFilter(value);
|
|
356
|
+
}
|
|
357
|
+
return filter;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private fieldFilter(value: unknown): Filter[string] {
|
|
361
|
+
if (value === null) return { isNull: true };
|
|
362
|
+
if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)) {
|
|
363
|
+
const entries = Object.entries(value as Record<string, unknown>);
|
|
364
|
+
if (entries.length > 0 && entries.every(([op]) => FIELD_OP_NAMES.has(op))) {
|
|
365
|
+
const ops: Record<string, unknown> = {};
|
|
366
|
+
for (const [op, operand] of entries) {
|
|
367
|
+
if (operand === undefined) continue;
|
|
368
|
+
ops[op] = Array.isArray(operand)
|
|
369
|
+
? operand.map(encodeScalar)
|
|
370
|
+
: op === 'isNull'
|
|
371
|
+
? operand
|
|
372
|
+
: encodeScalar(operand);
|
|
373
|
+
}
|
|
374
|
+
return ops as Filter[string];
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return { equalTo: encodeScalar(value) };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private applyOrderBy(query: QueryBuilder, orderBy: OrderBy<App> | OrderBy<App>[] | undefined): void {
|
|
381
|
+
if (!orderBy) return;
|
|
382
|
+
for (const spec of Array.isArray(orderBy) ? orderBy : [orderBy]) {
|
|
383
|
+
for (const [field, direction] of Object.entries(spec)) {
|
|
384
|
+
if (!direction) continue;
|
|
385
|
+
query.orderBy(this.column(field), direction as OrderDirection);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private encodeData(data: Data<App>): Record<string, SqlValue> {
|
|
391
|
+
const encoded: Record<string, SqlValue> = {};
|
|
392
|
+
for (const [field, value] of Object.entries(data)) {
|
|
393
|
+
if (value === undefined) continue;
|
|
394
|
+
if (value !== null && this.spec.jsonFields?.includes(field)) {
|
|
395
|
+
encoded[this.column(field)] = JSON.stringify(value);
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
// pg serializes JS arrays into PostgreSQL array literals.
|
|
399
|
+
encoded[this.column(field)] = Array.isArray(value)
|
|
400
|
+
? (value.map(encodeScalar) as unknown as SqlValue)
|
|
401
|
+
: encodeScalar(value);
|
|
402
|
+
}
|
|
403
|
+
return encoded;
|
|
404
|
+
}
|
|
405
|
+
}
|
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
|
};
|
package/generate.js
CHANGED
|
@@ -12,6 +12,7 @@ const fs_1 = require("fs");
|
|
|
12
12
|
const introspectron_1 = require("introspectron");
|
|
13
13
|
const path_1 = __importDefault(require("path"));
|
|
14
14
|
const barrel_1 = require("./emit/barrel");
|
|
15
|
+
const client_1 = require("./emit/client");
|
|
15
16
|
const enums_1 = require("./emit/enums");
|
|
16
17
|
const record_1 = require("./emit/record");
|
|
17
18
|
const ir_1 = require("./ir");
|
|
@@ -25,8 +26,10 @@ const emitFileTree = (ir) => {
|
|
|
25
26
|
for (const table of schema.tables) {
|
|
26
27
|
files[`${schema.name}/${(0, barrel_1.tableFileName)(table.name)}.ts`] = (0, record_1.emitRecordModule)(table);
|
|
27
28
|
}
|
|
29
|
+
files[`${schema.name}/db.ts`] = (0, client_1.emitSchemaDbModule)(schema);
|
|
28
30
|
files[`${schema.name}/index.ts`] = (0, barrel_1.emitSchemaIndex)(schema);
|
|
29
31
|
}
|
|
32
|
+
files['client.ts'] = (0, client_1.emitClientRuntime)();
|
|
30
33
|
files['index.ts'] = (0, barrel_1.emitRootIndex)(ir.schemas);
|
|
31
34
|
return files;
|
|
32
35
|
};
|