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
package/emit/record.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.emitRecordModule = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Emits one module per table: the camelCase application interface, the
|
|
6
|
+
* snake_case row interface, coerce-backed decoders for both, row/application
|
|
7
|
+
* converters, a serializer for writes, and typed table metadata.
|
|
8
|
+
*/
|
|
9
|
+
const inflekt_1 = require("inflekt");
|
|
10
|
+
const babel_1 = require("./babel");
|
|
11
|
+
const enums_1 = require("./enums");
|
|
12
|
+
const COERCERS = {
|
|
13
|
+
boolean: { require: 'requireBoolean', as: 'asBoolean', expectedArray: 'an array of booleans' },
|
|
14
|
+
integer: { require: 'requireInteger', as: 'asInteger', expectedArray: 'an array of integers' },
|
|
15
|
+
bigint: { require: 'requireNumericInteger', as: 'asNumericInteger', expectedArray: 'an array of integers' },
|
|
16
|
+
number: { require: 'requireNumeric', as: 'asNumeric', expectedArray: 'an array of numbers' },
|
|
17
|
+
string: { require: 'requireString', as: 'asString', expectedArray: 'an array of non-empty strings' },
|
|
18
|
+
uuid: { require: 'requireUuid', as: 'asUuid', expectedArray: 'an array of UUIDs' },
|
|
19
|
+
timestamp: { require: 'requireIsoString', as: 'asIsoString', expectedArray: 'an array of timestamps' },
|
|
20
|
+
json: { require: 'requireJson', as: 'asJson', expectedArray: 'an array of JSON documents' }
|
|
21
|
+
};
|
|
22
|
+
const scalarTsType = (column) => {
|
|
23
|
+
switch (column.scalar) {
|
|
24
|
+
case 'boolean':
|
|
25
|
+
return babel_1.t.tsBooleanKeyword();
|
|
26
|
+
case 'integer':
|
|
27
|
+
case 'bigint':
|
|
28
|
+
case 'number':
|
|
29
|
+
return babel_1.t.tsNumberKeyword();
|
|
30
|
+
case 'string':
|
|
31
|
+
case 'uuid':
|
|
32
|
+
case 'timestamp':
|
|
33
|
+
return babel_1.t.tsStringKeyword();
|
|
34
|
+
case 'json':
|
|
35
|
+
return babel_1.t.tsUnionType([
|
|
36
|
+
babel_1.t.tsTypeReference(babel_1.t.identifier('Record'), babel_1.t.tsTypeParameterInstantiation([babel_1.t.tsStringKeyword(), babel_1.t.tsUnknownKeyword()])),
|
|
37
|
+
babel_1.t.tsArrayType(babel_1.t.tsUnknownKeyword())
|
|
38
|
+
]);
|
|
39
|
+
case 'enum':
|
|
40
|
+
return babel_1.t.tsTypeReference(babel_1.t.identifier((0, enums_1.enumTypeName)(column.enumName)));
|
|
41
|
+
default:
|
|
42
|
+
return babel_1.t.tsUnknownKeyword();
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const columnTsType = (column) => {
|
|
46
|
+
let type = scalarTsType(column);
|
|
47
|
+
if (column.isArray)
|
|
48
|
+
type = babel_1.t.tsArrayType(type);
|
|
49
|
+
if (column.nullable && column.scalar !== 'unknown') {
|
|
50
|
+
type = babel_1.t.tsUnionType([type, babel_1.t.tsNullKeyword()]);
|
|
51
|
+
}
|
|
52
|
+
return type;
|
|
53
|
+
};
|
|
54
|
+
const property = (name, type, comment) => {
|
|
55
|
+
const key = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? babel_1.t.identifier(name) : babel_1.t.stringLiteral(name);
|
|
56
|
+
const prop = babel_1.t.tsPropertySignature(key, babel_1.t.tsTypeAnnotation(type));
|
|
57
|
+
if (comment)
|
|
58
|
+
babel_1.t.addComment(prop, 'leading', `* ${comment} `, false);
|
|
59
|
+
return prop;
|
|
60
|
+
};
|
|
61
|
+
const member = (object, key) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
|
|
62
|
+
? babel_1.t.memberExpression(babel_1.t.identifier(object), babel_1.t.identifier(key))
|
|
63
|
+
: babel_1.t.memberExpression(babel_1.t.identifier(object), babel_1.t.stringLiteral(key), true);
|
|
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
|
+
* 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) => {
|
|
72
|
+
if (column.scalar === 'unknown') {
|
|
73
|
+
// No runtime shape to assert; the value passes through typed `unknown`.
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
if (column.scalar === 'enum') {
|
|
77
|
+
const enumName = column.enumName;
|
|
78
|
+
if (column.isArray) {
|
|
79
|
+
const elementName = (0, enums_1.enumAsName)(enumName);
|
|
80
|
+
usage.enumImports.add(elementName);
|
|
81
|
+
if (column.nullable) {
|
|
82
|
+
usage.coerceImports.add('asArrayOf');
|
|
83
|
+
return babel_1.t.callExpression(babel_1.t.identifier('asArrayOf'), [value, babel_1.t.identifier(elementName)]);
|
|
84
|
+
}
|
|
85
|
+
usage.coerceImports.add('requireArrayOf');
|
|
86
|
+
return babel_1.t.callExpression(babel_1.t.identifier('requireArrayOf'), [
|
|
87
|
+
value,
|
|
88
|
+
babel_1.t.identifier(elementName),
|
|
89
|
+
label,
|
|
90
|
+
babel_1.t.stringLiteral(`an array of ${(0, enums_1.enumTypeName)(enumName)} values`)
|
|
91
|
+
]);
|
|
92
|
+
}
|
|
93
|
+
const fnName = column.nullable ? (0, enums_1.enumAsName)(enumName) : (0, enums_1.enumRequireName)(enumName);
|
|
94
|
+
usage.enumImports.add(fnName);
|
|
95
|
+
return column.nullable
|
|
96
|
+
? babel_1.t.callExpression(babel_1.t.identifier(fnName), [value])
|
|
97
|
+
: babel_1.t.callExpression(babel_1.t.identifier(fnName), [value, label]);
|
|
98
|
+
}
|
|
99
|
+
const coercer = COERCERS[column.scalar];
|
|
100
|
+
if (column.isArray) {
|
|
101
|
+
usage.coerceImports.add(coercer.as);
|
|
102
|
+
if (column.nullable) {
|
|
103
|
+
usage.coerceImports.add('asArrayOf');
|
|
104
|
+
return babel_1.t.callExpression(babel_1.t.identifier('asArrayOf'), [value, babel_1.t.identifier(coercer.as)]);
|
|
105
|
+
}
|
|
106
|
+
usage.coerceImports.add('requireArrayOf');
|
|
107
|
+
return babel_1.t.callExpression(babel_1.t.identifier('requireArrayOf'), [
|
|
108
|
+
value,
|
|
109
|
+
babel_1.t.identifier(coercer.as),
|
|
110
|
+
label,
|
|
111
|
+
babel_1.t.stringLiteral(coercer.expectedArray)
|
|
112
|
+
]);
|
|
113
|
+
}
|
|
114
|
+
const fnName = column.nullable ? coercer.as : coercer.require;
|
|
115
|
+
usage.coerceImports.add(fnName);
|
|
116
|
+
return column.nullable
|
|
117
|
+
? 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)));
|
|
146
|
+
};
|
|
147
|
+
const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
|
|
148
|
+
usage.coerceImports.add('requireRecord');
|
|
149
|
+
const valueParam = babel_1.t.identifier('value');
|
|
150
|
+
valueParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
151
|
+
const labelParam = babel_1.t.assignmentPattern(babel_1.t.identifier('label'), babel_1.t.stringLiteral(`${table.schema}.${table.name}`));
|
|
152
|
+
const recordDecl = babel_1.t.variableDeclaration('const', [
|
|
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')]))
|
|
154
|
+
]);
|
|
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
|
+
}));
|
|
159
|
+
const fn = babel_1.t.arrowFunctionExpression([valueParam, labelParam], babel_1.t.blockStatement([recordDecl, babel_1.t.returnStatement(resultObject)]));
|
|
160
|
+
fn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(returnTypeName)));
|
|
161
|
+
return (0, babel_1.exportConst)(fnName, fn);
|
|
162
|
+
};
|
|
163
|
+
const emitRecordModule = (table) => {
|
|
164
|
+
const usage = { coerceImports: new Set(), enumImports: new Set() };
|
|
165
|
+
const pascal = (0, inflekt_1.toPascalCase)(table.name);
|
|
166
|
+
const rowTypeName = `${pascal}Row`;
|
|
167
|
+
const metadataName = `${(0, inflekt_1.toConstantCase)(table.name)}_TABLE`;
|
|
168
|
+
const fieldsName = `${(0, inflekt_1.toConstantCase)(table.name)}_FIELDS`;
|
|
169
|
+
const qualified = `${table.schema}.${table.name}`;
|
|
170
|
+
const statements = [];
|
|
171
|
+
// Application (camelCase) interface.
|
|
172
|
+
const appInterface = babel_1.t.exportNamedDeclaration(babel_1.t.tsInterfaceDeclaration(babel_1.t.identifier(pascal), null, null, babel_1.t.tsInterfaceBody(table.columns.map(column => property(column.propertyName, columnTsType(column), column.comment)))));
|
|
173
|
+
(0, babel_1.withJsDoc)(appInterface, `\`${qualified}\` — application (camelCase) shape.${table.comment ? `\n *\n * ${table.comment}` : ''}`);
|
|
174
|
+
statements.push(appInterface);
|
|
175
|
+
// Database row (snake_case) interface.
|
|
176
|
+
const rowInterface = babel_1.t.exportNamedDeclaration(babel_1.t.tsInterfaceDeclaration(babel_1.t.identifier(rowTypeName), null, null, babel_1.t.tsInterfaceBody(table.columns.map(column => property(column.name, columnTsType(column), column.comment)))));
|
|
177
|
+
(0, babel_1.withJsDoc)(rowInterface, `\`${qualified}\` — database row (snake_case) shape.`);
|
|
178
|
+
statements.push(rowInterface);
|
|
179
|
+
// Table metadata.
|
|
180
|
+
const metadata = (0, babel_1.exportConst)(metadataName, (0, babel_1.asConst)(babel_1.t.objectExpression([
|
|
181
|
+
babel_1.t.objectProperty(babel_1.t.identifier('schema'), babel_1.t.stringLiteral(table.schema)),
|
|
182
|
+
babel_1.t.objectProperty(babel_1.t.identifier('name'), babel_1.t.stringLiteral(table.name)),
|
|
183
|
+
babel_1.t.objectProperty(babel_1.t.identifier('qualifiedName'), babel_1.t.stringLiteral(qualified)),
|
|
184
|
+
babel_1.t.objectProperty(babel_1.t.identifier('columns'), babel_1.t.arrayExpression(table.columns.map(column => babel_1.t.stringLiteral(column.name)))),
|
|
185
|
+
babel_1.t.objectProperty(babel_1.t.identifier('primaryKey'), babel_1.t.arrayExpression(table.primaryKey.map(name => babel_1.t.stringLiteral(name)))),
|
|
186
|
+
babel_1.t.objectProperty(babel_1.t.identifier('columnByField'), babel_1.t.objectExpression(table.columns.map(column => babel_1.t.objectProperty(objectKey(column.propertyName), babel_1.t.stringLiteral(column.name)))))
|
|
187
|
+
])));
|
|
188
|
+
(0, babel_1.withJsDoc)(metadata, `Column metadata for \`${qualified}\`.`);
|
|
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 * \`\`\`` : ''}`));
|
|
193
|
+
// Decoders.
|
|
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.`));
|
|
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}\`.`));
|
|
196
|
+
// Row -> application converter.
|
|
197
|
+
const rowParam = babel_1.t.identifier('row');
|
|
198
|
+
rowParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(rowTypeName)));
|
|
199
|
+
const fromRowFn = babel_1.t.arrowFunctionExpression([rowParam], babel_1.t.objectExpression(table.columns.map(column => babel_1.t.objectProperty(objectKey(column.propertyName), member('row', column.name)))));
|
|
200
|
+
fromRowFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(pascal)));
|
|
201
|
+
const fromRowName = `${(0, inflekt_1.toCamelCase)(table.name)}FromRow`;
|
|
202
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(fromRowName, fromRowFn), `Convert a decoded \`${rowTypeName}\` into the camelCase application shape.`));
|
|
203
|
+
// unknown row -> application decoder.
|
|
204
|
+
const decodeFromRowValue = babel_1.t.identifier('value');
|
|
205
|
+
decodeFromRowValue.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
206
|
+
const decodeFromRowLabel = babel_1.t.assignmentPattern(babel_1.t.identifier('label'), babel_1.t.stringLiteral(qualified));
|
|
207
|
+
const decodeFromRowFn = babel_1.t.arrowFunctionExpression([decodeFromRowValue, decodeFromRowLabel], babel_1.t.callExpression(babel_1.t.identifier(fromRowName), [
|
|
208
|
+
babel_1.t.callExpression(babel_1.t.identifier(`decode${pascal}Row`), [babel_1.t.identifier('value'), babel_1.t.identifier('label')])
|
|
209
|
+
]));
|
|
210
|
+
decodeFromRowFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(pascal)));
|
|
211
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(`decode${pascal}FromRow`, decodeFromRowFn), `Decode an untrusted snake_case database row straight to \`${pascal}\`.`));
|
|
212
|
+
// Serializer: Partial application shape -> Partial row shape.
|
|
213
|
+
const patchParam = babel_1.t.identifier('patch');
|
|
214
|
+
patchParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Partial'), babel_1.t.tsTypeParameterInstantiation([babel_1.t.tsTypeReference(babel_1.t.identifier(pascal))])));
|
|
215
|
+
const partialRowType = babel_1.t.tsTypeReference(babel_1.t.identifier('Partial'), babel_1.t.tsTypeParameterInstantiation([babel_1.t.tsTypeReference(babel_1.t.identifier(rowTypeName))]));
|
|
216
|
+
const rowDecl = babel_1.t.variableDeclaration('const', [
|
|
217
|
+
babel_1.t.variableDeclarator(Object.assign(babel_1.t.identifier('row'), {
|
|
218
|
+
typeAnnotation: babel_1.t.tsTypeAnnotation(partialRowType)
|
|
219
|
+
}), babel_1.t.objectExpression([]))
|
|
220
|
+
]);
|
|
221
|
+
const assignments = table.columns.map(column => babel_1.t.ifStatement(babel_1.t.binaryExpression('!==', member('patch', column.propertyName), babel_1.t.identifier('undefined')), babel_1.t.expressionStatement(babel_1.t.assignmentExpression('=', member('row', column.name), member('patch', column.propertyName)))));
|
|
222
|
+
const serializeFn = babel_1.t.arrowFunctionExpression([patchParam], babel_1.t.blockStatement([rowDecl, ...assignments, babel_1.t.returnStatement(babel_1.t.identifier('row'))]));
|
|
223
|
+
serializeFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier('Partial'), babel_1.t.tsTypeParameterInstantiation([babel_1.t.tsTypeReference(babel_1.t.identifier(rowTypeName))])));
|
|
224
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.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.`));
|
|
225
|
+
// Imports, now that usage is known.
|
|
226
|
+
const imports = [];
|
|
227
|
+
if (usage.coerceImports.size > 0) {
|
|
228
|
+
imports.push((0, babel_1.namedImport)([...usage.coerceImports].sort(), '@constructive-io/coerce'));
|
|
229
|
+
}
|
|
230
|
+
if (usage.enumImports.size > 0) {
|
|
231
|
+
const typeImports = new Set(table.columns
|
|
232
|
+
.filter(column => column.scalar === 'enum')
|
|
233
|
+
.map(column => (0, enums_1.enumTypeName)(column.enumName)));
|
|
234
|
+
imports.push((0, babel_1.namedImport)([...usage.enumImports, ...typeImports].sort(), './enums'));
|
|
235
|
+
}
|
|
236
|
+
return (0, babel_1.generateCode)([...imports, ...statements]);
|
|
237
|
+
};
|
|
238
|
+
exports.emitRecordModule = emitRecordModule;
|
package/esm/cli.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* pg-codegen CLI.
|
|
4
|
+
*
|
|
5
|
+
* pg-codegen --schema app_public --out src/generated
|
|
6
|
+
* pg-codegen --schema app_public --schema app_jobs --out src/generated --check
|
|
7
|
+
*
|
|
8
|
+
* Connection settings come from the standard PG environment (pg-env):
|
|
9
|
+
* PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE.
|
|
10
|
+
*/
|
|
11
|
+
import { Client } from 'pg';
|
|
12
|
+
import { getPgEnvOptions } from 'pg-env';
|
|
13
|
+
import { checkFileTree, generate, isClean, writeFileTree } from './generate';
|
|
14
|
+
const USAGE = `Usage: pg-codegen --schema <name> [--schema <name> ...] --out <dir> [--check]
|
|
15
|
+
|
|
16
|
+
Options:
|
|
17
|
+
--schema <name> A schema to generate records for (repeatable, or comma-separated)
|
|
18
|
+
--out <dir> Directory the generated files are written to (or compared against)
|
|
19
|
+
--check Compare against the files already in --out and exit non-zero on drift
|
|
20
|
+
--help Show this message
|
|
21
|
+
|
|
22
|
+
Connection settings come from the standard PG environment variables.`;
|
|
23
|
+
export const parseArgs = (argv) => {
|
|
24
|
+
const schemas = [];
|
|
25
|
+
let out = '';
|
|
26
|
+
let check = false;
|
|
27
|
+
for (let i = 0; i < argv.length; i++) {
|
|
28
|
+
const arg = argv[i];
|
|
29
|
+
switch (arg) {
|
|
30
|
+
case '--schema': {
|
|
31
|
+
const value = argv[++i];
|
|
32
|
+
if (!value)
|
|
33
|
+
throw new Error('--schema requires a value');
|
|
34
|
+
schemas.push(...value.split(',').map(name => name.trim()).filter(Boolean));
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
case '--out': {
|
|
38
|
+
const value = argv[++i];
|
|
39
|
+
if (!value)
|
|
40
|
+
throw new Error('--out requires a value');
|
|
41
|
+
out = value;
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
case '--check':
|
|
45
|
+
check = true;
|
|
46
|
+
break;
|
|
47
|
+
case '--help':
|
|
48
|
+
case '-h':
|
|
49
|
+
console.log(USAGE);
|
|
50
|
+
process.exit(0);
|
|
51
|
+
break;
|
|
52
|
+
default:
|
|
53
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (schemas.length === 0)
|
|
57
|
+
throw new Error('At least one --schema is required');
|
|
58
|
+
if (!out)
|
|
59
|
+
throw new Error('--out is required');
|
|
60
|
+
return { schemas, out, check };
|
|
61
|
+
};
|
|
62
|
+
export const main = async (argv) => {
|
|
63
|
+
let args;
|
|
64
|
+
try {
|
|
65
|
+
args = parseArgs(argv);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
console.error(error.message);
|
|
69
|
+
console.error();
|
|
70
|
+
console.error(USAGE);
|
|
71
|
+
return 2;
|
|
72
|
+
}
|
|
73
|
+
const pg = getPgEnvOptions();
|
|
74
|
+
const client = new Client({
|
|
75
|
+
host: pg.host,
|
|
76
|
+
port: pg.port,
|
|
77
|
+
user: pg.user,
|
|
78
|
+
password: pg.password,
|
|
79
|
+
database: pg.database
|
|
80
|
+
});
|
|
81
|
+
await client.connect();
|
|
82
|
+
try {
|
|
83
|
+
const files = await generate(client, { schemas: args.schemas });
|
|
84
|
+
if (args.check) {
|
|
85
|
+
const report = await checkFileTree(args.out, files);
|
|
86
|
+
if (isClean(report)) {
|
|
87
|
+
console.log(`pg-codegen: ${Object.keys(files).length} files up to date in ${args.out}`);
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
for (const file of report.missing)
|
|
91
|
+
console.error(`missing: ${file}`);
|
|
92
|
+
for (const file of report.stale)
|
|
93
|
+
console.error(`stale: ${file}`);
|
|
94
|
+
console.error('pg-codegen --check failed: regenerate with the same command without --check');
|
|
95
|
+
return 1;
|
|
96
|
+
}
|
|
97
|
+
await writeFileTree(args.out, files);
|
|
98
|
+
console.log(`pg-codegen: wrote ${Object.keys(files).length} files to ${args.out}`);
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
await client.end();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
if (require.main === module) {
|
|
106
|
+
main(process.argv.slice(2)).then(code => process.exit(code), error => {
|
|
107
|
+
console.error(error);
|
|
108
|
+
process.exit(1);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import generate from '@babel/generator';
|
|
2
|
+
import * as t from '@babel/types';
|
|
3
|
+
export { t };
|
|
4
|
+
export const HEADER = [
|
|
5
|
+
'/**',
|
|
6
|
+
' * Generated by pg-codegen. DO NOT EDIT.',
|
|
7
|
+
' */',
|
|
8
|
+
'/* eslint-disable */',
|
|
9
|
+
''
|
|
10
|
+
].join('\n');
|
|
11
|
+
export const generateCode = (statements) => {
|
|
12
|
+
const program = t.program(statements);
|
|
13
|
+
const { code } = generate(program, {
|
|
14
|
+
jsescOption: { quotes: 'single' },
|
|
15
|
+
retainLines: false
|
|
16
|
+
});
|
|
17
|
+
return `${HEADER}${code}\n`;
|
|
18
|
+
};
|
|
19
|
+
/** Attach a JSDoc block as a leading comment. */
|
|
20
|
+
export const withJsDoc = (node, text) => {
|
|
21
|
+
t.addComment(node, 'leading', `* ${text} `, false);
|
|
22
|
+
return node;
|
|
23
|
+
};
|
|
24
|
+
export const namedImport = (names, source) => t.importDeclaration(names.map(name => t.importSpecifier(t.identifier(name), t.identifier(name))), t.stringLiteral(source));
|
|
25
|
+
export const asConst = (expression) => t.tsAsExpression(expression, t.tsTypeReference(t.identifier('const')));
|
|
26
|
+
export const exportConst = (name, init, typeAnnotation) => {
|
|
27
|
+
const id = t.identifier(name);
|
|
28
|
+
if (typeAnnotation)
|
|
29
|
+
id.typeAnnotation = t.tsTypeAnnotation(typeAnnotation);
|
|
30
|
+
return t.exportNamedDeclaration(t.variableDeclaration('const', [t.variableDeclarator(id, init)]));
|
|
31
|
+
};
|
|
32
|
+
/** `` `${label}.suffix` `` */
|
|
33
|
+
export const labelTemplate = (suffix) => t.templateLiteral([
|
|
34
|
+
t.templateElement({ raw: '', cooked: '' }),
|
|
35
|
+
t.templateElement({ raw: `.${suffix}`, cooked: `.${suffix}` }, true)
|
|
36
|
+
], [t.identifier('label')]);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Emits the per-schema and root index modules. */
|
|
2
|
+
import { toCamelCase, toKebabCase } from 'inflekt';
|
|
3
|
+
import { generateCode, t } from './babel';
|
|
4
|
+
export const tableFileName = (tableName) => toKebabCase(tableName);
|
|
5
|
+
export const emitSchemaIndex = (schema) => {
|
|
6
|
+
const statements = [];
|
|
7
|
+
if (schema.enums.length > 0) {
|
|
8
|
+
statements.push(t.exportAllDeclaration(t.stringLiteral('./enums')));
|
|
9
|
+
}
|
|
10
|
+
for (const table of schema.tables) {
|
|
11
|
+
statements.push(t.exportAllDeclaration(t.stringLiteral(`./${tableFileName(table.name)}`)));
|
|
12
|
+
}
|
|
13
|
+
return generateCode(statements);
|
|
14
|
+
};
|
|
15
|
+
export const emitRootIndex = (schemas) => {
|
|
16
|
+
const statements = schemas.map(schema => t.exportNamedDeclaration(null, [t.exportNamespaceSpecifier(t.identifier(toCamelCase(schema.name)))], t.stringLiteral(`./${schema.name}`)));
|
|
17
|
+
return generateCode(statements);
|
|
18
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits one `enums.ts` module per schema: a literal tuple, a union type, and
|
|
3
|
+
* lenient/strict runtime checkers for every PostgreSQL enum the schema's
|
|
4
|
+
* tables reference.
|
|
5
|
+
*/
|
|
6
|
+
import { toConstantCase, toPascalCase } from 'inflekt';
|
|
7
|
+
import { asConst, exportConst, generateCode, namedImport, t, withJsDoc } from './babel';
|
|
8
|
+
export const enumConstName = (enumName) => toConstantCase(enumName);
|
|
9
|
+
export const enumTypeName = (enumName) => toPascalCase(enumName);
|
|
10
|
+
export const enumAsName = (enumName) => `as${toPascalCase(enumName)}`;
|
|
11
|
+
export const enumRequireName = (enumName) => `require${toPascalCase(enumName)}`;
|
|
12
|
+
export const emitEnumsModule = (enums) => {
|
|
13
|
+
const statements = [namedImport(['asOneOf', 'requireOneOf'], '@constructive-io/coerce')];
|
|
14
|
+
for (const irEnum of enums) {
|
|
15
|
+
const constName = enumConstName(irEnum.name);
|
|
16
|
+
const typeName = enumTypeName(irEnum.name);
|
|
17
|
+
statements.push(withJsDoc(exportConst(constName, asConst(t.arrayExpression(irEnum.values.map(value => t.stringLiteral(value))))), `Values of the \`${irEnum.schema}.${irEnum.name}\` enum.`));
|
|
18
|
+
statements.push(t.exportNamedDeclaration(t.tsTypeAliasDeclaration(t.identifier(typeName), null, t.tsIndexedAccessType(t.tsTypeQuery(t.identifier(constName)), t.tsNumberKeyword()))));
|
|
19
|
+
const valueParam = t.identifier('value');
|
|
20
|
+
valueParam.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
|
|
21
|
+
const asFn = t.arrowFunctionExpression([valueParam], t.callExpression(t.identifier('asOneOf'), [t.identifier('value'), t.identifier(constName)]));
|
|
22
|
+
asFn.returnType = t.tsTypeAnnotation(t.tsUnionType([t.tsTypeReference(t.identifier(typeName)), t.tsNullKeyword()]));
|
|
23
|
+
statements.push(withJsDoc(exportConst(enumAsName(irEnum.name), asFn), `A \`${typeName}\`, else \`null\`.`));
|
|
24
|
+
const requireValueParam = t.identifier('value');
|
|
25
|
+
requireValueParam.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
|
|
26
|
+
const labelParam = t.identifier('label');
|
|
27
|
+
labelParam.typeAnnotation = t.tsTypeAnnotation(t.tsStringKeyword());
|
|
28
|
+
const requireFn = t.arrowFunctionExpression([requireValueParam, labelParam], t.callExpression(t.identifier('requireOneOf'), [
|
|
29
|
+
t.identifier('value'),
|
|
30
|
+
t.identifier(constName),
|
|
31
|
+
t.identifier('label')
|
|
32
|
+
]));
|
|
33
|
+
requireFn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)));
|
|
34
|
+
statements.push(withJsDoc(exportConst(enumRequireName(irEnum.name), requireFn), `A \`${typeName}\`, throwing \`CoerceError\` when the value is not one of its members.`));
|
|
35
|
+
}
|
|
36
|
+
return generateCode(statements);
|
|
37
|
+
};
|