pg-codegen 5.14.1 → 5.16.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
@@ -75,6 +75,20 @@ await db.posts.findMany({ where: { or: [{ authorId }, { editorId: authorId }], n
75
75
 
76
76
  Writes are encoded from the generated column metadata (json/jsonb columns stringified, `Date` → ISO), and every returned row comes back through the generated per-column decoders, so a value that does not match its column's type raises `CoerceError` instead of flowing on as a lie.
77
77
 
78
+ A write value may also be an expression, so a write that reads the column it sets stays one statement instead of a read followed by a write:
79
+
80
+ ```ts
81
+ import { add, col } from '@constructive-io/query-builder';
82
+
83
+ await db.resources.update({
84
+ where: { id },
85
+ data: { status: 'failed', lastError: message, errorCount: add(col('error_count'), 1) }
86
+ });
87
+ // UPDATE … SET status = $1, last_error = $2, error_count = error_count + 1 WHERE id = $3
88
+ ```
89
+
90
+ An expression is deparsed in place — never bound as a value, never serialized as one.
91
+
78
92
  ### Selections type the result
79
93
 
80
94
  `select` is the only projection, stated either way round, and the return type follows it with nothing to annotate:
package/cli.d.ts CHANGED
@@ -3,6 +3,8 @@ interface CliArgs {
3
3
  schemas: string[];
4
4
  out: string;
5
5
  check: boolean;
6
+ include: string[];
7
+ exclude: string[];
6
8
  }
7
9
  export declare const parseArgs: (argv: string[]) => CliArgs;
8
10
  export declare const main: (argv: string[]) => Promise<number>;
package/cli.js CHANGED
@@ -19,24 +19,35 @@ const USAGE = `Usage: pg-codegen --schema <name> [--schema <name> ...] --out <di
19
19
  Options:
20
20
  --schema <name> A schema to generate records for (repeatable, or comma-separated)
21
21
  --out <dir> Directory the generated files are written to (or compared against)
22
+ --table <glob> Only generate these tables (repeatable, or comma-separated)
23
+ --exclude <glob> Skip these tables (repeatable, or comma-separated)
22
24
  --check Compare against the files already in --out and exit non-zero on drift
23
25
  --help Show this message
24
26
 
25
27
  Connection settings come from the standard PG environment variables.`;
26
28
  const parseArgs = (argv) => {
27
29
  const schemas = [];
30
+ const include = [];
31
+ const exclude = [];
28
32
  let out = '';
29
33
  let check = false;
34
+ const values = (value, flag) => {
35
+ if (!value)
36
+ throw new Error(`${flag} requires a value`);
37
+ return value.split(',').map(name => name.trim()).filter(Boolean);
38
+ };
30
39
  for (let i = 0; i < argv.length; i++) {
31
40
  const arg = argv[i];
32
41
  switch (arg) {
33
- case '--schema': {
34
- const value = argv[++i];
35
- if (!value)
36
- throw new Error('--schema requires a value');
37
- schemas.push(...value.split(',').map(name => name.trim()).filter(Boolean));
42
+ case '--schema':
43
+ schemas.push(...values(argv[++i], '--schema'));
44
+ break;
45
+ case '--table':
46
+ include.push(...values(argv[++i], '--table'));
47
+ break;
48
+ case '--exclude':
49
+ exclude.push(...values(argv[++i], '--exclude'));
38
50
  break;
39
- }
40
51
  case '--out': {
41
52
  const value = argv[++i];
42
53
  if (!value)
@@ -60,7 +71,7 @@ const parseArgs = (argv) => {
60
71
  throw new Error('At least one --schema is required');
61
72
  if (!out)
62
73
  throw new Error('--out is required');
63
- return { schemas, out, check };
74
+ return { schemas, out, check, include, exclude };
64
75
  };
65
76
  exports.parseArgs = parseArgs;
66
77
  const main = async (argv) => {
@@ -84,7 +95,13 @@ const main = async (argv) => {
84
95
  });
85
96
  await client.connect();
86
97
  try {
87
- const files = await (0, generate_1.generate)(client, { schemas: args.schemas });
98
+ const files = await (0, generate_1.generate)(client, {
99
+ schemas: args.schemas,
100
+ tables: {
101
+ ...(args.include.length > 0 ? { include: args.include } : {}),
102
+ ...(args.exclude.length > 0 ? { exclude: args.exclude } : {})
103
+ }
104
+ });
88
105
  if (args.check) {
89
106
  const report = await (0, generate_1.checkFileTree)(args.out, files);
90
107
  if ((0, generate_1.isClean)(report)) {
@@ -1,3 +1,16 @@
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 { Expr } from '@constructive-io/query-builder';
1
14
  /** Anything with pg's `query(text, values)` shape: Pool, PoolClient, Client. */
2
15
  export interface Queryable {
3
16
  query(text: string, values?: unknown[]): Promise<{
@@ -86,8 +99,17 @@ export type Where<App> = {
86
99
  * Write data keyed by camelCase field names. Extra string keys are physical
87
100
  * column names — runtime-configured scope key columns are stamped the same
88
101
  * way any other value is.
102
+ *
103
+ * A value may also be a query-builder expression, so a write that reads the
104
+ * column it sets stays one statement:
105
+ *
106
+ * ```ts
107
+ * data: { lastError: message, errorCount: add(col('error_count'), 1) }
108
+ * ```
89
109
  */
90
- export type Data<App> = Partial<App> & {
110
+ export type Data<App> = {
111
+ [K in keyof App]?: App[K] | Expr;
112
+ } & {
91
113
  [column: string]: unknown;
92
114
  };
93
115
  export type OrderDirection = 'ASC' | 'DESC';
@@ -224,6 +224,12 @@ class TableClient {
224
224
  for (const [field, value] of Object.entries(data)) {
225
225
  if (value === undefined)
226
226
  continue;
227
+ // An expression is SQL the caller wrote: it is deparsed in place, never
228
+ // bound as a value, and never serialized as one either.
229
+ if (typeof value === 'function') {
230
+ encoded[this.column(field)] = value;
231
+ continue;
232
+ }
227
233
  if (value !== null && this.spec.jsonFields?.includes(field)) {
228
234
  encoded[this.column(field)] = JSON.stringify(value);
229
235
  continue;
@@ -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 { Filter, SqlValue } from '@constructive-io/query-builder';
13
+ import type { Expr, Filter, 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. */
@@ -135,8 +135,17 @@ export type Where<App> = {
135
135
  * Write data keyed by camelCase field names. Extra string keys are physical
136
136
  * column names — runtime-configured scope key columns are stamped the same
137
137
  * way any other value is.
138
+ *
139
+ * A value may also be a query-builder expression, so a write that reads the
140
+ * column it sets stays one statement:
141
+ *
142
+ * ```ts
143
+ * data: { lastError: message, errorCount: add(col('error_count'), 1) }
144
+ * ```
138
145
  */
139
- export type Data<App> = Partial<App> & { [column: string]: unknown };
146
+ export type Data<App> = { [K in keyof App]?: App[K] | Expr } & {
147
+ [column: string]: unknown;
148
+ };
140
149
 
141
150
  export type OrderDirection = 'ASC' | 'DESC';
142
151
 
@@ -387,10 +396,16 @@ export class TableClient<App> {
387
396
  }
388
397
  }
389
398
 
390
- private encodeData(data: Data<App>): Record<string, SqlValue> {
391
- const encoded: Record<string, SqlValue> = {};
399
+ private encodeData(data: Data<App>): Record<string, Operand> {
400
+ const encoded: Record<string, Operand> = {};
392
401
  for (const [field, value] of Object.entries(data)) {
393
402
  if (value === undefined) continue;
403
+ // An expression is SQL the caller wrote: it is deparsed in place, never
404
+ // bound as a value, and never serialized as one either.
405
+ if (typeof value === 'function') {
406
+ encoded[this.column(field)] = value as Expr;
407
+ continue;
408
+ }
394
409
  if (value !== null && this.spec.jsonFields?.includes(field)) {
395
410
  encoded[this.column(field)] = JSON.stringify(value);
396
411
  continue;
package/esm/cli.js CHANGED
@@ -16,24 +16,35 @@ const USAGE = `Usage: pg-codegen --schema <name> [--schema <name> ...] --out <di
16
16
  Options:
17
17
  --schema <name> A schema to generate records for (repeatable, or comma-separated)
18
18
  --out <dir> Directory the generated files are written to (or compared against)
19
+ --table <glob> Only generate these tables (repeatable, or comma-separated)
20
+ --exclude <glob> Skip these tables (repeatable, or comma-separated)
19
21
  --check Compare against the files already in --out and exit non-zero on drift
20
22
  --help Show this message
21
23
 
22
24
  Connection settings come from the standard PG environment variables.`;
23
25
  export const parseArgs = (argv) => {
24
26
  const schemas = [];
27
+ const include = [];
28
+ const exclude = [];
25
29
  let out = '';
26
30
  let check = false;
31
+ const values = (value, flag) => {
32
+ if (!value)
33
+ throw new Error(`${flag} requires a value`);
34
+ return value.split(',').map(name => name.trim()).filter(Boolean);
35
+ };
27
36
  for (let i = 0; i < argv.length; i++) {
28
37
  const arg = argv[i];
29
38
  switch (arg) {
30
- case '--schema': {
31
- const value = argv[++i];
32
- if (!value)
33
- throw new Error('--schema requires a value');
34
- schemas.push(...value.split(',').map(name => name.trim()).filter(Boolean));
39
+ case '--schema':
40
+ schemas.push(...values(argv[++i], '--schema'));
41
+ break;
42
+ case '--table':
43
+ include.push(...values(argv[++i], '--table'));
44
+ break;
45
+ case '--exclude':
46
+ exclude.push(...values(argv[++i], '--exclude'));
35
47
  break;
36
- }
37
48
  case '--out': {
38
49
  const value = argv[++i];
39
50
  if (!value)
@@ -57,7 +68,7 @@ export const parseArgs = (argv) => {
57
68
  throw new Error('At least one --schema is required');
58
69
  if (!out)
59
70
  throw new Error('--out is required');
60
- return { schemas, out, check };
71
+ return { schemas, out, check, include, exclude };
61
72
  };
62
73
  export const main = async (argv) => {
63
74
  let args;
@@ -80,7 +91,13 @@ export const main = async (argv) => {
80
91
  });
81
92
  await client.connect();
82
93
  try {
83
- const files = await generate(client, { schemas: args.schemas });
94
+ const files = await generate(client, {
95
+ schemas: args.schemas,
96
+ tables: {
97
+ ...(args.include.length > 0 ? { include: args.include } : {}),
98
+ ...(args.exclude.length > 0 ? { exclude: args.exclude } : {})
99
+ }
100
+ });
84
101
  if (args.check) {
85
102
  const report = await checkFileTree(args.out, files);
86
103
  if (isClean(report)) {
@@ -220,6 +220,12 @@ export class TableClient {
220
220
  for (const [field, value] of Object.entries(data)) {
221
221
  if (value === undefined)
222
222
  continue;
223
+ // An expression is SQL the caller wrote: it is deparsed in place, never
224
+ // bound as a value, and never serialized as one either.
225
+ if (typeof value === 'function') {
226
+ encoded[this.column(field)] = value;
227
+ continue;
228
+ }
223
229
  if (value !== null && this.spec.jsonFields?.includes(field)) {
224
230
  encoded[this.column(field)] = JSON.stringify(value);
225
231
  continue;
@@ -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 { Filter, SqlValue } from '@constructive-io/query-builder';
13
+ import type { Expr, Filter, 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. */
@@ -135,8 +135,17 @@ export type Where<App> = {
135
135
  * Write data keyed by camelCase field names. Extra string keys are physical
136
136
  * column names — runtime-configured scope key columns are stamped the same
137
137
  * way any other value is.
138
+ *
139
+ * A value may also be a query-builder expression, so a write that reads the
140
+ * column it sets stays one statement:
141
+ *
142
+ * ```ts
143
+ * data: { lastError: message, errorCount: add(col('error_count'), 1) }
144
+ * ```
138
145
  */
139
- export type Data<App> = Partial<App> & { [column: string]: unknown };
146
+ export type Data<App> = { [K in keyof App]?: App[K] | Expr } & {
147
+ [column: string]: unknown;
148
+ };
140
149
 
141
150
  export type OrderDirection = 'ASC' | 'DESC';
142
151
 
@@ -387,10 +396,16 @@ export class TableClient<App> {
387
396
  }
388
397
  }
389
398
 
390
- private encodeData(data: Data<App>): Record<string, SqlValue> {
391
- const encoded: Record<string, SqlValue> = {};
399
+ private encodeData(data: Data<App>): Record<string, Operand> {
400
+ const encoded: Record<string, Operand> = {};
392
401
  for (const [field, value] of Object.entries(data)) {
393
402
  if (value === undefined) continue;
403
+ // An expression is SQL the caller wrote: it is deparsed in place, never
404
+ // bound as a value, and never serialized as one either.
405
+ if (typeof value === 'function') {
406
+ encoded[this.column(field)] = value as Expr;
407
+ continue;
408
+ }
394
409
  if (value !== null && this.spec.jsonFields?.includes(field)) {
395
410
  encoded[this.column(field)] = JSON.stringify(value);
396
411
  continue;
package/esm/generate.js CHANGED
@@ -28,9 +28,9 @@ export const emitFileTree = (ir) => {
28
28
  return files;
29
29
  };
30
30
  /** Introspect `schemas` through the given client and emit the file tree. */
31
- export const generate = async (client, { schemas }) => {
31
+ export const generate = async (client, { schemas, tables }) => {
32
32
  const introspection = await introspect(client, { schemas });
33
- const ir = buildIr(introspection, { schemas });
33
+ const ir = buildIr(introspection, { schemas, tables });
34
34
  return emitFileTree(ir);
35
35
  };
36
36
  /** Write an emitted file tree under `outDir`, creating directories as needed. */
package/esm/ir.js CHANGED
@@ -71,7 +71,26 @@ const resolveType = (type, typeById) => {
71
71
  const scalar = SCALAR_BY_TYPE_NAME[type.name];
72
72
  return { scalar: scalar ?? 'unknown', isArray: false };
73
73
  };
74
- export const buildIr = (introspection, { schemas }) => {
74
+ /** Matches a name against simple `*`/`?` glob patterns, as graphql/codegen does. */
75
+ const matchesPatterns = (name, patterns) => patterns.some(pattern => {
76
+ if (pattern.includes('*') || pattern.includes('?')) {
77
+ const expression = new RegExp(`^${pattern.replace(/\*/g, '.*').replace(/\?/g, '.')}$`);
78
+ return expression.test(name);
79
+ }
80
+ return name === pattern;
81
+ });
82
+ export const buildIr = (introspection, { schemas, tables: tableFilter }) => {
83
+ const include = tableFilter?.include ?? ['*'];
84
+ const exclude = [...(tableFilter?.exclude ?? []), ...(tableFilter?.systemExclude ?? [])];
85
+ const isEmitted = (cls) => {
86
+ // A child partition is storage for its parent partitioned table, which is
87
+ // the relation callers read and write.
88
+ if (cls.isPartition === true)
89
+ return false;
90
+ if (!matchesPatterns(cls.name, include))
91
+ return false;
92
+ return exclude.length === 0 || !matchesPatterns(cls.name, exclude);
93
+ };
75
94
  const typeById = new Map(introspection.type.map(type => [type.id, type]));
76
95
  const namespaceNameById = new Map(introspection.namespace.map(namespace => [namespace.id, namespace.name]));
77
96
  const attributesByClassId = new Map();
@@ -103,7 +122,10 @@ export const buildIr = (introspection, { schemas }) => {
103
122
  return enumType.name;
104
123
  };
105
124
  const tables = introspection.class
106
- .filter((cls) => cls.namespaceName === schemaName && cls.classKind !== undefined && cls.classKind in TABLE_KINDS)
125
+ .filter((cls) => cls.namespaceName === schemaName &&
126
+ cls.classKind !== undefined &&
127
+ cls.classKind in TABLE_KINDS &&
128
+ isEmitted(cls))
107
129
  .map((cls) => {
108
130
  const attributes = (attributesByClassId.get(cls.id) ?? [])
109
131
  .filter(attribute => attribute.num > 0)
package/generate.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { ClientBase } from 'pg';
2
- import { Ir } from './ir';
2
+ import { Ir, IrTableFilter } from './ir';
3
3
  /** Emit the full generated file tree (relative path -> content) from an IR. */
4
4
  export declare const emitFileTree: (ir: Ir) => Record<string, string>;
5
5
  export interface GenerateOptions {
6
6
  schemas: string[];
7
+ /** Which tables of those schemas to emit; child partitions are never emitted. */
8
+ tables?: IrTableFilter;
7
9
  }
8
10
  /** Introspect `schemas` through the given client and emit the file tree. */
9
- export declare const generate: (client: ClientBase, { schemas }: GenerateOptions) => Promise<Record<string, string>>;
11
+ export declare const generate: (client: ClientBase, { schemas, tables }: GenerateOptions) => Promise<Record<string, string>>;
10
12
  /** Write an emitted file tree under `outDir`, creating directories as needed. */
11
13
  export declare const writeFileTree: (outDir: string, files: Record<string, string>) => Promise<void>;
12
14
  export interface DriftReport {
package/generate.js CHANGED
@@ -35,9 +35,9 @@ const emitFileTree = (ir) => {
35
35
  };
36
36
  exports.emitFileTree = emitFileTree;
37
37
  /** Introspect `schemas` through the given client and emit the file tree. */
38
- const generate = async (client, { schemas }) => {
38
+ const generate = async (client, { schemas, tables }) => {
39
39
  const introspection = await (0, introspectron_1.introspect)(client, { schemas });
40
- const ir = (0, ir_1.buildIr)(introspection, { schemas });
40
+ const ir = (0, ir_1.buildIr)(introspection, { schemas, tables });
41
41
  return (0, exports.emitFileTree)(ir);
42
42
  };
43
43
  exports.generate = generate;
package/ir.d.ts CHANGED
@@ -40,8 +40,18 @@ export interface IrSchema {
40
40
  export interface Ir {
41
41
  schemas: IrSchema[];
42
42
  }
43
+ export interface IrTableFilter {
44
+ /** Table names to emit; glob patterns supported. Defaults to `['*']`. */
45
+ include?: string[];
46
+ /** Table names to skip; glob patterns supported. */
47
+ exclude?: string[];
48
+ /** Table names always skipped by a project convention; glob patterns supported. */
49
+ systemExclude?: string[];
50
+ }
43
51
  export interface BuildIrOptions {
44
52
  /** The schemas to include, in the order their modules should be emitted. */
45
53
  schemas: string[];
54
+ /** Which tables of those schemas to emit. */
55
+ tables?: IrTableFilter;
46
56
  }
47
- export declare const buildIr: (introspection: PgIntrospectionResultByKind, { schemas }: BuildIrOptions) => Ir;
57
+ export declare const buildIr: (introspection: PgIntrospectionResultByKind, { schemas, tables: tableFilter }: BuildIrOptions) => Ir;
package/ir.js CHANGED
@@ -74,7 +74,26 @@ const resolveType = (type, typeById) => {
74
74
  const scalar = SCALAR_BY_TYPE_NAME[type.name];
75
75
  return { scalar: scalar ?? 'unknown', isArray: false };
76
76
  };
77
- const buildIr = (introspection, { schemas }) => {
77
+ /** Matches a name against simple `*`/`?` glob patterns, as graphql/codegen does. */
78
+ const matchesPatterns = (name, patterns) => patterns.some(pattern => {
79
+ if (pattern.includes('*') || pattern.includes('?')) {
80
+ const expression = new RegExp(`^${pattern.replace(/\*/g, '.*').replace(/\?/g, '.')}$`);
81
+ return expression.test(name);
82
+ }
83
+ return name === pattern;
84
+ });
85
+ const buildIr = (introspection, { schemas, tables: tableFilter }) => {
86
+ const include = tableFilter?.include ?? ['*'];
87
+ const exclude = [...(tableFilter?.exclude ?? []), ...(tableFilter?.systemExclude ?? [])];
88
+ const isEmitted = (cls) => {
89
+ // A child partition is storage for its parent partitioned table, which is
90
+ // the relation callers read and write.
91
+ if (cls.isPartition === true)
92
+ return false;
93
+ if (!matchesPatterns(cls.name, include))
94
+ return false;
95
+ return exclude.length === 0 || !matchesPatterns(cls.name, exclude);
96
+ };
78
97
  const typeById = new Map(introspection.type.map(type => [type.id, type]));
79
98
  const namespaceNameById = new Map(introspection.namespace.map(namespace => [namespace.id, namespace.name]));
80
99
  const attributesByClassId = new Map();
@@ -106,7 +125,10 @@ const buildIr = (introspection, { schemas }) => {
106
125
  return enumType.name;
107
126
  };
108
127
  const tables = introspection.class
109
- .filter((cls) => cls.namespaceName === schemaName && cls.classKind !== undefined && cls.classKind in TABLE_KINDS)
128
+ .filter((cls) => cls.namespaceName === schemaName &&
129
+ cls.classKind !== undefined &&
130
+ cls.classKind in TABLE_KINDS &&
131
+ isEmitted(cls))
110
132
  .map((cls) => {
111
133
  const attributes = (attributesByClassId.get(cls.id) ?? [])
112
134
  .filter(attribute => attribute.num > 0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pg-codegen",
3
- "version": "5.14.1",
3
+ "version": "5.16.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",
@@ -48,7 +48,7 @@
48
48
  "@constructive-io/coerce": "^0.3.0",
49
49
  "@constructive-io/query-builder": "^3.10.5",
50
50
  "inflekt": "^0.8.1",
51
- "introspectron": "^5.12.0",
51
+ "introspectron": "^5.13.0",
52
52
  "pg": "^8.21.0",
53
53
  "pg-env": "^1.30.0"
54
54
  },
@@ -58,5 +58,5 @@
58
58
  "makage": "^0.3.0",
59
59
  "pgsql-test": "^5.11.0"
60
60
  },
61
- "gitHead": "13e2212f24fa050e8bcd9e805ec30a94918bf8fd"
61
+ "gitHead": "51a32e8527c226772c2219b721c3cb6af8e66979"
62
62
  }