cogsbox-shape 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ import { z } from "zod";
2
+ import { createSchema, hasMany, shape } from "../schema";
3
+ export const userSchema = {
4
+ _tableName: "users",
5
+ id: shape.sql({ type: "int", pk: true }),
6
+ firstname: shape
7
+ .sql({ type: "varchar", length: 255 })
8
+ .db(({ zod }) => zod.min(1)),
9
+ surname: shape
10
+ .sql({ type: "varchar", length: 255 })
11
+ .db(({ zod }) => zod.min(1)),
12
+ email: shape
13
+ .sql({ type: "varchar", length: 255 })
14
+ .db(({ zod }) => zod.email()),
15
+ pets: hasMany({
16
+ fromKey: "id",
17
+ toKey: () => petSchema.userId,
18
+ schema: () => petSchema,
19
+ defaultCount: 1,
20
+ }),
21
+ };
22
+ export const petSchema = {
23
+ _tableName: "pets",
24
+ id: shape.sql({ type: "int", pk: true }).client(({ zod }) => zod.optional()),
25
+ name: shape.sql({ type: "varchar", length: 255 }),
26
+ userId: shape.sql({ type: "int" }),
27
+ fluffynessScale: shape
28
+ .sql({ type: "text" })
29
+ .client(({ zod }) => z.array(z.enum(["bald", "fuzzy", "fluffy", "poof"])))
30
+ .transform({
31
+ toClient: (value) => value.split(",").filter(Boolean),
32
+ toDb: (value) => value.join(","),
33
+ }),
34
+ favourite: shape
35
+ .sql({ type: "int" })
36
+ .client(({ zod }) => z.boolean())
37
+ .transform({
38
+ toClient: (dbValue) => dbValue === 1,
39
+ toDb: (clientValue) => (clientValue ? 1 : 0),
40
+ }),
41
+ };
42
+ export const { dbSchema, clientSchema, initialValues, serialized } = createSchema(userSchema);
@@ -0,0 +1,6 @@
1
+ import type { Schema } from "./schema";
2
+ type SchemaInput = Record<string, Schema<any>> | {
3
+ schemas: Record<string, Schema<any>>;
4
+ };
5
+ export declare function generateSQL(input: SchemaInput, outputPath?: string): Promise<string>;
6
+ export {};
@@ -0,0 +1,65 @@
1
+ import fs from "fs/promises";
2
+ // SQL Type mapping
3
+ const sqlTypeMap = {
4
+ int: "INTEGER",
5
+ varchar: (length = 255) => `VARCHAR(${length})`,
6
+ char: (length = 1) => `CHAR(${length})`,
7
+ text: "TEXT",
8
+ longtext: "LONGTEXT",
9
+ boolean: "BOOLEAN",
10
+ date: "DATE",
11
+ datetime: "DATETIME",
12
+ };
13
+ function isWrappedSchema(input) {
14
+ return (input !== null &&
15
+ typeof input === "object" &&
16
+ "schemas" in input &&
17
+ input.schemas !== null &&
18
+ typeof input.schemas === "object");
19
+ }
20
+ export async function generateSQL(input, outputPath = "cogsbox-shape-sql.sql") {
21
+ if (!input) {
22
+ throw new Error("No schema input provided");
23
+ }
24
+ // Extract schemas using type guard
25
+ const schemas = isWrappedSchema(input) ? input.schemas : input;
26
+ if (!schemas || typeof schemas !== "object") {
27
+ throw new Error("Invalid schemas input");
28
+ }
29
+ const sql = [];
30
+ // Generate SQL for each schema
31
+ for (const [name, schema] of Object.entries(schemas)) {
32
+ const tableName = schema._tableName;
33
+ const fields = [];
34
+ const foreignKeys = [];
35
+ // Process each field in the schema
36
+ for (const [fieldName, field] of Object.entries(schema)) {
37
+ if (fieldName === "_tableName")
38
+ continue;
39
+ // Handle regular fields
40
+ if ("sql" in field) {
41
+ const { type, nullable, pk, length } = field.sql;
42
+ const sqlType = typeof sqlTypeMap[type] === "function"
43
+ ? sqlTypeMap[type](length)
44
+ : sqlTypeMap[type];
45
+ fields.push(` ${fieldName} ${sqlType}${pk ? " PRIMARY KEY" : ""}${nullable ? "" : " NOT NULL"}`);
46
+ }
47
+ // Handle relations
48
+ if (typeof field === "function") {
49
+ const relation = field();
50
+ if (relation.type === "belongsTo") {
51
+ fields.push(` ${relation.fromKey} INTEGER`);
52
+ foreignKeys.push(` FOREIGN KEY (${relation.fromKey}) REFERENCES ${relation.schema._tableName}(id)`);
53
+ }
54
+ }
55
+ }
56
+ // Combine fields and foreign keys
57
+ const allFields = [...fields, ...foreignKeys];
58
+ // Create table SQL
59
+ sql.push(`CREATE TABLE ${tableName} (\n${allFields.join(",\n")}\n);\n`);
60
+ }
61
+ // Write to file
62
+ const sqlContent = sql.join("\n");
63
+ await fs.writeFile(outputPath, sqlContent, "utf-8");
64
+ return sqlContent;
65
+ }
@@ -0,0 +1 @@
1
+ export * from "./schema";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./schema";