pg-codegen 5.11.0 → 5.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,31 +12,29 @@
12
12
  <a href="https://www.npmjs.com/package/pg-codegen"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=postgres%2Fpg-codegen%2Fpackage.json"/></a>
13
13
  </p>
14
14
 
15
- Generate fully-typed TypeScript classes and interfaces from a live PostgreSQL schema via introspection.
15
+ Type-safe TypeScript from a live PostgreSQL schema: application and row types, runtime decoders, serializers, column metadata and enum unions — one tree-shakable module per table.
16
16
 
17
- > Converts your PostgreSQL tables into idiomatic TypeScript code — fast, predictable, and schema-aware.
17
+ > A database row arrives as `unknown`. `pg-codegen` is what turns it into a value TypeScript can trust, without a hand-written `as string` in sight.
18
18
 
19
- ---
20
-
21
- ## ✨ Features
22
-
23
- 🧠 **Intelligent Introspection**
24
- Pulls schema structure using native SQL introspection — no GraphQL required.
25
-
26
- 🧱 **Interface + Class Output**
27
- Generates matching `interface` + `class` pairs for each table using PascalCase naming.
19
+ ## ✨ What it generates
28
20
 
29
- 🧹 **Schema-Aware Output**
30
- Writes files into `schemas/<schema>.ts`, grouped and re-exported from an `index.ts`.
21
+ For every table, view, materialized view and partitioned table in the schemas you name, one module:
31
22
 
32
- 🔗 **Type Mapping for Postgres Primitives**
33
- Supports `UUID`, `Timestamp`, `Boolean`, `Text`, `Int`, and nullable detection.
23
+ | Export | What it is |
24
+ |---|---|
25
+ | `AgentRuns` | application shape, camelCase |
26
+ | `AgentRunsRow` | database row shape, snake_case |
27
+ | `AGENT_RUNS_TABLE` | `schema`, `name`, `qualifiedName`, `columns`, `primaryKey`, `columnByField` |
28
+ | `AGENT_RUNS_FIELDS` | one decoder per column, for projections |
29
+ | `decodeAgentRuns` | decode an untrusted camelCase envelope (a wire payload, a parsed body) |
30
+ | `decodeAgentRunsRow` | decode an untrusted database row |
31
+ | `agentRunsFromRow` | row → application shape |
32
+ | `decodeAgentRunsFromRow` | both, composed |
33
+ | `serializeAgentRuns` | `Partial<AgentRuns>` → `Partial<AgentRunsRow>` for INSERT/UPDATE |
34
34
 
35
- 🪴 **Auto Imports from \_common.ts**
36
- Deduplicates and imports shared scalar types intelligently.
35
+ Plus an `enums.ts` per schema: a literal union, a `readonly` value list and `as*`/`require*` checkers for every PostgreSQL enum a column references.
37
36
 
38
- 🧪 **Snapshot-Ready for Testing**
39
- Babel AST-based output is stable and perfect for inline snapshot tests.
37
+ 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.
40
38
 
41
39
  ## 🛠️ Install
42
40
 
@@ -46,57 +44,89 @@ npm install pg-codegen
46
44
 
47
45
  ## 🚀 Usage
48
46
 
49
- ```ts
50
- import { generateCodeTree } from 'pg-codegen';
51
- import getIntrospectionRows from 'pg-codegen/introspect';
52
-
53
- const rows = await getIntrospectionRows({
54
- client: pgClient,
55
- introspectionOptions: {
56
- pgLegacyFunctionsOnly: false,
57
- pgIgnoreRBAC: true
58
- },
59
- namespacesToIntrospect: ['my_schema'],
60
- includeExtensions: false
61
- });
62
-
63
- const output = generateCodeTree(rows, {
64
- includeUUID: true,
65
- includeTimestamps: true
66
- });
67
-
68
- // Example: write output['schemas/my_schema.ts'] to disk
47
+ ```bash
48
+ pg-codegen --schema app_public --out src/generated
49
+ pg-codegen --schema app_public,app_jobs --out src/generated
50
+ pg-codegen --schema app_public --out src/generated --check
69
51
  ```
70
52
 
71
- ## 📟 Example Output
53
+ `--check` re-introspects and compares against the committed output, exiting non-zero on drift — run it in CI so generated types cannot go stale against a migration.
72
54
 
73
- ```ts
74
- // schemas/_common.ts
75
- export type UUID = string;
76
- export type Timestamp = string;
55
+ Connection settings come from the standard PG environment (`PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`) via `pg-env`.
77
56
 
78
- // schemas/my_schema.ts
79
- import { UUID, Timestamp } from './_common';
57
+ Programmatically — for a schema whose physical name is per-tenant, say, where you want to rewrite it to a stable alias before emitting:
80
58
 
81
- export interface Users {
82
- id: UUID;
83
- email: string;
84
- created_at: Timestamp;
59
+ ```ts
60
+ import { Client } from 'pg';
61
+ import { introspect } from 'introspectron';
62
+ import { buildIr, emitFileTree, writeFileTree, checkFileTree } from 'pg-codegen';
63
+
64
+ const introspection = await introspect(client, { schemas: [physicalSchema] });
65
+ const ir = buildIr(introspection, { schemas: [physicalSchema] });
66
+ for (const schema of ir.schemas) {
67
+ schema.name = 'agent';
68
+ for (const table of schema.tables) table.schema = 'agent';
85
69
  }
70
+ await writeFileTree(outDir, emitFileTree(ir));
71
+ ```
86
72
 
87
- export class Users implements Users {
88
- id: UUID;
89
- email: string;
90
- created_at: Timestamp;
73
+ ## 📟 Example output
91
74
 
92
- constructor(data: Users) {
93
- this.id = data.id;
94
- this.email = data.email;
95
- this.created_at = data.created_at;
96
- }
75
+ ```ts
76
+ // generated/codegen_test/agent-runs.ts
77
+ export interface AgentRuns {
78
+ id: string;
79
+ threadId: string;
80
+ status: RunStatus;
81
+ tags: string[];
82
+ retrySeconds: number[] | null;
83
+ lastEventSeq: number;
84
+ finishedAt: string | null;
97
85
  }
86
+
87
+ export const decodeAgentRunsFromRow = (value: unknown, label = 'codegen_test.agent_runs'): AgentRuns =>
88
+ agentRunsFromRow(decodeAgentRunsRow(value, label));
98
89
  ```
99
90
 
91
+ Consume per table, so a bundle carries only the tables it touches:
92
+
93
+ ```ts
94
+ import { decodeAgentRunsFromRow } from '@my/db-types/codegen_test/agent-runs';
95
+
96
+ const { rows } = await db.query('SELECT * FROM agent_runs WHERE id = $1', [id]);
97
+ const run = decodeAgentRunsFromRow(rows[0]); // AgentRuns, or CoerceError naming the column
98
+ ```
99
+
100
+ ### Projections
101
+
102
+ A joined or partial SELECT is not a whole row, so a record decoder would reject it. Decode it column by column instead — `FIELDS` takes an overridable label so the error names the alias the query actually used:
103
+
104
+ ```ts
105
+ import { AGENT_RUNS_FIELDS } from '@my/db-types/codegen_test/agent-runs';
106
+ import { THREADS_FIELDS } from '@my/db-types/codegen_test/threads';
107
+
108
+ const { rows } = await db.query(`
109
+ SELECT r.id, r.status, t.title AS thread_title
110
+ FROM agent_runs r JOIN threads t ON t.id = r.thread_id
111
+ `);
112
+
113
+ const summaries = rows.map(row => ({
114
+ id: AGENT_RUNS_FIELDS.id(row.id),
115
+ status: AGENT_RUNS_FIELDS.status(row.status),
116
+ threadTitle: THREADS_FIELDS.title(row.thread_title, 'run_summary.thread_title')
117
+ }));
118
+ ```
119
+
120
+ ## 🧱 How it works
121
+
122
+ ```
123
+ PostgreSQL → introspectron → IR (ir.ts) → emitters (emit/*) → file tree
124
+ ```
125
+
126
+ `buildIr` normalizes an introspection result into the shape every emitter consumes: columns with a resolved scalar, nullability, defaults, primary keys, and the enums they reference. Domains are unwrapped to their base type, arrays carry their element scalar, and a type with no mapping degrades to `unknown` rather than to `any` — the generator never claims to know a shape it does not.
127
+
128
+ Emission is Babel AST rather than string templates, so output is stable enough to snapshot and to diff in `--check`.
129
+
100
130
  ---
101
131
 
102
132
  ## Education and Tutorials
package/emit/barrel.js CHANGED
@@ -4,7 +4,12 @@ exports.emitRootIndex = exports.emitSchemaIndex = exports.tableFileName = void 0
4
4
  /** Emits the per-schema and root index modules. */
5
5
  const inflekt_1 = require("inflekt");
6
6
  const babel_1 = require("./babel");
7
- const tableFileName = (tableName) => (0, inflekt_1.toKebabCase)(tableName);
7
+ /** File names the schema directory reserves for its own modules. */
8
+ const RESERVED_FILE_NAMES = new Set(['index', 'db', 'enums']);
9
+ const tableFileName = (tableName) => {
10
+ const name = (0, inflekt_1.toKebabCase)(tableName);
11
+ return RESERVED_FILE_NAMES.has(name) ? `${name}-table` : name;
12
+ };
8
13
  exports.tableFileName = tableFileName;
9
14
  const emitSchemaIndex = (schema) => {
10
15
  const statements = [];
@@ -14,6 +19,7 @@ const emitSchemaIndex = (schema) => {
14
19
  for (const table of schema.tables) {
15
20
  statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral(`./${(0, exports.tableFileName)(table.name)}`)));
16
21
  }
22
+ statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral('./db')));
17
23
  return (0, babel_1.generateCode)(statements);
18
24
  };
19
25
  exports.emitSchemaIndex = emitSchemaIndex;
@@ -0,0 +1,5 @@
1
+ import { IrSchema } from '../ir';
2
+ /** The shared runtime, copied verbatim with the template note replaced. */
3
+ export declare const emitClientRuntime: () => string;
4
+ /** The per-schema `db.ts`: a `create<Schema>Db` factory of bound TableClients. */
5
+ export declare const emitSchemaDbModule: (schema: IrSchema) => string;
package/emit/client.js ADDED
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.emitSchemaDbModule = exports.emitClientRuntime = void 0;
37
+ /**
38
+ * Emits the Prisma-like database client: the shared `client.ts` runtime
39
+ * (copied from a typechecked template) and one `db.ts` per schema binding a
40
+ * TableClient per table over the generated metadata and field decoders.
41
+ */
42
+ const fs = __importStar(require("fs"));
43
+ const inflekt_1 = require("inflekt");
44
+ const path = __importStar(require("path"));
45
+ const babel_1 = require("./babel");
46
+ const barrel_1 = require("./barrel");
47
+ const findTemplateFile = (templateName) => {
48
+ const templatePath = path.join(__dirname, 'templates', templateName);
49
+ if (fs.existsSync(templatePath))
50
+ return templatePath;
51
+ throw new Error(`Could not find template file: ${templateName}. Searched in: ${templatePath}`);
52
+ };
53
+ /** The shared runtime, copied verbatim with the template note replaced. */
54
+ const emitClientRuntime = () => {
55
+ const content = fs.readFileSync(findTemplateFile('client.ts'), 'utf8');
56
+ return content.replace(/ \* NOTE: This file is read at codegen time and written to output\.\n \* Any changes here will affect all generated clients\.\n \*\/\n/, ' * Generated by pg-codegen. DO NOT EDIT.\n */\n/* eslint-disable */\n');
57
+ };
58
+ exports.emitClientRuntime = emitClientRuntime;
59
+ const typeImport = (names, source) => {
60
+ const declaration = (0, babel_1.namedImport)(names, source);
61
+ declaration.importKind = 'type';
62
+ return declaration;
63
+ };
64
+ const modelKey = (table) => (0, inflekt_1.toCamelCase)(table.name);
65
+ /** The per-schema `db.ts`: a `create<Schema>Db` factory of bound TableClients. */
66
+ const emitSchemaDbModule = (schema) => {
67
+ const pascal = (0, inflekt_1.toPascalCase)(schema.name);
68
+ const dbTypeName = `${pascal}Db`;
69
+ const optionsName = `${pascal}DbOptions`;
70
+ const factoryName = `create${pascal}Db`;
71
+ const statements = [
72
+ (0, babel_1.namedImport)(['TableClient'], '../client'),
73
+ typeImport(['Queryable'], '../client')
74
+ ];
75
+ for (const table of schema.tables) {
76
+ const appType = (0, inflekt_1.toPascalCase)(table.name);
77
+ const constant = (0, inflekt_1.toConstantCase)(table.name);
78
+ const file = `./${(0, barrel_1.tableFileName)(table.name)}`;
79
+ statements.push(typeImport([appType], file));
80
+ statements.push((0, babel_1.namedImport)([`${constant}_FIELDS`, `${constant}_TABLE`], file));
81
+ }
82
+ const tableNameProps = schema.tables.map(table => {
83
+ const prop = babel_1.t.tsPropertySignature(babel_1.t.identifier(modelKey(table)), babel_1.t.tsTypeAnnotation(babel_1.t.tsStringKeyword()));
84
+ prop.optional = true;
85
+ return prop;
86
+ });
87
+ const schemaProp = babel_1.t.tsPropertySignature(babel_1.t.identifier('schema'), babel_1.t.tsTypeAnnotation(babel_1.t.tsStringKeyword()));
88
+ schemaProp.optional = true;
89
+ const tablesProp = babel_1.t.tsPropertySignature(babel_1.t.identifier('tables'), babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeLiteral(tableNameProps)));
90
+ tablesProp.optional = true;
91
+ statements.push((0, babel_1.withJsDoc)(babel_1.t.exportNamedDeclaration(babel_1.t.tsInterfaceDeclaration(babel_1.t.identifier(optionsName), null, null, babel_1.t.tsInterfaceBody([schemaProp, tablesProp]))), 'Runtime overrides for the physical schema and per-table names, for tables provisioned into per-tenant schemas.'));
92
+ const dbMembers = schema.tables.map(table => babel_1.t.tsPropertySignature(babel_1.t.identifier(modelKey(table)), babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('TableClient'), babel_1.t.tsTypeParameterInstantiation([babel_1.t.tsTypeReference(babel_1.t.identifier((0, inflekt_1.toPascalCase)(table.name)))])))));
93
+ const withParam = babel_1.t.identifier('db');
94
+ withParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Queryable')));
95
+ const withMember = babel_1.t.tsMethodSignature(babel_1.t.identifier('$with'), null, [withParam], babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(dbTypeName))));
96
+ babel_1.t.addComment(withMember, 'leading', "* Rebind every table client to another connection (e.g. a transaction's PoolClient). ", false);
97
+ dbMembers.push(withMember);
98
+ statements.push(babel_1.t.exportNamedDeclaration(babel_1.t.tsInterfaceDeclaration(babel_1.t.identifier(dbTypeName), null, null, babel_1.t.tsInterfaceBody(dbMembers))));
99
+ const clientProperties = schema.tables.map(table => {
100
+ const constant = (0, inflekt_1.toConstantCase)(table.name);
101
+ const spec = babel_1.t.objectExpression([
102
+ babel_1.t.objectProperty(babel_1.t.identifier('schema'), babel_1.t.logicalExpression('??', babel_1.t.optionalMemberExpression(babel_1.t.identifier('options'), babel_1.t.identifier('schema'), false, true), babel_1.t.memberExpression(babel_1.t.identifier(`${constant}_TABLE`), babel_1.t.identifier('schema')))),
103
+ babel_1.t.objectProperty(babel_1.t.identifier('table'), babel_1.t.logicalExpression('??', babel_1.t.optionalMemberExpression(babel_1.t.optionalMemberExpression(babel_1.t.identifier('options'), babel_1.t.identifier('tables'), false, true), babel_1.t.identifier(modelKey(table)), false, true), babel_1.t.memberExpression(babel_1.t.identifier(`${constant}_TABLE`), babel_1.t.identifier('name')))),
104
+ babel_1.t.objectProperty(babel_1.t.identifier('columnByField'), babel_1.t.memberExpression(babel_1.t.identifier(`${constant}_TABLE`), babel_1.t.identifier('columnByField'))),
105
+ babel_1.t.objectProperty(babel_1.t.identifier('fields'), babel_1.t.identifier(`${constant}_FIELDS`))
106
+ ]);
107
+ const jsonFields = table.columns.filter(column => column.scalar === 'json');
108
+ if (jsonFields.length > 0) {
109
+ spec.properties.push(babel_1.t.objectProperty(babel_1.t.identifier('jsonFields'), babel_1.t.arrayExpression(jsonFields.map(column => babel_1.t.stringLiteral(column.propertyName)))));
110
+ }
111
+ const client = babel_1.t.newExpression(babel_1.t.identifier('TableClient'), [spec, babel_1.t.identifier('db')]);
112
+ client.typeParameters = babel_1.t.tsTypeParameterInstantiation([
113
+ babel_1.t.tsTypeReference(babel_1.t.identifier((0, inflekt_1.toPascalCase)(table.name)))
114
+ ]);
115
+ return babel_1.t.objectProperty(babel_1.t.identifier(modelKey(table)), client);
116
+ });
117
+ const nextParam = babel_1.t.identifier('next');
118
+ nextParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Queryable')));
119
+ clientProperties.push(babel_1.t.objectProperty(babel_1.t.identifier('$with'), babel_1.t.arrowFunctionExpression([nextParam], babel_1.t.callExpression(babel_1.t.identifier(factoryName), [babel_1.t.identifier('next'), babel_1.t.identifier('options')]))));
120
+ const dbParam = babel_1.t.identifier('db');
121
+ dbParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Queryable')));
122
+ const optionsParam = babel_1.t.assignmentPattern((() => {
123
+ const id = babel_1.t.identifier('options');
124
+ id.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(optionsName)));
125
+ return id;
126
+ })(), babel_1.t.objectExpression([]));
127
+ const factory = babel_1.t.arrowFunctionExpression([dbParam, optionsParam], babel_1.t.objectExpression(clientProperties));
128
+ factory.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(dbTypeName)));
129
+ statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(factoryName, factory), `One Prisma-like client per table over any pg Pool/Client, decoding rows into the generated ${pascal} application types.`));
130
+ return (0, babel_1.generateCode)(statements);
131
+ };
132
+ exports.emitSchemaDbModule = emitSchemaDbModule;
package/emit/record.js CHANGED
@@ -62,8 +62,13 @@ const member = (object, key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
62
62
  ? babel_1.t.memberExpression(babel_1.t.identifier(object), babel_1.t.identifier(key))
63
63
  : babel_1.t.memberExpression(babel_1.t.identifier(object), babel_1.t.stringLiteral(key), true);
64
64
  const objectKey = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? babel_1.t.identifier(name) : babel_1.t.stringLiteral(name);
65
- const decodeExpression = (column, key, usage) => {
66
- const value = member('record', key);
65
+ /**
66
+ * The decode call for one column, against an arbitrary value expression and an
67
+ * arbitrary label expression, so a whole-record decoder (`record.foo`, label
68
+ * `` `${label}.foo` ``) and a single-field decoder (`value`, label `label`)
69
+ * share one definition of what a column's runtime check is.
70
+ */
71
+ const decodeExpression = (column, value, label, usage) => {
67
72
  if (column.scalar === 'unknown') {
68
73
  // No runtime shape to assert; the value passes through typed `unknown`.
69
74
  return value;
@@ -81,7 +86,7 @@ const decodeExpression = (column, key, usage) => {
81
86
  return babel_1.t.callExpression(babel_1.t.identifier('requireArrayOf'), [
82
87
  value,
83
88
  babel_1.t.identifier(elementName),
84
- (0, babel_1.labelTemplate)(key),
89
+ label,
85
90
  babel_1.t.stringLiteral(`an array of ${(0, enums_1.enumTypeName)(enumName)} values`)
86
91
  ]);
87
92
  }
@@ -89,7 +94,7 @@ const decodeExpression = (column, key, usage) => {
89
94
  usage.enumImports.add(fnName);
90
95
  return column.nullable
91
96
  ? babel_1.t.callExpression(babel_1.t.identifier(fnName), [value])
92
- : babel_1.t.callExpression(babel_1.t.identifier(fnName), [value, (0, babel_1.labelTemplate)(key)]);
97
+ : babel_1.t.callExpression(babel_1.t.identifier(fnName), [value, label]);
93
98
  }
94
99
  const coercer = COERCERS[column.scalar];
95
100
  if (column.isArray) {
@@ -102,7 +107,7 @@ const decodeExpression = (column, key, usage) => {
102
107
  return babel_1.t.callExpression(babel_1.t.identifier('requireArrayOf'), [
103
108
  value,
104
109
  babel_1.t.identifier(coercer.as),
105
- (0, babel_1.labelTemplate)(key),
110
+ label,
106
111
  babel_1.t.stringLiteral(coercer.expectedArray)
107
112
  ]);
108
113
  }
@@ -110,7 +115,34 @@ const decodeExpression = (column, key, usage) => {
110
115
  usage.coerceImports.add(fnName);
111
116
  return column.nullable
112
117
  ? babel_1.t.callExpression(babel_1.t.identifier(fnName), [value])
113
- : babel_1.t.callExpression(babel_1.t.identifier(fnName), [value, (0, babel_1.labelTemplate)(key)]);
118
+ : babel_1.t.callExpression(babel_1.t.identifier(fnName), [value, label]);
119
+ };
120
+ /**
121
+ * `<TABLE>_FIELDS`: one decoder per column, for rows that are NOT a whole
122
+ * table row — a joined projection, an aliased column, a partial SELECT — where
123
+ * a record decoder would reject the absent columns.
124
+ *
125
+ * A nullable column's decoder is lenient (`T | null`, no label); a NOT NULL
126
+ * column's is strict and throws `CoerceError` naming the column, with the label
127
+ * overridable so a projection can name its own alias.
128
+ */
129
+ const fieldsConstant = (table, name, usage) => {
130
+ const properties = table.columns.map(column => {
131
+ const valueParam = babel_1.t.identifier('value');
132
+ valueParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
133
+ const params = [valueParam];
134
+ let label = babel_1.t.stringLiteral(`${table.name}.${column.name}`);
135
+ if (!column.nullable && column.scalar !== 'unknown') {
136
+ params.push(babel_1.t.assignmentPattern(babel_1.t.identifier('label'), label));
137
+ label = babel_1.t.identifier('label');
138
+ }
139
+ const fn = babel_1.t.arrowFunctionExpression(params, decodeExpression(column, valueParam, label, usage));
140
+ fn.returnType = babel_1.t.tsTypeAnnotation(columnTsType(column));
141
+ const property = babel_1.t.objectProperty(objectKey(column.propertyName), fn);
142
+ babel_1.t.addComment(property, 'leading', `* \`${column.name}\` (${column.pgType}) `, false);
143
+ return property;
144
+ });
145
+ return (0, babel_1.exportConst)(name, (0, babel_1.asConst)(babel_1.t.objectExpression(properties)));
114
146
  };
115
147
  const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
116
148
  usage.coerceImports.add('requireRecord');
@@ -120,7 +152,10 @@ const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
120
152
  const recordDecl = babel_1.t.variableDeclaration('const', [
121
153
  babel_1.t.variableDeclarator(babel_1.t.identifier('record'), babel_1.t.callExpression(babel_1.t.identifier('requireRecord'), [babel_1.t.identifier('value'), babel_1.t.identifier('label')]))
122
154
  ]);
123
- const resultObject = babel_1.t.objectExpression(table.columns.map(column => babel_1.t.objectProperty(objectKey(keyFor(column)), decodeExpression(column, keyFor(column), usage))));
155
+ const resultObject = babel_1.t.objectExpression(table.columns.map(column => {
156
+ const key = keyFor(column);
157
+ return babel_1.t.objectProperty(objectKey(key), decodeExpression(column, member('record', key), (0, babel_1.labelTemplate)(key), usage));
158
+ }));
124
159
  const fn = babel_1.t.arrowFunctionExpression([valueParam, labelParam], babel_1.t.blockStatement([recordDecl, babel_1.t.returnStatement(resultObject)]));
125
160
  fn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(returnTypeName)));
126
161
  return (0, babel_1.exportConst)(fnName, fn);
@@ -130,6 +165,7 @@ const emitRecordModule = (table) => {
130
165
  const pascal = (0, inflekt_1.toPascalCase)(table.name);
131
166
  const rowTypeName = `${pascal}Row`;
132
167
  const metadataName = `${(0, inflekt_1.toConstantCase)(table.name)}_TABLE`;
168
+ const fieldsName = `${(0, inflekt_1.toConstantCase)(table.name)}_FIELDS`;
133
169
  const qualified = `${table.schema}.${table.name}`;
134
170
  const statements = [];
135
171
  // Application (camelCase) interface.
@@ -151,6 +187,9 @@ const emitRecordModule = (table) => {
151
187
  ])));
152
188
  (0, babel_1.withJsDoc)(metadata, `Column metadata for \`${qualified}\`.`);
153
189
  statements.push(metadata);
190
+ // Per-column decoders, for projections a record decoder cannot describe.
191
+ const example = table.columns[0];
192
+ statements.push((0, babel_1.withJsDoc)(fieldsConstant(table, fieldsName, usage), `Per-column decoders for \`${qualified}\`, for a value that is not a whole\n * row: a joined projection, an aliased column, a partial SELECT.\n *\n * A NOT NULL column's decoder throws \`CoerceError\` and takes an overridable\n * label, so a projection can name its own alias; a nullable column's is\n * lenient and answers \`null\`.${example ? `\n *\n * \`\`\`ts\n * ${example.propertyName}: ${fieldsName}.${example.propertyName}(row.${example.name}),\n * \`\`\`` : ''}`));
154
193
  // Decoders.
155
194
  statements.push((0, babel_1.withJsDoc)(decoderFunction(table, `decode${pascal}`, pascal, column => column.propertyName, usage), `Decode an untrusted camelCase value (a wire envelope, a parsed body) into \`${pascal}\`.\n *\n * Throws \`CoerceError\` naming the offending field when a required column is\n * missing or of the wrong shape.`));
156
195
  statements.push((0, babel_1.withJsDoc)(decoderFunction(table, `decode${pascal}Row`, rowTypeName, column => column.name, usage), `Decode an untrusted snake_case database row into \`${rowTypeName}\`.`));
@@ -0,0 +1,135 @@
1
+ /** Anything with pg's `query(text, values)` shape: Pool, PoolClient, Client. */
2
+ export interface Queryable {
3
+ query(text: string, values?: unknown[]): Promise<{
4
+ rows: unknown[];
5
+ rowCount?: number | null;
6
+ }>;
7
+ }
8
+ /** One generated decoder per field, as emitted in the `<TABLE>_FIELDS` constant. */
9
+ export type FieldDecoders<App> = {
10
+ [K in keyof App]: (value: unknown, label?: string) => App[K];
11
+ };
12
+ /** Table wiring supplied by the generated per-schema `db` factory. */
13
+ export interface TableSpec<App> {
14
+ schema: string;
15
+ table: string;
16
+ columnByField: Record<string, string>;
17
+ fields: FieldDecoders<App>;
18
+ /** camelCase fields backed by json/jsonb columns, serialized on writes. */
19
+ jsonFields?: readonly string[];
20
+ }
21
+ /** Select shape: `{ id: true, name: true }` — same as the GraphQL ORM. */
22
+ export type SelectShape<App> = {
23
+ [K in keyof App]?: boolean;
24
+ };
25
+ type TrueKeys<App, S> = {
26
+ [K in keyof S]-?: S[K] extends true ? K & keyof App : never;
27
+ }[keyof S];
28
+ /** Rows narrow to the selected fields; no `select` returns the full record. */
29
+ export type SelectResult<App, S extends SelectShape<App> | undefined> = S extends SelectShape<App> ? [TrueKeys<App, S>] extends [never] ? App : Pick<App, TrueKeys<App, S>> : App;
30
+ /** Per-field operators from the shared query-spec grammar. */
31
+ export interface FieldOps<V> {
32
+ equalTo?: V;
33
+ notEqualTo?: V;
34
+ distinctFrom?: V;
35
+ notDistinctFrom?: V;
36
+ lessThan?: V;
37
+ lessThanOrEqualTo?: V;
38
+ greaterThan?: V;
39
+ greaterThanOrEqualTo?: V;
40
+ in?: V[];
41
+ notIn?: V[];
42
+ like?: string;
43
+ notLike?: string;
44
+ likeInsensitive?: string;
45
+ notLikeInsensitive?: string;
46
+ includes?: string;
47
+ notIncludes?: string;
48
+ includesInsensitive?: string;
49
+ startsWith?: string;
50
+ endsWith?: string;
51
+ isNull?: boolean;
52
+ }
53
+ /**
54
+ * Where filter keyed by camelCase field names. A bare value means `equalTo`
55
+ * (`null` means `isNull`). Extra string keys are physical column names —
56
+ * runtime-configured scope key columns qualify rows the same way any other
57
+ * condition does.
58
+ */
59
+ export type Where<App> = {
60
+ [K in keyof App]?: App[K] | FieldOps<NonNullable<App[K]>>;
61
+ } & {
62
+ [column: string]: unknown;
63
+ } & {
64
+ and?: Where<App>[];
65
+ or?: Where<App>[];
66
+ not?: Where<App>;
67
+ };
68
+ /**
69
+ * Write data keyed by camelCase field names. Extra string keys are physical
70
+ * column names — runtime-configured scope key columns are stamped the same
71
+ * way any other value is.
72
+ */
73
+ export type Data<App> = Partial<App> & {
74
+ [column: string]: unknown;
75
+ };
76
+ export type OrderDirection = 'ASC' | 'DESC';
77
+ /** Order spec keyed by camelCase field names, e.g. `{ createdAt: 'DESC' }`. */
78
+ export type OrderBy<App> = {
79
+ [K in keyof App]?: OrderDirection;
80
+ };
81
+ export interface FindManyArgs<App, S extends SelectShape<App> | undefined> {
82
+ where?: Where<App>;
83
+ select?: S;
84
+ orderBy?: OrderBy<App> | OrderBy<App>[];
85
+ limit?: number;
86
+ offset?: number;
87
+ }
88
+ export interface FindFirstArgs<App, S extends SelectShape<App> | undefined> {
89
+ where?: Where<App>;
90
+ select?: S;
91
+ orderBy?: OrderBy<App> | OrderBy<App>[];
92
+ }
93
+ export interface CreateArgs<App, S extends SelectShape<App> | undefined> {
94
+ data: Data<App>;
95
+ select?: S;
96
+ }
97
+ export interface UpdateArgs<App, S extends SelectShape<App> | undefined> {
98
+ where: Where<App>;
99
+ data: Data<App>;
100
+ select?: S;
101
+ }
102
+ export interface DeleteArgs<App, S extends SelectShape<App> | undefined> {
103
+ where: Where<App>;
104
+ select?: S;
105
+ }
106
+ /** Thrown by `findFirstOrThrow` / `updateOrThrow` when no row matches. */
107
+ export declare class RowNotFoundError extends Error {
108
+ readonly table: string;
109
+ readonly operation: string;
110
+ constructor(table: string, operation: string);
111
+ }
112
+ export declare class TableClient<App> {
113
+ private readonly spec;
114
+ private readonly db;
115
+ constructor(spec: TableSpec<App>, db: Queryable);
116
+ findMany<S extends SelectShape<App> | undefined = undefined>(args?: FindManyArgs<App, S>): Promise<SelectResult<App, S>[]>;
117
+ findFirst<S extends SelectShape<App> | undefined = undefined>(args?: FindFirstArgs<App, S>): Promise<SelectResult<App, S> | null>;
118
+ findFirstOrThrow<S extends SelectShape<App> | undefined = undefined>(args?: FindFirstArgs<App, S>): Promise<SelectResult<App, S>>;
119
+ count(where?: Where<App>): Promise<number>;
120
+ create<S extends SelectShape<App> | undefined = undefined>(args: CreateArgs<App, S>): Promise<SelectResult<App, S>>;
121
+ update<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>[]>;
122
+ updateOrThrow<S extends SelectShape<App> | undefined = undefined>(args: UpdateArgs<App, S>): Promise<SelectResult<App, S>>;
123
+ delete<S extends SelectShape<App> | undefined = undefined>(args: DeleteArgs<App, S>): Promise<SelectResult<App, S>[]>;
124
+ /** Rebind to another connection (e.g. a transaction's PoolClient). */
125
+ $with(db: Queryable): TableClient<App>;
126
+ private baseQuery;
127
+ private column;
128
+ private selectedFields;
129
+ private decodeRow;
130
+ private filter;
131
+ private fieldFilter;
132
+ private applyOrderBy;
133
+ private encodeData;
134
+ }
135
+ export {};