pg-codegen 5.16.0 → 5.18.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 CHANGED
@@ -57,6 +57,7 @@ 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 |
@@ -89,6 +90,23 @@ await db.resources.update({
89
90
 
90
91
  An expression is deparsed in place — never bound as a value, never serialized as one.
91
92
 
93
+ ### Upsert
94
+
95
+ `upsert` states the unique fields it conflicts on, the row to insert, and what to set when one already exists:
96
+
97
+ ```ts
98
+ import { fn } from '@constructive-io/query-builder';
99
+
100
+ await db.appConfigs.upsert({
101
+ conflict: ['namespaceId', 'name'],
102
+ create: { name, value, namespaceId },
103
+ update: { value, updatedAt: fn('now') }
104
+ });
105
+ // INSERT INTO … ON CONFLICT (namespace_id, name) DO UPDATE SET value = $1, updated_at = now() RETURNING …
106
+ ```
107
+
108
+ 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.
109
+
92
110
  ### Selections type the result
93
111
 
94
112
  `select` is the only projection, stated either way round, and the return type follows it with nothing to annotate:
@@ -106,6 +124,20 @@ await db.emailIdentities.findFirst({ select: { databaseId: false } });
106
124
 
107
125
  Excluding is what a caller reaches for when a field must not be carried — a secret's id, row bookkeeping — or when this binding's table genuinely lacks it: an excluded field is absent from the type, so reading it does not compile. Naming any field `true` is a projection and wins outright; the excluded ones are simply not in it.
108
126
 
127
+ ### Naming a filter or a write input
128
+
129
+ The client's own vocabulary is exported from the package root, keyed by a generated record, so a function that takes a filter or the values of a write says so without restating the fields:
130
+
131
+ ```ts
132
+ import type { Data, Where } from './generated';
133
+ import type { EmailIdentities } from './generated/routing_public';
134
+
135
+ const active = (extra: Where<EmailIdentities>) => ({ isActive: true, ...extra });
136
+ type IdentityInput = Data<EmailIdentities>; // every field optional, camelCase
137
+ ```
138
+
139
+ `Where`, `Data`, `SelectShape`, `OrderBy` and `Queryable` all come from there.
140
+
109
141
  ### Transactions
110
142
 
111
143
  `$with` rebinds every table client to another connection, so a transaction is the same code against a different handle:
@@ -152,7 +184,9 @@ For every table, view, materialized view and partitioned table in the schemas yo
152
184
 
153
185
  Plus, per schema, a `db.ts` (the client above), an `enums.ts` — a literal union, a `readonly` value list and `as*`/`require*` checkers for every PostgreSQL enum a column references — and barrels; and one shared `client.ts` runtime at the root.
154
186
 
155
- Every decoder is backed by [`@constructive-io/coerce`](../../packages/coerce): a NOT NULL column throws `CoerceError` naming the offending column, a nullable column answers `null`, and the text forms `pg` returns for `int8`/`numeric` are parsed rather than passed through as strings. Nothing is silently coerced across types, so a malformed row cannot become a default value.
187
+ Every decoder is backed by [`@constructive-io/coerce`](../../packages/coerce): a NOT NULL column throws `CoerceError` naming the offending column, a nullable column answers `null`, and the text form `pg` returns for `numeric` is parsed to a number. Nothing is silently coerced across types, so a malformed row cannot become a default value.
188
+
189
+ An `int8` column is a **`string`** — the canonical digits of the value, which is how `pg` returns the type, how `graphql/codegen` spells its `BigInt` scalar, and the only representation that keeps an id past 2^53 (a `number` would round `9007199254740993` to its neighbour). Its decoder accepts any of the three shapes a 64-bit value arrives in — `bigint`, integer `number`, digit string — and answers the canonical digits, so `'007'` and `7` both decode to `'7'`; a write states the string and PostgreSQL reads it as `int8`.
156
190
 
157
191
  ## 🔧 Below the client
158
192
 
package/emit/barrel.js CHANGED
@@ -25,6 +25,10 @@ const emitSchemaIndex = (schema) => {
25
25
  exports.emitSchemaIndex = emitSchemaIndex;
26
26
  const emitRootIndex = (schemas) => {
27
27
  const statements = schemas.map(schema => babel_1.t.exportNamedDeclaration(null, [babel_1.t.exportNamespaceSpecifier(babel_1.t.identifier((0, inflekt_1.toCamelCase)(schema.name)))], babel_1.t.stringLiteral(`./${schema.name}`)));
28
+ // The client's own vocabulary — `Where`, `Data`, `SelectShape`, `OrderBy` —
29
+ // so a consumer that names a filter or a write input states it over a
30
+ // generated record instead of hand-writing the field list again.
31
+ statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral('./client')));
28
32
  return (0, babel_1.generateCode)(statements);
29
33
  };
30
34
  exports.emitRootIndex = emitRootIndex;
package/emit/record.js CHANGED
@@ -12,7 +12,11 @@ const enums_1 = require("./enums");
12
12
  const COERCERS = {
13
13
  boolean: { require: 'requireBoolean', as: 'asBoolean', expectedArray: 'an array of booleans' },
14
14
  integer: { require: 'requireInteger', as: 'asInteger', expectedArray: 'an array of integers' },
15
- bigint: { require: 'requireNumericInteger', as: 'asNumericInteger', expectedArray: 'an array of integers' },
15
+ bigint: {
16
+ require: 'requireBigIntString',
17
+ as: 'asBigIntString',
18
+ expectedArray: 'an array of whole numbers'
19
+ },
16
20
  number: { require: 'requireNumeric', as: 'asNumeric', expectedArray: 'an array of numbers' },
17
21
  string: { require: 'requireString', as: 'asString', expectedArray: 'an array of non-empty strings' },
18
22
  uuid: { require: 'requireUuid', as: 'asUuid', expectedArray: 'an array of UUIDs' },
@@ -24,9 +28,12 @@ const scalarTsType = (column) => {
24
28
  case 'boolean':
25
29
  return babel_1.t.tsBooleanKeyword();
26
30
  case 'integer':
27
- case 'bigint':
28
31
  case 'number':
29
32
  return babel_1.t.tsNumberKeyword();
33
+ // int8 carries values a JS number cannot hold, so it is a digit string —
34
+ // the same spelling graphql/codegen gives the `BigInt` scalar, and the one
35
+ // node-postgres already returns for the type.
36
+ case 'bigint':
30
37
  case 'string':
31
38
  case 'uuid':
32
39
  case 'timestamp':
@@ -133,6 +133,31 @@ export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
133
133
  data: Data<App>;
134
134
  select?: S;
135
135
  }
136
+ /**
137
+ * An upsert states the unique columns it conflicts on, the row to insert, and
138
+ * what to set when one already exists. No `update` means an existing row is
139
+ * left as it is (`ON CONFLICT DO NOTHING`), and then there may be no row to
140
+ * return.
141
+ *
142
+ * ```ts
143
+ * await db.appConfigs.upsert({
144
+ * conflict: ['namespaceId', 'name'],
145
+ * create: { name, value, namespaceId },
146
+ * update: { value, updatedAt: fn('now') }
147
+ * });
148
+ * ```
149
+ */
150
+ export interface UpsertArgs<App, S extends SelectShape<App> | undefined> {
151
+ /**
152
+ * The unique fields to conflict on. Generated fields autocomplete and map to
153
+ * their columns; a runtime-configured column (a scope key this binding's
154
+ * table carries) is named as the column it is.
155
+ */
156
+ conflict: readonly (keyof App & string)[] | readonly string[];
157
+ create: Data<App>;
158
+ update?: Data<App>;
159
+ select?: S;
160
+ }
136
161
  export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
137
162
  where: Where<App>;
138
163
  data: Data<App>;
@@ -157,6 +182,12 @@ export declare class TableClient<App> {
157
182
  findFirstOrThrow<S extends SelectShape<App> | undefined = undefined>(args?: FindFirstArgs<App, S>): Promise<SelectResult<App, S>>;
158
183
  count(where?: Where<App>): Promise<number>;
159
184
  create<S extends SelectShape<App> | undefined = undefined>(args: CreateArgs<App, S>): Promise<SelectResult<App, S>>;
185
+ /**
186
+ * Insert a row, or reconcile the one the conflict target already matches.
187
+ * Returns the resulting row, or null when a conflicting row was left as it
188
+ * is by an upsert that states no `update`.
189
+ */
190
+ upsert<S extends SelectShape<App> | undefined = undefined>(args: UpsertArgs<App, S>): Promise<SelectResult<App, S> | null>;
160
191
  update<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>[]>;
161
192
  updateOrThrow<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>>;
162
193
  delete<S extends SelectShape<App> | undefined = undefined>(args: DeleteArgs<App, S>): Promise<SelectResult<App, S>[]>;
@@ -96,6 +96,28 @@ class TableClient {
96
96
  const { rows } = await this.db.query(text, values);
97
97
  return this.decodeRow(rows[0], fields);
98
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
+ }
99
121
  async update(args) {
100
122
  const fields = this.selectedFields(args.select);
101
123
  const query = this.baseQuery()
@@ -171,6 +171,32 @@ export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
171
171
  select?: S;
172
172
  }
173
173
 
174
+ /**
175
+ * An upsert states the unique columns it conflicts on, the row to insert, and
176
+ * what to set when one already exists. No `update` means an existing row is
177
+ * left as it is (`ON CONFLICT DO NOTHING`), and then there may be no row to
178
+ * return.
179
+ *
180
+ * ```ts
181
+ * await db.appConfigs.upsert({
182
+ * conflict: ['namespaceId', 'name'],
183
+ * create: { name, value, namespaceId },
184
+ * update: { value, updatedAt: fn('now') }
185
+ * });
186
+ * ```
187
+ */
188
+ export interface UpsertArgs<App, S extends SelectShape<App> | undefined> {
189
+ /**
190
+ * The unique fields to conflict on. Generated fields autocomplete and map to
191
+ * their columns; a runtime-configured column (a scope key this binding's
192
+ * table carries) is named as the column it is.
193
+ */
194
+ conflict: readonly (keyof App & string)[] | readonly string[];
195
+ create: Data<App>;
196
+ update?: Data<App>;
197
+ select?: S;
198
+ }
199
+
174
200
  export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
175
201
  where: Where<App>;
176
202
  data: Data<App>;
@@ -258,6 +284,35 @@ export class TableClient<App> {
258
284
  return this.decodeRow(rows[0], fields);
259
285
  }
260
286
 
287
+ /**
288
+ * Insert a row, or reconcile the one the conflict target already matches.
289
+ * Returns the resulting row, or null when a conflicting row was left as it
290
+ * is by an upsert that states no `update`.
291
+ */
292
+ async upsert<S extends SelectShape<App> | undefined = undefined>(
293
+ args: UpsertArgs<App, S>
294
+ ): Promise<SelectResult<App, S> | null> {
295
+ if (args.conflict.length === 0) {
296
+ throw new Error(
297
+ `${this.spec.table}.upsert: refusing an empty conflict target, which names no unique constraint`
298
+ );
299
+ }
300
+ const fields = this.selectedFields(args.select);
301
+ const columns = args.conflict.map(field => this.column(field));
302
+ const updateColumns = args.update ? this.encodeData(args.update) : {};
303
+ const query = this.baseQuery()
304
+ .insert(this.encodeData(args.create))
305
+ .onConflict(
306
+ Object.keys(updateColumns).length > 0
307
+ ? { columns, action: 'update', updateColumns }
308
+ : { columns, action: 'nothing' }
309
+ )
310
+ .returning(fields.map(field => this.column(field)));
311
+ const { text, values } = query.build();
312
+ const { rows } = await this.db.query(text, values);
313
+ return rows.length > 0 ? this.decodeRow(rows[0], fields) : null;
314
+ }
315
+
261
316
  async update<S extends SelectShape<App> | undefined = undefined>(
262
317
  args: UpdateArgs<App, S>
263
318
  ): Promise<SelectResult<App, S>[]> {
@@ -20,5 +20,9 @@ export const emitSchemaIndex = (schema) => {
20
20
  };
21
21
  export const emitRootIndex = (schemas) => {
22
22
  const statements = schemas.map(schema => t.exportNamedDeclaration(null, [t.exportNamespaceSpecifier(t.identifier(toCamelCase(schema.name)))], t.stringLiteral(`./${schema.name}`)));
23
+ // The client's own vocabulary — `Where`, `Data`, `SelectShape`, `OrderBy` —
24
+ // so a consumer that names a filter or a write input states it over a
25
+ // generated record instead of hand-writing the field list again.
26
+ statements.push(t.exportAllDeclaration(t.stringLiteral('./client')));
23
27
  return generateCode(statements);
24
28
  };
@@ -9,7 +9,11 @@ import { enumAsName, enumRequireName, enumTypeName } from './enums';
9
9
  const COERCERS = {
10
10
  boolean: { require: 'requireBoolean', as: 'asBoolean', expectedArray: 'an array of booleans' },
11
11
  integer: { require: 'requireInteger', as: 'asInteger', expectedArray: 'an array of integers' },
12
- bigint: { require: 'requireNumericInteger', as: 'asNumericInteger', expectedArray: 'an array of integers' },
12
+ bigint: {
13
+ require: 'requireBigIntString',
14
+ as: 'asBigIntString',
15
+ expectedArray: 'an array of whole numbers'
16
+ },
13
17
  number: { require: 'requireNumeric', as: 'asNumeric', expectedArray: 'an array of numbers' },
14
18
  string: { require: 'requireString', as: 'asString', expectedArray: 'an array of non-empty strings' },
15
19
  uuid: { require: 'requireUuid', as: 'asUuid', expectedArray: 'an array of UUIDs' },
@@ -21,9 +25,12 @@ const scalarTsType = (column) => {
21
25
  case 'boolean':
22
26
  return t.tsBooleanKeyword();
23
27
  case 'integer':
24
- case 'bigint':
25
28
  case 'number':
26
29
  return t.tsNumberKeyword();
30
+ // int8 carries values a JS number cannot hold, so it is a digit string —
31
+ // the same spelling graphql/codegen gives the `BigInt` scalar, and the one
32
+ // node-postgres already returns for the type.
33
+ case 'bigint':
27
34
  case 'string':
28
35
  case 'uuid':
29
36
  case 'timestamp':
@@ -92,6 +92,28 @@ export class TableClient {
92
92
  const { rows } = await this.db.query(text, values);
93
93
  return this.decodeRow(rows[0], fields);
94
94
  }
95
+ /**
96
+ * Insert a row, or reconcile the one the conflict target already matches.
97
+ * Returns the resulting row, or null when a conflicting row was left as it
98
+ * is by an upsert that states no `update`.
99
+ */
100
+ async upsert(args) {
101
+ if (args.conflict.length === 0) {
102
+ throw new Error(`${this.spec.table}.upsert: refusing an empty conflict target, which names no unique constraint`);
103
+ }
104
+ const fields = this.selectedFields(args.select);
105
+ const columns = args.conflict.map(field => this.column(field));
106
+ const updateColumns = args.update ? this.encodeData(args.update) : {};
107
+ const query = this.baseQuery()
108
+ .insert(this.encodeData(args.create))
109
+ .onConflict(Object.keys(updateColumns).length > 0
110
+ ? { columns, action: 'update', updateColumns }
111
+ : { columns, action: 'nothing' })
112
+ .returning(fields.map(field => this.column(field)));
113
+ const { text, values } = query.build();
114
+ const { rows } = await this.db.query(text, values);
115
+ return rows.length > 0 ? this.decodeRow(rows[0], fields) : null;
116
+ }
95
117
  async update(args) {
96
118
  const fields = this.selectedFields(args.select);
97
119
  const query = this.baseQuery()
@@ -171,6 +171,32 @@ export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
171
171
  select?: S;
172
172
  }
173
173
 
174
+ /**
175
+ * An upsert states the unique columns it conflicts on, the row to insert, and
176
+ * what to set when one already exists. No `update` means an existing row is
177
+ * left as it is (`ON CONFLICT DO NOTHING`), and then there may be no row to
178
+ * return.
179
+ *
180
+ * ```ts
181
+ * await db.appConfigs.upsert({
182
+ * conflict: ['namespaceId', 'name'],
183
+ * create: { name, value, namespaceId },
184
+ * update: { value, updatedAt: fn('now') }
185
+ * });
186
+ * ```
187
+ */
188
+ export interface UpsertArgs<App, S extends SelectShape<App> | undefined> {
189
+ /**
190
+ * The unique fields to conflict on. Generated fields autocomplete and map to
191
+ * their columns; a runtime-configured column (a scope key this binding's
192
+ * table carries) is named as the column it is.
193
+ */
194
+ conflict: readonly (keyof App & string)[] | readonly string[];
195
+ create: Data<App>;
196
+ update?: Data<App>;
197
+ select?: S;
198
+ }
199
+
174
200
  export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
175
201
  where: Where<App>;
176
202
  data: Data<App>;
@@ -258,6 +284,35 @@ export class TableClient<App> {
258
284
  return this.decodeRow(rows[0], fields);
259
285
  }
260
286
 
287
+ /**
288
+ * Insert a row, or reconcile the one the conflict target already matches.
289
+ * Returns the resulting row, or null when a conflicting row was left as it
290
+ * is by an upsert that states no `update`.
291
+ */
292
+ async upsert<S extends SelectShape<App> | undefined = undefined>(
293
+ args: UpsertArgs<App, S>
294
+ ): Promise<SelectResult<App, S> | null> {
295
+ if (args.conflict.length === 0) {
296
+ throw new Error(
297
+ `${this.spec.table}.upsert: refusing an empty conflict target, which names no unique constraint`
298
+ );
299
+ }
300
+ const fields = this.selectedFields(args.select);
301
+ const columns = args.conflict.map(field => this.column(field));
302
+ const updateColumns = args.update ? this.encodeData(args.update) : {};
303
+ const query = this.baseQuery()
304
+ .insert(this.encodeData(args.create))
305
+ .onConflict(
306
+ Object.keys(updateColumns).length > 0
307
+ ? { columns, action: 'update', updateColumns }
308
+ : { columns, action: 'nothing' }
309
+ )
310
+ .returning(fields.map(field => this.column(field)));
311
+ const { text, values } = query.build();
312
+ const { rows } = await this.db.query(text, values);
313
+ return rows.length > 0 ? this.decodeRow(rows[0], fields) : null;
314
+ }
315
+
261
316
  async update<S extends SelectShape<App> | undefined = undefined>(
262
317
  args: UpdateArgs<App, S>
263
318
  ): Promise<SelectResult<App, S>[]> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pg-codegen",
3
- "version": "5.16.0",
3
+ "version": "5.18.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",
@@ -45,18 +45,18 @@
45
45
  "dependencies": {
46
46
  "@babel/generator": "^7.29.1",
47
47
  "@babel/types": "^7.29.0",
48
- "@constructive-io/coerce": "^0.3.0",
49
- "@constructive-io/query-builder": "^3.10.5",
48
+ "@constructive-io/coerce": "^0.3.1",
49
+ "@constructive-io/query-builder": "^3.10.6",
50
50
  "inflekt": "^0.8.1",
51
- "introspectron": "^5.13.0",
51
+ "introspectron": "^5.13.1",
52
52
  "pg": "^8.21.0",
53
- "pg-env": "^1.30.0"
53
+ "pg-env": "^1.30.1"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@types/babel__generator": "^7.6.8",
57
57
  "@types/pg": "^8.20.4",
58
58
  "makage": "^0.3.0",
59
- "pgsql-test": "^5.11.0"
59
+ "pgsql-test": "^5.11.1"
60
60
  },
61
- "gitHead": "51a32e8527c226772c2219b721c3cb6af8e66979"
61
+ "gitHead": "fa46a8b1cceb187c59f9c64e3a69e94dc9171f88"
62
62
  }