pg-codegen 5.10.10 → 5.11.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/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 +199 -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 +195 -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/cli.d.ts
ADDED
package/cli.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.main = exports.parseArgs = void 0;
|
|
5
|
+
/**
|
|
6
|
+
* pg-codegen CLI.
|
|
7
|
+
*
|
|
8
|
+
* pg-codegen --schema app_public --out src/generated
|
|
9
|
+
* pg-codegen --schema app_public --schema app_jobs --out src/generated --check
|
|
10
|
+
*
|
|
11
|
+
* Connection settings come from the standard PG environment (pg-env):
|
|
12
|
+
* PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE.
|
|
13
|
+
*/
|
|
14
|
+
const pg_1 = require("pg");
|
|
15
|
+
const pg_env_1 = require("pg-env");
|
|
16
|
+
const generate_1 = require("./generate");
|
|
17
|
+
const USAGE = `Usage: pg-codegen --schema <name> [--schema <name> ...] --out <dir> [--check]
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--schema <name> A schema to generate records for (repeatable, or comma-separated)
|
|
21
|
+
--out <dir> Directory the generated files are written to (or compared against)
|
|
22
|
+
--check Compare against the files already in --out and exit non-zero on drift
|
|
23
|
+
--help Show this message
|
|
24
|
+
|
|
25
|
+
Connection settings come from the standard PG environment variables.`;
|
|
26
|
+
const parseArgs = (argv) => {
|
|
27
|
+
const schemas = [];
|
|
28
|
+
let out = '';
|
|
29
|
+
let check = false;
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const arg = argv[i];
|
|
32
|
+
switch (arg) {
|
|
33
|
+
case '--schema': {
|
|
34
|
+
const value = argv[++i];
|
|
35
|
+
if (!value)
|
|
36
|
+
throw new Error('--schema requires a value');
|
|
37
|
+
schemas.push(...value.split(',').map(name => name.trim()).filter(Boolean));
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
case '--out': {
|
|
41
|
+
const value = argv[++i];
|
|
42
|
+
if (!value)
|
|
43
|
+
throw new Error('--out requires a value');
|
|
44
|
+
out = value;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
case '--check':
|
|
48
|
+
check = true;
|
|
49
|
+
break;
|
|
50
|
+
case '--help':
|
|
51
|
+
case '-h':
|
|
52
|
+
console.log(USAGE);
|
|
53
|
+
process.exit(0);
|
|
54
|
+
break;
|
|
55
|
+
default:
|
|
56
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (schemas.length === 0)
|
|
60
|
+
throw new Error('At least one --schema is required');
|
|
61
|
+
if (!out)
|
|
62
|
+
throw new Error('--out is required');
|
|
63
|
+
return { schemas, out, check };
|
|
64
|
+
};
|
|
65
|
+
exports.parseArgs = parseArgs;
|
|
66
|
+
const main = async (argv) => {
|
|
67
|
+
let args;
|
|
68
|
+
try {
|
|
69
|
+
args = (0, exports.parseArgs)(argv);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
console.error(error.message);
|
|
73
|
+
console.error();
|
|
74
|
+
console.error(USAGE);
|
|
75
|
+
return 2;
|
|
76
|
+
}
|
|
77
|
+
const pg = (0, pg_env_1.getPgEnvOptions)();
|
|
78
|
+
const client = new pg_1.Client({
|
|
79
|
+
host: pg.host,
|
|
80
|
+
port: pg.port,
|
|
81
|
+
user: pg.user,
|
|
82
|
+
password: pg.password,
|
|
83
|
+
database: pg.database
|
|
84
|
+
});
|
|
85
|
+
await client.connect();
|
|
86
|
+
try {
|
|
87
|
+
const files = await (0, generate_1.generate)(client, { schemas: args.schemas });
|
|
88
|
+
if (args.check) {
|
|
89
|
+
const report = await (0, generate_1.checkFileTree)(args.out, files);
|
|
90
|
+
if ((0, generate_1.isClean)(report)) {
|
|
91
|
+
console.log(`pg-codegen: ${Object.keys(files).length} files up to date in ${args.out}`);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
for (const file of report.missing)
|
|
95
|
+
console.error(`missing: ${file}`);
|
|
96
|
+
for (const file of report.stale)
|
|
97
|
+
console.error(`stale: ${file}`);
|
|
98
|
+
console.error('pg-codegen --check failed: regenerate with the same command without --check');
|
|
99
|
+
return 1;
|
|
100
|
+
}
|
|
101
|
+
await (0, generate_1.writeFileTree)(args.out, files);
|
|
102
|
+
console.log(`pg-codegen: wrote ${Object.keys(files).length} files to ${args.out}`);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
await client.end();
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
exports.main = main;
|
|
110
|
+
if (require.main === module) {
|
|
111
|
+
(0, exports.main)(process.argv.slice(2)).then(code => process.exit(code), error => {
|
|
112
|
+
console.error(error);
|
|
113
|
+
process.exit(1);
|
|
114
|
+
});
|
|
115
|
+
}
|
package/emit/babel.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
export { t };
|
|
3
|
+
export declare const HEADER: string;
|
|
4
|
+
export declare const generateCode: (statements: t.Statement[]) => string;
|
|
5
|
+
/** Attach a JSDoc block as a leading comment. */
|
|
6
|
+
export declare const withJsDoc: <T extends t.Statement>(node: T, text: string) => T;
|
|
7
|
+
export declare const namedImport: (names: string[], source: string) => t.ImportDeclaration;
|
|
8
|
+
export declare const asConst: (expression: t.Expression) => t.TSAsExpression;
|
|
9
|
+
export declare const exportConst: (name: string, init: t.Expression, typeAnnotation?: t.TSType) => t.ExportNamedDeclaration;
|
|
10
|
+
/** `` `${label}.suffix` `` */
|
|
11
|
+
export declare const labelTemplate: (suffix: string) => t.TemplateLiteral;
|
package/emit/babel.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.labelTemplate = exports.exportConst = exports.asConst = exports.namedImport = exports.withJsDoc = exports.generateCode = exports.HEADER = exports.t = void 0;
|
|
40
|
+
const generator_1 = __importDefault(require("@babel/generator"));
|
|
41
|
+
const t = __importStar(require("@babel/types"));
|
|
42
|
+
exports.t = t;
|
|
43
|
+
exports.HEADER = [
|
|
44
|
+
'/**',
|
|
45
|
+
' * Generated by pg-codegen. DO NOT EDIT.',
|
|
46
|
+
' */',
|
|
47
|
+
'/* eslint-disable */',
|
|
48
|
+
''
|
|
49
|
+
].join('\n');
|
|
50
|
+
const generateCode = (statements) => {
|
|
51
|
+
const program = t.program(statements);
|
|
52
|
+
const { code } = (0, generator_1.default)(program, {
|
|
53
|
+
jsescOption: { quotes: 'single' },
|
|
54
|
+
retainLines: false
|
|
55
|
+
});
|
|
56
|
+
return `${exports.HEADER}${code}\n`;
|
|
57
|
+
};
|
|
58
|
+
exports.generateCode = generateCode;
|
|
59
|
+
/** Attach a JSDoc block as a leading comment. */
|
|
60
|
+
const withJsDoc = (node, text) => {
|
|
61
|
+
t.addComment(node, 'leading', `* ${text} `, false);
|
|
62
|
+
return node;
|
|
63
|
+
};
|
|
64
|
+
exports.withJsDoc = withJsDoc;
|
|
65
|
+
const namedImport = (names, source) => t.importDeclaration(names.map(name => t.importSpecifier(t.identifier(name), t.identifier(name))), t.stringLiteral(source));
|
|
66
|
+
exports.namedImport = namedImport;
|
|
67
|
+
const asConst = (expression) => t.tsAsExpression(expression, t.tsTypeReference(t.identifier('const')));
|
|
68
|
+
exports.asConst = asConst;
|
|
69
|
+
const exportConst = (name, init, typeAnnotation) => {
|
|
70
|
+
const id = t.identifier(name);
|
|
71
|
+
if (typeAnnotation)
|
|
72
|
+
id.typeAnnotation = t.tsTypeAnnotation(typeAnnotation);
|
|
73
|
+
return t.exportNamedDeclaration(t.variableDeclaration('const', [t.variableDeclarator(id, init)]));
|
|
74
|
+
};
|
|
75
|
+
exports.exportConst = exportConst;
|
|
76
|
+
/** `` `${label}.suffix` `` */
|
|
77
|
+
const labelTemplate = (suffix) => t.templateLiteral([
|
|
78
|
+
t.templateElement({ raw: '', cooked: '' }),
|
|
79
|
+
t.templateElement({ raw: `.${suffix}`, cooked: `.${suffix}` }, true)
|
|
80
|
+
], [t.identifier('label')]);
|
|
81
|
+
exports.labelTemplate = labelTemplate;
|
package/emit/barrel.d.ts
ADDED
package/emit/barrel.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.emitRootIndex = exports.emitSchemaIndex = exports.tableFileName = void 0;
|
|
4
|
+
/** Emits the per-schema and root index modules. */
|
|
5
|
+
const inflekt_1 = require("inflekt");
|
|
6
|
+
const babel_1 = require("./babel");
|
|
7
|
+
const tableFileName = (tableName) => (0, inflekt_1.toKebabCase)(tableName);
|
|
8
|
+
exports.tableFileName = tableFileName;
|
|
9
|
+
const emitSchemaIndex = (schema) => {
|
|
10
|
+
const statements = [];
|
|
11
|
+
if (schema.enums.length > 0) {
|
|
12
|
+
statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral('./enums')));
|
|
13
|
+
}
|
|
14
|
+
for (const table of schema.tables) {
|
|
15
|
+
statements.push(babel_1.t.exportAllDeclaration(babel_1.t.stringLiteral(`./${(0, exports.tableFileName)(table.name)}`)));
|
|
16
|
+
}
|
|
17
|
+
return (0, babel_1.generateCode)(statements);
|
|
18
|
+
};
|
|
19
|
+
exports.emitSchemaIndex = emitSchemaIndex;
|
|
20
|
+
const emitRootIndex = (schemas) => {
|
|
21
|
+
const statements = schemas.map(schema => babel_1.t.exportNamedDeclaration(null, [babel_1.t.exportNamespaceSpecifier(babel_1.t.identifier((0, inflekt_1.toCamelCase)(schema.name)))], babel_1.t.stringLiteral(`./${schema.name}`)));
|
|
22
|
+
return (0, babel_1.generateCode)(statements);
|
|
23
|
+
};
|
|
24
|
+
exports.emitRootIndex = emitRootIndex;
|
package/emit/enums.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { IrEnum } from '../ir';
|
|
2
|
+
export declare const enumConstName: (enumName: string) => string;
|
|
3
|
+
export declare const enumTypeName: (enumName: string) => string;
|
|
4
|
+
export declare const enumAsName: (enumName: string) => string;
|
|
5
|
+
export declare const enumRequireName: (enumName: string) => string;
|
|
6
|
+
export declare const emitEnumsModule: (enums: IrEnum[]) => string;
|
package/emit/enums.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.emitEnumsModule = exports.enumRequireName = exports.enumAsName = exports.enumTypeName = exports.enumConstName = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Emits one `enums.ts` module per schema: a literal tuple, a union type, and
|
|
6
|
+
* lenient/strict runtime checkers for every PostgreSQL enum the schema's
|
|
7
|
+
* tables reference.
|
|
8
|
+
*/
|
|
9
|
+
const inflekt_1 = require("inflekt");
|
|
10
|
+
const babel_1 = require("./babel");
|
|
11
|
+
const enumConstName = (enumName) => (0, inflekt_1.toConstantCase)(enumName);
|
|
12
|
+
exports.enumConstName = enumConstName;
|
|
13
|
+
const enumTypeName = (enumName) => (0, inflekt_1.toPascalCase)(enumName);
|
|
14
|
+
exports.enumTypeName = enumTypeName;
|
|
15
|
+
const enumAsName = (enumName) => `as${(0, inflekt_1.toPascalCase)(enumName)}`;
|
|
16
|
+
exports.enumAsName = enumAsName;
|
|
17
|
+
const enumRequireName = (enumName) => `require${(0, inflekt_1.toPascalCase)(enumName)}`;
|
|
18
|
+
exports.enumRequireName = enumRequireName;
|
|
19
|
+
const emitEnumsModule = (enums) => {
|
|
20
|
+
const statements = [(0, babel_1.namedImport)(['asOneOf', 'requireOneOf'], '@constructive-io/coerce')];
|
|
21
|
+
for (const irEnum of enums) {
|
|
22
|
+
const constName = (0, exports.enumConstName)(irEnum.name);
|
|
23
|
+
const typeName = (0, exports.enumTypeName)(irEnum.name);
|
|
24
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(constName, (0, babel_1.asConst)(babel_1.t.arrayExpression(irEnum.values.map(value => babel_1.t.stringLiteral(value))))), `Values of the \`${irEnum.schema}.${irEnum.name}\` enum.`));
|
|
25
|
+
statements.push(babel_1.t.exportNamedDeclaration(babel_1.t.tsTypeAliasDeclaration(babel_1.t.identifier(typeName), null, babel_1.t.tsIndexedAccessType(babel_1.t.tsTypeQuery(babel_1.t.identifier(constName)), babel_1.t.tsNumberKeyword()))));
|
|
26
|
+
const valueParam = babel_1.t.identifier('value');
|
|
27
|
+
valueParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
28
|
+
const asFn = babel_1.t.arrowFunctionExpression([valueParam], babel_1.t.callExpression(babel_1.t.identifier('asOneOf'), [babel_1.t.identifier('value'), babel_1.t.identifier(constName)]));
|
|
29
|
+
asFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnionType([babel_1.t.tsTypeReference(babel_1.t.identifier(typeName)), babel_1.t.tsNullKeyword()]));
|
|
30
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)((0, exports.enumAsName)(irEnum.name), asFn), `A \`${typeName}\`, else \`null\`.`));
|
|
31
|
+
const requireValueParam = babel_1.t.identifier('value');
|
|
32
|
+
requireValueParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
33
|
+
const labelParam = babel_1.t.identifier('label');
|
|
34
|
+
labelParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsStringKeyword());
|
|
35
|
+
const requireFn = babel_1.t.arrowFunctionExpression([requireValueParam, labelParam], babel_1.t.callExpression(babel_1.t.identifier('requireOneOf'), [
|
|
36
|
+
babel_1.t.identifier('value'),
|
|
37
|
+
babel_1.t.identifier(constName),
|
|
38
|
+
babel_1.t.identifier('label')
|
|
39
|
+
]));
|
|
40
|
+
requireFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(typeName)));
|
|
41
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)((0, exports.enumRequireName)(irEnum.name), requireFn), `A \`${typeName}\`, throwing \`CoerceError\` when the value is not one of its members.`));
|
|
42
|
+
}
|
|
43
|
+
return (0, babel_1.generateCode)(statements);
|
|
44
|
+
};
|
|
45
|
+
exports.emitEnumsModule = emitEnumsModule;
|
package/emit/record.d.ts
ADDED
package/emit/record.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
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
|
+
const decodeExpression = (column, key, usage) => {
|
|
66
|
+
const value = member('record', key);
|
|
67
|
+
if (column.scalar === 'unknown') {
|
|
68
|
+
// No runtime shape to assert; the value passes through typed `unknown`.
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
if (column.scalar === 'enum') {
|
|
72
|
+
const enumName = column.enumName;
|
|
73
|
+
if (column.isArray) {
|
|
74
|
+
const elementName = (0, enums_1.enumAsName)(enumName);
|
|
75
|
+
usage.enumImports.add(elementName);
|
|
76
|
+
if (column.nullable) {
|
|
77
|
+
usage.coerceImports.add('asArrayOf');
|
|
78
|
+
return babel_1.t.callExpression(babel_1.t.identifier('asArrayOf'), [value, babel_1.t.identifier(elementName)]);
|
|
79
|
+
}
|
|
80
|
+
usage.coerceImports.add('requireArrayOf');
|
|
81
|
+
return babel_1.t.callExpression(babel_1.t.identifier('requireArrayOf'), [
|
|
82
|
+
value,
|
|
83
|
+
babel_1.t.identifier(elementName),
|
|
84
|
+
(0, babel_1.labelTemplate)(key),
|
|
85
|
+
babel_1.t.stringLiteral(`an array of ${(0, enums_1.enumTypeName)(enumName)} values`)
|
|
86
|
+
]);
|
|
87
|
+
}
|
|
88
|
+
const fnName = column.nullable ? (0, enums_1.enumAsName)(enumName) : (0, enums_1.enumRequireName)(enumName);
|
|
89
|
+
usage.enumImports.add(fnName);
|
|
90
|
+
return column.nullable
|
|
91
|
+
? 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)]);
|
|
93
|
+
}
|
|
94
|
+
const coercer = COERCERS[column.scalar];
|
|
95
|
+
if (column.isArray) {
|
|
96
|
+
usage.coerceImports.add(coercer.as);
|
|
97
|
+
if (column.nullable) {
|
|
98
|
+
usage.coerceImports.add('asArrayOf');
|
|
99
|
+
return babel_1.t.callExpression(babel_1.t.identifier('asArrayOf'), [value, babel_1.t.identifier(coercer.as)]);
|
|
100
|
+
}
|
|
101
|
+
usage.coerceImports.add('requireArrayOf');
|
|
102
|
+
return babel_1.t.callExpression(babel_1.t.identifier('requireArrayOf'), [
|
|
103
|
+
value,
|
|
104
|
+
babel_1.t.identifier(coercer.as),
|
|
105
|
+
(0, babel_1.labelTemplate)(key),
|
|
106
|
+
babel_1.t.stringLiteral(coercer.expectedArray)
|
|
107
|
+
]);
|
|
108
|
+
}
|
|
109
|
+
const fnName = column.nullable ? coercer.as : coercer.require;
|
|
110
|
+
usage.coerceImports.add(fnName);
|
|
111
|
+
return column.nullable
|
|
112
|
+
? 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)]);
|
|
114
|
+
};
|
|
115
|
+
const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
|
|
116
|
+
usage.coerceImports.add('requireRecord');
|
|
117
|
+
const valueParam = babel_1.t.identifier('value');
|
|
118
|
+
valueParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
119
|
+
const labelParam = babel_1.t.assignmentPattern(babel_1.t.identifier('label'), babel_1.t.stringLiteral(`${table.schema}.${table.name}`));
|
|
120
|
+
const recordDecl = babel_1.t.variableDeclaration('const', [
|
|
121
|
+
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
|
+
]);
|
|
123
|
+
const resultObject = babel_1.t.objectExpression(table.columns.map(column => babel_1.t.objectProperty(objectKey(keyFor(column)), decodeExpression(column, keyFor(column), usage))));
|
|
124
|
+
const fn = babel_1.t.arrowFunctionExpression([valueParam, labelParam], babel_1.t.blockStatement([recordDecl, babel_1.t.returnStatement(resultObject)]));
|
|
125
|
+
fn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(returnTypeName)));
|
|
126
|
+
return (0, babel_1.exportConst)(fnName, fn);
|
|
127
|
+
};
|
|
128
|
+
const emitRecordModule = (table) => {
|
|
129
|
+
const usage = { coerceImports: new Set(), enumImports: new Set() };
|
|
130
|
+
const pascal = (0, inflekt_1.toPascalCase)(table.name);
|
|
131
|
+
const rowTypeName = `${pascal}Row`;
|
|
132
|
+
const metadataName = `${(0, inflekt_1.toConstantCase)(table.name)}_TABLE`;
|
|
133
|
+
const qualified = `${table.schema}.${table.name}`;
|
|
134
|
+
const statements = [];
|
|
135
|
+
// Application (camelCase) interface.
|
|
136
|
+
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)))));
|
|
137
|
+
(0, babel_1.withJsDoc)(appInterface, `\`${qualified}\` — application (camelCase) shape.${table.comment ? `\n *\n * ${table.comment}` : ''}`);
|
|
138
|
+
statements.push(appInterface);
|
|
139
|
+
// Database row (snake_case) interface.
|
|
140
|
+
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)))));
|
|
141
|
+
(0, babel_1.withJsDoc)(rowInterface, `\`${qualified}\` — database row (snake_case) shape.`);
|
|
142
|
+
statements.push(rowInterface);
|
|
143
|
+
// Table metadata.
|
|
144
|
+
const metadata = (0, babel_1.exportConst)(metadataName, (0, babel_1.asConst)(babel_1.t.objectExpression([
|
|
145
|
+
babel_1.t.objectProperty(babel_1.t.identifier('schema'), babel_1.t.stringLiteral(table.schema)),
|
|
146
|
+
babel_1.t.objectProperty(babel_1.t.identifier('name'), babel_1.t.stringLiteral(table.name)),
|
|
147
|
+
babel_1.t.objectProperty(babel_1.t.identifier('qualifiedName'), babel_1.t.stringLiteral(qualified)),
|
|
148
|
+
babel_1.t.objectProperty(babel_1.t.identifier('columns'), babel_1.t.arrayExpression(table.columns.map(column => babel_1.t.stringLiteral(column.name)))),
|
|
149
|
+
babel_1.t.objectProperty(babel_1.t.identifier('primaryKey'), babel_1.t.arrayExpression(table.primaryKey.map(name => babel_1.t.stringLiteral(name)))),
|
|
150
|
+
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)))))
|
|
151
|
+
])));
|
|
152
|
+
(0, babel_1.withJsDoc)(metadata, `Column metadata for \`${qualified}\`.`);
|
|
153
|
+
statements.push(metadata);
|
|
154
|
+
// Decoders.
|
|
155
|
+
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
|
+
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}\`.`));
|
|
157
|
+
// Row -> application converter.
|
|
158
|
+
const rowParam = babel_1.t.identifier('row');
|
|
159
|
+
rowParam.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(rowTypeName)));
|
|
160
|
+
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)))));
|
|
161
|
+
fromRowFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(pascal)));
|
|
162
|
+
const fromRowName = `${(0, inflekt_1.toCamelCase)(table.name)}FromRow`;
|
|
163
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(fromRowName, fromRowFn), `Convert a decoded \`${rowTypeName}\` into the camelCase application shape.`));
|
|
164
|
+
// unknown row -> application decoder.
|
|
165
|
+
const decodeFromRowValue = babel_1.t.identifier('value');
|
|
166
|
+
decodeFromRowValue.typeAnnotation = babel_1.t.tsTypeAnnotation(babel_1.t.tsUnknownKeyword());
|
|
167
|
+
const decodeFromRowLabel = babel_1.t.assignmentPattern(babel_1.t.identifier('label'), babel_1.t.stringLiteral(qualified));
|
|
168
|
+
const decodeFromRowFn = babel_1.t.arrowFunctionExpression([decodeFromRowValue, decodeFromRowLabel], babel_1.t.callExpression(babel_1.t.identifier(fromRowName), [
|
|
169
|
+
babel_1.t.callExpression(babel_1.t.identifier(`decode${pascal}Row`), [babel_1.t.identifier('value'), babel_1.t.identifier('label')])
|
|
170
|
+
]));
|
|
171
|
+
decodeFromRowFn.returnType = babel_1.t.tsTypeAnnotation(babel_1.t.tsTypeReference(babel_1.t.identifier(pascal)));
|
|
172
|
+
statements.push((0, babel_1.withJsDoc)((0, babel_1.exportConst)(`decode${pascal}FromRow`, decodeFromRowFn), `Decode an untrusted snake_case database row straight to \`${pascal}\`.`));
|
|
173
|
+
// Serializer: Partial application shape -> Partial row shape.
|
|
174
|
+
const patchParam = babel_1.t.identifier('patch');
|
|
175
|
+
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))])));
|
|
176
|
+
const partialRowType = babel_1.t.tsTypeReference(babel_1.t.identifier('Partial'), babel_1.t.tsTypeParameterInstantiation([babel_1.t.tsTypeReference(babel_1.t.identifier(rowTypeName))]));
|
|
177
|
+
const rowDecl = babel_1.t.variableDeclaration('const', [
|
|
178
|
+
babel_1.t.variableDeclarator(Object.assign(babel_1.t.identifier('row'), {
|
|
179
|
+
typeAnnotation: babel_1.t.tsTypeAnnotation(partialRowType)
|
|
180
|
+
}), babel_1.t.objectExpression([]))
|
|
181
|
+
]);
|
|
182
|
+
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)))));
|
|
183
|
+
const serializeFn = babel_1.t.arrowFunctionExpression([patchParam], babel_1.t.blockStatement([rowDecl, ...assignments, babel_1.t.returnStatement(babel_1.t.identifier('row'))]));
|
|
184
|
+
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))])));
|
|
185
|
+
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.`));
|
|
186
|
+
// Imports, now that usage is known.
|
|
187
|
+
const imports = [];
|
|
188
|
+
if (usage.coerceImports.size > 0) {
|
|
189
|
+
imports.push((0, babel_1.namedImport)([...usage.coerceImports].sort(), '@constructive-io/coerce'));
|
|
190
|
+
}
|
|
191
|
+
if (usage.enumImports.size > 0) {
|
|
192
|
+
const typeImports = new Set(table.columns
|
|
193
|
+
.filter(column => column.scalar === 'enum')
|
|
194
|
+
.map(column => (0, enums_1.enumTypeName)(column.enumName)));
|
|
195
|
+
imports.push((0, babel_1.namedImport)([...usage.enumImports, ...typeImports].sort(), './enums'));
|
|
196
|
+
}
|
|
197
|
+
return (0, babel_1.generateCode)([...imports, ...statements]);
|
|
198
|
+
};
|
|
199
|
+
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')]);
|