pg-codegen 2.1.5

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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Hyperweb <developers@hyperweb.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ # pg-codegen
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/launchql/launchql/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/launchql/launchql/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/pg-codegen"><img height="20" src="https://img.shields.io/github/package-json/v/launchql/launchql?filename=packages%2Fcodegen%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ Generate fully-typed TypeScript classes and interfaces from a live PostgreSQL schema via introspection.
16
+
17
+ > Converts your PostgreSQL tables into idiomatic TypeScript code — fast, predictable, and schema-aware.
18
+
19
+ ---
20
+
21
+ ## ✨ Features
22
+
23
+ 🧠 **Intelligent Introspection**
24
+ Pulls schema structure using native SQL introspection — no GraphQL required.
25
+
26
+ 🧱 **Interface + Class Output**
27
+ Generates matching `interface` + `class` pairs for each table using PascalCase naming.
28
+
29
+ 🧹 **Schema-Aware Output**
30
+ Writes files into `schemas/<schema>.ts`, grouped and re-exported from an `index.ts`.
31
+
32
+ 🔗 **Type Mapping for Postgres Primitives**
33
+ Supports `UUID`, `Timestamp`, `Boolean`, `Text`, `Int`, and nullable detection.
34
+
35
+ 🪴 **Auto Imports from \_common.ts**
36
+ Deduplicates and imports shared scalar types intelligently.
37
+
38
+ 🧪 **Snapshot-Ready for Testing**
39
+ Babel AST-based output is stable and perfect for inline snapshot tests.
40
+
41
+ ## 🛠️ Install
42
+
43
+ ```bash
44
+ npm install pg-codegen
45
+ ```
46
+
47
+ ## 🚀 Usage
48
+
49
+ ```ts
50
+ import { generateCodeTree } from 'pg-codegen';
51
+ import getIntrospectionRows from 'pg-codegen/introspect';
52
+
53
+ const rows = await getIntrospectionRows({
54
+ client: pgClient,
55
+ introspectionOptions: {
56
+ pgLegacyFunctionsOnly: false,
57
+ pgIgnoreRBAC: true
58
+ },
59
+ namespacesToIntrospect: ['my_schema'],
60
+ includeExtensions: false
61
+ });
62
+
63
+ const output = generateCodeTree(rows, {
64
+ includeUUID: true,
65
+ includeTimestamps: true
66
+ });
67
+
68
+ // Example: write output['schemas/my_schema.ts'] to disk
69
+ ```
70
+
71
+ ## 📟 Example Output
72
+
73
+ ```ts
74
+ // schemas/_common.ts
75
+ export type UUID = string;
76
+ export type Timestamp = string;
77
+
78
+ // schemas/my_schema.ts
79
+ import { UUID, Timestamp } from './_common';
80
+
81
+ export interface Users {
82
+ id: UUID;
83
+ email: string;
84
+ created_at: Timestamp;
85
+ }
86
+
87
+ export class Users implements Users {
88
+ id: UUID;
89
+ email: string;
90
+ created_at: Timestamp;
91
+
92
+ constructor(data: Users) {
93
+ this.id = data.id;
94
+ this.email = data.email;
95
+ this.created_at = data.created_at;
96
+ }
97
+ }
98
+ ```
99
+
100
+ ## Related LaunchQL Tooling
101
+
102
+ ### 🧪 Testing
103
+
104
+ * [launchql/pgsql-test](https://github.com/launchql/launchql/tree/main/packages/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
105
+ * [launchql/graphile-test](https://github.com/launchql/launchql/tree/main/packages/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
106
+ * [launchql/pg-query-context](https://github.com/launchql/launchql/tree/main/packages/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
107
+
108
+ ### 🧠 Parsing & AST
109
+
110
+ * [launchql/pgsql-parser](https://github.com/launchql/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
111
+ * [launchql/libpg-query-node](https://github.com/launchql/libpg-query-node): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
112
+ * [launchql/pg-proto-parser](https://github.com/launchql/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
113
+ * [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
114
+ * [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
115
+ * [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
116
+ * [launchql/pg-ast](https://github.com/launchql/launchql/tree/main/packages/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
117
+
118
+ ### 🚀 API & Dev Tools
119
+
120
+ * [launchql/server](https://github.com/launchql/launchql/tree/main/packages/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
121
+ * [launchql/explorer](https://github.com/launchql/launchql/tree/main/packages/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
122
+
123
+ ### 🔁 Streaming & Uploads
124
+
125
+ * [launchql/s3-streamer](https://github.com/launchql/launchql/tree/main/packages/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
126
+ * [launchql/etag-hash](https://github.com/launchql/launchql/tree/main/packages/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
127
+ * [launchql/etag-stream](https://github.com/launchql/launchql/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
128
+ * [launchql/uuid-hash](https://github.com/launchql/launchql/tree/main/packages/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
129
+ * [launchql/uuid-stream](https://github.com/launchql/launchql/tree/main/packages/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
130
+ * [launchql/upload-names](https://github.com/launchql/launchql/tree/main/packages/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
131
+
132
+ ### 🧰 CLI & Codegen
133
+
134
+ * [@launchql/cli](https://github.com/launchql/launchql/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing LaunchQL projects—supports database scaffolding, migrations, seeding, code generation, and automation.
135
+ * [launchql/launchql-gen](https://github.com/launchql/launchql/tree/main/packages/launchql-gen): **✨ Auto-generated GraphQL** mutations and queries dynamically built from introspected schema data.
136
+ * [@launchql/query-builder](https://github.com/launchql/launchql/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
137
+ * [@launchql/query](https://github.com/launchql/launchql/tree/main/packages/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
138
+
139
+ ## Disclaimer
140
+
141
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
142
+
143
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
144
+
@@ -0,0 +1,7 @@
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 {};
@@ -0,0 +1,152 @@
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 (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.generateCodeTree = void 0;
30
+ const generator_1 = __importDefault(require("@babel/generator"));
31
+ const t = __importStar(require("@babel/types"));
32
+ const generateCodeTree = (databaseObjects, options) => {
33
+ const { includeTimestamps, includeUUID } = options;
34
+ const schemaFiles = {};
35
+ // Common types
36
+ const commonTypes = [];
37
+ if (includeTimestamps) {
38
+ commonTypes.push(t.exportNamedDeclaration(t.tsTypeAliasDeclaration(t.identifier('Timestamp'), null, t.tsStringKeyword())));
39
+ }
40
+ if (includeUUID) {
41
+ commonTypes.push(t.exportNamedDeclaration(t.tsTypeAliasDeclaration(t.identifier('UUID'), null, t.tsStringKeyword())));
42
+ }
43
+ schemaFiles['schemas/_common.ts'] = commonTypes;
44
+ // Classes & Interfaces per schema
45
+ databaseObjects.forEach((obj) => {
46
+ if (obj.kind === 'class' && obj.classKind === 'r') {
47
+ const schemaName = obj.namespaceName;
48
+ const pascalName = toPascalCase(obj.name);
49
+ const interfaceFields = [];
50
+ const classFields = [];
51
+ const constructorBody = [];
52
+ const usedTypes = new Set();
53
+ databaseObjects.forEach((attr) => {
54
+ if (attr.kind === 'attribute' && attr.classId === obj.id) {
55
+ const fieldType = mapPostgresTypeToTSType(attr.typeId, attr.isNotNull);
56
+ const postgresType = mapPostgresTypeToIdentifier(attr.typeId);
57
+ if (postgresType)
58
+ usedTypes.add(postgresType);
59
+ interfaceFields.push(t.tsPropertySignature(t.identifier(attr.name), t.tsTypeAnnotation(fieldType)));
60
+ classFields.push(t.classProperty(t.identifier(attr.name), undefined, t.tsTypeAnnotation(fieldType)));
61
+ constructorBody.push(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier(attr.name)), t.memberExpression(t.identifier('data'), t.identifier(attr.name)))));
62
+ }
63
+ });
64
+ const interfaceDeclaration = t.exportNamedDeclaration(t.tsInterfaceDeclaration(t.identifier(pascalName), null, [], t.tsInterfaceBody(interfaceFields)));
65
+ const data = t.identifier('data');
66
+ data.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(pascalName)));
67
+ const classImplements = t.tsExpressionWithTypeArguments(t.identifier(pascalName));
68
+ const classDeclaration = t.exportNamedDeclaration(t.classDeclaration(t.identifier(pascalName), null, t.classBody([
69
+ ...classFields,
70
+ t.classMethod('constructor', t.identifier('constructor'), [data], t.blockStatement(constructorBody))
71
+ ])));
72
+ classDeclaration.declaration.implements = [classImplements];
73
+ const filePath = `schemas/${schemaName}.ts`;
74
+ if (!schemaFiles[filePath])
75
+ schemaFiles[filePath] = [];
76
+ if (usedTypes.size > 0) {
77
+ const existingImports = schemaFiles[filePath].find((s) => t.isImportDeclaration(s) && s.source.value === './_common');
78
+ if (!existingImports) {
79
+ schemaFiles[filePath].unshift(t.importDeclaration(Array.from(usedTypes).map((type) => t.importSpecifier(t.identifier(type), t.identifier(type))), t.stringLiteral('./_common')));
80
+ }
81
+ else {
82
+ const current = new Set(existingImports.specifiers.map((s) => s.local.name));
83
+ Array.from(usedTypes).forEach((type) => {
84
+ if (!current.has(type)) {
85
+ existingImports.specifiers.push(t.importSpecifier(t.identifier(type), t.identifier(type)));
86
+ }
87
+ });
88
+ }
89
+ }
90
+ schemaFiles[filePath].push(interfaceDeclaration, classDeclaration);
91
+ }
92
+ });
93
+ // index.ts exports
94
+ const indexFileStatements = [];
95
+ Object.keys(schemaFiles).forEach((filePath) => {
96
+ const schemaName = filePath.replace('schemas/', '').replace('.ts', '');
97
+ if (schemaName === '_common')
98
+ return;
99
+ if (schemaName === 'public') {
100
+ indexFileStatements.push(t.exportAllDeclaration(t.stringLiteral(`./${filePath.replace('.ts', '')}`)));
101
+ }
102
+ else {
103
+ indexFileStatements.push(t.importDeclaration([t.importNamespaceSpecifier(t.identifier(schemaName))], t.stringLiteral(`./${filePath.replace('.ts', '')}`)), t.exportNamedDeclaration(null, [
104
+ t.exportSpecifier(t.identifier(schemaName), t.identifier(schemaName))
105
+ ]));
106
+ }
107
+ });
108
+ const fileTree = {};
109
+ Object.entries(schemaFiles).forEach(([filePath, statements]) => {
110
+ fileTree[filePath] = (0, generator_1.default)(t.program(statements)).code;
111
+ });
112
+ fileTree['index.ts'] = (0, generator_1.default)(t.program(indexFileStatements)).code;
113
+ return fileTree;
114
+ };
115
+ exports.generateCodeTree = generateCodeTree;
116
+ const toPascalCase = (str) => str
117
+ .replace(/[_-](\w)/g, (_, c) => c.toUpperCase())
118
+ .replace(/^\w/, (c) => c.toUpperCase());
119
+ const mapPostgresTypeToTSType = (typeId, isNotNull) => {
120
+ const optionalType = (type) => isNotNull ? type : t.tsUnionType([type, t.tsNullKeyword()]);
121
+ switch (typeId) {
122
+ case '20': // BIGINT
123
+ case '21': // SMALLINT
124
+ case '23': // INTEGER
125
+ case '1700': // NUMERIC
126
+ return optionalType(t.tsNumberKeyword());
127
+ case '25': // TEXT
128
+ case '1043': // VARCHAR
129
+ return optionalType(t.tsStringKeyword());
130
+ case '1114': // TIMESTAMP
131
+ case '1184': // TIMESTAMPTZ
132
+ return optionalType(t.tsTypeReference(t.identifier('Timestamp')));
133
+ case '2950': // UUID
134
+ return optionalType(t.tsTypeReference(t.identifier('UUID')));
135
+ case '16': // BOOLEAN
136
+ return optionalType(t.tsBooleanKeyword());
137
+ default:
138
+ return optionalType(t.tsAnyKeyword());
139
+ }
140
+ };
141
+ // Map Postgres type OIDs to type names for imports
142
+ const mapPostgresTypeToIdentifier = (typeId) => {
143
+ switch (typeId) {
144
+ case '1114': // TIMESTAMP
145
+ case '1184': // TIMESTAMPTZ
146
+ return 'Timestamp';
147
+ case '2950': // UUID
148
+ return 'UUID';
149
+ default:
150
+ return null;
151
+ }
152
+ };
@@ -0,0 +1,7 @@
1
+ import { DatabaseObject } from '../types';
2
+ type CodegenOptions = {
3
+ includeTimestamps: boolean;
4
+ includeUUID: boolean;
5
+ };
6
+ export declare const generateCode: (databaseObjects: DatabaseObject[], options: CodegenOptions) => string;
7
+ export {};
@@ -0,0 +1,100 @@
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 (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.generateCode = void 0;
30
+ const generator_1 = __importDefault(require("@babel/generator"));
31
+ const t = __importStar(require("@babel/types"));
32
+ const generateCode = (databaseObjects, options) => {
33
+ const { includeTimestamps, includeUUID } = options;
34
+ const namespaces = {};
35
+ // Organize objects by namespace
36
+ databaseObjects.forEach((obj) => {
37
+ if (obj.kind === 'namespace') {
38
+ namespaces[obj.name] = [];
39
+ }
40
+ });
41
+ // Generate interfaces for tables (Class objects with kind 'r')
42
+ databaseObjects.forEach((obj) => {
43
+ if (obj.kind === 'class' && obj.classKind === 'r') {
44
+ const namespace = obj.namespaceName;
45
+ const fields = [];
46
+ // Find attributes for the class
47
+ databaseObjects.forEach((attr) => {
48
+ if (attr.kind === 'attribute' && attr.classId === obj.id) {
49
+ fields.push(t.tsPropertySignature(t.identifier(attr.name), t.tsTypeAnnotation(mapPostgresTypeToTSType(attr.typeId, attr.isNotNull))));
50
+ }
51
+ });
52
+ // Create the interface declaration
53
+ const interfaceDeclaration = t.tsInterfaceDeclaration(t.identifier(obj.name), null, [], t.tsInterfaceBody(fields));
54
+ // Add to the namespace
55
+ if (namespaces[namespace]) {
56
+ namespaces[namespace].push(interfaceDeclaration);
57
+ }
58
+ }
59
+ });
60
+ // Generate the final AST
61
+ const programBody = [];
62
+ if (includeTimestamps) {
63
+ programBody.push(t.tsTypeAliasDeclaration(t.identifier('Timestamp'), null, t.tsStringKeyword()));
64
+ }
65
+ if (includeUUID) {
66
+ programBody.push(t.tsTypeAliasDeclaration(t.identifier('UUID'), null, t.tsStringKeyword()));
67
+ }
68
+ Object.keys(namespaces).forEach((namespace) => {
69
+ const namespaceDeclaration = t.tsModuleDeclaration(t.identifier(namespace), t.tsModuleBlock(namespaces[namespace]));
70
+ namespaceDeclaration.declare = true;
71
+ programBody.push(namespaceDeclaration);
72
+ });
73
+ const program = t.program(programBody);
74
+ // Generate the code
75
+ return (0, generator_1.default)(program).code;
76
+ };
77
+ exports.generateCode = generateCode;
78
+ // Map Postgres type OIDs to TypeScript types
79
+ const mapPostgresTypeToTSType = (typeId, isNotNull) => {
80
+ const optionalType = (type) => isNotNull ? type : t.tsUnionType([type, t.tsNullKeyword()]);
81
+ switch (typeId) {
82
+ case '20': // BIGINT
83
+ case '21': // SMALLINT
84
+ case '23': // INTEGER
85
+ case '1700': // NUMERIC
86
+ return optionalType(t.tsNumberKeyword());
87
+ case '25': // TEXT
88
+ case '1043': // VARCHAR
89
+ return optionalType(t.tsStringKeyword());
90
+ case '1114': // TIMESTAMP
91
+ case '1184': // TIMESTAMPTZ
92
+ return optionalType(t.tsTypeReference(t.identifier('Timestamp')));
93
+ case '2950': // UUID
94
+ return optionalType(t.tsTypeReference(t.identifier('UUID')));
95
+ case '16': // BOOLEAN
96
+ return optionalType(t.tsBooleanKeyword());
97
+ default:
98
+ return optionalType(t.tsAnyKeyword());
99
+ }
100
+ };
package/dist/README.md ADDED
@@ -0,0 +1,144 @@
1
+ # pg-codegen
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/launchql/launchql/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/launchql/launchql/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/pg-codegen"><img height="20" src="https://img.shields.io/github/package-json/v/launchql/launchql?filename=packages%2Fcodegen%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ Generate fully-typed TypeScript classes and interfaces from a live PostgreSQL schema via introspection.
16
+
17
+ > Converts your PostgreSQL tables into idiomatic TypeScript code — fast, predictable, and schema-aware.
18
+
19
+ ---
20
+
21
+ ## ✨ Features
22
+
23
+ 🧠 **Intelligent Introspection**
24
+ Pulls schema structure using native SQL introspection — no GraphQL required.
25
+
26
+ 🧱 **Interface + Class Output**
27
+ Generates matching `interface` + `class` pairs for each table using PascalCase naming.
28
+
29
+ 🧹 **Schema-Aware Output**
30
+ Writes files into `schemas/<schema>.ts`, grouped and re-exported from an `index.ts`.
31
+
32
+ 🔗 **Type Mapping for Postgres Primitives**
33
+ Supports `UUID`, `Timestamp`, `Boolean`, `Text`, `Int`, and nullable detection.
34
+
35
+ 🪴 **Auto Imports from \_common.ts**
36
+ Deduplicates and imports shared scalar types intelligently.
37
+
38
+ 🧪 **Snapshot-Ready for Testing**
39
+ Babel AST-based output is stable and perfect for inline snapshot tests.
40
+
41
+ ## 🛠️ Install
42
+
43
+ ```bash
44
+ npm install pg-codegen
45
+ ```
46
+
47
+ ## 🚀 Usage
48
+
49
+ ```ts
50
+ import { generateCodeTree } from 'pg-codegen';
51
+ import getIntrospectionRows from 'pg-codegen/introspect';
52
+
53
+ const rows = await getIntrospectionRows({
54
+ client: pgClient,
55
+ introspectionOptions: {
56
+ pgLegacyFunctionsOnly: false,
57
+ pgIgnoreRBAC: true
58
+ },
59
+ namespacesToIntrospect: ['my_schema'],
60
+ includeExtensions: false
61
+ });
62
+
63
+ const output = generateCodeTree(rows, {
64
+ includeUUID: true,
65
+ includeTimestamps: true
66
+ });
67
+
68
+ // Example: write output['schemas/my_schema.ts'] to disk
69
+ ```
70
+
71
+ ## 📟 Example Output
72
+
73
+ ```ts
74
+ // schemas/_common.ts
75
+ export type UUID = string;
76
+ export type Timestamp = string;
77
+
78
+ // schemas/my_schema.ts
79
+ import { UUID, Timestamp } from './_common';
80
+
81
+ export interface Users {
82
+ id: UUID;
83
+ email: string;
84
+ created_at: Timestamp;
85
+ }
86
+
87
+ export class Users implements Users {
88
+ id: UUID;
89
+ email: string;
90
+ created_at: Timestamp;
91
+
92
+ constructor(data: Users) {
93
+ this.id = data.id;
94
+ this.email = data.email;
95
+ this.created_at = data.created_at;
96
+ }
97
+ }
98
+ ```
99
+
100
+ ## Related LaunchQL Tooling
101
+
102
+ ### 🧪 Testing
103
+
104
+ * [launchql/pgsql-test](https://github.com/launchql/launchql/tree/main/packages/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
105
+ * [launchql/graphile-test](https://github.com/launchql/launchql/tree/main/packages/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
106
+ * [launchql/pg-query-context](https://github.com/launchql/launchql/tree/main/packages/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
107
+
108
+ ### 🧠 Parsing & AST
109
+
110
+ * [launchql/pgsql-parser](https://github.com/launchql/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
111
+ * [launchql/libpg-query-node](https://github.com/launchql/libpg-query-node): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
112
+ * [launchql/pg-proto-parser](https://github.com/launchql/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
113
+ * [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
114
+ * [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
115
+ * [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
116
+ * [launchql/pg-ast](https://github.com/launchql/launchql/tree/main/packages/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
117
+
118
+ ### 🚀 API & Dev Tools
119
+
120
+ * [launchql/server](https://github.com/launchql/launchql/tree/main/packages/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
121
+ * [launchql/explorer](https://github.com/launchql/launchql/tree/main/packages/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
122
+
123
+ ### 🔁 Streaming & Uploads
124
+
125
+ * [launchql/s3-streamer](https://github.com/launchql/launchql/tree/main/packages/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
126
+ * [launchql/etag-hash](https://github.com/launchql/launchql/tree/main/packages/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
127
+ * [launchql/etag-stream](https://github.com/launchql/launchql/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
128
+ * [launchql/uuid-hash](https://github.com/launchql/launchql/tree/main/packages/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
129
+ * [launchql/uuid-stream](https://github.com/launchql/launchql/tree/main/packages/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
130
+ * [launchql/upload-names](https://github.com/launchql/launchql/tree/main/packages/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
131
+
132
+ ### 🧰 CLI & Codegen
133
+
134
+ * [@launchql/cli](https://github.com/launchql/launchql/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing LaunchQL projects—supports database scaffolding, migrations, seeding, code generation, and automation.
135
+ * [launchql/launchql-gen](https://github.com/launchql/launchql/tree/main/packages/launchql-gen): **✨ Auto-generated GraphQL** mutations and queries dynamically built from introspected schema data.
136
+ * [@launchql/query-builder](https://github.com/launchql/launchql/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
137
+ * [@launchql/query](https://github.com/launchql/launchql/tree/main/packages/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
138
+
139
+ ## Disclaimer
140
+
141
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
142
+
143
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
144
+
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "pg-codegen",
3
+ "version": "2.1.5",
4
+ "author": "Dan Lynch <pyramation@gmail.com>",
5
+ "description": "PostgreSQL Codegen",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/launchql/launchql",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/launchql/launchql"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/launchql/launchql/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "copyfiles -f ../../LICENSE README.md package.json dist",
24
+ "clean": "rimraf dist/**",
25
+ "prepare": "npm run build",
26
+ "build": "npm run clean; tsc; tsc -p tsconfig.esm.json; npm run copy",
27
+ "build:dev": "npm run clean; tsc --declarationMap; tsc -p tsconfig.esm.json; npm run copy",
28
+ "dev": "ts-node ./src/index.ts",
29
+ "lint": "eslint . --fix",
30
+ "test": "jest",
31
+ "test:watch": "jest --watch"
32
+ },
33
+ "keywords": [
34
+ "codegen",
35
+ "graphql",
36
+ "typescript",
37
+ "launchql",
38
+ "generator"
39
+ ],
40
+ "dependencies": {
41
+ "@babel/generator": "^7.26.3",
42
+ "@babel/types": "^7.26.3",
43
+ "@launchql/types": "^2.1.6",
44
+ "@launchql/server-utils": "^2.1.8",
45
+ "pg": "^8.16.0",
46
+ "pgsql-test": "^2.1.14"
47
+ },
48
+ "devDependencies": {
49
+ "@types/pg": "^8.15.2"
50
+ }
51
+ }