pg-codegen 5.10.11 → 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/cli.d.ts +9 -0
- package/cli.js +115 -0
- package/emit/babel.d.ts +11 -0
- package/emit/babel.js +81 -0
- package/emit/barrel.d.ts +4 -0
- package/emit/barrel.js +24 -0
- package/emit/enums.d.ts +6 -0
- package/emit/enums.js +45 -0
- package/emit/record.d.ts +6 -0
- package/emit/record.js +238 -0
- package/esm/cli.js +110 -0
- package/esm/emit/babel.js +36 -0
- package/esm/emit/barrel.js +18 -0
- package/esm/emit/enums.js +37 -0
- package/esm/emit/record.js +234 -0
- package/esm/generate.js +63 -0
- package/esm/index.js +5 -69
- package/esm/ir.js +152 -0
- package/generate.d.ts +20 -0
- package/generate.js +74 -0
- package/index.d.ts +5 -1
- package/index.js +17 -72
- package/ir.d.ts +47 -0
- package/ir.js +156 -0
- package/package.json +12 -11
- package/codegen/codegen.d.ts +0 -7
- package/codegen/codegen.js +0 -162
- package/codegen/namespaces.d.ts +0 -7
- package/codegen/namespaces.js +0 -110
- package/esm/codegen/codegen.js +0 -122
- package/esm/codegen/namespaces.js +0 -70
- package/esm/introspect.js +0 -26
- package/esm/query.js +0 -420
- package/esm/types.js +0 -1
- package/introspect.d.ts +0 -11
- package/introspect.js +0 -30
- package/query.d.ts +0 -5
- package/query.js +0 -424
- package/types.d.ts +0 -128
- package/types.js +0 -2
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits one module per table: the camelCase application interface, the
|
|
3
|
+
* snake_case row interface, coerce-backed decoders for both, row/application
|
|
4
|
+
* converters, a serializer for writes, and typed table metadata.
|
|
5
|
+
*/
|
|
6
|
+
import { toCamelCase, toConstantCase, toPascalCase } from 'inflekt';
|
|
7
|
+
import { asConst, exportConst, generateCode, labelTemplate, namedImport, t, withJsDoc } from './babel';
|
|
8
|
+
import { enumAsName, enumRequireName, enumTypeName } from './enums';
|
|
9
|
+
const COERCERS = {
|
|
10
|
+
boolean: { require: 'requireBoolean', as: 'asBoolean', expectedArray: 'an array of booleans' },
|
|
11
|
+
integer: { require: 'requireInteger', as: 'asInteger', expectedArray: 'an array of integers' },
|
|
12
|
+
bigint: { require: 'requireNumericInteger', as: 'asNumericInteger', expectedArray: 'an array of integers' },
|
|
13
|
+
number: { require: 'requireNumeric', as: 'asNumeric', expectedArray: 'an array of numbers' },
|
|
14
|
+
string: { require: 'requireString', as: 'asString', expectedArray: 'an array of non-empty strings' },
|
|
15
|
+
uuid: { require: 'requireUuid', as: 'asUuid', expectedArray: 'an array of UUIDs' },
|
|
16
|
+
timestamp: { require: 'requireIsoString', as: 'asIsoString', expectedArray: 'an array of timestamps' },
|
|
17
|
+
json: { require: 'requireJson', as: 'asJson', expectedArray: 'an array of JSON documents' }
|
|
18
|
+
};
|
|
19
|
+
const scalarTsType = (column) => {
|
|
20
|
+
switch (column.scalar) {
|
|
21
|
+
case 'boolean':
|
|
22
|
+
return t.tsBooleanKeyword();
|
|
23
|
+
case 'integer':
|
|
24
|
+
case 'bigint':
|
|
25
|
+
case 'number':
|
|
26
|
+
return t.tsNumberKeyword();
|
|
27
|
+
case 'string':
|
|
28
|
+
case 'uuid':
|
|
29
|
+
case 'timestamp':
|
|
30
|
+
return t.tsStringKeyword();
|
|
31
|
+
case 'json':
|
|
32
|
+
return t.tsUnionType([
|
|
33
|
+
t.tsTypeReference(t.identifier('Record'), t.tsTypeParameterInstantiation([t.tsStringKeyword(), t.tsUnknownKeyword()])),
|
|
34
|
+
t.tsArrayType(t.tsUnknownKeyword())
|
|
35
|
+
]);
|
|
36
|
+
case 'enum':
|
|
37
|
+
return t.tsTypeReference(t.identifier(enumTypeName(column.enumName)));
|
|
38
|
+
default:
|
|
39
|
+
return t.tsUnknownKeyword();
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const columnTsType = (column) => {
|
|
43
|
+
let type = scalarTsType(column);
|
|
44
|
+
if (column.isArray)
|
|
45
|
+
type = t.tsArrayType(type);
|
|
46
|
+
if (column.nullable && column.scalar !== 'unknown') {
|
|
47
|
+
type = t.tsUnionType([type, t.tsNullKeyword()]);
|
|
48
|
+
}
|
|
49
|
+
return type;
|
|
50
|
+
};
|
|
51
|
+
const property = (name, type, comment) => {
|
|
52
|
+
const key = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? t.identifier(name) : t.stringLiteral(name);
|
|
53
|
+
const prop = t.tsPropertySignature(key, t.tsTypeAnnotation(type));
|
|
54
|
+
if (comment)
|
|
55
|
+
t.addComment(prop, 'leading', `* ${comment} `, false);
|
|
56
|
+
return prop;
|
|
57
|
+
};
|
|
58
|
+
const member = (object, key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
|
|
59
|
+
? t.memberExpression(t.identifier(object), t.identifier(key))
|
|
60
|
+
: t.memberExpression(t.identifier(object), t.stringLiteral(key), true);
|
|
61
|
+
const objectKey = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? t.identifier(name) : t.stringLiteral(name);
|
|
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) => {
|
|
69
|
+
if (column.scalar === 'unknown') {
|
|
70
|
+
// No runtime shape to assert; the value passes through typed `unknown`.
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
if (column.scalar === 'enum') {
|
|
74
|
+
const enumName = column.enumName;
|
|
75
|
+
if (column.isArray) {
|
|
76
|
+
const elementName = enumAsName(enumName);
|
|
77
|
+
usage.enumImports.add(elementName);
|
|
78
|
+
if (column.nullable) {
|
|
79
|
+
usage.coerceImports.add('asArrayOf');
|
|
80
|
+
return t.callExpression(t.identifier('asArrayOf'), [value, t.identifier(elementName)]);
|
|
81
|
+
}
|
|
82
|
+
usage.coerceImports.add('requireArrayOf');
|
|
83
|
+
return t.callExpression(t.identifier('requireArrayOf'), [
|
|
84
|
+
value,
|
|
85
|
+
t.identifier(elementName),
|
|
86
|
+
label,
|
|
87
|
+
t.stringLiteral(`an array of ${enumTypeName(enumName)} values`)
|
|
88
|
+
]);
|
|
89
|
+
}
|
|
90
|
+
const fnName = column.nullable ? enumAsName(enumName) : enumRequireName(enumName);
|
|
91
|
+
usage.enumImports.add(fnName);
|
|
92
|
+
return column.nullable
|
|
93
|
+
? t.callExpression(t.identifier(fnName), [value])
|
|
94
|
+
: t.callExpression(t.identifier(fnName), [value, label]);
|
|
95
|
+
}
|
|
96
|
+
const coercer = COERCERS[column.scalar];
|
|
97
|
+
if (column.isArray) {
|
|
98
|
+
usage.coerceImports.add(coercer.as);
|
|
99
|
+
if (column.nullable) {
|
|
100
|
+
usage.coerceImports.add('asArrayOf');
|
|
101
|
+
return t.callExpression(t.identifier('asArrayOf'), [value, t.identifier(coercer.as)]);
|
|
102
|
+
}
|
|
103
|
+
usage.coerceImports.add('requireArrayOf');
|
|
104
|
+
return t.callExpression(t.identifier('requireArrayOf'), [
|
|
105
|
+
value,
|
|
106
|
+
t.identifier(coercer.as),
|
|
107
|
+
label,
|
|
108
|
+
t.stringLiteral(coercer.expectedArray)
|
|
109
|
+
]);
|
|
110
|
+
}
|
|
111
|
+
const fnName = column.nullable ? coercer.as : coercer.require;
|
|
112
|
+
usage.coerceImports.add(fnName);
|
|
113
|
+
return column.nullable
|
|
114
|
+
? 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)));
|
|
143
|
+
};
|
|
144
|
+
const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
|
|
145
|
+
usage.coerceImports.add('requireRecord');
|
|
146
|
+
const valueParam = t.identifier('value');
|
|
147
|
+
valueParam.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
|
|
148
|
+
const labelParam = t.assignmentPattern(t.identifier('label'), t.stringLiteral(`${table.schema}.${table.name}`));
|
|
149
|
+
const recordDecl = t.variableDeclaration('const', [
|
|
150
|
+
t.variableDeclarator(t.identifier('record'), t.callExpression(t.identifier('requireRecord'), [t.identifier('value'), t.identifier('label')]))
|
|
151
|
+
]);
|
|
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
|
+
}));
|
|
156
|
+
const fn = t.arrowFunctionExpression([valueParam, labelParam], t.blockStatement([recordDecl, t.returnStatement(resultObject)]));
|
|
157
|
+
fn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(returnTypeName)));
|
|
158
|
+
return exportConst(fnName, fn);
|
|
159
|
+
};
|
|
160
|
+
export const emitRecordModule = (table) => {
|
|
161
|
+
const usage = { coerceImports: new Set(), enumImports: new Set() };
|
|
162
|
+
const pascal = toPascalCase(table.name);
|
|
163
|
+
const rowTypeName = `${pascal}Row`;
|
|
164
|
+
const metadataName = `${toConstantCase(table.name)}_TABLE`;
|
|
165
|
+
const fieldsName = `${toConstantCase(table.name)}_FIELDS`;
|
|
166
|
+
const qualified = `${table.schema}.${table.name}`;
|
|
167
|
+
const statements = [];
|
|
168
|
+
// Application (camelCase) interface.
|
|
169
|
+
const appInterface = t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(pascal), null, null, t.tsInterfaceBody(table.columns.map(column => property(column.propertyName, columnTsType(column), column.comment)))));
|
|
170
|
+
withJsDoc(appInterface, `\`${qualified}\` — application (camelCase) shape.${table.comment ? `\n *\n * ${table.comment}` : ''}`);
|
|
171
|
+
statements.push(appInterface);
|
|
172
|
+
// Database row (snake_case) interface.
|
|
173
|
+
const rowInterface = t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(rowTypeName), null, null, t.tsInterfaceBody(table.columns.map(column => property(column.name, columnTsType(column), column.comment)))));
|
|
174
|
+
withJsDoc(rowInterface, `\`${qualified}\` — database row (snake_case) shape.`);
|
|
175
|
+
statements.push(rowInterface);
|
|
176
|
+
// Table metadata.
|
|
177
|
+
const metadata = exportConst(metadataName, asConst(t.objectExpression([
|
|
178
|
+
t.objectProperty(t.identifier('schema'), t.stringLiteral(table.schema)),
|
|
179
|
+
t.objectProperty(t.identifier('name'), t.stringLiteral(table.name)),
|
|
180
|
+
t.objectProperty(t.identifier('qualifiedName'), t.stringLiteral(qualified)),
|
|
181
|
+
t.objectProperty(t.identifier('columns'), t.arrayExpression(table.columns.map(column => t.stringLiteral(column.name)))),
|
|
182
|
+
t.objectProperty(t.identifier('primaryKey'), t.arrayExpression(table.primaryKey.map(name => t.stringLiteral(name)))),
|
|
183
|
+
t.objectProperty(t.identifier('columnByField'), t.objectExpression(table.columns.map(column => t.objectProperty(objectKey(column.propertyName), t.stringLiteral(column.name)))))
|
|
184
|
+
])));
|
|
185
|
+
withJsDoc(metadata, `Column metadata for \`${qualified}\`.`);
|
|
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 * \`\`\`` : ''}`));
|
|
190
|
+
// Decoders.
|
|
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.`));
|
|
192
|
+
statements.push(withJsDoc(decoderFunction(table, `decode${pascal}Row`, rowTypeName, column => column.name, usage), `Decode an untrusted snake_case database row into \`${rowTypeName}\`.`));
|
|
193
|
+
// Row -> application converter.
|
|
194
|
+
const rowParam = t.identifier('row');
|
|
195
|
+
rowParam.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(rowTypeName)));
|
|
196
|
+
const fromRowFn = t.arrowFunctionExpression([rowParam], t.objectExpression(table.columns.map(column => t.objectProperty(objectKey(column.propertyName), member('row', column.name)))));
|
|
197
|
+
fromRowFn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(pascal)));
|
|
198
|
+
const fromRowName = `${toCamelCase(table.name)}FromRow`;
|
|
199
|
+
statements.push(withJsDoc(exportConst(fromRowName, fromRowFn), `Convert a decoded \`${rowTypeName}\` into the camelCase application shape.`));
|
|
200
|
+
// unknown row -> application decoder.
|
|
201
|
+
const decodeFromRowValue = t.identifier('value');
|
|
202
|
+
decodeFromRowValue.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
|
|
203
|
+
const decodeFromRowLabel = t.assignmentPattern(t.identifier('label'), t.stringLiteral(qualified));
|
|
204
|
+
const decodeFromRowFn = t.arrowFunctionExpression([decodeFromRowValue, decodeFromRowLabel], t.callExpression(t.identifier(fromRowName), [
|
|
205
|
+
t.callExpression(t.identifier(`decode${pascal}Row`), [t.identifier('value'), t.identifier('label')])
|
|
206
|
+
]));
|
|
207
|
+
decodeFromRowFn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(pascal)));
|
|
208
|
+
statements.push(withJsDoc(exportConst(`decode${pascal}FromRow`, decodeFromRowFn), `Decode an untrusted snake_case database row straight to \`${pascal}\`.`));
|
|
209
|
+
// Serializer: Partial application shape -> Partial row shape.
|
|
210
|
+
const patchParam = t.identifier('patch');
|
|
211
|
+
patchParam.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Partial'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(pascal))])));
|
|
212
|
+
const partialRowType = t.tsTypeReference(t.identifier('Partial'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(rowTypeName))]));
|
|
213
|
+
const rowDecl = t.variableDeclaration('const', [
|
|
214
|
+
t.variableDeclarator(Object.assign(t.identifier('row'), {
|
|
215
|
+
typeAnnotation: t.tsTypeAnnotation(partialRowType)
|
|
216
|
+
}), t.objectExpression([]))
|
|
217
|
+
]);
|
|
218
|
+
const assignments = table.columns.map(column => t.ifStatement(t.binaryExpression('!==', member('patch', column.propertyName), t.identifier('undefined')), t.expressionStatement(t.assignmentExpression('=', member('row', column.name), member('patch', column.propertyName)))));
|
|
219
|
+
const serializeFn = t.arrowFunctionExpression([patchParam], t.blockStatement([rowDecl, ...assignments, t.returnStatement(t.identifier('row'))]));
|
|
220
|
+
serializeFn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Partial'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(rowTypeName))])));
|
|
221
|
+
statements.push(withJsDoc(exportConst(`serialize${pascal}`, serializeFn), `Map a partial \`${pascal}\` onto snake_case column values for a parameterized\n * INSERT or UPDATE. Absent fields stay absent; \`null\` writes NULL.`));
|
|
222
|
+
// Imports, now that usage is known.
|
|
223
|
+
const imports = [];
|
|
224
|
+
if (usage.coerceImports.size > 0) {
|
|
225
|
+
imports.push(namedImport([...usage.coerceImports].sort(), '@constructive-io/coerce'));
|
|
226
|
+
}
|
|
227
|
+
if (usage.enumImports.size > 0) {
|
|
228
|
+
const typeImports = new Set(table.columns
|
|
229
|
+
.filter(column => column.scalar === 'enum')
|
|
230
|
+
.map(column => enumTypeName(column.enumName)));
|
|
231
|
+
imports.push(namedImport([...usage.enumImports, ...typeImports].sort(), './enums'));
|
|
232
|
+
}
|
|
233
|
+
return generateCode([...imports, ...statements]);
|
|
234
|
+
};
|
package/esm/generate.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The generation pipeline: introspect -> IR -> emitted file tree, plus the
|
|
3
|
+
* filesystem write and `--check` drift comparison.
|
|
4
|
+
*/
|
|
5
|
+
import { promises as fs } from 'fs';
|
|
6
|
+
import { introspect } from 'introspectron';
|
|
7
|
+
import path from 'path';
|
|
8
|
+
import { emitRootIndex, emitSchemaIndex, tableFileName } from './emit/barrel';
|
|
9
|
+
import { emitEnumsModule } from './emit/enums';
|
|
10
|
+
import { emitRecordModule } from './emit/record';
|
|
11
|
+
import { buildIr } from './ir';
|
|
12
|
+
/** Emit the full generated file tree (relative path -> content) from an IR. */
|
|
13
|
+
export const emitFileTree = (ir) => {
|
|
14
|
+
const files = {};
|
|
15
|
+
for (const schema of ir.schemas) {
|
|
16
|
+
if (schema.enums.length > 0) {
|
|
17
|
+
files[`${schema.name}/enums.ts`] = emitEnumsModule(schema.enums);
|
|
18
|
+
}
|
|
19
|
+
for (const table of schema.tables) {
|
|
20
|
+
files[`${schema.name}/${tableFileName(table.name)}.ts`] = emitRecordModule(table);
|
|
21
|
+
}
|
|
22
|
+
files[`${schema.name}/index.ts`] = emitSchemaIndex(schema);
|
|
23
|
+
}
|
|
24
|
+
files['index.ts'] = emitRootIndex(ir.schemas);
|
|
25
|
+
return files;
|
|
26
|
+
};
|
|
27
|
+
/** Introspect `schemas` through the given client and emit the file tree. */
|
|
28
|
+
export const generate = async (client, { schemas }) => {
|
|
29
|
+
const introspection = await introspect(client, { schemas });
|
|
30
|
+
const ir = buildIr(introspection, { schemas });
|
|
31
|
+
return emitFileTree(ir);
|
|
32
|
+
};
|
|
33
|
+
/** Write an emitted file tree under `outDir`, creating directories as needed. */
|
|
34
|
+
export const writeFileTree = async (outDir, files) => {
|
|
35
|
+
for (const [relativePath, content] of Object.entries(files)) {
|
|
36
|
+
const fullPath = path.join(outDir, relativePath);
|
|
37
|
+
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
|
38
|
+
await fs.writeFile(fullPath, content, 'utf8');
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
export const isClean = (report) => report.missing.length === 0 && report.stale.length === 0;
|
|
42
|
+
/** Compare an emitted file tree against what is committed under `outDir`. */
|
|
43
|
+
export const checkFileTree = async (outDir, files) => {
|
|
44
|
+
const missing = [];
|
|
45
|
+
const stale = [];
|
|
46
|
+
for (const [relativePath, content] of Object.entries(files)) {
|
|
47
|
+
const fullPath = path.join(outDir, relativePath);
|
|
48
|
+
let existing;
|
|
49
|
+
try {
|
|
50
|
+
existing = await fs.readFile(fullPath, 'utf8');
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code === 'ENOENT') {
|
|
54
|
+
missing.push(relativePath);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
if (existing !== content)
|
|
60
|
+
stale.push(relativePath);
|
|
61
|
+
}
|
|
62
|
+
return { missing, stale };
|
|
63
|
+
};
|
package/esm/index.js
CHANGED
|
@@ -1,69 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import { generateCodeTree } from './codegen/codegen';
|
|
7
|
-
import getIntrospectionRows from './introspect';
|
|
8
|
-
const log = new Logger('pg-codegen');
|
|
9
|
-
/**
|
|
10
|
-
* Writes the generated code files to the specified directory.
|
|
11
|
-
*
|
|
12
|
-
* @param outputDir The base directory to write the files.
|
|
13
|
-
* @param fileTree The file tree containing file paths and content.
|
|
14
|
-
*/
|
|
15
|
-
const writeGeneratedFiles = async (outputDir, fileTree) => {
|
|
16
|
-
try {
|
|
17
|
-
// Ensure the output directory exists
|
|
18
|
-
await fs.mkdir(outputDir, { recursive: true });
|
|
19
|
-
// Write each file to its corresponding path
|
|
20
|
-
for (const [filePath, content] of Object.entries(fileTree)) {
|
|
21
|
-
const fullPath = path.join(outputDir, filePath);
|
|
22
|
-
// Ensure the directory for the file exists
|
|
23
|
-
const dirName = path.dirname(fullPath);
|
|
24
|
-
await fs.mkdir(dirName, { recursive: true });
|
|
25
|
-
// Write the file content
|
|
26
|
-
await fs.writeFile(fullPath, content, 'utf8');
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
catch (error) {
|
|
30
|
-
log.error(`Failed to write files to ${outputDir}:`, error);
|
|
31
|
-
throw error;
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
(async () => {
|
|
35
|
-
const env = getPgEnvOptions();
|
|
36
|
-
const pool = getPgPool(env);
|
|
37
|
-
const options = {
|
|
38
|
-
// @ts-ignore
|
|
39
|
-
client: pool, // hope this is ok?
|
|
40
|
-
introspectionOptions: {
|
|
41
|
-
pgLegacyFunctionsOnly: false,
|
|
42
|
-
pgIgnoreRBAC: true,
|
|
43
|
-
},
|
|
44
|
-
namespacesToIntrospect: ['metaschema_public'],
|
|
45
|
-
includeExtensions: false,
|
|
46
|
-
};
|
|
47
|
-
const outputDirectory = path.join(__dirname, '../../../__fixtures__/output');
|
|
48
|
-
try {
|
|
49
|
-
// Clean the output directory
|
|
50
|
-
await fs.rm(outputDirectory, { recursive: true, force: true });
|
|
51
|
-
log.info(`Cleaned output directory: ${outputDirectory}`);
|
|
52
|
-
// Fetch introspection rows
|
|
53
|
-
const rows = await getIntrospectionRows(options);
|
|
54
|
-
log.info('Introspection Rows Fetched:', rows);
|
|
55
|
-
// Generate TypeScript code
|
|
56
|
-
const codegenOptions = {
|
|
57
|
-
includeTimestamps: true,
|
|
58
|
-
includeUUID: true,
|
|
59
|
-
};
|
|
60
|
-
const generatedCode = generateCodeTree(rows, codegenOptions);
|
|
61
|
-
log.info('Generated TypeScript Code Tree:', generatedCode);
|
|
62
|
-
// Write the generated code to files
|
|
63
|
-
await writeGeneratedFiles(outputDirectory, generatedCode);
|
|
64
|
-
log.info(`Generated files written to ${outputDirectory}`);
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
log.error('Failed to fetch introspection rows or generate code:', error);
|
|
68
|
-
}
|
|
69
|
-
})();
|
|
1
|
+
export { emitRootIndex, emitSchemaIndex, tableFileName } from './emit/barrel';
|
|
2
|
+
export { emitEnumsModule } from './emit/enums';
|
|
3
|
+
export { emitRecordModule } from './emit/record';
|
|
4
|
+
export { checkFileTree, emitFileTree, generate, isClean, writeFileTree } from './generate';
|
|
5
|
+
export { buildIr } from './ir';
|
package/esm/ir.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Normalized intermediate representation of a database schema.
|
|
3
|
+
*
|
|
4
|
+
* `buildIr` reduces an introspectron result to the shape every emitter
|
|
5
|
+
* consumes: tables with resolved column scalars, primary keys, and the enums
|
|
6
|
+
* they reference. Domains are unwrapped to their base type; arrays carry
|
|
7
|
+
* their element scalar.
|
|
8
|
+
*/
|
|
9
|
+
import { toCamelCase } from 'inflekt';
|
|
10
|
+
const TABLE_KINDS = {
|
|
11
|
+
r: 'table',
|
|
12
|
+
p: 'partitioned table',
|
|
13
|
+
v: 'view',
|
|
14
|
+
m: 'materialized view',
|
|
15
|
+
f: 'foreign table'
|
|
16
|
+
};
|
|
17
|
+
const SCALAR_BY_TYPE_NAME = {
|
|
18
|
+
bool: 'boolean',
|
|
19
|
+
int2: 'integer',
|
|
20
|
+
int4: 'integer',
|
|
21
|
+
int8: 'bigint',
|
|
22
|
+
float4: 'number',
|
|
23
|
+
float8: 'number',
|
|
24
|
+
numeric: 'number',
|
|
25
|
+
money: 'number',
|
|
26
|
+
text: 'string',
|
|
27
|
+
varchar: 'string',
|
|
28
|
+
bpchar: 'string',
|
|
29
|
+
char: 'string',
|
|
30
|
+
name: 'string',
|
|
31
|
+
citext: 'string',
|
|
32
|
+
inet: 'string',
|
|
33
|
+
cidr: 'string',
|
|
34
|
+
macaddr: 'string',
|
|
35
|
+
macaddr8: 'string',
|
|
36
|
+
interval: 'string',
|
|
37
|
+
time: 'string',
|
|
38
|
+
timetz: 'string',
|
|
39
|
+
bit: 'string',
|
|
40
|
+
varbit: 'string',
|
|
41
|
+
xml: 'string',
|
|
42
|
+
ltree: 'string',
|
|
43
|
+
date: 'timestamp',
|
|
44
|
+
timestamp: 'timestamp',
|
|
45
|
+
timestamptz: 'timestamp',
|
|
46
|
+
uuid: 'uuid',
|
|
47
|
+
json: 'json',
|
|
48
|
+
jsonb: 'json'
|
|
49
|
+
};
|
|
50
|
+
const resolveType = (type, typeById) => {
|
|
51
|
+
if (type.type === 'd' && type.domainBaseTypeId) {
|
|
52
|
+
const base = typeById.get(type.domainBaseTypeId);
|
|
53
|
+
if (base)
|
|
54
|
+
return resolveType(base, typeById);
|
|
55
|
+
}
|
|
56
|
+
if (type.isPgArray && type.arrayItemTypeId) {
|
|
57
|
+
const element = typeById.get(type.arrayItemTypeId);
|
|
58
|
+
if (element) {
|
|
59
|
+
const resolved = resolveType(element, typeById);
|
|
60
|
+
// Arrays of arrays and arrays of unresolvable elements degrade to a
|
|
61
|
+
// plain `unknown` scalar rather than pretend to a typed element.
|
|
62
|
+
if (resolved.isArray || resolved.scalar === 'unknown') {
|
|
63
|
+
return { scalar: 'unknown', isArray: false };
|
|
64
|
+
}
|
|
65
|
+
return { ...resolved, isArray: true };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (type.type === 'e' && Array.isArray(type.enumVariants) && type.enumVariants.length > 0) {
|
|
69
|
+
return { scalar: 'enum', isArray: false, enumType: type };
|
|
70
|
+
}
|
|
71
|
+
const scalar = SCALAR_BY_TYPE_NAME[type.name];
|
|
72
|
+
return { scalar: scalar ?? 'unknown', isArray: false };
|
|
73
|
+
};
|
|
74
|
+
export const buildIr = (introspection, { schemas }) => {
|
|
75
|
+
const typeById = new Map(introspection.type.map(type => [type.id, type]));
|
|
76
|
+
const namespaceNameById = new Map(introspection.namespace.map(namespace => [namespace.id, namespace.name]));
|
|
77
|
+
const attributesByClassId = new Map();
|
|
78
|
+
for (const attribute of introspection.attribute) {
|
|
79
|
+
const list = attributesByClassId.get(attribute.classId);
|
|
80
|
+
if (list)
|
|
81
|
+
list.push(attribute);
|
|
82
|
+
else
|
|
83
|
+
attributesByClassId.set(attribute.classId, [attribute]);
|
|
84
|
+
}
|
|
85
|
+
const primaryKeyByClassId = new Map();
|
|
86
|
+
for (const constraint of introspection.constraint) {
|
|
87
|
+
if (constraint.type === 'p')
|
|
88
|
+
primaryKeyByClassId.set(constraint.classId, constraint);
|
|
89
|
+
}
|
|
90
|
+
const irSchemas = schemas.map(schemaName => {
|
|
91
|
+
const enums = [];
|
|
92
|
+
const enumNames = new Set();
|
|
93
|
+
const registerEnum = (enumType) => {
|
|
94
|
+
const owningSchema = namespaceNameById.get(enumType.namespaceId) ?? schemaName;
|
|
95
|
+
if (!enumNames.has(enumType.name)) {
|
|
96
|
+
enumNames.add(enumType.name);
|
|
97
|
+
enums.push({
|
|
98
|
+
schema: owningSchema,
|
|
99
|
+
name: enumType.name,
|
|
100
|
+
values: enumType.enumVariants ?? []
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return enumType.name;
|
|
104
|
+
};
|
|
105
|
+
const tables = introspection.class
|
|
106
|
+
.filter((cls) => cls.namespaceName === schemaName && cls.classKind !== undefined && cls.classKind in TABLE_KINDS)
|
|
107
|
+
.map((cls) => {
|
|
108
|
+
const attributes = (attributesByClassId.get(cls.id) ?? [])
|
|
109
|
+
.filter(attribute => attribute.num > 0)
|
|
110
|
+
.sort((a, b) => a.num - b.num);
|
|
111
|
+
const primaryKeyConstraint = primaryKeyByClassId.get(cls.id);
|
|
112
|
+
const primaryKeyNums = new Set(primaryKeyConstraint?.keyAttributeNums ?? []);
|
|
113
|
+
const columns = attributes.map((attribute) => {
|
|
114
|
+
const type = typeById.get(attribute.typeId);
|
|
115
|
+
const resolved = type
|
|
116
|
+
? resolveType(type, typeById)
|
|
117
|
+
: { scalar: 'unknown', isArray: false };
|
|
118
|
+
const column = {
|
|
119
|
+
name: attribute.name,
|
|
120
|
+
propertyName: toCamelCase(attribute.name),
|
|
121
|
+
ordinal: attribute.num,
|
|
122
|
+
scalar: resolved.scalar,
|
|
123
|
+
isArray: resolved.isArray,
|
|
124
|
+
nullable: attribute.isNotNull !== true,
|
|
125
|
+
hasDefault: attribute.hasDefault === true || (attribute.identity ?? '') !== '',
|
|
126
|
+
pgType: type?.name ?? 'unknown'
|
|
127
|
+
};
|
|
128
|
+
if (resolved.enumType)
|
|
129
|
+
column.enumName = registerEnum(resolved.enumType);
|
|
130
|
+
if (attribute.description)
|
|
131
|
+
column.comment = attribute.description;
|
|
132
|
+
return column;
|
|
133
|
+
});
|
|
134
|
+
const table = {
|
|
135
|
+
schema: schemaName,
|
|
136
|
+
name: cls.name,
|
|
137
|
+
kind: TABLE_KINDS[cls.classKind],
|
|
138
|
+
columns,
|
|
139
|
+
primaryKey: attributes
|
|
140
|
+
.filter(attribute => primaryKeyNums.has(attribute.num))
|
|
141
|
+
.map(attribute => attribute.name)
|
|
142
|
+
};
|
|
143
|
+
if (cls.description)
|
|
144
|
+
table.comment = cls.description;
|
|
145
|
+
return table;
|
|
146
|
+
})
|
|
147
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
148
|
+
enums.sort((a, b) => a.name.localeCompare(b.name));
|
|
149
|
+
return { name: schemaName, tables, enums };
|
|
150
|
+
});
|
|
151
|
+
return { schemas: irSchemas };
|
|
152
|
+
};
|
package/generate.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ClientBase } from 'pg';
|
|
2
|
+
import { Ir } from './ir';
|
|
3
|
+
/** Emit the full generated file tree (relative path -> content) from an IR. */
|
|
4
|
+
export declare const emitFileTree: (ir: Ir) => Record<string, string>;
|
|
5
|
+
export interface GenerateOptions {
|
|
6
|
+
schemas: string[];
|
|
7
|
+
}
|
|
8
|
+
/** Introspect `schemas` through the given client and emit the file tree. */
|
|
9
|
+
export declare const generate: (client: ClientBase, { schemas }: GenerateOptions) => Promise<Record<string, string>>;
|
|
10
|
+
/** Write an emitted file tree under `outDir`, creating directories as needed. */
|
|
11
|
+
export declare const writeFileTree: (outDir: string, files: Record<string, string>) => Promise<void>;
|
|
12
|
+
export interface DriftReport {
|
|
13
|
+
/** Files the generator emits that are absent on disk. */
|
|
14
|
+
missing: string[];
|
|
15
|
+
/** Files on disk whose content no longer matches the generator's output. */
|
|
16
|
+
stale: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare const isClean: (report: DriftReport) => boolean;
|
|
19
|
+
/** Compare an emitted file tree against what is committed under `outDir`. */
|
|
20
|
+
export declare const checkFileTree: (outDir: string, files: Record<string, string>) => Promise<DriftReport>;
|
package/generate.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.checkFileTree = exports.isClean = exports.writeFileTree = exports.generate = exports.emitFileTree = void 0;
|
|
7
|
+
/**
|
|
8
|
+
* The generation pipeline: introspect -> IR -> emitted file tree, plus the
|
|
9
|
+
* filesystem write and `--check` drift comparison.
|
|
10
|
+
*/
|
|
11
|
+
const fs_1 = require("fs");
|
|
12
|
+
const introspectron_1 = require("introspectron");
|
|
13
|
+
const path_1 = __importDefault(require("path"));
|
|
14
|
+
const barrel_1 = require("./emit/barrel");
|
|
15
|
+
const enums_1 = require("./emit/enums");
|
|
16
|
+
const record_1 = require("./emit/record");
|
|
17
|
+
const ir_1 = require("./ir");
|
|
18
|
+
/** Emit the full generated file tree (relative path -> content) from an IR. */
|
|
19
|
+
const emitFileTree = (ir) => {
|
|
20
|
+
const files = {};
|
|
21
|
+
for (const schema of ir.schemas) {
|
|
22
|
+
if (schema.enums.length > 0) {
|
|
23
|
+
files[`${schema.name}/enums.ts`] = (0, enums_1.emitEnumsModule)(schema.enums);
|
|
24
|
+
}
|
|
25
|
+
for (const table of schema.tables) {
|
|
26
|
+
files[`${schema.name}/${(0, barrel_1.tableFileName)(table.name)}.ts`] = (0, record_1.emitRecordModule)(table);
|
|
27
|
+
}
|
|
28
|
+
files[`${schema.name}/index.ts`] = (0, barrel_1.emitSchemaIndex)(schema);
|
|
29
|
+
}
|
|
30
|
+
files['index.ts'] = (0, barrel_1.emitRootIndex)(ir.schemas);
|
|
31
|
+
return files;
|
|
32
|
+
};
|
|
33
|
+
exports.emitFileTree = emitFileTree;
|
|
34
|
+
/** Introspect `schemas` through the given client and emit the file tree. */
|
|
35
|
+
const generate = async (client, { schemas }) => {
|
|
36
|
+
const introspection = await (0, introspectron_1.introspect)(client, { schemas });
|
|
37
|
+
const ir = (0, ir_1.buildIr)(introspection, { schemas });
|
|
38
|
+
return (0, exports.emitFileTree)(ir);
|
|
39
|
+
};
|
|
40
|
+
exports.generate = generate;
|
|
41
|
+
/** Write an emitted file tree under `outDir`, creating directories as needed. */
|
|
42
|
+
const writeFileTree = async (outDir, files) => {
|
|
43
|
+
for (const [relativePath, content] of Object.entries(files)) {
|
|
44
|
+
const fullPath = path_1.default.join(outDir, relativePath);
|
|
45
|
+
await fs_1.promises.mkdir(path_1.default.dirname(fullPath), { recursive: true });
|
|
46
|
+
await fs_1.promises.writeFile(fullPath, content, 'utf8');
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
exports.writeFileTree = writeFileTree;
|
|
50
|
+
const isClean = (report) => report.missing.length === 0 && report.stale.length === 0;
|
|
51
|
+
exports.isClean = isClean;
|
|
52
|
+
/** Compare an emitted file tree against what is committed under `outDir`. */
|
|
53
|
+
const checkFileTree = async (outDir, files) => {
|
|
54
|
+
const missing = [];
|
|
55
|
+
const stale = [];
|
|
56
|
+
for (const [relativePath, content] of Object.entries(files)) {
|
|
57
|
+
const fullPath = path_1.default.join(outDir, relativePath);
|
|
58
|
+
let existing;
|
|
59
|
+
try {
|
|
60
|
+
existing = await fs_1.promises.readFile(fullPath, 'utf8');
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (error.code === 'ENOENT') {
|
|
64
|
+
missing.push(relativePath);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
if (existing !== content)
|
|
70
|
+
stale.push(relativePath);
|
|
71
|
+
}
|
|
72
|
+
return { missing, stale };
|
|
73
|
+
};
|
|
74
|
+
exports.checkFileTree = checkFileTree;
|
package/index.d.ts
CHANGED
|
@@ -1 +1,5 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export { emitRootIndex, emitSchemaIndex, tableFileName } from './emit/barrel';
|
|
2
|
+
export { emitEnumsModule } from './emit/enums';
|
|
3
|
+
export { emitRecordModule } from './emit/record';
|
|
4
|
+
export { checkFileTree, DriftReport, emitFileTree, generate, GenerateOptions, isClean, writeFileTree } from './generate';
|
|
5
|
+
export { buildIr, BuildIrOptions, Ir, IrColumn, IrEnum, IrScalar, IrSchema, IrTable, IrTableKind } from './ir';
|