Files
lettersoup-online/001_documentation/Requirements/REQ0006/convert.js
2025-05-09 14:14:00 +08:00

87 lines
2.3 KiB
JavaScript

//
// # REQ0015:
// ## PURPOSE:
//
// This is a script to convert `schema.json` exported from pocketbase to dbml formatted file `schema.dbml`
//
//
const fs = require("fs");
const path = require("path");
// Load schema.json
const schemaPath = path.join(process.cwd(), "schema.json");
const schema = JSON.parse(fs.readFileSync(schemaPath, "utf8"));
// Type mapping from PocketBase to DBML/SQL
const typeMapping = {
text: "text",
number: "integer",
bool: "boolean",
email: "text",
url: "varchar",
date: "datetime",
select: "varchar",
json: "text",
file: "file",
password: "varchar",
relation: "integer", // Assuming relations are stored as integer IDs
autodate: "datetime",
};
function convertToDBML(schema) {
let dbml = "";
dbml = "// Generated at: " + new Date().toISOString();
dbml = dbml + "\n\n\n";
let collectionIdToTableMapping = {};
for (const [idx, tableDef] of Object.entries(schema)) {
collectionIdToTableMapping[tableDef.id] = tableDef.name;
}
for (const [idx, tableDef] of Object.entries(schema)) {
console.log({ idx });
dbml += `// \n`;
dbml += `// collection id: ${tableDef.id} \n`;
dbml += `// collection name: ${tableDef.name} \n`;
dbml += `// collection type: ${tableDef.type} \n`;
dbml += `Table ${tableDef.name} {\n`;
for (const field of tableDef.fields) {
// Get field type
let fieldType = typeMapping[field.type] || "text";
// Handle special cases
if (field.type === "number" && field.options?.max === 1) {
fieldType = "boolean";
}
// Build field definition
let line = ` ${field.name} ${fieldType}`;
// Add constraints
const constraints = [];
if (field.name === "id" || field.primary) constraints.push("pk");
if (field.required) constraints.push("not null");
if (constraints.length > 0) line += ` [${constraints.join(", ")}]`;
if (field.collectionId) {
line += ` [ref: > ${
collectionIdToTableMapping[field.collectionId]
}.id] // ${field.id}`;
}
dbml += `${line}\n`;
console.log({ line });
}
dbml += "}\n\n";
}
return dbml;
}
// Convert and save
const dbmlOutput = convertToDBML(schema);
fs.writeFileSync("schema.dbml", dbmlOutput);
console.log("DBML file generated successfully!");