true-pg 0.0.2 → 0.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.
package/src/types.ts DELETED
@@ -1,297 +0,0 @@
1
- import type {
2
- CanonicalType,
3
- CompositeTypeDetails,
4
- EnumDetails,
5
- FunctionDetails,
6
- TableDetails,
7
- SchemaType,
8
- Schema,
9
- } from "pg-extract";
10
-
11
- import { dirname, relative } from "node:path";
12
- import { join } from "./util.ts";
13
-
14
- // To be updated when we add support for other kinds
15
- export const allowed_kind_names = ["tables", "enums", "composites", "functions"] as const;
16
- export type allowed_kind_names = (typeof allowed_kind_names)[number];
17
-
18
- export interface FolderStructure {
19
- name: string;
20
- type: "root";
21
- children: {
22
- [realname: string]: {
23
- name: string;
24
- type: "schema";
25
- children: {
26
- [kind: string]: {
27
- kind: allowed_kind_names;
28
- type: "kind";
29
- children: {
30
- [realname: string]: {
31
- name: string;
32
- type: "type";
33
- };
34
- };
35
- };
36
- };
37
- };
38
- };
39
- }
40
-
41
- export namespace Nodes {
42
- export class ExternalImport {
43
- // what to import
44
- name: string;
45
- // use `type` syntax?
46
- typeOnly: boolean;
47
- // use `* as` syntax?
48
- star: boolean;
49
-
50
- // this is an external import
51
- external: true;
52
- // what module to import from
53
- module: string;
54
-
55
- constructor(args: { name: string; module: string; typeOnly: boolean; star: boolean }) {
56
- this.name = args.name;
57
- this.typeOnly = args.typeOnly;
58
- this.star = args.star;
59
- this.external = true;
60
- this.module = args.module;
61
- }
62
- }
63
-
64
- export class InternalImport {
65
- // what to import
66
- name: string;
67
- // underlying type that is being imported
68
- canonical_type: CanonicalType;
69
- // use `type` syntax?
70
- typeOnly: boolean;
71
- // use `* as` syntax?
72
- star: boolean;
73
-
74
- // this is an internal import
75
- external: false;
76
-
77
- constructor(args: { name: string; canonical_type: CanonicalType; typeOnly: boolean; star: boolean }) {
78
- this.name = args.name;
79
- this.canonical_type = args.canonical_type;
80
- this.star = args.star;
81
- this.typeOnly = args.typeOnly;
82
- this.external = false;
83
- }
84
- }
85
-
86
- export class ImportList {
87
- constructor(public imports: (ExternalImport | InternalImport)[]) {}
88
-
89
- static merge(lists: ImportList[]) {
90
- return new ImportList(lists.flatMap(l => l.imports));
91
- }
92
-
93
- add(item: ExternalImport | InternalImport) {
94
- this.imports.push(item);
95
- }
96
-
97
- stringify(context_file: string, files: FolderStructure) {
98
- const externals = this.imports.filter(i => i.external);
99
- const internals = this.imports.filter(i => !i.external);
100
-
101
- const modulegroups: Record<string, ExternalImport[]> = {};
102
- for (const item of externals) {
103
- const group = modulegroups[item.module];
104
- if (group) group.push(item);
105
- else modulegroups[item.module] = [item];
106
- }
107
-
108
- const out = [];
109
-
110
- // TODO: normalise external and internal imports and handle the stringification of the imports in a single place
111
-
112
- {
113
- // EXTERNAL IMPORTS
114
-
115
- const imports = [];
116
- for (const module in modulegroups) {
117
- const items = modulegroups[module]!;
118
- const star = items.find(i => i.star);
119
- const unique = items.filter((i, index, arr) => {
120
- if (i.star) return false;
121
- if (arr.findIndex(i2 => i2.name === i.name) !== index) return false;
122
- return true;
123
- });
124
-
125
- const bits = [];
126
- const typeOnlys = unique.filter(i => i.typeOnly);
127
- const values = unique.filter(i => !i.typeOnly);
128
-
129
- // if no values to import, use `import type { ... }` instead of `import { type ... }`
130
- const typeInline = values.length !== 0;
131
-
132
- let import_line = `import `;
133
- for (const type of typeOnlys) bits.push(typeInline ? "type " : "" + type.name);
134
- for (const type of values) bits.push(type.name);
135
- if (bits.length) import_line += (typeInline ? "" : "type ") + "{ " + bits.join(", ") + " }";
136
- if (bits.length && star) import_line += `, `;
137
- if (star) import_line += `* as ${star.name}`;
138
- if (bits.length || star) import_line += ` from`;
139
- import_line += `"${module}";`;
140
- imports.push(import_line);
141
- }
142
- out.push(join(imports, "\n"));
143
- }
144
-
145
- {
146
- // INTERNAL IMPORTS
147
-
148
- const imports = [];
149
- const unique_types = internals
150
- .filter(({ name: name1, canonical_type: int }, index, arr) => {
151
- return (
152
- arr.findIndex(({ name: name2, canonical_type: int2 }) => {
153
- return (
154
- // adapter-assigned name
155
- name2 === name1 &&
156
- // canonical type details
157
- int2.name === int.name &&
158
- int2.schema === int.schema &&
159
- int2.kind === int.kind
160
- );
161
- }) === index
162
- );
163
- })
164
- .map(imp => {
165
- const t = imp.canonical_type;
166
- const schema = files.children[t.schema]!;
167
- const kind = schema.children[`${t.kind}s`]!;
168
- const type = kind.children[t.name]!;
169
- const located_file = `${files.name}/${schema.name}/${kind.kind}/${type.name}.ts`;
170
- return { ...imp, located_file };
171
- });
172
-
173
- const group_by_file: Record<string, (InternalImport & { located_file: string })[]> = {};
174
- for (const type of unique_types) {
175
- const file = group_by_file[type.located_file] || [];
176
- file.push(type);
177
- group_by_file[type.located_file] = file;
178
- }
179
-
180
- for (const group in group_by_file) {
181
- let relative_path = relative(dirname(context_file), group);
182
- if (/^[^\.+\/]/.test(relative_path)) relative_path = "./" + relative_path;
183
- const items = group_by_file[group]!;
184
- const typeOnlys = items.filter(i => i.typeOnly);
185
- const values = items.filter(i => !i.typeOnly);
186
- const star = values.find(i => i.star);
187
- let import_line = "import ";
188
- const bits = [];
189
-
190
- // if no values to import, use `import type { ... }` instead of `import { type ... }`
191
- const typeInline = values.length !== 0;
192
-
193
- for (const type of typeOnlys) bits.push((typeInline ? "type " : "") + type.name);
194
- for (const type of values) bits.push(type.name);
195
- if (bits.length) import_line += (typeInline ? "" : "type ") + "{ " + bits.join(", ") + " }";
196
- if (star) import_line += `* as ${star.name}`;
197
- import_line += ` from "${relative_path}";`;
198
- imports.push(import_line);
199
- }
200
-
201
- out.push(join(imports, "\n"));
202
- }
203
-
204
- return join(out);
205
- }
206
- }
207
-
208
- export interface Export {
209
- // what to export
210
- name: string;
211
- // what kind of thing to export
212
- kind: SchemaType["kind"];
213
- // what schema to export from
214
- schema: string;
215
- // use `* as` syntax?
216
- star: boolean;
217
- }
218
- }
219
-
220
- export interface TruePGOpts {
221
- uri: string;
222
- out: string;
223
- adapters: string[];
224
- defaultSchema?: string;
225
- }
226
-
227
- export interface CreateGeneratorOpts {
228
- defaultSchema?: string;
229
- warnings: string[];
230
- }
231
-
232
- export interface createGenerator {
233
- (opts?: CreateGeneratorOpts): SchemaGenerator;
234
- }
235
-
236
- /* convenience function to create a generator with type inference */
237
- export const createGenerator = (generatorCreator: createGenerator): createGenerator => generatorCreator;
238
-
239
- export interface SchemaGenerator {
240
- /**
241
- * Use this function to define a name mapping for schema names.
242
- * This is useful if you want to use a different name for a schema in the generated code.
243
- * Example: "public" -> "PublicSchema"
244
- */
245
- formatSchema(name: string): string;
246
-
247
- /**
248
- * Use this function to define a name mapping for schema types.
249
- * This is useful if you want to use a different name for a type in the generated code.
250
- * Example: "users" -> "UsersTable"
251
- */
252
- formatSchemaType(type: SchemaType): string;
253
-
254
- /**
255
- * Use this function to define a name mapping for type names.
256
- * This is useful if you want to use a different name for a type in the generated code.
257
- * Example: "users" -> "UsersTable"
258
- */
259
- formatType(type: CanonicalType): string;
260
-
261
- table(
262
- /** @out Append used types to this array */
263
- imports: Nodes.ImportList,
264
- /** Information about the table */
265
- table: TableDetails,
266
- ): string;
267
-
268
- enum(
269
- /** @out Append used types to this array */
270
- imports: Nodes.ImportList,
271
- /** Information about the enum */
272
- en: EnumDetails,
273
- ): string;
274
-
275
- composite(
276
- /** @out Append used types to this array */
277
- imports: Nodes.ImportList,
278
- /** Information about the composite type */
279
- type: CompositeTypeDetails,
280
- ): string;
281
-
282
- function(
283
- /** @out Append used types to this array */
284
- imports: Nodes.ImportList,
285
- /** Information about the function */
286
- type: FunctionDetails,
287
- ): string;
288
-
289
- /** create the file `$out/$schema.name/$kind/index.ts` */
290
- schemaKindIndex(schema: Schema, kind: Exclude<keyof Schema, "name">, main_generator?: SchemaGenerator): string;
291
-
292
- /** create the file `$out/$schema.name/index.ts` */
293
- schemaIndex(schema: Schema, main_generator?: SchemaGenerator): string;
294
-
295
- /** create the file `$out/index.ts` */
296
- fullIndex(schemas: Schema[], main_generator?: SchemaGenerator): string;
297
- }
package/src/util.ts DELETED
@@ -1 +0,0 @@
1
- export const join = (parts: Iterable<string>, joiner = "\n\n") => Array.from(parts).filter(Boolean).join(joiner);
@@ -1,38 +0,0 @@
1
- // extended from https://github.com/kristiandupont/kanel/blob/e9332f03ff5e38f5b844dd7a4563580c0d9d1444/packages/kanel/src/defaultTypeMap.ts
2
-
3
- export const builtins: Record<string, string> = {
4
- "pg_catalog.int2": "z.number()",
5
- "pg_catalog.int4": "z.number()",
6
-
7
- // JS numbers are always floating point, so there is only 53 bits of precision
8
- // for the integer part. Thus, storing a 64-bit integer in a JS number will
9
- // result in potential data loss. We therefore use strings for 64-bit integers
10
- // the same way that the pg driver does.
11
- "pg_catalog.int8": "z.string()",
12
-
13
- "pg_catalog.float4": "z.number()",
14
- "pg_catalog.float8": "z.number()",
15
- "pg_catalog.numeric": "z.string()",
16
- "pg_catalog.bool": "z.boolean()",
17
- "pg_catalog.json": "z.unknown()",
18
- "pg_catalog.jsonb": "z.unknown()",
19
- "pg_catalog.char": "z.string()",
20
- "pg_catalog.bpchar": "z.string()",
21
- "pg_catalog.varchar": "z.string()",
22
- "pg_catalog.text": "z.string()",
23
- "pg_catalog.uuid": "z.string()",
24
- "pg_catalog.inet": "z.string()",
25
- "pg_catalog.date": "z.date()",
26
- "pg_catalog.time": "z.date()",
27
- "pg_catalog.timetz": "z.date()",
28
- "pg_catalog.timestamp": "z.date()",
29
- "pg_catalog.timestamptz": "z.date()",
30
- "pg_catalog.int4range": "z.string()",
31
- "pg_catalog.int8range": "z.string()",
32
- "pg_catalog.numrange": "z.string()",
33
- "pg_catalog.tsrange": "z.string()",
34
- "pg_catalog.tstzrange": "z.string()",
35
- "pg_catalog.daterange": "z.string()",
36
- "pg_catalog.record": "z.record(z.string(), z.unknown())",
37
- "pg_catalog.void": "z.void()",
38
- };
package/src/zod/index.ts DELETED
@@ -1,301 +0,0 @@
1
- import type { CanonicalType, Schema, TableColumn } from "pg-extract";
2
- import { allowed_kind_names, createGenerator, Nodes, type SchemaGenerator } from "../types.ts";
3
- import { builtins } from "./builtins.ts";
4
- import { join } from "../util.ts";
5
-
6
- const isIdentifierInvalid = (str: string) => {
7
- const invalid = str.match(/[^a-zA-Z0-9_]/);
8
- return invalid !== null;
9
- };
10
-
11
- const to_snake_case = (str: string) =>
12
- str
13
- .replace(/^[^a-zA-Z]+/, "") // remove leading non-alphabetic characters
14
- .replace(/[^a-zA-Z0-9]+/g, "_") // replace non-alphanumeric characters with underscores
15
- .replace(/([A-Z])/g, "_$1") // insert underscores before uppercase letters
16
- .toLowerCase();
17
-
18
- // TODO: create an insert and update zod interface for each type
19
- export const Zod = createGenerator(opts => {
20
- const defaultSchema = opts?.defaultSchema ?? "public";
21
-
22
- const zod = (imports: Nodes.ImportList, name?: string) =>
23
- imports.add(
24
- new Nodes.ExternalImport({
25
- name: name ?? "z",
26
- module: "zod",
27
- typeOnly: false,
28
- star: !name,
29
- }),
30
- );
31
-
32
- const add = (imports: Nodes.ImportList, type: CanonicalType) => {
33
- if (type.schema === "pg_catalog") zod(imports, "z");
34
- else
35
- imports.add(
36
- new Nodes.InternalImport({
37
- name: generator.formatType(type),
38
- canonical_type: type,
39
- typeOnly: false,
40
- star: false,
41
- }),
42
- );
43
- };
44
-
45
- const column = (
46
- imports: Nodes.ImportList,
47
- /** Information about the column */
48
- col: TableColumn,
49
- ) => {
50
- // don't create a property for always generated columns
51
- if (col.generated === "ALWAYS") return "";
52
-
53
- let out = col.comment ? `/** ${col.comment} */\n\t` : "";
54
- out += col.name;
55
- let type = generator.formatType(col.type);
56
- add(imports, col.type);
57
- if (col.type.dimensions > 0) type += ".array()".repeat(col.type.dimensions);
58
- if (col.isNullable || col.generated === "BY DEFAULT" || col.defaultValue) type += `.nullable().optional()`;
59
- out += `: ${type}`;
60
-
61
- return `\t${out},\n`;
62
- };
63
-
64
- const composite_attribute = (imports: Nodes.ImportList, attr: CanonicalType.CompositeAttribute) => {
65
- let out = attr.name;
66
- out += `: ${generator.formatType(attr.type)}`;
67
- add(imports, attr.type);
68
- if (attr.type.dimensions > 0) out += ".array()".repeat(attr.type.dimensions);
69
- if (attr.isNullable) out += ".nullable().optional()";
70
-
71
- return out;
72
- };
73
-
74
- const generator: SchemaGenerator = {
75
- formatSchema(name) {
76
- return to_snake_case(name) + "_validators";
77
- },
78
-
79
- formatSchemaType(type) {
80
- return to_snake_case(type.name);
81
- },
82
-
83
- formatType(type) {
84
- if (type.schema === "pg_catalog") {
85
- const name = type.canonical_name;
86
- const format = builtins[name];
87
- if (format) return format;
88
- opts?.warnings?.push(
89
- `Unknown builtin type: ${name}! Pass customBuiltinMap to map this type. Defaulting to "z.unknown()".`,
90
- );
91
- return "z.unknown()";
92
- }
93
- return to_snake_case(type.name);
94
- },
95
-
96
- table(imports, table) {
97
- let out = "";
98
-
99
- if (table.comment) out += `/** ${table.comment} */\n`;
100
- out += `export const ${this.formatSchemaType(table)} = z.object({\n`;
101
- zod(imports, "z");
102
- for (const col of table.columns) out += column(imports, col);
103
- out += "});";
104
-
105
- return out;
106
- },
107
-
108
- enum(imports, en) {
109
- let out = "";
110
-
111
- if (en.comment) out += `/** ${en.comment} */\n`;
112
-
113
- out += `export const ${this.formatSchemaType(en)} = z.union([\n`;
114
- out += en.values.map(v => `\tz.literal("${v}")`).join(",\n");
115
- out += "\n]);";
116
-
117
- zod(imports, "z");
118
-
119
- return out;
120
- },
121
-
122
- composite(imports, type) {
123
- let out = "";
124
-
125
- if (type.comment) out += `/** ${type.comment} */\n`;
126
- out += `export const ${this.formatSchemaType(type)} = z.object({\n`;
127
-
128
- const props = type.canonical.attributes.map(c => composite_attribute(imports, c)).map(t => `\t${t},`);
129
- out += props.join("\n");
130
- out += "\n});";
131
-
132
- return out;
133
- },
134
-
135
- function(imports, type) {
136
- let out = "export const ";
137
- out += this.formatSchemaType(type);
138
- out += " = {\n";
139
-
140
- out += `\tparameters: z.tuple([`;
141
-
142
- // Get the input parameters (those that appear in function signature)
143
- const inputParams = type.parameters.filter(p => p.mode === "IN" || p.mode === "INOUT");
144
-
145
- if (inputParams.length === 0) {
146
- out += "])";
147
- } else {
148
- out += "\n";
149
-
150
- for (const param of inputParams) {
151
- // TODO: update imports for non-primitive types based on typeInfo.kind
152
- out += "\t\t" + this.formatType(param.type);
153
- add(imports, param.type);
154
- if (param.type.dimensions > 0) out += ".array()".repeat(param.type.dimensions);
155
- if (param.hasDefault) out += ".nullable().optional()";
156
- out += `, // ${param.name}\n`;
157
- }
158
-
159
- out += "\t])";
160
- }
161
-
162
- const variadic = type.parameters.find(p => p.mode === "VARIADIC");
163
- if (variadic) {
164
- out += ".rest(";
165
- out += this.formatType(variadic.type);
166
- // reduce by 1 because it's already a rest parameter
167
- if (variadic.type.dimensions > 1) out += ".array()".repeat(variadic.type.dimensions - 1);
168
- out += ")" + ", // " + variadic.name + "\n";
169
- } else out += ",\n";
170
-
171
- out += "\treturnType: ";
172
-
173
- if (type.returnType.kind === "table") {
174
- out += "z.object({\n";
175
- for (const col of type.returnType.columns) {
176
- out += `\t\t${col.name}: `;
177
- out += this.formatType(col.type);
178
- add(imports, col.type);
179
- if (col.type.dimensions > 0) out += ".array()".repeat(col.type.dimensions);
180
- out += `,\n`;
181
- }
182
- out += "\t})";
183
- } else {
184
- out += this.formatType(type.returnType.type);
185
- add(imports, type.returnType.type);
186
- if (type.returnType.type.dimensions > 0) out += ".array()".repeat(type.returnType.type.dimensions);
187
- }
188
-
189
- // Add additional array brackets if it returns a set
190
- if (type.returnType.isSet) out += ".array()";
191
- out += ",\n};";
192
-
193
- return out;
194
- },
195
-
196
- schemaKindIndex(schema, kind, main_generator) {
197
- const imports = schema[kind];
198
- if (imports.length === 0) return "";
199
- const generator = main_generator ?? this;
200
-
201
- return imports
202
- .map(each => {
203
- const name = this.formatSchemaType(each);
204
- const file = generator.formatSchemaType(each);
205
- return `export { ${name} } from "./${file}.ts";`;
206
- })
207
- .join("\n");
208
- },
209
-
210
- schemaIndex(schema, main_generator) {
211
- let out = allowed_kind_names.map(kind => `import * as zod_${kind} from "./${kind}/index.ts";`).join("\n");
212
-
213
- out += "\n\n";
214
- out += `export const ${this.formatSchema(schema.name)} = {\n`;
215
-
216
- for (const kind of allowed_kind_names) {
217
- const items = schema[kind];
218
- if (items.length === 0) continue;
219
-
220
- out += `\t${kind}: {\n`;
221
-
222
- const formatted = items
223
- .map(each => {
224
- const formatted = this.formatSchemaType(each);
225
- return { ...each, formatted };
226
- })
227
- .filter(x => x !== undefined);
228
-
229
- out += formatted
230
- .map(t => {
231
- let name = t.name;
232
- if (isIdentifierInvalid(name)) name = `"${name}"`;
233
- return `\t\t${name}: zod_${t.kind}s.${t.formatted},`;
234
- })
235
- .join("\n");
236
- out += "\n\t},\n";
237
- }
238
-
239
- out += "}";
240
-
241
- return out;
242
- },
243
-
244
- fullIndex(schemas: Schema[], main_generator) {
245
- const generator = main_generator ?? this;
246
-
247
- let out = "";
248
-
249
- out += schemas
250
- .map(s => `import { ${generator.formatSchema(s.name)} } from "./${s.name}/index.ts";`)
251
- .join("\n");
252
-
253
- out += "\n\n";
254
- out += `export const Validators = {\n`;
255
- out += join(
256
- schemas.map(schema => {
257
- const schema_validators = join(
258
- allowed_kind_names.map(kind => {
259
- const current = schema[kind];
260
-
261
- const seen = new Set<string>();
262
- const formatted = current
263
- .map(each => {
264
- const formatted = generator.formatSchemaType(each);
265
- // skip clashing names
266
- if (seen.has(formatted)) return;
267
- seen.add(formatted);
268
- return { ...each, formatted };
269
- })
270
- .filter(x => x !== undefined);
271
-
272
- if (!formatted.length) return "";
273
-
274
- let out = "";
275
- out += "\t// " + kind + "\n";
276
- out += join(
277
- formatted.map(t => {
278
- const prefix = defaultSchema === schema.name ? "" : schema.name + ".";
279
- let qualified = prefix + t.name;
280
- if (isIdentifierInvalid(qualified)) qualified = `"${qualified}"`;
281
- return `\t${qualified}: ${this.formatSchema(schema.name)}["${t.kind}s"]["${t.name}"],`;
282
- }),
283
- "\n",
284
- );
285
- return out;
286
- }),
287
- );
288
- return `\t/* -- ${schema.name} --*/\n\n` + schema_validators || "\t-- no validators\n\n";
289
- }),
290
- );
291
-
292
- out += "\n}\n\n";
293
-
294
- out += schemas.map(s => `export type { ${this.formatSchema(s.name)} };`).join("\n");
295
-
296
- return out;
297
- },
298
- };
299
-
300
- return generator;
301
- });
package/tsconfig.json DELETED
@@ -1,29 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- // Environment setup & latest features
4
- "lib": ["esnext"],
5
- "target": "ESNext",
6
- "module": "NodeNext",
7
- "moduleDetection": "force",
8
-
9
- // Bundler mode
10
- "moduleResolution": "nodenext",
11
- "allowImportingTsExtensions": true,
12
- "rewriteRelativeImportExtensions": true,
13
- "verbatimModuleSyntax": true,
14
-
15
- // Best practices
16
- "strict": true,
17
- "skipLibCheck": true,
18
- "noFallthroughCasesInSwitch": true,
19
- "noUncheckedIndexedAccess": true,
20
- "declaration": true,
21
-
22
- // Some stricter flags (disabled by default)
23
- "noUnusedLocals": false,
24
- "noUnusedParameters": false,
25
- "noPropertyAccessFromIndexSignature": false,
26
- "outDir": "lib"
27
- },
28
- "include": ["src/**/*.ts"]
29
- }