pg-codegen 5.17.0 → 5.19.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 +37 -0
- package/emit/templates/client.d.ts +50 -1
- package/emit/templates/client.js +26 -0
- package/emit/templates/client.ts +77 -1
- package/esm/emit/templates/client.js +26 -0
- package/esm/emit/templates/client.ts +77 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -57,11 +57,14 @@ One `create<Schema>Db(db, options?)` factory per schema, one client per table:
|
|
|
57
57
|
| `findFirstOrThrow(args?)` | `SelectResult`, else `RowNotFoundError` |
|
|
58
58
|
| `count(where?)` | `number` |
|
|
59
59
|
| `create({ data, select? })` | the inserted row |
|
|
60
|
+
| `upsert({ conflict, create, update?, select? })` | the inserted or reconciled row, else `null` |
|
|
60
61
|
| `update({ where, data, select? })` | the updated rows |
|
|
61
62
|
| `updateOrThrow({ where, data, select? })` | one updated row, else `RowNotFoundError` |
|
|
62
63
|
| `delete({ where, select? })` | the deleted rows |
|
|
63
64
|
| `$with(db)` | the same clients bound to another connection |
|
|
64
65
|
|
|
66
|
+
A read also takes `lock` — `FOR UPDATE` and friends, see [Transactions](#transactions).
|
|
67
|
+
|
|
65
68
|
`where` / `select` / `orderBy` are keyed by camelCase field names and mapped to physical columns for you. `where` speaks the same query-spec grammar as the GraphQL side — `equalTo`, `notEqualTo`, `in`, `notIn`, `lessThan`, `greaterThanOrEqualTo`, `like`, `likeInsensitive`, `startsWith`, `includes`, `isNull`, … — and a bare value means `equalTo` (`null` means `isNull`):
|
|
66
69
|
|
|
67
70
|
```ts
|
|
@@ -89,6 +92,23 @@ await db.resources.update({
|
|
|
89
92
|
|
|
90
93
|
An expression is deparsed in place — never bound as a value, never serialized as one.
|
|
91
94
|
|
|
95
|
+
### Upsert
|
|
96
|
+
|
|
97
|
+
`upsert` states the unique fields it conflicts on, the row to insert, and what to set when one already exists:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { fn } from '@constructive-io/query-builder';
|
|
101
|
+
|
|
102
|
+
await db.appConfigs.upsert({
|
|
103
|
+
conflict: ['namespaceId', 'name'],
|
|
104
|
+
create: { name, value, namespaceId },
|
|
105
|
+
update: { value, updatedAt: fn('now') }
|
|
106
|
+
});
|
|
107
|
+
// INSERT INTO … ON CONFLICT (namespace_id, name) DO UPDATE SET value = $1, updated_at = now() RETURNING …
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Stating no `update` leaves a conflicting row as it is (`ON CONFLICT DO NOTHING`), and then there is no row to return — the result is `null`. An empty `conflict` throws, since it names no unique constraint.
|
|
111
|
+
|
|
92
112
|
### Selections type the result
|
|
93
113
|
|
|
94
114
|
`select` is the only projection, stated either way round, and the return type follows it with nothing to annotate:
|
|
@@ -137,6 +157,23 @@ try {
|
|
|
137
157
|
}
|
|
138
158
|
```
|
|
139
159
|
|
|
160
|
+
A read that decides a write states the lock it needs, so two concurrent workers cannot both act on the same row:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
const run = await tx.agentRuns.findFirstOrThrow({ where: { id }, lock: 'update' });
|
|
164
|
+
// FOR UPDATE — the other transaction waits here
|
|
165
|
+
await tx.agentRuns.update({ where: { id: run.id }, data: { status: 'running' } });
|
|
166
|
+
|
|
167
|
+
// a queue claim would rather move on than wait
|
|
168
|
+
const next = await tx.jobs.findFirst({
|
|
169
|
+
where: { status: 'pending' },
|
|
170
|
+
orderBy: { createdAt: 'ASC' },
|
|
171
|
+
lock: { strength: 'update', skipLocked: true }
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`lock` takes `'update'`, `'noKeyUpdate'`, `'share'` or `'keyShare'`, and the object form adds `skipLocked` or `noWait`.
|
|
176
|
+
|
|
140
177
|
### Tables provisioned under a different name
|
|
141
178
|
|
|
142
179
|
The schema and physical table names are runtime arguments, so one generated client serves a per-tenant or per-scope deployment of the same tables:
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* NOTE: This file is read at codegen time and written to output.
|
|
11
11
|
* Any changes here will affect all generated clients.
|
|
12
12
|
*/
|
|
13
|
-
import type { Expr } from '@constructive-io/query-builder';
|
|
13
|
+
import type { Expr, LockOptions, LockStrength } from '@constructive-io/query-builder';
|
|
14
14
|
/** Anything with pg's `query(text, values)` shape: Pool, PoolClient, Client. */
|
|
15
15
|
export interface Queryable {
|
|
16
16
|
query(text: string, values?: unknown[]): Promise<{
|
|
@@ -113,6 +113,22 @@ export type Data<App> = {
|
|
|
113
113
|
[column: string]: unknown;
|
|
114
114
|
};
|
|
115
115
|
export type OrderDirection = 'ASC' | 'DESC';
|
|
116
|
+
/**
|
|
117
|
+
* Row-level lock the read takes, so a read-then-write stays serialized against
|
|
118
|
+
* a concurrent one: `'update'` is `FOR UPDATE`, and the object form states what
|
|
119
|
+
* to do about a row someone else holds.
|
|
120
|
+
*
|
|
121
|
+
* ```ts
|
|
122
|
+
* const run = await runs.$with(tx).findFirst({ where: { id }, lock: 'update' });
|
|
123
|
+
* const job = await jobs.$with(tx).findFirst({
|
|
124
|
+
* where: { status: 'pending' },
|
|
125
|
+
* lock: { strength: 'update', skipLocked: true }
|
|
126
|
+
* });
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
export type Lock = LockStrength | ({
|
|
130
|
+
strength: LockStrength;
|
|
131
|
+
} & LockOptions);
|
|
116
132
|
/** Order spec keyed by camelCase field names, e.g. `{ createdAt: 'DESC' }`. */
|
|
117
133
|
export type OrderBy<App> = {
|
|
118
134
|
[K in keyof App]?: OrderDirection;
|
|
@@ -123,16 +139,43 @@ export interface FindManyArgs<App, S extends SelectShape<App> | undefined> {
|
|
|
123
139
|
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
124
140
|
limit?: number;
|
|
125
141
|
offset?: number;
|
|
142
|
+
lock?: Lock;
|
|
126
143
|
}
|
|
127
144
|
export interface FindFirstArgs<App, S extends SelectShape<App> | undefined> {
|
|
128
145
|
where?: Where<App>;
|
|
129
146
|
select?: S;
|
|
130
147
|
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
148
|
+
lock?: Lock;
|
|
131
149
|
}
|
|
132
150
|
export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
|
|
133
151
|
data: Data<App>;
|
|
134
152
|
select?: S;
|
|
135
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* An upsert states the unique columns it conflicts on, the row to insert, and
|
|
156
|
+
* what to set when one already exists. No `update` means an existing row is
|
|
157
|
+
* left as it is (`ON CONFLICT DO NOTHING`), and then there may be no row to
|
|
158
|
+
* return.
|
|
159
|
+
*
|
|
160
|
+
* ```ts
|
|
161
|
+
* await db.appConfigs.upsert({
|
|
162
|
+
* conflict: ['namespaceId', 'name'],
|
|
163
|
+
* create: { name, value, namespaceId },
|
|
164
|
+
* update: { value, updatedAt: fn('now') }
|
|
165
|
+
* });
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
export interface UpsertArgs<App, S extends SelectShape<App> | undefined> {
|
|
169
|
+
/**
|
|
170
|
+
* The unique fields to conflict on. Generated fields autocomplete and map to
|
|
171
|
+
* their columns; a runtime-configured column (a scope key this binding's
|
|
172
|
+
* table carries) is named as the column it is.
|
|
173
|
+
*/
|
|
174
|
+
conflict: readonly (keyof App & string)[] | readonly string[];
|
|
175
|
+
create: Data<App>;
|
|
176
|
+
update?: Data<App>;
|
|
177
|
+
select?: S;
|
|
178
|
+
}
|
|
136
179
|
export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
|
|
137
180
|
where: Where<App>;
|
|
138
181
|
data: Data<App>;
|
|
@@ -157,6 +200,12 @@ export declare class TableClient<App> {
|
|
|
157
200
|
findFirstOrThrow<S extends SelectShape<App> | undefined = undefined>(args?: FindFirstArgs<App, S>): Promise<SelectResult<App, S>>;
|
|
158
201
|
count(where?: Where<App>): Promise<number>;
|
|
159
202
|
create<S extends SelectShape<App> | undefined = undefined>(args: CreateArgs<App, S>): Promise<SelectResult<App, S>>;
|
|
203
|
+
/**
|
|
204
|
+
* Insert a row, or reconcile the one the conflict target already matches.
|
|
205
|
+
* Returns the resulting row, or null when a conflicting row was left as it
|
|
206
|
+
* is by an upsert that states no `update`.
|
|
207
|
+
*/
|
|
208
|
+
upsert<S extends SelectShape<App> | undefined = undefined>(args: UpsertArgs<App, S>): Promise<SelectResult<App, S> | null>;
|
|
160
209
|
update<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>[]>;
|
|
161
210
|
updateOrThrow<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>>;
|
|
162
211
|
delete<S extends SelectShape<App> | undefined = undefined>(args: DeleteArgs<App, S>): Promise<SelectResult<App, S>[]>;
|
package/emit/templates/client.js
CHANGED
|
@@ -63,6 +63,10 @@ class TableClient {
|
|
|
63
63
|
query.limit(args.limit);
|
|
64
64
|
if (args.offset !== undefined)
|
|
65
65
|
query.offset(args.offset);
|
|
66
|
+
if (args.lock) {
|
|
67
|
+
const lock = typeof args.lock === 'string' ? { strength: args.lock } : args.lock;
|
|
68
|
+
query.lock(lock.strength, { skipLocked: lock.skipLocked, noWait: lock.noWait });
|
|
69
|
+
}
|
|
66
70
|
const { text, values } = query.build();
|
|
67
71
|
const { rows } = await this.db.query(text, values);
|
|
68
72
|
return rows.map(row => this.decodeRow(row, fields));
|
|
@@ -96,6 +100,28 @@ class TableClient {
|
|
|
96
100
|
const { rows } = await this.db.query(text, values);
|
|
97
101
|
return this.decodeRow(rows[0], fields);
|
|
98
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Insert a row, or reconcile the one the conflict target already matches.
|
|
105
|
+
* Returns the resulting row, or null when a conflicting row was left as it
|
|
106
|
+
* is by an upsert that states no `update`.
|
|
107
|
+
*/
|
|
108
|
+
async upsert(args) {
|
|
109
|
+
if (args.conflict.length === 0) {
|
|
110
|
+
throw new Error(`${this.spec.table}.upsert: refusing an empty conflict target, which names no unique constraint`);
|
|
111
|
+
}
|
|
112
|
+
const fields = this.selectedFields(args.select);
|
|
113
|
+
const columns = args.conflict.map(field => this.column(field));
|
|
114
|
+
const updateColumns = args.update ? this.encodeData(args.update) : {};
|
|
115
|
+
const query = this.baseQuery()
|
|
116
|
+
.insert(this.encodeData(args.create))
|
|
117
|
+
.onConflict(Object.keys(updateColumns).length > 0
|
|
118
|
+
? { columns, action: 'update', updateColumns }
|
|
119
|
+
: { columns, action: 'nothing' })
|
|
120
|
+
.returning(fields.map(field => this.column(field)));
|
|
121
|
+
const { text, values } = query.build();
|
|
122
|
+
const { rows } = await this.db.query(text, values);
|
|
123
|
+
return rows.length > 0 ? this.decodeRow(rows[0], fields) : null;
|
|
124
|
+
}
|
|
99
125
|
async update(args) {
|
|
100
126
|
const fields = this.selectedFields(args.select);
|
|
101
127
|
const query = this.baseQuery()
|
package/emit/templates/client.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* NOTE: This file is read at codegen time and written to output.
|
|
11
11
|
* Any changes here will affect all generated clients.
|
|
12
12
|
*/
|
|
13
|
-
import type { Expr, Filter, Operand, SqlValue } from '@constructive-io/query-builder';
|
|
13
|
+
import type { Expr, Filter, LockOptions, LockStrength, Operand, SqlValue } from '@constructive-io/query-builder';
|
|
14
14
|
import { fn, lit, QueryBuilder } from '@constructive-io/query-builder';
|
|
15
15
|
|
|
16
16
|
/** Anything with pg's `query(text, values)` shape: Pool, PoolClient, Client. */
|
|
@@ -149,6 +149,21 @@ export type Data<App> = { [K in keyof App]?: App[K] | Expr } & {
|
|
|
149
149
|
|
|
150
150
|
export type OrderDirection = 'ASC' | 'DESC';
|
|
151
151
|
|
|
152
|
+
/**
|
|
153
|
+
* Row-level lock the read takes, so a read-then-write stays serialized against
|
|
154
|
+
* a concurrent one: `'update'` is `FOR UPDATE`, and the object form states what
|
|
155
|
+
* to do about a row someone else holds.
|
|
156
|
+
*
|
|
157
|
+
* ```ts
|
|
158
|
+
* const run = await runs.$with(tx).findFirst({ where: { id }, lock: 'update' });
|
|
159
|
+
* const job = await jobs.$with(tx).findFirst({
|
|
160
|
+
* where: { status: 'pending' },
|
|
161
|
+
* lock: { strength: 'update', skipLocked: true }
|
|
162
|
+
* });
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
export type Lock = LockStrength | ({ strength: LockStrength } & LockOptions);
|
|
166
|
+
|
|
152
167
|
/** Order spec keyed by camelCase field names, e.g. `{ createdAt: 'DESC' }`. */
|
|
153
168
|
export type OrderBy<App> = { [K in keyof App]?: OrderDirection };
|
|
154
169
|
|
|
@@ -158,12 +173,14 @@ export interface FindManyArgs<App, S extends SelectShape<App> | undefined> {
|
|
|
158
173
|
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
159
174
|
limit?: number;
|
|
160
175
|
offset?: number;
|
|
176
|
+
lock?: Lock;
|
|
161
177
|
}
|
|
162
178
|
|
|
163
179
|
export interface FindFirstArgs<App, S extends SelectShape<App> | undefined> {
|
|
164
180
|
where?: Where<App>;
|
|
165
181
|
select?: S;
|
|
166
182
|
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
183
|
+
lock?: Lock;
|
|
167
184
|
}
|
|
168
185
|
|
|
169
186
|
export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
|
|
@@ -171,6 +188,32 @@ export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
|
|
|
171
188
|
select?: S;
|
|
172
189
|
}
|
|
173
190
|
|
|
191
|
+
/**
|
|
192
|
+
* An upsert states the unique columns it conflicts on, the row to insert, and
|
|
193
|
+
* what to set when one already exists. No `update` means an existing row is
|
|
194
|
+
* left as it is (`ON CONFLICT DO NOTHING`), and then there may be no row to
|
|
195
|
+
* return.
|
|
196
|
+
*
|
|
197
|
+
* ```ts
|
|
198
|
+
* await db.appConfigs.upsert({
|
|
199
|
+
* conflict: ['namespaceId', 'name'],
|
|
200
|
+
* create: { name, value, namespaceId },
|
|
201
|
+
* update: { value, updatedAt: fn('now') }
|
|
202
|
+
* });
|
|
203
|
+
* ```
|
|
204
|
+
*/
|
|
205
|
+
export interface UpsertArgs<App, S extends SelectShape<App> | undefined> {
|
|
206
|
+
/**
|
|
207
|
+
* The unique fields to conflict on. Generated fields autocomplete and map to
|
|
208
|
+
* their columns; a runtime-configured column (a scope key this binding's
|
|
209
|
+
* table carries) is named as the column it is.
|
|
210
|
+
*/
|
|
211
|
+
conflict: readonly (keyof App & string)[] | readonly string[];
|
|
212
|
+
create: Data<App>;
|
|
213
|
+
update?: Data<App>;
|
|
214
|
+
select?: S;
|
|
215
|
+
}
|
|
216
|
+
|
|
174
217
|
export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
|
|
175
218
|
where: Where<App>;
|
|
176
219
|
data: Data<App>;
|
|
@@ -216,6 +259,10 @@ export class TableClient<App> {
|
|
|
216
259
|
this.applyOrderBy(query, args.orderBy);
|
|
217
260
|
if (args.limit !== undefined) query.limit(args.limit);
|
|
218
261
|
if (args.offset !== undefined) query.offset(args.offset);
|
|
262
|
+
if (args.lock) {
|
|
263
|
+
const lock = typeof args.lock === 'string' ? { strength: args.lock } : args.lock;
|
|
264
|
+
query.lock(lock.strength, { skipLocked: lock.skipLocked, noWait: lock.noWait });
|
|
265
|
+
}
|
|
219
266
|
const { text, values } = query.build();
|
|
220
267
|
const { rows } = await this.db.query(text, values);
|
|
221
268
|
return rows.map(row => this.decodeRow(row, fields));
|
|
@@ -258,6 +305,35 @@ export class TableClient<App> {
|
|
|
258
305
|
return this.decodeRow(rows[0], fields);
|
|
259
306
|
}
|
|
260
307
|
|
|
308
|
+
/**
|
|
309
|
+
* Insert a row, or reconcile the one the conflict target already matches.
|
|
310
|
+
* Returns the resulting row, or null when a conflicting row was left as it
|
|
311
|
+
* is by an upsert that states no `update`.
|
|
312
|
+
*/
|
|
313
|
+
async upsert<S extends SelectShape<App> | undefined = undefined>(
|
|
314
|
+
args: UpsertArgs<App, S>
|
|
315
|
+
): Promise<SelectResult<App, S> | null> {
|
|
316
|
+
if (args.conflict.length === 0) {
|
|
317
|
+
throw new Error(
|
|
318
|
+
`${this.spec.table}.upsert: refusing an empty conflict target, which names no unique constraint`
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
const fields = this.selectedFields(args.select);
|
|
322
|
+
const columns = args.conflict.map(field => this.column(field));
|
|
323
|
+
const updateColumns = args.update ? this.encodeData(args.update) : {};
|
|
324
|
+
const query = this.baseQuery()
|
|
325
|
+
.insert(this.encodeData(args.create))
|
|
326
|
+
.onConflict(
|
|
327
|
+
Object.keys(updateColumns).length > 0
|
|
328
|
+
? { columns, action: 'update', updateColumns }
|
|
329
|
+
: { columns, action: 'nothing' }
|
|
330
|
+
)
|
|
331
|
+
.returning(fields.map(field => this.column(field)));
|
|
332
|
+
const { text, values } = query.build();
|
|
333
|
+
const { rows } = await this.db.query(text, values);
|
|
334
|
+
return rows.length > 0 ? this.decodeRow(rows[0], fields) : null;
|
|
335
|
+
}
|
|
336
|
+
|
|
261
337
|
async update<S extends SelectShape<App> | undefined = undefined>(
|
|
262
338
|
args: UpdateArgs<App, S>
|
|
263
339
|
): Promise<SelectResult<App, S>[]> {
|
|
@@ -59,6 +59,10 @@ export class TableClient {
|
|
|
59
59
|
query.limit(args.limit);
|
|
60
60
|
if (args.offset !== undefined)
|
|
61
61
|
query.offset(args.offset);
|
|
62
|
+
if (args.lock) {
|
|
63
|
+
const lock = typeof args.lock === 'string' ? { strength: args.lock } : args.lock;
|
|
64
|
+
query.lock(lock.strength, { skipLocked: lock.skipLocked, noWait: lock.noWait });
|
|
65
|
+
}
|
|
62
66
|
const { text, values } = query.build();
|
|
63
67
|
const { rows } = await this.db.query(text, values);
|
|
64
68
|
return rows.map(row => this.decodeRow(row, fields));
|
|
@@ -92,6 +96,28 @@ export class TableClient {
|
|
|
92
96
|
const { rows } = await this.db.query(text, values);
|
|
93
97
|
return this.decodeRow(rows[0], fields);
|
|
94
98
|
}
|
|
99
|
+
/**
|
|
100
|
+
* Insert a row, or reconcile the one the conflict target already matches.
|
|
101
|
+
* Returns the resulting row, or null when a conflicting row was left as it
|
|
102
|
+
* is by an upsert that states no `update`.
|
|
103
|
+
*/
|
|
104
|
+
async upsert(args) {
|
|
105
|
+
if (args.conflict.length === 0) {
|
|
106
|
+
throw new Error(`${this.spec.table}.upsert: refusing an empty conflict target, which names no unique constraint`);
|
|
107
|
+
}
|
|
108
|
+
const fields = this.selectedFields(args.select);
|
|
109
|
+
const columns = args.conflict.map(field => this.column(field));
|
|
110
|
+
const updateColumns = args.update ? this.encodeData(args.update) : {};
|
|
111
|
+
const query = this.baseQuery()
|
|
112
|
+
.insert(this.encodeData(args.create))
|
|
113
|
+
.onConflict(Object.keys(updateColumns).length > 0
|
|
114
|
+
? { columns, action: 'update', updateColumns }
|
|
115
|
+
: { columns, action: 'nothing' })
|
|
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.length > 0 ? this.decodeRow(rows[0], fields) : null;
|
|
120
|
+
}
|
|
95
121
|
async update(args) {
|
|
96
122
|
const fields = this.selectedFields(args.select);
|
|
97
123
|
const query = this.baseQuery()
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* NOTE: This file is read at codegen time and written to output.
|
|
11
11
|
* Any changes here will affect all generated clients.
|
|
12
12
|
*/
|
|
13
|
-
import type { Expr, Filter, Operand, SqlValue } from '@constructive-io/query-builder';
|
|
13
|
+
import type { Expr, Filter, LockOptions, LockStrength, Operand, SqlValue } from '@constructive-io/query-builder';
|
|
14
14
|
import { fn, lit, QueryBuilder } from '@constructive-io/query-builder';
|
|
15
15
|
|
|
16
16
|
/** Anything with pg's `query(text, values)` shape: Pool, PoolClient, Client. */
|
|
@@ -149,6 +149,21 @@ export type Data<App> = { [K in keyof App]?: App[K] | Expr } & {
|
|
|
149
149
|
|
|
150
150
|
export type OrderDirection = 'ASC' | 'DESC';
|
|
151
151
|
|
|
152
|
+
/**
|
|
153
|
+
* Row-level lock the read takes, so a read-then-write stays serialized against
|
|
154
|
+
* a concurrent one: `'update'` is `FOR UPDATE`, and the object form states what
|
|
155
|
+
* to do about a row someone else holds.
|
|
156
|
+
*
|
|
157
|
+
* ```ts
|
|
158
|
+
* const run = await runs.$with(tx).findFirst({ where: { id }, lock: 'update' });
|
|
159
|
+
* const job = await jobs.$with(tx).findFirst({
|
|
160
|
+
* where: { status: 'pending' },
|
|
161
|
+
* lock: { strength: 'update', skipLocked: true }
|
|
162
|
+
* });
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
export type Lock = LockStrength | ({ strength: LockStrength } & LockOptions);
|
|
166
|
+
|
|
152
167
|
/** Order spec keyed by camelCase field names, e.g. `{ createdAt: 'DESC' }`. */
|
|
153
168
|
export type OrderBy<App> = { [K in keyof App]?: OrderDirection };
|
|
154
169
|
|
|
@@ -158,12 +173,14 @@ export interface FindManyArgs<App, S extends SelectShape<App> | undefined> {
|
|
|
158
173
|
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
159
174
|
limit?: number;
|
|
160
175
|
offset?: number;
|
|
176
|
+
lock?: Lock;
|
|
161
177
|
}
|
|
162
178
|
|
|
163
179
|
export interface FindFirstArgs<App, S extends SelectShape<App> | undefined> {
|
|
164
180
|
where?: Where<App>;
|
|
165
181
|
select?: S;
|
|
166
182
|
orderBy?: OrderBy<App> | OrderBy<App>[];
|
|
183
|
+
lock?: Lock;
|
|
167
184
|
}
|
|
168
185
|
|
|
169
186
|
export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
|
|
@@ -171,6 +188,32 @@ export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
|
|
|
171
188
|
select?: S;
|
|
172
189
|
}
|
|
173
190
|
|
|
191
|
+
/**
|
|
192
|
+
* An upsert states the unique columns it conflicts on, the row to insert, and
|
|
193
|
+
* what to set when one already exists. No `update` means an existing row is
|
|
194
|
+
* left as it is (`ON CONFLICT DO NOTHING`), and then there may be no row to
|
|
195
|
+
* return.
|
|
196
|
+
*
|
|
197
|
+
* ```ts
|
|
198
|
+
* await db.appConfigs.upsert({
|
|
199
|
+
* conflict: ['namespaceId', 'name'],
|
|
200
|
+
* create: { name, value, namespaceId },
|
|
201
|
+
* update: { value, updatedAt: fn('now') }
|
|
202
|
+
* });
|
|
203
|
+
* ```
|
|
204
|
+
*/
|
|
205
|
+
export interface UpsertArgs<App, S extends SelectShape<App> | undefined> {
|
|
206
|
+
/**
|
|
207
|
+
* The unique fields to conflict on. Generated fields autocomplete and map to
|
|
208
|
+
* their columns; a runtime-configured column (a scope key this binding's
|
|
209
|
+
* table carries) is named as the column it is.
|
|
210
|
+
*/
|
|
211
|
+
conflict: readonly (keyof App & string)[] | readonly string[];
|
|
212
|
+
create: Data<App>;
|
|
213
|
+
update?: Data<App>;
|
|
214
|
+
select?: S;
|
|
215
|
+
}
|
|
216
|
+
|
|
174
217
|
export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
|
|
175
218
|
where: Where<App>;
|
|
176
219
|
data: Data<App>;
|
|
@@ -216,6 +259,10 @@ export class TableClient<App> {
|
|
|
216
259
|
this.applyOrderBy(query, args.orderBy);
|
|
217
260
|
if (args.limit !== undefined) query.limit(args.limit);
|
|
218
261
|
if (args.offset !== undefined) query.offset(args.offset);
|
|
262
|
+
if (args.lock) {
|
|
263
|
+
const lock = typeof args.lock === 'string' ? { strength: args.lock } : args.lock;
|
|
264
|
+
query.lock(lock.strength, { skipLocked: lock.skipLocked, noWait: lock.noWait });
|
|
265
|
+
}
|
|
219
266
|
const { text, values } = query.build();
|
|
220
267
|
const { rows } = await this.db.query(text, values);
|
|
221
268
|
return rows.map(row => this.decodeRow(row, fields));
|
|
@@ -258,6 +305,35 @@ export class TableClient<App> {
|
|
|
258
305
|
return this.decodeRow(rows[0], fields);
|
|
259
306
|
}
|
|
260
307
|
|
|
308
|
+
/**
|
|
309
|
+
* Insert a row, or reconcile the one the conflict target already matches.
|
|
310
|
+
* Returns the resulting row, or null when a conflicting row was left as it
|
|
311
|
+
* is by an upsert that states no `update`.
|
|
312
|
+
*/
|
|
313
|
+
async upsert<S extends SelectShape<App> | undefined = undefined>(
|
|
314
|
+
args: UpsertArgs<App, S>
|
|
315
|
+
): Promise<SelectResult<App, S> | null> {
|
|
316
|
+
if (args.conflict.length === 0) {
|
|
317
|
+
throw new Error(
|
|
318
|
+
`${this.spec.table}.upsert: refusing an empty conflict target, which names no unique constraint`
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
const fields = this.selectedFields(args.select);
|
|
322
|
+
const columns = args.conflict.map(field => this.column(field));
|
|
323
|
+
const updateColumns = args.update ? this.encodeData(args.update) : {};
|
|
324
|
+
const query = this.baseQuery()
|
|
325
|
+
.insert(this.encodeData(args.create))
|
|
326
|
+
.onConflict(
|
|
327
|
+
Object.keys(updateColumns).length > 0
|
|
328
|
+
? { columns, action: 'update', updateColumns }
|
|
329
|
+
: { columns, action: 'nothing' }
|
|
330
|
+
)
|
|
331
|
+
.returning(fields.map(field => this.column(field)));
|
|
332
|
+
const { text, values } = query.build();
|
|
333
|
+
const { rows } = await this.db.query(text, values);
|
|
334
|
+
return rows.length > 0 ? this.decodeRow(rows[0], fields) : null;
|
|
335
|
+
}
|
|
336
|
+
|
|
261
337
|
async update<S extends SelectShape<App> | undefined = undefined>(
|
|
262
338
|
args: UpdateArgs<App, S>
|
|
263
339
|
): Promise<SelectResult<App, S>[]> {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pg-codegen",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.19.0",
|
|
4
4
|
"author": "Constructive <developers@constructive.io>",
|
|
5
5
|
"description": "Type-safe TypeScript codegen from live PostgreSQL schemas: row types, coerce-backed decoders, serializers, table metadata, and enum unions",
|
|
6
6
|
"main": "index.js",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"@babel/generator": "^7.29.1",
|
|
47
47
|
"@babel/types": "^7.29.0",
|
|
48
48
|
"@constructive-io/coerce": "^0.3.1",
|
|
49
|
-
"@constructive-io/query-builder": "^3.
|
|
49
|
+
"@constructive-io/query-builder": "^3.11.0",
|
|
50
50
|
"inflekt": "^0.8.1",
|
|
51
51
|
"introspectron": "^5.13.1",
|
|
52
52
|
"pg": "^8.21.0",
|
|
@@ -58,5 +58,5 @@
|
|
|
58
58
|
"makage": "^0.3.0",
|
|
59
59
|
"pgsql-test": "^5.11.1"
|
|
60
60
|
},
|
|
61
|
-
"gitHead": "
|
|
61
|
+
"gitHead": "6880388c8cd5fb21745decff8bd23c3a430338b3"
|
|
62
62
|
}
|