introspeql 0.0.4 → 1.1.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.
Files changed (134) hide show
  1. package/README.md +313 -83
  2. package/dist/comments/comment-converter.d.ts +54 -0
  3. package/dist/comments/comment-converter.js +185 -0
  4. package/dist/comments/index.d.ts +2 -0
  5. package/dist/comments/index.js +18 -0
  6. package/dist/comments/prettify-comment.d.ts +1 -0
  7. package/dist/comments/prettify-comment.js +18 -0
  8. package/dist/config/connection-options.d.ts +14 -0
  9. package/dist/config/connection-options.js +42 -0
  10. package/dist/config/create-relation-options.d.ts +22 -0
  11. package/dist/config/create-relation-options.js +60 -0
  12. package/dist/config/default-type-mappings.d.ts +13 -0
  13. package/dist/config/default-type-mappings.js +16 -0
  14. package/dist/config/entity-data.d.ts +6 -0
  15. package/dist/config/entity-data.js +8 -0
  16. package/dist/config/function-options.d.ts +23 -0
  17. package/dist/config/function-options.js +74 -0
  18. package/dist/config/general-options.d.ts +7 -0
  19. package/dist/config/general-options.js +75 -0
  20. package/dist/config/index.d.ts +123 -0
  21. package/dist/config/index.js +43 -0
  22. package/dist/config/materialized-view-options.d.ts +24 -0
  23. package/dist/config/materialized-view-options.js +5 -0
  24. package/dist/config/output-options.d.ts +8 -0
  25. package/dist/config/output-options.js +40 -0
  26. package/dist/config/table-options.d.ts +24 -0
  27. package/dist/config/table-options.js +5 -0
  28. package/dist/config/view-options.d.ts +24 -0
  29. package/dist/config/view-options.js +5 -0
  30. package/dist/enums/enum-data.d.ts +9 -0
  31. package/dist/enums/enum-data.js +11 -0
  32. package/dist/enums/enum-definition.d.ts +7 -0
  33. package/dist/enums/enum-definition.js +24 -0
  34. package/dist/enums/index.d.ts +4 -0
  35. package/dist/enums/index.js +20 -0
  36. package/dist/enums/is-enum-replaced-with-custom-type.d.ts +3 -0
  37. package/dist/enums/is-enum-replaced-with-custom-type.js +9 -0
  38. package/dist/enums/read-enum-data.d.ts +3 -0
  39. package/dist/enums/read-enum-data.js +57 -0
  40. package/dist/functions/function-data.d.ts +26 -0
  41. package/dist/functions/function-data.js +27 -0
  42. package/dist/functions/function-definition.d.ts +7 -0
  43. package/dist/functions/function-definition.js +21 -0
  44. package/dist/functions/index.d.ts +9 -0
  45. package/dist/functions/index.js +25 -0
  46. package/dist/functions/overload-type-definition.d.ts +8 -0
  47. package/dist/functions/overload-type-definition.js +21 -0
  48. package/dist/functions/parameter-type-definition-builder.d.ts +16 -0
  49. package/dist/functions/parameter-type-definition-builder.js +41 -0
  50. package/dist/functions/parameter-type-definition.d.ts +9 -0
  51. package/dist/functions/parameter-type-definition.js +28 -0
  52. package/dist/functions/read-function-data.d.ts +4 -0
  53. package/dist/functions/read-function-data.js +93 -0
  54. package/dist/functions/return-type-definition.d.ts +7 -0
  55. package/dist/functions/return-type-definition.js +20 -0
  56. package/dist/functions/should-include-function.d.ts +2 -0
  57. package/dist/functions/should-include-function.js +6 -0
  58. package/dist/functions/should-include-overload.d.ts +2 -0
  59. package/dist/functions/should-include-overload.js +23 -0
  60. package/dist/index.d.ts +3 -2
  61. package/dist/index.js +7 -1
  62. package/dist/introspeql.d.ts +7 -0
  63. package/dist/introspeql.js +161 -0
  64. package/dist/relations/abstract-relation-definition.d.ts +11 -0
  65. package/dist/relations/abstract-relation-definition.js +43 -0
  66. package/dist/relations/column-data.d.ts +14 -0
  67. package/dist/relations/column-data.js +16 -0
  68. package/dist/relations/column-definition.d.ts +8 -0
  69. package/dist/relations/column-definition.js +19 -0
  70. package/dist/relations/column-type-definition.d.ts +7 -0
  71. package/dist/relations/column-type-definition.js +19 -0
  72. package/dist/relations/index.d.ts +11 -0
  73. package/dist/relations/index.js +27 -0
  74. package/dist/relations/materialized-view-definition.d.ts +4 -0
  75. package/dist/relations/materialized-view-definition.js +29 -0
  76. package/dist/relations/read-column-data.d.ts +3 -0
  77. package/dist/relations/read-column-data.js +55 -0
  78. package/dist/relations/read-relation-data.d.ts +4 -0
  79. package/dist/relations/read-relation-data.js +87 -0
  80. package/dist/relations/relation-data.d.ts +8 -0
  81. package/dist/relations/relation-data.js +10 -0
  82. package/dist/relations/should-include-relation.d.ts +10 -0
  83. package/dist/relations/should-include-relation.js +24 -0
  84. package/dist/relations/table-definition.d.ts +4 -0
  85. package/dist/relations/table-definition.js +29 -0
  86. package/dist/relations/view-definition.d.ts +4 -0
  87. package/dist/relations/view-definition.js +29 -0
  88. package/dist/schemas/index.d.ts +3 -0
  89. package/dist/schemas/index.js +19 -0
  90. package/dist/schemas/read-schema-data.d.ts +17 -0
  91. package/dist/schemas/read-schema-data.js +219 -0
  92. package/dist/schemas/schema-definition-factory.d.ts +15 -0
  93. package/dist/schemas/schema-definition-factory.js +177 -0
  94. package/dist/schemas/schema-definition.d.ts +13 -0
  95. package/dist/schemas/schema-definition.js +52 -0
  96. package/dist/shared/capitalize.d.ts +1 -0
  97. package/dist/shared/capitalize.js +6 -0
  98. package/dist/shared/convert-pg-identifier-to-ts-identifier.d.ts +19 -0
  99. package/dist/shared/convert-pg-identifier-to-ts-identifier.js +55 -0
  100. package/dist/shared/directives.d.ts +12 -0
  101. package/dist/shared/directives.js +16 -0
  102. package/dist/shared/get-tokens.d.ts +1 -0
  103. package/dist/shared/get-tokens.js +7 -0
  104. package/dist/shared/indent.d.ts +1 -0
  105. package/dist/shared/indent.js +9 -0
  106. package/dist/shared/index.d.ts +6 -0
  107. package/dist/shared/index.js +22 -0
  108. package/dist/shared/parsing-error.d.ts +3 -0
  109. package/dist/shared/parsing-error.js +26 -0
  110. package/dist/types/index.d.ts +1 -0
  111. package/dist/types/index.js +17 -0
  112. package/dist/types/lookup-type.d.ts +15 -0
  113. package/dist/types/lookup-type.js +25 -0
  114. package/package.json +32 -17
  115. package/dist/append-schema.d.ts +0 -8
  116. package/dist/append-schema.js +0 -96
  117. package/dist/generate-types.d.ts +0 -8
  118. package/dist/generate-types.js +0 -110
  119. package/dist/introspect-columns.d.ts +0 -21
  120. package/dist/introspect-columns.js +0 -53
  121. package/dist/introspect-enum.d.ts +0 -20
  122. package/dist/introspect-enum.js +0 -24
  123. package/dist/introspect-procedures.d.ts +0 -53
  124. package/dist/introspect-procedures.js +0 -129
  125. package/dist/introspect-tables.d.ts +0 -19
  126. package/dist/introspect-tables.js +0 -43
  127. package/dist/introspeql-config.d.ts +0 -40
  128. package/dist/introspeql-config.js +0 -104
  129. package/dist/prepare-data-for-writing.d.ts +0 -38
  130. package/dist/prepare-data-for-writing.js +0 -145
  131. package/dist/snake-case-to-pascal-case.d.ts +0 -8
  132. package/dist/snake-case-to-pascal-case.js +0 -17
  133. package/dist/write-header.d.ts +0 -2
  134. package/dist/write-header.js +0 -10
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Converts a PostgreSQL identifier to a valid TypeScript identifier.
3
+ *
4
+ * @remarks
5
+ * In PostgreSQL, if an identifier is enclosed in double quotes, it can include
6
+ * a wider selection of characters than are valid in TypeScript.
7
+ * Additionally, while it is idiomatic to use snake_case in PostgreSQL, it is
8
+ * more commonplace to use PascalCase for TypeScript types. Therefore, the
9
+ * following rules are followed when converting identifiers:
10
+ *
11
+ * - If the PostgreSQL identifier begins with underscore(s), these are
12
+ * preserved.
13
+ * - Otherwise, only alphanumeric and $ characters are copied.
14
+ * - All non-letter characters are treated as separators, except for
15
+ * apostrophes, which are simply discarded.
16
+ * - Each word (i.e. the letters between separators) is capitalized.
17
+ * - If the result begins with a number, it is prefaced with an underscore.
18
+ */
19
+ export declare function convertPGIdentifierToTSIdentifier(identifier: string): string;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.convertPGIdentifierToTSIdentifier = convertPGIdentifierToTSIdentifier;
4
+ var capitalize_1 = require("./capitalize");
5
+ /**
6
+ * Converts a PostgreSQL identifier to a valid TypeScript identifier.
7
+ *
8
+ * @remarks
9
+ * In PostgreSQL, if an identifier is enclosed in double quotes, it can include
10
+ * a wider selection of characters than are valid in TypeScript.
11
+ * Additionally, while it is idiomatic to use snake_case in PostgreSQL, it is
12
+ * more commonplace to use PascalCase for TypeScript types. Therefore, the
13
+ * following rules are followed when converting identifiers:
14
+ *
15
+ * - If the PostgreSQL identifier begins with underscore(s), these are
16
+ * preserved.
17
+ * - Otherwise, only alphanumeric and $ characters are copied.
18
+ * - All non-letter characters are treated as separators, except for
19
+ * apostrophes, which are simply discarded.
20
+ * - Each word (i.e. the letters between separators) is capitalized.
21
+ * - If the result begins with a number, it is prefaced with an underscore.
22
+ */
23
+ function convertPGIdentifierToTSIdentifier(identifier) {
24
+ // preserve leading underscores
25
+ var prefix = '';
26
+ while (identifier.startsWith('_')) {
27
+ prefix += '_';
28
+ identifier = identifier.slice(1);
29
+ }
30
+ var words = [];
31
+ var word = '';
32
+ for (var _i = 0, identifier_1 = identifier; _i < identifier_1.length; _i++) {
33
+ var char = identifier_1[_i];
34
+ if (char === "'")
35
+ continue;
36
+ if (/[^A-Za-z]/.test(char)) {
37
+ if (word.length)
38
+ words.push(word);
39
+ if (/[0-9$]/.test(char)) {
40
+ words.push(char);
41
+ }
42
+ word = '';
43
+ }
44
+ else {
45
+ word += char;
46
+ }
47
+ }
48
+ if (word.length) {
49
+ words.push(word);
50
+ }
51
+ var result = prefix + words.map(function (word) { return (0, capitalize_1.capitalize)(word); }).join('');
52
+ if (/^\d/.test(result))
53
+ result = '_' + result;
54
+ return result;
55
+ }
@@ -0,0 +1,12 @@
1
+ export declare enum Directives {
2
+ Include = "@introspeql-include",
3
+ Exclude = "@introspeql-exclude",
4
+ EnableNullableArgs = "@introspeql-enable-nullable-args",
5
+ DisableNullableArgs = "@introspeql-disable-nullable-args",
6
+ EnableNullableReturnTypes = "@introspeql-enable-nullable-return-types",
7
+ DisableNullableReturnTypes = "@introspeql-disable-nullable-return-types",
8
+ EnableTSDocComments = "@introspeql-enable-tsdoc-comments",
9
+ DisableTSDocComments = "@introspeql-disable-tsdoc-comments",
10
+ BeginTSDocComment = "@introspeql-begin-tsdoc-comment",
11
+ EndTSDocComment = "@introspeql-end-tsdoc-comment"
12
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Directives = void 0;
4
+ var Directives;
5
+ (function (Directives) {
6
+ Directives["Include"] = "@introspeql-include";
7
+ Directives["Exclude"] = "@introspeql-exclude";
8
+ Directives["EnableNullableArgs"] = "@introspeql-enable-nullable-args";
9
+ Directives["DisableNullableArgs"] = "@introspeql-disable-nullable-args";
10
+ Directives["EnableNullableReturnTypes"] = "@introspeql-enable-nullable-return-types";
11
+ Directives["DisableNullableReturnTypes"] = "@introspeql-disable-nullable-return-types";
12
+ Directives["EnableTSDocComments"] = "@introspeql-enable-tsdoc-comments";
13
+ Directives["DisableTSDocComments"] = "@introspeql-disable-tsdoc-comments";
14
+ Directives["BeginTSDocComment"] = "@introspeql-begin-tsdoc-comment";
15
+ Directives["EndTSDocComment"] = "@introspeql-end-tsdoc-comment";
16
+ })(Directives || (exports.Directives = Directives = {}));
@@ -0,0 +1 @@
1
+ export declare function getTokens(comment: string | null): string[];
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTokens = getTokens;
4
+ function getTokens(comment) {
5
+ var tokens = comment ? comment.split(/\s/).map(function (t) { return t.toLowerCase(); }) : [];
6
+ return tokens;
7
+ }
@@ -0,0 +1 @@
1
+ export declare function indent(str: string, spaces: number): string;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.indent = indent;
4
+ function indent(str, spaces) {
5
+ return str
6
+ .split('\n')
7
+ .map(function (line) { return ' '.repeat(spaces) + line; })
8
+ .join('\n');
9
+ }
@@ -0,0 +1,6 @@
1
+ export * from './capitalize';
2
+ export * from './directives';
3
+ export * from './get-tokens';
4
+ export * from './indent';
5
+ export * from './parsing-error';
6
+ export * from './convert-pg-identifier-to-ts-identifier';
@@ -0,0 +1,22 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./capitalize"), exports);
18
+ __exportStar(require("./directives"), exports);
19
+ __exportStar(require("./get-tokens"), exports);
20
+ __exportStar(require("./indent"), exports);
21
+ __exportStar(require("./parsing-error"), exports);
22
+ __exportStar(require("./convert-pg-identifier-to-ts-identifier"), exports);
@@ -0,0 +1,3 @@
1
+ export declare class ParsingError extends Error {
2
+ constructor(message: string);
3
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.ParsingError = void 0;
19
+ var ParsingError = /** @class */ (function (_super) {
20
+ __extends(ParsingError, _super);
21
+ function ParsingError(message) {
22
+ return _super.call(this, message) || this;
23
+ }
24
+ return ParsingError;
25
+ }(Error));
26
+ exports.ParsingError = ParsingError;
@@ -0,0 +1 @@
1
+ export * from './lookup-type';
@@ -0,0 +1,17 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./lookup-type"), exports);
@@ -0,0 +1,15 @@
1
+ import type { ParsedConfig } from '../config';
2
+ interface TypeInformation {
3
+ schema: string;
4
+ name: string;
5
+ isEnum: boolean;
6
+ }
7
+ /**
8
+ * Looks up the correct TypeScript type for a given PostgreSQL type. First
9
+ * checks the config.types object for the type, then checks whether or not the
10
+ * type is an Enum, and if it is, creates a string that will refer to the
11
+ * enum definition generated by IntrospeQL. If the type is not defined in
12
+ * config.types and is not an enum, 'string' is returned.
13
+ */
14
+ export declare function lookupType({ schema, name, isEnum }: TypeInformation, parentSchema: string, config: ParsedConfig): string;
15
+ export {};
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lookupType = lookupType;
4
+ var shared_1 = require("../shared");
5
+ /**
6
+ * Looks up the correct TypeScript type for a given PostgreSQL type. First
7
+ * checks the config.types object for the type, then checks whether or not the
8
+ * type is an Enum, and if it is, creates a string that will refer to the
9
+ * enum definition generated by IntrospeQL. If the type is not defined in
10
+ * config.types and is not an enum, 'string' is returned.
11
+ */
12
+ function lookupType(_a, parentSchema, config) {
13
+ var schema = _a.schema, name = _a.name, isEnum = _a.isEnum;
14
+ var key = "".concat(schema, ".").concat(name);
15
+ if (key in config.types) {
16
+ return config.types[key];
17
+ }
18
+ if (isEnum) {
19
+ var type = "Enums.".concat((0, shared_1.convertPGIdentifierToTSIdentifier)(name));
20
+ if (schema !== parentSchema)
21
+ type = "".concat((0, shared_1.convertPGIdentifierToTSIdentifier)(schema), ".").concat(type);
22
+ return type;
23
+ }
24
+ return 'string';
25
+ }
package/package.json CHANGED
@@ -1,37 +1,52 @@
1
1
  {
2
2
  "name": "introspeql",
3
- "version": "0.0.4",
4
- "description": "Easy Postgres to TypeScript type generation.",
5
- "exports": {
6
- ".": "./dist/index.js"
7
- },
8
- "types": "./dist/index.d.ts",
9
- "scripts": {
10
- "format": "npx prettier . --write",
11
- "test": "echo \"Error: no test specified\" && exit 1",
12
- "build": "tsc"
13
- },
3
+ "version": "1.1.0",
4
+ "description": "IntrospeQL reads information about the schemas, tables, views, materialized views, functions and enums in your PostgreSQL database and produces a TypeScript file detailing type information for each object in the database.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
14
7
  "files": [
15
8
  "dist",
16
9
  "README.md"
17
10
  ],
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "format": "npx prettier . --write",
14
+ "lint": "npx eslint --fix",
15
+ "test": "vitest --no-watch"
16
+ },
18
17
  "keywords": [
19
18
  "PostgreSQL",
20
19
  "Postgres",
21
20
  "TypeScript"
22
21
  ],
23
22
  "author": "Joseph Dvorak",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/dvorakjt/introspeql"
26
+ },
24
27
  "license": "MIT",
25
- "type": "module",
28
+ "type": "commonjs",
26
29
  "devDependencies": {
27
- "@types/node": "^24.5.2",
30
+ "@eslint/js": "^9.39.2",
31
+ "@eslint/json": "^0.14.0",
32
+ "@eslint/markdown": "^7.5.1",
33
+ "@faker-js/faker": "^10.1.0",
34
+ "@types/node": "^24.7.0",
28
35
  "@types/pg": "^8.15.5",
29
- "prettier": "^3.6.2",
30
- "tsx": "^4.20.6",
31
- "typescript": "^5.9.2"
36
+ "dotenv": "^17.2.3",
37
+ "eslint": "^9.39.2",
38
+ "globals": "^16.5.0",
39
+ "nanoid": "^5.1.6",
40
+ "pgmock": "^1.0.3",
41
+ "prettier": "^3.7.4",
42
+ "typescript": "^5.9.3",
43
+ "typescript-eslint": "^8.51.0",
44
+ "vitest": "^3.2.4"
32
45
  },
33
46
  "dependencies": {
47
+ "@prettier/sync": "^0.6.1",
34
48
  "pg": "^8.16.3",
35
- "zod": "^4.1.11"
49
+ "prettier-plugin-jsdoc": "^1.8.0",
50
+ "zod": "^4.1.12"
36
51
  }
37
52
  }
@@ -1,8 +0,0 @@
1
- import type { Schema } from './prepare-data-for-writing';
2
- /**
3
- * Appends a namespace representing the given schema to the provided output file.
4
- *
5
- * @param outputPath
6
- * @param schema
7
- */
8
- export declare function appendSchema(outputPath: string, schema: Schema): void;
@@ -1,96 +0,0 @@
1
- import fs from 'node:fs';
2
- /**
3
- * Appends a namespace representing the given schema to the provided output file.
4
- *
5
- * @param outputPath
6
- * @param schema
7
- */
8
- export function appendSchema(outputPath, schema) {
9
- let schemaTypeDefinitions = `export namespace ${schema.formattedName} {\n`;
10
- schemaTypeDefinitions += ` export const SchemaName = '${schema.rawName}';\n`;
11
- if (schema.enums.length > 0) {
12
- schemaTypeDefinitions = appendEnums(schemaTypeDefinitions, schema);
13
- }
14
- if (schema.tables.length > 0) {
15
- schemaTypeDefinitions = appendTables(schemaTypeDefinitions, schema);
16
- }
17
- if (schema.procedures.length > 0) {
18
- schemaTypeDefinitions = appendProcedures(schemaTypeDefinitions, schema);
19
- }
20
- schemaTypeDefinitions += `};`;
21
- fs.appendFileSync(outputPath, schemaTypeDefinitions, 'utf-8');
22
- }
23
- function appendEnums(typeDefs, schema) {
24
- typeDefs += '\n' + ' '.repeat(2) + 'export namespace Enums {';
25
- for (const e of schema.enums) {
26
- typeDefs += '\n' + ' '.repeat(4) + `export enum ${e.name} {\n`;
27
- typeDefs += e.values.map(v => ' '.repeat(6) + `${v} = '${v}',\n`).join('');
28
- typeDefs += ' '.repeat(4) + '};\n';
29
- }
30
- typeDefs += ' '.repeat(2) + `};\n`;
31
- return typeDefs;
32
- }
33
- function appendTables(typeDefs, schema) {
34
- typeDefs += '\n' + ' '.repeat(2) + 'export namespace Tables {';
35
- for (const t of schema.tables) {
36
- typeDefs +=
37
- '\n' + ' '.repeat(4) + `export namespace ${t.formattedName} {\n`;
38
- typeDefs += ' '.repeat(6) + `export const TableName = '${t.rawName}';\n`;
39
- if (Object.entries(t.columnNames).length > 0) {
40
- typeDefs += '\n' + ' '.repeat(6) + 'export enum ColumnNames {\n';
41
- for (const [formattedName, rawName] of Object.entries(t.columnNames)) {
42
- typeDefs += ' '.repeat(8) + `${formattedName} = '${rawName}',\n`;
43
- }
44
- typeDefs += ' '.repeat(6) + '};\n';
45
- }
46
- if (Object.entries(t.rowType).length > 0) {
47
- typeDefs += '\n' + ' '.repeat(6) + 'export interface RowType {\n';
48
- for (const [rawName, type] of Object.entries(t.rowType)) {
49
- const columnName = Object.entries(t.columnNames).find(entry => {
50
- return entry[1] === rawName;
51
- })[0];
52
- typeDefs += ' '.repeat(8) + `[ColumnNames.${columnName}]: ${type};\n`;
53
- }
54
- typeDefs += ' '.repeat(6) + '};\n';
55
- }
56
- typeDefs += ' '.repeat(4) + '};\n';
57
- }
58
- typeDefs += ' '.repeat(2) + '};\n';
59
- return typeDefs;
60
- }
61
- function appendProcedures(typeDefs, schema) {
62
- typeDefs += '\n' + ' '.repeat(2) + 'export namespace Procedures {';
63
- for (const proc of schema.procedures) {
64
- typeDefs +=
65
- '\n' + ' '.repeat(4) + `export namespace ${proc.formattedName} {\n`;
66
- typeDefs +=
67
- ' '.repeat(6) + `export const ProcedureName = '${proc.rawName}';\n`;
68
- typeDefs +=
69
- '\n' +
70
- ' '.repeat(6) +
71
- `export const ArgNames = [\n` +
72
- proc.argNames
73
- .map(n => {
74
- return ' '.repeat(8) + `'${n}',\n`;
75
- })
76
- .join('') +
77
- ' '.repeat(6) +
78
- '] as const;\n';
79
- typeDefs +=
80
- '\n' +
81
- ' '.repeat(6) +
82
- `export type ArgTypes = [\n` +
83
- proc.argTypes
84
- .map(t => {
85
- return ' '.repeat(8) + t + ',\n';
86
- })
87
- .join('') +
88
- ' '.repeat(6) +
89
- '];\n';
90
- typeDefs +=
91
- '\n' + ' '.repeat(6) + `export type ReturnType = ${proc.returnType};\n`;
92
- typeDefs += ' '.repeat(4) + '};\n';
93
- }
94
- typeDefs += ' '.repeat(2) + '};\n';
95
- return typeDefs;
96
- }
@@ -1,8 +0,0 @@
1
- import { type IntrospeQLConfig } from './introspeql-config';
2
- /**
3
- * Reads table, function, and enum metadata from a database and writes
4
- * corresponding TypeScript type definitions to the provided output path.
5
- *
6
- * @param config
7
- */
8
- export declare function generateTypes(config: IntrospeQLConfig): Promise<void>;
@@ -1,110 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { Client } from 'pg';
4
- import { introspectTables } from './introspect-tables';
5
- import { introspectColumns } from './introspect-columns';
6
- import { introspectProcedures } from './introspect-procedures';
7
- import { introspectEnum, } from './introspect-enum';
8
- import { writeHeader } from './write-header';
9
- import { prepareDataForWriting } from './prepare-data-for-writing';
10
- import { appendSchema } from './append-schema';
11
- import { introspeqlConfig } from './introspeql-config';
12
- /**
13
- * Reads table, function, and enum metadata from a database and writes
14
- * corresponding TypeScript type definitions to the provided output path.
15
- *
16
- * @param config
17
- */
18
- export async function generateTypes(config) {
19
- const parsedConfig = introspeqlConfig.parse(config);
20
- const client = 'dbConnectionString' in parsedConfig ?
21
- new Client({
22
- connectionString: parsedConfig.dbConnectionString,
23
- })
24
- : new Client({
25
- ...parsedConfig.dbConnectionParams,
26
- });
27
- try {
28
- await client.connect();
29
- }
30
- catch (e) {
31
- throw new Error('Failed to connect to the database.', { cause: e });
32
- }
33
- // Read table data
34
- let tableDataObjects;
35
- try {
36
- tableDataObjects = await introspectTables(client, parsedConfig);
37
- }
38
- catch (e) {
39
- throw new Error('Failed to introspect tables.', { cause: e });
40
- }
41
- // Read column data and update enums object when enum types are found
42
- const columnDataObjectsByTableId = {};
43
- const partialEnumDataObjects = [];
44
- for (const tableDataObj of tableDataObjects) {
45
- try {
46
- const columnDataObjects = await introspectColumns(client, tableDataObj.id);
47
- columnDataObjectsByTableId[tableDataObj.id] = columnDataObjects;
48
- for (const columnDataObj of columnDataObjects) {
49
- if (columnDataObj.is_enum &&
50
- !partialEnumDataObjects.find(d => d.id === columnDataObj.column_type_id)) {
51
- partialEnumDataObjects.push({
52
- id: columnDataObj.column_type_id,
53
- schema: columnDataObj.column_type_schema,
54
- name: columnDataObj.column_type,
55
- });
56
- }
57
- }
58
- }
59
- catch (e) {
60
- throw new Error('Failed to introspect columns.', { cause: e });
61
- }
62
- }
63
- // Read procedure data and update enums object when enum types are found
64
- let procedureDataObjects;
65
- try {
66
- procedureDataObjects = await introspectProcedures(client, parsedConfig);
67
- }
68
- catch (e) {
69
- throw new Error('Failed to introspect procedures.', { cause: e });
70
- }
71
- for (const procedureDataObject of procedureDataObjects) {
72
- for (const argType of procedureDataObject.arg_types) {
73
- if (argType.is_enum &&
74
- !partialEnumDataObjects.find(d => d.id === argType.id)) {
75
- partialEnumDataObjects.push({
76
- id: argType.id,
77
- schema: argType.schema,
78
- name: argType.name,
79
- });
80
- }
81
- }
82
- if (procedureDataObject.return_type.is_enum &&
83
- !partialEnumDataObjects.find(d => d.id === procedureDataObject.return_type.id)) {
84
- partialEnumDataObjects.push({
85
- id: procedureDataObject.return_type.id,
86
- schema: procedureDataObject.return_type.schema,
87
- name: procedureDataObject.return_type.name,
88
- });
89
- }
90
- }
91
- // Read enum metadata for all enums that were featured in tables or procedures
92
- const enumDataObjects = [];
93
- for (const partialEnumDataObj of partialEnumDataObjects) {
94
- try {
95
- const enumData = await introspectEnum(client, partialEnumDataObj);
96
- enumDataObjects.push(enumData);
97
- }
98
- catch (e) {
99
- throw new Error('Failed to introspect enum.', { cause: e });
100
- }
101
- }
102
- await client.end();
103
- const outDir = path.dirname(config.outFile);
104
- if (!fs.existsSync(outDir)) {
105
- fs.mkdirSync(outDir, { recursive: true });
106
- }
107
- writeHeader(parsedConfig.outFile, parsedConfig);
108
- const schemas = prepareDataForWriting(enumDataObjects, tableDataObjects, columnDataObjectsByTableId, procedureDataObjects, parsedConfig);
109
- schemas.forEach(schema => appendSchema(parsedConfig.outFile, schema));
110
- }
@@ -1,21 +0,0 @@
1
- import { z } from 'zod';
2
- import type { Client } from 'pg';
3
- declare const columnDataSchema: z.ZodObject<{
4
- column_name: z.ZodString;
5
- column_type_schema: z.ZodString;
6
- column_type_id: z.ZodNumber;
7
- column_type: z.ZodString;
8
- is_enum: z.ZodBoolean;
9
- num_dimensions: z.ZodNumber;
10
- nullable: z.ZodBoolean;
11
- }, z.core.$strip>;
12
- export type ColumnData = z.infer<typeof columnDataSchema>;
13
- /**
14
- * Reads metadata for each column of a given table.
15
- *
16
- * @param client
17
- * @param tableId
18
- * @returns A {@link Promise}<{@link ColumnData}[]>
19
- */
20
- export declare function introspectColumns(client: Client, tableId: number): Promise<ColumnData[]>;
21
- export {};
@@ -1,53 +0,0 @@
1
- import { z } from 'zod';
2
- const columnDataSchema = z.object({
3
- column_name: z.string(),
4
- column_type_schema: z.string(),
5
- column_type_id: z.number(),
6
- column_type: z.string(),
7
- is_enum: z.boolean(),
8
- num_dimensions: z.number(),
9
- nullable: z.boolean(),
10
- });
11
- /**
12
- * Reads metadata for each column of a given table.
13
- *
14
- * @param client
15
- * @param tableId
16
- * @returns A {@link Promise}<{@link ColumnData}[]>
17
- */
18
- export async function introspectColumns(client, tableId) {
19
- const result = await client.query(`
20
- SELECT
21
- a.attname AS column_name,
22
- (
23
- SELECT nspname
24
- FROM pg_catalog.pg_namespace
25
- WHERE oid = t.typnamespace
26
- ) AS column_type_schema,
27
- CASE WHEN a.attndims > 0 THEN (
28
- SELECT base_type.oid
29
- FROM pg_catalog.pg_type AS array_type, pg_catalog.pg_type as base_type
30
- WHERE array_type.oid = a.atttypid AND base_type.typarray = array_type.oid
31
- ) ELSE a.atttypid END AS column_type_id,
32
- CASE WHEN a.attndims > 0 THEN (
33
- SELECT base_type.typname
34
- FROM pg_catalog.pg_type AS array_type, pg_catalog.pg_type as base_type
35
- WHERE array_type.oid = a.atttypid AND base_type.typarray = array_type.oid
36
- ) ELSE t.typname END AS column_type,
37
- CASE WHEN a.attndims > 0 THEN (
38
- SELECT t2.typtype = 'e' AS is_enum
39
- FROM pg_catalog.pg_type AS t1, pg_catalog.pg_type as t2
40
- INNER JOIN pg_catalog.pg_namespace AS n ON t2.typnamespace = n.oid
41
- WHERE t1.oid = a.atttypid AND t2.typarray = t1.oid
42
- ) ELSE t.typtype = 'e' END AS is_enum,
43
- a.attndims AS num_dimensions,
44
- NOT a.attnotnull As nullable
45
- FROM pg_catalog.pg_class AS c
46
- INNER JOIN pg_catalog.pg_namespace AS n ON c.relnamespace = n.oid
47
- INNER JOIN pg_catalog.pg_attribute AS a ON c.oid = a.attrelid
48
- INNER JOIN pg_catalog.pg_type AS t ON a.atttypid = t.oid
49
- WHERE c.oid = $1
50
- AND a.attnum >= 1;`, [tableId]);
51
- const columnData = columnDataSchema.array().parse(result.rows);
52
- return columnData;
53
- }
@@ -1,20 +0,0 @@
1
- import type { Client } from 'pg';
2
- export type PartialEnumData = {
3
- /** The OID of the enum. */
4
- id: number;
5
- /** The name of the schema in which the enum was defined. */
6
- schema: string;
7
- /** The name of the enum. */
8
- name: string;
9
- };
10
- export type EnumData = PartialEnumData & {
11
- values: string[];
12
- };
13
- /**
14
- * Reads metadata for the provided enum.
15
- *
16
- * @param client
17
- * @param data
18
- * @returns A {@link Promise}<{@link EnumData}[]>
19
- */
20
- export declare function introspectEnum(client: Client, data: PartialEnumData): Promise<EnumData>;