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/index.js
CHANGED
|
@@ -1,74 +1,19 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
await fs_1.promises.mkdir(outputDir, { recursive: true });
|
|
24
|
-
// Write each file to its corresponding path
|
|
25
|
-
for (const [filePath, content] of Object.entries(fileTree)) {
|
|
26
|
-
const fullPath = path_1.default.join(outputDir, filePath);
|
|
27
|
-
// Ensure the directory for the file exists
|
|
28
|
-
const dirName = path_1.default.dirname(fullPath);
|
|
29
|
-
await fs_1.promises.mkdir(dirName, { recursive: true });
|
|
30
|
-
// Write the file content
|
|
31
|
-
await fs_1.promises.writeFile(fullPath, content, 'utf8');
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
catch (error) {
|
|
35
|
-
log.error(`Failed to write files to ${outputDir}:`, error);
|
|
36
|
-
throw error;
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
(async () => {
|
|
40
|
-
const env = (0, pg_env_1.getPgEnvOptions)();
|
|
41
|
-
const pool = (0, pg_cache_1.getPgPool)(env);
|
|
42
|
-
const options = {
|
|
43
|
-
// @ts-ignore
|
|
44
|
-
client: pool, // hope this is ok?
|
|
45
|
-
introspectionOptions: {
|
|
46
|
-
pgLegacyFunctionsOnly: false,
|
|
47
|
-
pgIgnoreRBAC: true,
|
|
48
|
-
},
|
|
49
|
-
namespacesToIntrospect: ['metaschema_public'],
|
|
50
|
-
includeExtensions: false,
|
|
51
|
-
};
|
|
52
|
-
const outputDirectory = path_1.default.join(__dirname, '../../../__fixtures__/output');
|
|
53
|
-
try {
|
|
54
|
-
// Clean the output directory
|
|
55
|
-
await fs_1.promises.rm(outputDirectory, { recursive: true, force: true });
|
|
56
|
-
log.info(`Cleaned output directory: ${outputDirectory}`);
|
|
57
|
-
// Fetch introspection rows
|
|
58
|
-
const rows = await (0, introspect_1.default)(options);
|
|
59
|
-
log.info('Introspection Rows Fetched:', rows);
|
|
60
|
-
// Generate TypeScript code
|
|
61
|
-
const codegenOptions = {
|
|
62
|
-
includeTimestamps: true,
|
|
63
|
-
includeUUID: true,
|
|
64
|
-
};
|
|
65
|
-
const generatedCode = (0, codegen_1.generateCodeTree)(rows, codegenOptions);
|
|
66
|
-
log.info('Generated TypeScript Code Tree:', generatedCode);
|
|
67
|
-
// Write the generated code to files
|
|
68
|
-
await writeGeneratedFiles(outputDirectory, generatedCode);
|
|
69
|
-
log.info(`Generated files written to ${outputDirectory}`);
|
|
70
|
-
}
|
|
71
|
-
catch (error) {
|
|
72
|
-
log.error('Failed to fetch introspection rows or generate code:', error);
|
|
73
|
-
}
|
|
74
|
-
})();
|
|
3
|
+
exports.buildIr = exports.writeFileTree = exports.isClean = exports.generate = exports.emitFileTree = exports.checkFileTree = exports.emitRecordModule = exports.emitEnumsModule = exports.tableFileName = exports.emitSchemaIndex = exports.emitRootIndex = void 0;
|
|
4
|
+
var barrel_1 = require("./emit/barrel");
|
|
5
|
+
Object.defineProperty(exports, "emitRootIndex", { enumerable: true, get: function () { return barrel_1.emitRootIndex; } });
|
|
6
|
+
Object.defineProperty(exports, "emitSchemaIndex", { enumerable: true, get: function () { return barrel_1.emitSchemaIndex; } });
|
|
7
|
+
Object.defineProperty(exports, "tableFileName", { enumerable: true, get: function () { return barrel_1.tableFileName; } });
|
|
8
|
+
var enums_1 = require("./emit/enums");
|
|
9
|
+
Object.defineProperty(exports, "emitEnumsModule", { enumerable: true, get: function () { return enums_1.emitEnumsModule; } });
|
|
10
|
+
var record_1 = require("./emit/record");
|
|
11
|
+
Object.defineProperty(exports, "emitRecordModule", { enumerable: true, get: function () { return record_1.emitRecordModule; } });
|
|
12
|
+
var generate_1 = require("./generate");
|
|
13
|
+
Object.defineProperty(exports, "checkFileTree", { enumerable: true, get: function () { return generate_1.checkFileTree; } });
|
|
14
|
+
Object.defineProperty(exports, "emitFileTree", { enumerable: true, get: function () { return generate_1.emitFileTree; } });
|
|
15
|
+
Object.defineProperty(exports, "generate", { enumerable: true, get: function () { return generate_1.generate; } });
|
|
16
|
+
Object.defineProperty(exports, "isClean", { enumerable: true, get: function () { return generate_1.isClean; } });
|
|
17
|
+
Object.defineProperty(exports, "writeFileTree", { enumerable: true, get: function () { return generate_1.writeFileTree; } });
|
|
18
|
+
var ir_1 = require("./ir");
|
|
19
|
+
Object.defineProperty(exports, "buildIr", { enumerable: true, get: function () { return ir_1.buildIr; } });
|
package/ir.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { PgIntrospectionResultByKind } from 'introspectron';
|
|
2
|
+
/** The TypeScript-facing shape of a PostgreSQL scalar. */
|
|
3
|
+
export type IrScalar = 'boolean' | 'integer' | 'bigint' | 'number' | 'string' | 'uuid' | 'timestamp' | 'json' | 'enum' | 'unknown';
|
|
4
|
+
export interface IrEnum {
|
|
5
|
+
schema: string;
|
|
6
|
+
/** The PostgreSQL enum type name, e.g. `run_status`. */
|
|
7
|
+
name: string;
|
|
8
|
+
values: string[];
|
|
9
|
+
}
|
|
10
|
+
export interface IrColumn {
|
|
11
|
+
/** The column name as it appears in the database, e.g. `thread_id`. */
|
|
12
|
+
name: string;
|
|
13
|
+
/** The camelCase application-facing property name, e.g. `threadId`. */
|
|
14
|
+
propertyName: string;
|
|
15
|
+
ordinal: number;
|
|
16
|
+
scalar: IrScalar;
|
|
17
|
+
isArray: boolean;
|
|
18
|
+
nullable: boolean;
|
|
19
|
+
hasDefault: boolean;
|
|
20
|
+
/** The declared PostgreSQL type name, e.g. `timestamptz`, `_text`. */
|
|
21
|
+
pgType: string;
|
|
22
|
+
/** For `scalar: 'enum'`, the enum type name within the same IR. */
|
|
23
|
+
enumName?: string;
|
|
24
|
+
comment?: string;
|
|
25
|
+
}
|
|
26
|
+
export type IrTableKind = 'table' | 'partitioned table' | 'view' | 'materialized view' | 'foreign table';
|
|
27
|
+
export interface IrTable {
|
|
28
|
+
schema: string;
|
|
29
|
+
name: string;
|
|
30
|
+
kind: IrTableKind;
|
|
31
|
+
columns: IrColumn[];
|
|
32
|
+
primaryKey: string[];
|
|
33
|
+
comment?: string;
|
|
34
|
+
}
|
|
35
|
+
export interface IrSchema {
|
|
36
|
+
name: string;
|
|
37
|
+
tables: IrTable[];
|
|
38
|
+
enums: IrEnum[];
|
|
39
|
+
}
|
|
40
|
+
export interface Ir {
|
|
41
|
+
schemas: IrSchema[];
|
|
42
|
+
}
|
|
43
|
+
export interface BuildIrOptions {
|
|
44
|
+
/** The schemas to include, in the order their modules should be emitted. */
|
|
45
|
+
schemas: string[];
|
|
46
|
+
}
|
|
47
|
+
export declare const buildIr: (introspection: PgIntrospectionResultByKind, { schemas }: BuildIrOptions) => Ir;
|
package/ir.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildIr = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Normalized intermediate representation of a database schema.
|
|
6
|
+
*
|
|
7
|
+
* `buildIr` reduces an introspectron result to the shape every emitter
|
|
8
|
+
* consumes: tables with resolved column scalars, primary keys, and the enums
|
|
9
|
+
* they reference. Domains are unwrapped to their base type; arrays carry
|
|
10
|
+
* their element scalar.
|
|
11
|
+
*/
|
|
12
|
+
const inflekt_1 = require("inflekt");
|
|
13
|
+
const TABLE_KINDS = {
|
|
14
|
+
r: 'table',
|
|
15
|
+
p: 'partitioned table',
|
|
16
|
+
v: 'view',
|
|
17
|
+
m: 'materialized view',
|
|
18
|
+
f: 'foreign table'
|
|
19
|
+
};
|
|
20
|
+
const SCALAR_BY_TYPE_NAME = {
|
|
21
|
+
bool: 'boolean',
|
|
22
|
+
int2: 'integer',
|
|
23
|
+
int4: 'integer',
|
|
24
|
+
int8: 'bigint',
|
|
25
|
+
float4: 'number',
|
|
26
|
+
float8: 'number',
|
|
27
|
+
numeric: 'number',
|
|
28
|
+
money: 'number',
|
|
29
|
+
text: 'string',
|
|
30
|
+
varchar: 'string',
|
|
31
|
+
bpchar: 'string',
|
|
32
|
+
char: 'string',
|
|
33
|
+
name: 'string',
|
|
34
|
+
citext: 'string',
|
|
35
|
+
inet: 'string',
|
|
36
|
+
cidr: 'string',
|
|
37
|
+
macaddr: 'string',
|
|
38
|
+
macaddr8: 'string',
|
|
39
|
+
interval: 'string',
|
|
40
|
+
time: 'string',
|
|
41
|
+
timetz: 'string',
|
|
42
|
+
bit: 'string',
|
|
43
|
+
varbit: 'string',
|
|
44
|
+
xml: 'string',
|
|
45
|
+
ltree: 'string',
|
|
46
|
+
date: 'timestamp',
|
|
47
|
+
timestamp: 'timestamp',
|
|
48
|
+
timestamptz: 'timestamp',
|
|
49
|
+
uuid: 'uuid',
|
|
50
|
+
json: 'json',
|
|
51
|
+
jsonb: 'json'
|
|
52
|
+
};
|
|
53
|
+
const resolveType = (type, typeById) => {
|
|
54
|
+
if (type.type === 'd' && type.domainBaseTypeId) {
|
|
55
|
+
const base = typeById.get(type.domainBaseTypeId);
|
|
56
|
+
if (base)
|
|
57
|
+
return resolveType(base, typeById);
|
|
58
|
+
}
|
|
59
|
+
if (type.isPgArray && type.arrayItemTypeId) {
|
|
60
|
+
const element = typeById.get(type.arrayItemTypeId);
|
|
61
|
+
if (element) {
|
|
62
|
+
const resolved = resolveType(element, typeById);
|
|
63
|
+
// Arrays of arrays and arrays of unresolvable elements degrade to a
|
|
64
|
+
// plain `unknown` scalar rather than pretend to a typed element.
|
|
65
|
+
if (resolved.isArray || resolved.scalar === 'unknown') {
|
|
66
|
+
return { scalar: 'unknown', isArray: false };
|
|
67
|
+
}
|
|
68
|
+
return { ...resolved, isArray: true };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (type.type === 'e' && Array.isArray(type.enumVariants) && type.enumVariants.length > 0) {
|
|
72
|
+
return { scalar: 'enum', isArray: false, enumType: type };
|
|
73
|
+
}
|
|
74
|
+
const scalar = SCALAR_BY_TYPE_NAME[type.name];
|
|
75
|
+
return { scalar: scalar ?? 'unknown', isArray: false };
|
|
76
|
+
};
|
|
77
|
+
const buildIr = (introspection, { schemas }) => {
|
|
78
|
+
const typeById = new Map(introspection.type.map(type => [type.id, type]));
|
|
79
|
+
const namespaceNameById = new Map(introspection.namespace.map(namespace => [namespace.id, namespace.name]));
|
|
80
|
+
const attributesByClassId = new Map();
|
|
81
|
+
for (const attribute of introspection.attribute) {
|
|
82
|
+
const list = attributesByClassId.get(attribute.classId);
|
|
83
|
+
if (list)
|
|
84
|
+
list.push(attribute);
|
|
85
|
+
else
|
|
86
|
+
attributesByClassId.set(attribute.classId, [attribute]);
|
|
87
|
+
}
|
|
88
|
+
const primaryKeyByClassId = new Map();
|
|
89
|
+
for (const constraint of introspection.constraint) {
|
|
90
|
+
if (constraint.type === 'p')
|
|
91
|
+
primaryKeyByClassId.set(constraint.classId, constraint);
|
|
92
|
+
}
|
|
93
|
+
const irSchemas = schemas.map(schemaName => {
|
|
94
|
+
const enums = [];
|
|
95
|
+
const enumNames = new Set();
|
|
96
|
+
const registerEnum = (enumType) => {
|
|
97
|
+
const owningSchema = namespaceNameById.get(enumType.namespaceId) ?? schemaName;
|
|
98
|
+
if (!enumNames.has(enumType.name)) {
|
|
99
|
+
enumNames.add(enumType.name);
|
|
100
|
+
enums.push({
|
|
101
|
+
schema: owningSchema,
|
|
102
|
+
name: enumType.name,
|
|
103
|
+
values: enumType.enumVariants ?? []
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return enumType.name;
|
|
107
|
+
};
|
|
108
|
+
const tables = introspection.class
|
|
109
|
+
.filter((cls) => cls.namespaceName === schemaName && cls.classKind !== undefined && cls.classKind in TABLE_KINDS)
|
|
110
|
+
.map((cls) => {
|
|
111
|
+
const attributes = (attributesByClassId.get(cls.id) ?? [])
|
|
112
|
+
.filter(attribute => attribute.num > 0)
|
|
113
|
+
.sort((a, b) => a.num - b.num);
|
|
114
|
+
const primaryKeyConstraint = primaryKeyByClassId.get(cls.id);
|
|
115
|
+
const primaryKeyNums = new Set(primaryKeyConstraint?.keyAttributeNums ?? []);
|
|
116
|
+
const columns = attributes.map((attribute) => {
|
|
117
|
+
const type = typeById.get(attribute.typeId);
|
|
118
|
+
const resolved = type
|
|
119
|
+
? resolveType(type, typeById)
|
|
120
|
+
: { scalar: 'unknown', isArray: false };
|
|
121
|
+
const column = {
|
|
122
|
+
name: attribute.name,
|
|
123
|
+
propertyName: (0, inflekt_1.toCamelCase)(attribute.name),
|
|
124
|
+
ordinal: attribute.num,
|
|
125
|
+
scalar: resolved.scalar,
|
|
126
|
+
isArray: resolved.isArray,
|
|
127
|
+
nullable: attribute.isNotNull !== true,
|
|
128
|
+
hasDefault: attribute.hasDefault === true || (attribute.identity ?? '') !== '',
|
|
129
|
+
pgType: type?.name ?? 'unknown'
|
|
130
|
+
};
|
|
131
|
+
if (resolved.enumType)
|
|
132
|
+
column.enumName = registerEnum(resolved.enumType);
|
|
133
|
+
if (attribute.description)
|
|
134
|
+
column.comment = attribute.description;
|
|
135
|
+
return column;
|
|
136
|
+
});
|
|
137
|
+
const table = {
|
|
138
|
+
schema: schemaName,
|
|
139
|
+
name: cls.name,
|
|
140
|
+
kind: TABLE_KINDS[cls.classKind],
|
|
141
|
+
columns,
|
|
142
|
+
primaryKey: attributes
|
|
143
|
+
.filter(attribute => primaryKeyNums.has(attribute.num))
|
|
144
|
+
.map(attribute => attribute.name)
|
|
145
|
+
};
|
|
146
|
+
if (cls.description)
|
|
147
|
+
table.comment = cls.description;
|
|
148
|
+
return table;
|
|
149
|
+
})
|
|
150
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
151
|
+
enums.sort((a, b) => a.name.localeCompare(b.name));
|
|
152
|
+
return { name: schemaName, tables, enums };
|
|
153
|
+
});
|
|
154
|
+
return { schemas: irSchemas };
|
|
155
|
+
};
|
|
156
|
+
exports.buildIr = buildIr;
|
package/package.json
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pg-codegen",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.11.0",
|
|
4
4
|
"author": "Constructive <developers@constructive.io>",
|
|
5
|
-
"description": "PostgreSQL
|
|
5
|
+
"description": "Type-safe TypeScript codegen from live PostgreSQL schemas: row types, coerce-backed decoders, serializers, table metadata, and enum unions",
|
|
6
6
|
"main": "index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"pg-codegen": "cli.js"
|
|
9
|
+
},
|
|
7
10
|
"module": "esm/index.js",
|
|
8
11
|
"types": "index.d.ts",
|
|
9
12
|
"homepage": "https://github.com/constructive-io/constructive",
|
|
@@ -25,7 +28,7 @@
|
|
|
25
28
|
"prepack": "npm run build",
|
|
26
29
|
"build": "makage build",
|
|
27
30
|
"build:dev": "makage build --dev",
|
|
28
|
-
"dev": "ts-node ./src/
|
|
31
|
+
"dev": "ts-node ./src/cli.ts",
|
|
29
32
|
"lint": "eslint . --fix",
|
|
30
33
|
"test": "jest",
|
|
31
34
|
"test:watch": "jest --watch"
|
|
@@ -41,19 +44,17 @@
|
|
|
41
44
|
"dependencies": {
|
|
42
45
|
"@babel/generator": "^7.29.1",
|
|
43
46
|
"@babel/types": "^7.29.0",
|
|
44
|
-
"@
|
|
45
|
-
"@pgpmjs/server-utils": "^3.25.6",
|
|
46
|
-
"@pgpmjs/types": "^2.50.5",
|
|
47
|
+
"@constructive-io/coerce": "^0.3.0",
|
|
47
48
|
"inflekt": "^0.8.1",
|
|
49
|
+
"introspectron": "^5.12.0",
|
|
48
50
|
"pg": "^8.21.0",
|
|
49
|
-
"pg-
|
|
50
|
-
"pg-env": "^1.29.3",
|
|
51
|
-
"pgsql-test": "^5.10.9"
|
|
51
|
+
"pg-env": "^1.30.0"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@types/babel__generator": "^7.6.8",
|
|
55
55
|
"@types/pg": "^8.20.4",
|
|
56
|
-
"makage": "^0.3.0"
|
|
56
|
+
"makage": "^0.3.0",
|
|
57
|
+
"pgsql-test": "^5.11.0"
|
|
57
58
|
},
|
|
58
|
-
"gitHead": "
|
|
59
|
+
"gitHead": "06bf3edad0d1d1dba9b44f17b8c791de6768576d"
|
|
59
60
|
}
|
package/codegen/codegen.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { DatabaseObject } from '../types';
|
|
2
|
-
type CodegenOptions = {
|
|
3
|
-
includeTimestamps: boolean;
|
|
4
|
-
includeUUID: boolean;
|
|
5
|
-
};
|
|
6
|
-
export declare const generateCodeTree: (databaseObjects: DatabaseObject[], options: CodegenOptions) => Record<string, string>;
|
|
7
|
-
export {};
|
package/codegen/codegen.js
DELETED
|
@@ -1,162 +0,0 @@
|
|
|
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.generateCodeTree = void 0;
|
|
40
|
-
const generator_1 = __importDefault(require("@babel/generator"));
|
|
41
|
-
const t = __importStar(require("@babel/types"));
|
|
42
|
-
const inflekt_1 = require("inflekt");
|
|
43
|
-
const generateCodeTree = (databaseObjects, options) => {
|
|
44
|
-
const { includeTimestamps, includeUUID } = options;
|
|
45
|
-
const schemaFiles = {};
|
|
46
|
-
// Common types
|
|
47
|
-
const commonTypes = [];
|
|
48
|
-
if (includeTimestamps) {
|
|
49
|
-
commonTypes.push(t.exportNamedDeclaration(t.tsTypeAliasDeclaration(t.identifier('Timestamp'), null, t.tsStringKeyword())));
|
|
50
|
-
}
|
|
51
|
-
if (includeUUID) {
|
|
52
|
-
commonTypes.push(t.exportNamedDeclaration(t.tsTypeAliasDeclaration(t.identifier('UUID'), null, t.tsStringKeyword())));
|
|
53
|
-
}
|
|
54
|
-
schemaFiles['schemas/_common.ts'] = commonTypes;
|
|
55
|
-
// Classes & Interfaces per schema
|
|
56
|
-
databaseObjects.forEach((obj) => {
|
|
57
|
-
if (obj.kind === 'class' && obj.classKind === 'r') {
|
|
58
|
-
const schemaName = obj.namespaceName;
|
|
59
|
-
const pascalName = (0, inflekt_1.toPascalCase)(obj.name);
|
|
60
|
-
const interfaceFields = [];
|
|
61
|
-
const classFields = [];
|
|
62
|
-
const constructorBody = [];
|
|
63
|
-
const usedTypes = new Set();
|
|
64
|
-
databaseObjects.forEach((attr) => {
|
|
65
|
-
if (attr.kind === 'attribute' && attr.classId === obj.id) {
|
|
66
|
-
const fieldType = mapPostgresTypeToTSType(attr.typeId, attr.isNotNull);
|
|
67
|
-
const postgresType = mapPostgresTypeToIdentifier(attr.typeId);
|
|
68
|
-
if (postgresType)
|
|
69
|
-
usedTypes.add(postgresType);
|
|
70
|
-
interfaceFields.push(t.tsPropertySignature(t.identifier(attr.name), t.tsTypeAnnotation(fieldType)));
|
|
71
|
-
classFields.push(t.classProperty(t.identifier(attr.name), undefined, t.tsTypeAnnotation(fieldType)));
|
|
72
|
-
constructorBody.push(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier(attr.name)), t.memberExpression(t.identifier('data'), t.identifier(attr.name)))));
|
|
73
|
-
}
|
|
74
|
-
});
|
|
75
|
-
const interfaceDeclaration = t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(pascalName), null, [], t.tsInterfaceBody(interfaceFields)));
|
|
76
|
-
const data = t.identifier('data');
|
|
77
|
-
data.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(pascalName)));
|
|
78
|
-
const classImplements = t.tsExpressionWithTypeArguments(t.identifier(pascalName));
|
|
79
|
-
const classDeclaration = t.exportNamedDeclaration(t.classDeclaration(t.identifier(pascalName), null, t.classBody([
|
|
80
|
-
...classFields,
|
|
81
|
-
t.classMethod('constructor', t.identifier('constructor'), [data], t.blockStatement(constructorBody))
|
|
82
|
-
])));
|
|
83
|
-
classDeclaration.declaration.implements = [classImplements];
|
|
84
|
-
const filePath = `schemas/${schemaName}.ts`;
|
|
85
|
-
if (!schemaFiles[filePath])
|
|
86
|
-
schemaFiles[filePath] = [];
|
|
87
|
-
if (usedTypes.size > 0) {
|
|
88
|
-
const existingImports = schemaFiles[filePath].find((s) => t.isImportDeclaration(s) && s.source.value === './_common');
|
|
89
|
-
if (!existingImports) {
|
|
90
|
-
schemaFiles[filePath].unshift(t.importDeclaration(Array.from(usedTypes).map((type) => t.importSpecifier(t.identifier(type), t.identifier(type))), t.stringLiteral('./_common')));
|
|
91
|
-
}
|
|
92
|
-
else {
|
|
93
|
-
const current = new Set(existingImports.specifiers.map((s) => s.local.name));
|
|
94
|
-
Array.from(usedTypes).forEach((type) => {
|
|
95
|
-
if (!current.has(type)) {
|
|
96
|
-
existingImports.specifiers.push(t.importSpecifier(t.identifier(type), t.identifier(type)));
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
schemaFiles[filePath].push(interfaceDeclaration, classDeclaration);
|
|
102
|
-
}
|
|
103
|
-
});
|
|
104
|
-
// index.ts exports
|
|
105
|
-
const indexFileStatements = [];
|
|
106
|
-
Object.keys(schemaFiles).forEach((filePath) => {
|
|
107
|
-
const schemaName = filePath.replace('schemas/', '').replace('.ts', '');
|
|
108
|
-
if (schemaName === '_common')
|
|
109
|
-
return;
|
|
110
|
-
if (schemaName === 'public') {
|
|
111
|
-
indexFileStatements.push(t.exportAllDeclaration(t.stringLiteral(`./${filePath.replace('.ts', '')}`)));
|
|
112
|
-
}
|
|
113
|
-
else {
|
|
114
|
-
indexFileStatements.push(t.importDeclaration([t.importNamespaceSpecifier(t.identifier(schemaName))], t.stringLiteral(`./${filePath.replace('.ts', '')}`)), t.exportNamedDeclaration(null, [
|
|
115
|
-
t.exportSpecifier(t.identifier(schemaName), t.identifier(schemaName))
|
|
116
|
-
]));
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
const fileTree = {};
|
|
120
|
-
Object.entries(schemaFiles).forEach(([filePath, statements]) => {
|
|
121
|
-
// @ts-ignore
|
|
122
|
-
fileTree[filePath] = (0, generator_1.default)(t.program(statements)).code;
|
|
123
|
-
});
|
|
124
|
-
// @ts-ignore
|
|
125
|
-
fileTree['index.ts'] = (0, generator_1.default)(t.program(indexFileStatements)).code;
|
|
126
|
-
return fileTree;
|
|
127
|
-
};
|
|
128
|
-
exports.generateCodeTree = generateCodeTree;
|
|
129
|
-
const mapPostgresTypeToTSType = (typeId, isNotNull) => {
|
|
130
|
-
const optionalType = (type) => isNotNull ? type : t.tsUnionType([type, t.tsNullKeyword()]);
|
|
131
|
-
switch (typeId) {
|
|
132
|
-
case '20': // BIGINT
|
|
133
|
-
case '21': // SMALLINT
|
|
134
|
-
case '23': // INTEGER
|
|
135
|
-
case '1700': // NUMERIC
|
|
136
|
-
return optionalType(t.tsNumberKeyword());
|
|
137
|
-
case '25': // TEXT
|
|
138
|
-
case '1043': // VARCHAR
|
|
139
|
-
return optionalType(t.tsStringKeyword());
|
|
140
|
-
case '1114': // TIMESTAMP
|
|
141
|
-
case '1184': // TIMESTAMPTZ
|
|
142
|
-
return optionalType(t.tsTypeReference(t.identifier('Timestamp')));
|
|
143
|
-
case '2950': // UUID
|
|
144
|
-
return optionalType(t.tsTypeReference(t.identifier('UUID')));
|
|
145
|
-
case '16': // BOOLEAN
|
|
146
|
-
return optionalType(t.tsBooleanKeyword());
|
|
147
|
-
default:
|
|
148
|
-
return optionalType(t.tsAnyKeyword());
|
|
149
|
-
}
|
|
150
|
-
};
|
|
151
|
-
// Map Postgres type OIDs to type names for imports
|
|
152
|
-
const mapPostgresTypeToIdentifier = (typeId) => {
|
|
153
|
-
switch (typeId) {
|
|
154
|
-
case '1114': // TIMESTAMP
|
|
155
|
-
case '1184': // TIMESTAMPTZ
|
|
156
|
-
return 'Timestamp';
|
|
157
|
-
case '2950': // UUID
|
|
158
|
-
return 'UUID';
|
|
159
|
-
default:
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
};
|
package/codegen/namespaces.d.ts
DELETED
package/codegen/namespaces.js
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
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.generateCode = void 0;
|
|
40
|
-
const generator_1 = __importDefault(require("@babel/generator"));
|
|
41
|
-
const t = __importStar(require("@babel/types"));
|
|
42
|
-
const generateCode = (databaseObjects, options) => {
|
|
43
|
-
const { includeTimestamps, includeUUID } = options;
|
|
44
|
-
const namespaces = {};
|
|
45
|
-
// Organize objects by namespace
|
|
46
|
-
databaseObjects.forEach((obj) => {
|
|
47
|
-
if (obj.kind === 'namespace') {
|
|
48
|
-
namespaces[obj.name] = [];
|
|
49
|
-
}
|
|
50
|
-
});
|
|
51
|
-
// Generate interfaces for tables (Class objects with kind 'r')
|
|
52
|
-
databaseObjects.forEach((obj) => {
|
|
53
|
-
if (obj.kind === 'class' && obj.classKind === 'r') {
|
|
54
|
-
const namespace = obj.namespaceName;
|
|
55
|
-
const fields = [];
|
|
56
|
-
// Find attributes for the class
|
|
57
|
-
databaseObjects.forEach((attr) => {
|
|
58
|
-
if (attr.kind === 'attribute' && attr.classId === obj.id) {
|
|
59
|
-
fields.push(t.tsPropertySignature(t.identifier(attr.name), t.tsTypeAnnotation(mapPostgresTypeToTSType(attr.typeId, attr.isNotNull))));
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
// Create the interface declaration
|
|
63
|
-
const interfaceDeclaration = t.tsInterfaceDeclaration(t.identifier(obj.name), null, [], t.tsInterfaceBody(fields));
|
|
64
|
-
// Add to the namespace
|
|
65
|
-
if (namespaces[namespace]) {
|
|
66
|
-
namespaces[namespace].push(interfaceDeclaration);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
});
|
|
70
|
-
// Generate the final AST
|
|
71
|
-
const programBody = [];
|
|
72
|
-
if (includeTimestamps) {
|
|
73
|
-
programBody.push(t.tsTypeAliasDeclaration(t.identifier('Timestamp'), null, t.tsStringKeyword()));
|
|
74
|
-
}
|
|
75
|
-
if (includeUUID) {
|
|
76
|
-
programBody.push(t.tsTypeAliasDeclaration(t.identifier('UUID'), null, t.tsStringKeyword()));
|
|
77
|
-
}
|
|
78
|
-
Object.keys(namespaces).forEach((namespace) => {
|
|
79
|
-
const namespaceDeclaration = t.tsModuleDeclaration(t.identifier(namespace), t.tsModuleBlock(namespaces[namespace]));
|
|
80
|
-
namespaceDeclaration.declare = true;
|
|
81
|
-
programBody.push(namespaceDeclaration);
|
|
82
|
-
});
|
|
83
|
-
const program = t.program(programBody);
|
|
84
|
-
// Generate the code
|
|
85
|
-
return (0, generator_1.default)(program).code;
|
|
86
|
-
};
|
|
87
|
-
exports.generateCode = generateCode;
|
|
88
|
-
// Map Postgres type OIDs to TypeScript types
|
|
89
|
-
const mapPostgresTypeToTSType = (typeId, isNotNull) => {
|
|
90
|
-
const optionalType = (type) => isNotNull ? type : t.tsUnionType([type, t.tsNullKeyword()]);
|
|
91
|
-
switch (typeId) {
|
|
92
|
-
case '20': // BIGINT
|
|
93
|
-
case '21': // SMALLINT
|
|
94
|
-
case '23': // INTEGER
|
|
95
|
-
case '1700': // NUMERIC
|
|
96
|
-
return optionalType(t.tsNumberKeyword());
|
|
97
|
-
case '25': // TEXT
|
|
98
|
-
case '1043': // VARCHAR
|
|
99
|
-
return optionalType(t.tsStringKeyword());
|
|
100
|
-
case '1114': // TIMESTAMP
|
|
101
|
-
case '1184': // TIMESTAMPTZ
|
|
102
|
-
return optionalType(t.tsTypeReference(t.identifier('Timestamp')));
|
|
103
|
-
case '2950': // UUID
|
|
104
|
-
return optionalType(t.tsTypeReference(t.identifier('UUID')));
|
|
105
|
-
case '16': // BOOLEAN
|
|
106
|
-
return optionalType(t.tsBooleanKeyword());
|
|
107
|
-
default:
|
|
108
|
-
return optionalType(t.tsAnyKeyword());
|
|
109
|
-
}
|
|
110
|
-
};
|