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.
@@ -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
+ };
@@ -0,0 +1,195 @@
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
+ const decodeExpression = (column, key, usage) => {
63
+ const value = member('record', key);
64
+ if (column.scalar === 'unknown') {
65
+ // No runtime shape to assert; the value passes through typed `unknown`.
66
+ return value;
67
+ }
68
+ if (column.scalar === 'enum') {
69
+ const enumName = column.enumName;
70
+ if (column.isArray) {
71
+ const elementName = enumAsName(enumName);
72
+ usage.enumImports.add(elementName);
73
+ if (column.nullable) {
74
+ usage.coerceImports.add('asArrayOf');
75
+ return t.callExpression(t.identifier('asArrayOf'), [value, t.identifier(elementName)]);
76
+ }
77
+ usage.coerceImports.add('requireArrayOf');
78
+ return t.callExpression(t.identifier('requireArrayOf'), [
79
+ value,
80
+ t.identifier(elementName),
81
+ labelTemplate(key),
82
+ t.stringLiteral(`an array of ${enumTypeName(enumName)} values`)
83
+ ]);
84
+ }
85
+ const fnName = column.nullable ? enumAsName(enumName) : enumRequireName(enumName);
86
+ usage.enumImports.add(fnName);
87
+ return column.nullable
88
+ ? t.callExpression(t.identifier(fnName), [value])
89
+ : t.callExpression(t.identifier(fnName), [value, labelTemplate(key)]);
90
+ }
91
+ const coercer = COERCERS[column.scalar];
92
+ if (column.isArray) {
93
+ usage.coerceImports.add(coercer.as);
94
+ if (column.nullable) {
95
+ usage.coerceImports.add('asArrayOf');
96
+ return t.callExpression(t.identifier('asArrayOf'), [value, t.identifier(coercer.as)]);
97
+ }
98
+ usage.coerceImports.add('requireArrayOf');
99
+ return t.callExpression(t.identifier('requireArrayOf'), [
100
+ value,
101
+ t.identifier(coercer.as),
102
+ labelTemplate(key),
103
+ t.stringLiteral(coercer.expectedArray)
104
+ ]);
105
+ }
106
+ const fnName = column.nullable ? coercer.as : coercer.require;
107
+ usage.coerceImports.add(fnName);
108
+ return column.nullable
109
+ ? t.callExpression(t.identifier(fnName), [value])
110
+ : t.callExpression(t.identifier(fnName), [value, labelTemplate(key)]);
111
+ };
112
+ const decoderFunction = (table, fnName, returnTypeName, keyFor, usage) => {
113
+ usage.coerceImports.add('requireRecord');
114
+ const valueParam = t.identifier('value');
115
+ valueParam.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
116
+ const labelParam = t.assignmentPattern(t.identifier('label'), t.stringLiteral(`${table.schema}.${table.name}`));
117
+ const recordDecl = t.variableDeclaration('const', [
118
+ t.variableDeclarator(t.identifier('record'), t.callExpression(t.identifier('requireRecord'), [t.identifier('value'), t.identifier('label')]))
119
+ ]);
120
+ const resultObject = t.objectExpression(table.columns.map(column => t.objectProperty(objectKey(keyFor(column)), decodeExpression(column, keyFor(column), usage))));
121
+ const fn = t.arrowFunctionExpression([valueParam, labelParam], t.blockStatement([recordDecl, t.returnStatement(resultObject)]));
122
+ fn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(returnTypeName)));
123
+ return exportConst(fnName, fn);
124
+ };
125
+ export const emitRecordModule = (table) => {
126
+ const usage = { coerceImports: new Set(), enumImports: new Set() };
127
+ const pascal = toPascalCase(table.name);
128
+ const rowTypeName = `${pascal}Row`;
129
+ const metadataName = `${toConstantCase(table.name)}_TABLE`;
130
+ const qualified = `${table.schema}.${table.name}`;
131
+ const statements = [];
132
+ // Application (camelCase) interface.
133
+ const appInterface = t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(pascal), null, null, t.tsInterfaceBody(table.columns.map(column => property(column.propertyName, columnTsType(column), column.comment)))));
134
+ withJsDoc(appInterface, `\`${qualified}\` — application (camelCase) shape.${table.comment ? `\n *\n * ${table.comment}` : ''}`);
135
+ statements.push(appInterface);
136
+ // Database row (snake_case) interface.
137
+ const rowInterface = t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(rowTypeName), null, null, t.tsInterfaceBody(table.columns.map(column => property(column.name, columnTsType(column), column.comment)))));
138
+ withJsDoc(rowInterface, `\`${qualified}\` — database row (snake_case) shape.`);
139
+ statements.push(rowInterface);
140
+ // Table metadata.
141
+ const metadata = exportConst(metadataName, asConst(t.objectExpression([
142
+ t.objectProperty(t.identifier('schema'), t.stringLiteral(table.schema)),
143
+ t.objectProperty(t.identifier('name'), t.stringLiteral(table.name)),
144
+ t.objectProperty(t.identifier('qualifiedName'), t.stringLiteral(qualified)),
145
+ t.objectProperty(t.identifier('columns'), t.arrayExpression(table.columns.map(column => t.stringLiteral(column.name)))),
146
+ t.objectProperty(t.identifier('primaryKey'), t.arrayExpression(table.primaryKey.map(name => t.stringLiteral(name)))),
147
+ t.objectProperty(t.identifier('columnByField'), t.objectExpression(table.columns.map(column => t.objectProperty(objectKey(column.propertyName), t.stringLiteral(column.name)))))
148
+ ])));
149
+ withJsDoc(metadata, `Column metadata for \`${qualified}\`.`);
150
+ statements.push(metadata);
151
+ // Decoders.
152
+ statements.push(withJsDoc(decoderFunction(table, `decode${pascal}`, pascal, column => column.propertyName, usage), `Decode an untrusted camelCase value (a wire envelope, a parsed body) into \`${pascal}\`.\n *\n * Throws \`CoerceError\` naming the offending field when a required column is\n * missing or of the wrong shape.`));
153
+ statements.push(withJsDoc(decoderFunction(table, `decode${pascal}Row`, rowTypeName, column => column.name, usage), `Decode an untrusted snake_case database row into \`${rowTypeName}\`.`));
154
+ // Row -> application converter.
155
+ const rowParam = t.identifier('row');
156
+ rowParam.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(rowTypeName)));
157
+ const fromRowFn = t.arrowFunctionExpression([rowParam], t.objectExpression(table.columns.map(column => t.objectProperty(objectKey(column.propertyName), member('row', column.name)))));
158
+ fromRowFn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(pascal)));
159
+ const fromRowName = `${toCamelCase(table.name)}FromRow`;
160
+ statements.push(withJsDoc(exportConst(fromRowName, fromRowFn), `Convert a decoded \`${rowTypeName}\` into the camelCase application shape.`));
161
+ // unknown row -> application decoder.
162
+ const decodeFromRowValue = t.identifier('value');
163
+ decodeFromRowValue.typeAnnotation = t.tsTypeAnnotation(t.tsUnknownKeyword());
164
+ const decodeFromRowLabel = t.assignmentPattern(t.identifier('label'), t.stringLiteral(qualified));
165
+ const decodeFromRowFn = t.arrowFunctionExpression([decodeFromRowValue, decodeFromRowLabel], t.callExpression(t.identifier(fromRowName), [
166
+ t.callExpression(t.identifier(`decode${pascal}Row`), [t.identifier('value'), t.identifier('label')])
167
+ ]));
168
+ decodeFromRowFn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(pascal)));
169
+ statements.push(withJsDoc(exportConst(`decode${pascal}FromRow`, decodeFromRowFn), `Decode an untrusted snake_case database row straight to \`${pascal}\`.`));
170
+ // Serializer: Partial application shape -> Partial row shape.
171
+ const patchParam = t.identifier('patch');
172
+ patchParam.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Partial'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(pascal))])));
173
+ const partialRowType = t.tsTypeReference(t.identifier('Partial'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(rowTypeName))]));
174
+ const rowDecl = t.variableDeclaration('const', [
175
+ t.variableDeclarator(Object.assign(t.identifier('row'), {
176
+ typeAnnotation: t.tsTypeAnnotation(partialRowType)
177
+ }), t.objectExpression([]))
178
+ ]);
179
+ 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)))));
180
+ const serializeFn = t.arrowFunctionExpression([patchParam], t.blockStatement([rowDecl, ...assignments, t.returnStatement(t.identifier('row'))]));
181
+ serializeFn.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Partial'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(rowTypeName))])));
182
+ 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.`));
183
+ // Imports, now that usage is known.
184
+ const imports = [];
185
+ if (usage.coerceImports.size > 0) {
186
+ imports.push(namedImport([...usage.coerceImports].sort(), '@constructive-io/coerce'));
187
+ }
188
+ if (usage.enumImports.size > 0) {
189
+ const typeImports = new Set(table.columns
190
+ .filter(column => column.scalar === 'enum')
191
+ .map(column => enumTypeName(column.enumName)));
192
+ imports.push(namedImport([...usage.enumImports, ...typeImports].sort(), './enums'));
193
+ }
194
+ return generateCode([...imports, ...statements]);
195
+ };
@@ -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
- import { Logger } from '@pgpmjs/logger';
2
- import { promises as fs } from 'fs';
3
- import path from 'path';
4
- import { getPgPool } from 'pg-cache';
5
- import { getPgEnvOptions } from 'pg-env';
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';