Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add dbml support for postgres #260

Open
wants to merge 1 commit into
base: dbml
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/components/EditorHeader/ControlPanel.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import { jsonToMermaid } from "../../utils/exportAs/mermaid";
import { isRtl } from "../../i18n/utils/rtl";
import { jsonToDocumentation } from "../../utils/exportAs/documentation";
import { IdContext } from "../Workspace";
import { jsonToDBML } from "../../utils/exportAs/dbml";

export default function ControlPanel({
diagramId,
Expand Down Expand Up @@ -1086,6 +1087,26 @@ export default function ControlPanel({
}));
},
},
{
DBML: () => {
setModal(MODAL.CODE);
const result = jsonToDBML({
tables: tables,
references: relationships,
notes: notes,
subjectAreas: areas,
database: database,
title: title,
...(databases[database].hasTypes && { types: types }),
...(databases[database].hasEnums && { enums: enums }),
});
setExportData((prev) => ({
...prev,
data: result,
extension: "dbml",
}));
},
},
],
function: () => {},
},
Expand Down
107 changes: 107 additions & 0 deletions src/utils/exportAs/dbml.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { toPostgres } from "../exportSQL/postgres";
import { DB } from '../../data/constants';

export function jsonToDBML(obj) {
let dbml = "Not supported yet.";

switch (obj.database) {
case DB.POSTGRES:
dbml = convertPostgresToDBML(toPostgres(obj));
break;
}

return dbml;
}

function convertPostgresToDBML(postgresSchema) {
function mapDataType(type) {
const typeMap = {
'character varying': 'varchar',
'character': 'char',
'text': 'text',
'integer': 'int',
'bigint': 'bigint',
'smallint': 'smallint',
'decimal': 'decimal',
'numeric': 'decimal',
'real': 'float',
'double precision': 'double',
'boolean': 'boolean',
'date': 'date',
'timestamp without time zone': 'datetime',
'timestamp with time zone': 'datetime',
'smallserial': 'smallserial',
'serial': 'serial',
'bigserial': 'bigserial',
};

return typeMap[type] || type; // Fallback to the original type if not mapped
}

let dbmlOutput = '';
const tableDefinitions = postgresSchema.split(/;\s*CREATE TABLE/i).filter(Boolean);

if (!tableDefinitions) {
return dbmlOutput;
}

tableDefinitions.forEach(definition => {
const tableNameMatch = definition.match(/"([^"]+)"/);
const columnsMatch = definition.match(/\(([^)]+)\)/);

if (!tableNameMatch || !columnsMatch) return;

const tableName = tableNameMatch[1];
const columns = columnsMatch[1].trim();

dbmlOutput += `Table ${tableName} {\n`;

// Split column definitions by comma, allowing for potential whitespace
const columnDefinitions = columns.split(/\s*,\s*(?![^()]*\))/);

columnDefinitions.forEach(colDef => {
// Match the column name and type, and check for additional attributes
const colMatch = colDef.match(/"([^"]+)"\s+(\w+)/);
if (!colMatch) return;

const colName = colMatch[1];
const colType = mapDataType(colMatch[2]);
const colDefExtras = [];
let colExtras = '';

if (/DEFAULT\s+([^)]+)/i.test(colDef)) {
const defaultValue = colDef.match(/DEFAULT\s+([^)]+)/i)[1];
colDefExtras.push(`default: '${defaultValue}'`);
}

if (/NOT NULL/i.test(colDef)) {
colDefExtras.push('not null');
}

if (/UNIQUE/i.test(colDef)) {
colDefExtras.push('unique');
}

if (colDefExtras.length > 0) {
colExtras = ` [${colDefExtras.join(', ')}]`;
}

dbmlOutput += ` ${colName} ${colType}${colExtras}\n`;
});

dbmlOutput += `}\n\n`;
});

// Handle foreign keys
const foreignKeyMatches = postgresSchema.match(/ALTER TABLE "([^"]+)"\s+ADD FOREIGN KEY\("([^"]+)"\)\s+REFERENCES "([^"]+)"\("([^"]+)"\)/g);
if (foreignKeyMatches) {
foreignKeyMatches.forEach(fk => {
const match = fk.match(/ALTER TABLE "([^"]+)"\s+ADD FOREIGN KEY\("([^"]+)"\)\s+REFERENCES "([^"]+)"\("([^"]+)"\)/);
if (match) {
dbmlOutput += `Ref: ${match[1]}.${match[2]} > ${match[3]}.${match[4]}\n`;
}
});
}

return dbmlOutput;
}
Loading