pg-codegen 5.11.0 → 5.12.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 +89 -57
- package/emit/record.js +46 -7
- package/esm/emit/record.js +46 -7
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -12,31 +12,31 @@
|
|
|
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
|
-
|
|
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
|
-
>
|
|
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
19
|
---
|
|
20
20
|
|
|
21
|
-
## ✨
|
|
21
|
+
## ✨ What it generates
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
Pulls schema structure using native SQL introspection — no GraphQL required.
|
|
23
|
+
For every table, view, materialized view and partitioned table in the schemas you name, one module:
|
|
25
24
|
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
| Export | What it is |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `AgentRuns` | application shape, camelCase |
|
|
28
|
+
| `AgentRunsRow` | database row shape, snake_case |
|
|
29
|
+
| `AGENT_RUNS_TABLE` | `schema`, `name`, `qualifiedName`, `columns`, `primaryKey`, `columnByField` |
|
|
30
|
+
| `AGENT_RUNS_FIELDS` | one decoder per column, for projections |
|
|
31
|
+
| `decodeAgentRuns` | decode an untrusted camelCase envelope (a wire payload, a parsed body) |
|
|
32
|
+
| `decodeAgentRunsRow` | decode an untrusted database row |
|
|
33
|
+
| `agentRunsFromRow` | row → application shape |
|
|
34
|
+
| `decodeAgentRunsFromRow` | both, composed |
|
|
35
|
+
| `serializeAgentRuns` | `Partial<AgentRuns>` → `Partial<AgentRunsRow>` for INSERT/UPDATE |
|
|
28
36
|
|
|
29
|
-
|
|
30
|
-
Writes files into `schemas/<schema>.ts`, grouped and re-exported from an `index.ts`.
|
|
37
|
+
Plus an `enums.ts` per schema: a literal union, a `readonly` value list and `as*`/`require*` checkers for every PostgreSQL enum a column references.
|
|
31
38
|
|
|
32
|
-
|
|
33
|
-
Supports `UUID`, `Timestamp`, `Boolean`, `Text`, `Int`, and nullable detection.
|
|
34
|
-
|
|
35
|
-
🪴 **Auto Imports from \_common.ts**
|
|
36
|
-
Deduplicates and imports shared scalar types intelligently.
|
|
37
|
-
|
|
38
|
-
🧪 **Snapshot-Ready for Testing**
|
|
39
|
-
Babel AST-based output is stable and perfect for inline snapshot tests.
|
|
39
|
+
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
40
|
|
|
41
41
|
## 🛠️ Install
|
|
42
42
|
|
|
@@ -46,57 +46,89 @@ npm install pg-codegen
|
|
|
46
46
|
|
|
47
47
|
## 🚀 Usage
|
|
48
48
|
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
|
|
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
|
|
49
|
+
```bash
|
|
50
|
+
pg-codegen --schema app_public --out src/generated
|
|
51
|
+
pg-codegen --schema app_public,app_jobs --out src/generated
|
|
52
|
+
pg-codegen --schema app_public --out src/generated --check
|
|
69
53
|
```
|
|
70
54
|
|
|
71
|
-
|
|
55
|
+
`--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
56
|
|
|
73
|
-
|
|
74
|
-
// schemas/_common.ts
|
|
75
|
-
export type UUID = string;
|
|
76
|
-
export type Timestamp = string;
|
|
57
|
+
Connection settings come from the standard PG environment (`PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`) via `pg-env`.
|
|
77
58
|
|
|
78
|
-
|
|
79
|
-
import { UUID, Timestamp } from './_common';
|
|
59
|
+
Programmatically — for a schema whose physical name is per-tenant, say, where you want to rewrite it to a stable alias before emitting:
|
|
80
60
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
61
|
+
```ts
|
|
62
|
+
import { Client } from 'pg';
|
|
63
|
+
import { introspect } from 'introspectron';
|
|
64
|
+
import { buildIr, emitFileTree, writeFileTree, checkFileTree } from 'pg-codegen';
|
|
65
|
+
|
|
66
|
+
const introspection = await introspect(client, { schemas: [physicalSchema] });
|
|
67
|
+
const ir = buildIr(introspection, { schemas: [physicalSchema] });
|
|
68
|
+
for (const schema of ir.schemas) {
|
|
69
|
+
schema.name = 'agent';
|
|
70
|
+
for (const table of schema.tables) table.schema = 'agent';
|
|
85
71
|
}
|
|
72
|
+
await writeFileTree(outDir, emitFileTree(ir));
|
|
73
|
+
```
|
|
86
74
|
|
|
87
|
-
|
|
88
|
-
id: UUID;
|
|
89
|
-
email: string;
|
|
90
|
-
created_at: Timestamp;
|
|
75
|
+
## 📟 Example output
|
|
91
76
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
77
|
+
```ts
|
|
78
|
+
// generated/codegen_test/agent-runs.ts
|
|
79
|
+
export interface AgentRuns {
|
|
80
|
+
id: string;
|
|
81
|
+
threadId: string;
|
|
82
|
+
status: RunStatus;
|
|
83
|
+
tags: string[];
|
|
84
|
+
retrySeconds: number[] | null;
|
|
85
|
+
lastEventSeq: number;
|
|
86
|
+
finishedAt: string | null;
|
|
97
87
|
}
|
|
88
|
+
|
|
89
|
+
export const decodeAgentRunsFromRow = (value: unknown, label = 'codegen_test.agent_runs'): AgentRuns =>
|
|
90
|
+
agentRunsFromRow(decodeAgentRunsRow(value, label));
|
|
98
91
|
```
|
|
99
92
|
|
|
93
|
+
Consume per table, so a bundle carries only the tables it touches:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { decodeAgentRunsFromRow } from '@my/db-types/codegen_test/agent-runs';
|
|
97
|
+
|
|
98
|
+
const { rows } = await db.query('SELECT * FROM agent_runs WHERE id = $1', [id]);
|
|
99
|
+
const run = decodeAgentRunsFromRow(rows[0]); // AgentRuns, or CoerceError naming the column
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Projections
|
|
103
|
+
|
|
104
|
+
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:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { AGENT_RUNS_FIELDS } from '@my/db-types/codegen_test/agent-runs';
|
|
108
|
+
import { THREADS_FIELDS } from '@my/db-types/codegen_test/threads';
|
|
109
|
+
|
|
110
|
+
const { rows } = await db.query(`
|
|
111
|
+
SELECT r.id, r.status, t.title AS thread_title
|
|
112
|
+
FROM agent_runs r JOIN threads t ON t.id = r.thread_id
|
|
113
|
+
`);
|
|
114
|
+
|
|
115
|
+
const summaries = rows.map(row => ({
|
|
116
|
+
id: AGENT_RUNS_FIELDS.id(row.id),
|
|
117
|
+
status: AGENT_RUNS_FIELDS.status(row.status),
|
|
118
|
+
threadTitle: THREADS_FIELDS.title(row.thread_title, 'run_summary.thread_title')
|
|
119
|
+
}));
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## 🧱 How it works
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
PostgreSQL → introspectron → IR (ir.ts) → emitters (emit/*) → file tree
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`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.
|
|
129
|
+
|
|
130
|
+
Emission is Babel AST rather than string templates, so output is stable enough to snapshot and to diff in `--check`.
|
|
131
|
+
|
|
100
132
|
---
|
|
101
133
|
|
|
102
134
|
## Education and Tutorials
|
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
|
-
|
|
66
|
-
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
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,
|
|
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 =>
|
|
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}\`.`));
|
package/esm/emit/record.js
CHANGED
|
@@ -59,8 +59,13 @@ const member = (object, key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
|
|
|
59
59
|
? t.memberExpression(t.identifier(object), t.identifier(key))
|
|
60
60
|
: t.memberExpression(t.identifier(object), t.stringLiteral(key), true);
|
|
61
61
|
const objectKey = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? t.identifier(name) : t.stringLiteral(name);
|
|
62
|
-
|
|
63
|
-
|
|
62
|
+
/**
|
|
63
|
+
* The decode call for one column, against an arbitrary value expression and an
|
|
64
|
+
* arbitrary label expression, so a whole-record decoder (`record.foo`, label
|
|
65
|
+
* `` `${label}.foo` ``) and a single-field decoder (`value`, label `label`)
|
|
66
|
+
* share one definition of what a column's runtime check is.
|
|
67
|
+
*/
|
|
68
|
+
const decodeExpression = (column, value, label, usage) => {
|
|
64
69
|
if (column.scalar === 'unknown') {
|
|
65
70
|
// No runtime shape to assert; the value passes through typed `unknown`.
|
|
66
71
|
return value;
|
|
@@ -78,7 +83,7 @@ const decodeExpression = (column, key, usage) => {
|
|
|
78
83
|
return t.callExpression(t.identifier('requireArrayOf'), [
|
|
79
84
|
value,
|
|
80
85
|
t.identifier(elementName),
|
|
81
|
-
|
|
86
|
+
label,
|
|
82
87
|
t.stringLiteral(`an array of ${enumTypeName(enumName)} values`)
|
|
83
88
|
]);
|
|
84
89
|
}
|
|
@@ -86,7 +91,7 @@ const decodeExpression = (column, key, usage) => {
|
|
|
86
91
|
usage.enumImports.add(fnName);
|
|
87
92
|
return column.nullable
|
|
88
93
|
? t.callExpression(t.identifier(fnName), [value])
|
|
89
|
-
: t.callExpression(t.identifier(fnName), [value,
|
|
94
|
+
: t.callExpression(t.identifier(fnName), [value, label]);
|
|
90
95
|
}
|
|
91
96
|
const coercer = COERCERS[column.scalar];
|
|
92
97
|
if (column.isArray) {
|
|
@@ -99,7 +104,7 @@ const decodeExpression = (column, key, usage) => {
|
|
|
99
104
|
return t.callExpression(t.identifier('requireArrayOf'), [
|
|
100
105
|
value,
|
|
101
106
|
t.identifier(coercer.as),
|
|
102
|
-
|
|
107
|
+
label,
|
|
103
108
|
t.stringLiteral(coercer.expectedArray)
|
|
104
109
|
]);
|
|
105
110
|
}
|
|
@@ -107,7 +112,34 @@ const decodeExpression = (column, key, usage) => {
|
|
|
107
112
|
usage.coerceImports.add(fnName);
|
|
108
113
|
return column.nullable
|
|
109
114
|
? t.callExpression(t.identifier(fnName), [value])
|
|
110
|
-
: t.callExpression(t.identifier(fnName), [value,
|
|
115
|
+
: t.callExpression(t.identifier(fnName), [value, label]);
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* `<TABLE>_FIELDS`: one decoder per column, for rows that are NOT a whole
|
|
119
|
+
* table row — a joined projection, an aliased column, a partial SELECT — where
|
|
120
|
+
* a record decoder would reject the absent columns.
|
|
121
|
+
*
|
|
122
|
+
* A nullable column's decoder is lenient (`T | null`, no label); a NOT NULL
|
|
123
|
+
* column's is strict and throws `CoerceError` naming the column, with the label
|
|
124
|
+
* overridable so a projection can name its own alias.
|
|
125
|
+
*/
|
|
126
|
+
const fieldsConstant = (table, name, usage) => {
|
|
127
|
+
const properties = table.columns.map(column => {
|
|
128
|
+
const valueParam = t.identifier('value');
|
|
129
|
+
valueParam.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
|
|
130
|
+
const params = [valueParam];
|
|
131
|
+
let label = t.stringLiteral(`${table.name}.${column.name}`);
|
|
132
|
+
if (!column.nullable && column.scalar !== 'unknown') {
|
|
133
|
+
params.push(t.assignmentPattern(t.identifier('label'), label));
|
|
134
|
+
label = t.identifier('label');
|
|
135
|
+
}
|
|
136
|
+
const fn = t.arrowFunctionExpression(params, decodeExpression(column, valueParam, label, usage));
|
|
137
|
+
fn.returnType = t.tsTypeAnnotation(columnTsType(column));
|
|
138
|
+
const property = t.objectProperty(objectKey(column.propertyName), fn);
|
|
139
|
+
t.addComment(property, 'leading', `* \`${column.name}\` (${column.pgType}) `, false);
|
|
140
|
+
return property;
|
|
141
|
+
});
|
|
142
|
+
return exportConst(name, asConst(t.objectExpression(properties)));
|
|
111
143
|
};
|
|
112
144
|
const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
|
|
113
145
|
usage.coerceImports.add('requireRecord');
|
|
@@ -117,7 +149,10 @@ const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
|
|
|
117
149
|
const recordDecl = t.variableDeclaration('const', [
|
|
118
150
|
t.variableDeclarator(t.identifier('record'), t.callExpression(t.identifier('requireRecord'), [t.identifier('value'), t.identifier('label')]))
|
|
119
151
|
]);
|
|
120
|
-
const resultObject = t.objectExpression(table.columns.map(column =>
|
|
152
|
+
const resultObject = t.objectExpression(table.columns.map(column => {
|
|
153
|
+
const key = keyFor(column);
|
|
154
|
+
return t.objectProperty(objectKey(key), decodeExpression(column, member('record', key), labelTemplate(key), usage));
|
|
155
|
+
}));
|
|
121
156
|
const fn = t.arrowFunctionExpression([valueParam, labelParam], t.blockStatement([recordDecl, t.returnStatement(resultObject)]));
|
|
122
157
|
fn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(returnTypeName)));
|
|
123
158
|
return exportConst(fnName, fn);
|
|
@@ -127,6 +162,7 @@ export const emitRecordModule = (table) => {
|
|
|
127
162
|
const pascal = toPascalCase(table.name);
|
|
128
163
|
const rowTypeName = `${pascal}Row`;
|
|
129
164
|
const metadataName = `${toConstantCase(table.name)}_TABLE`;
|
|
165
|
+
const fieldsName = `${toConstantCase(table.name)}_FIELDS`;
|
|
130
166
|
const qualified = `${table.schema}.${table.name}`;
|
|
131
167
|
const statements = [];
|
|
132
168
|
// Application (camelCase) interface.
|
|
@@ -148,6 +184,9 @@ export const emitRecordModule = (table) => {
|
|
|
148
184
|
])));
|
|
149
185
|
withJsDoc(metadata, `Column metadata for \`${qualified}\`.`);
|
|
150
186
|
statements.push(metadata);
|
|
187
|
+
// Per-column decoders, for projections a record decoder cannot describe.
|
|
188
|
+
const example = table.columns[0];
|
|
189
|
+
statements.push(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 * \`\`\`` : ''}`));
|
|
151
190
|
// Decoders.
|
|
152
191
|
statements.push(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.`));
|
|
153
192
|
statements.push(withJsDoc(decoderFunction(table, `decode${pascal}Row`, rowTypeName, column => column.name, usage), `Decode an untrusted snake_case database row into \`${rowTypeName}\`.`));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pg-codegen",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.12.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",
|
|
@@ -56,5 +56,5 @@
|
|
|
56
56
|
"makage": "^0.3.0",
|
|
57
57
|
"pgsql-test": "^5.11.0"
|
|
58
58
|
},
|
|
59
|
-
"gitHead": "
|
|
59
|
+
"gitHead": "44a9cf96358c65dccab99871d61682a1ad6b32db"
|
|
60
60
|
}
|