Skip to content

Database diagrams editor that allows you to visualize and design your DB with a single query.

feat(import-dbml): add import dbml functionality (#549)

Jonathan Fishnerb42451821229
diff --git a/src/components/code-snippet/languages/dbml-language.ts b/src/components/code-snippet/languages/dbml-language.ts
new file mode 100644
index 00000000..ab934b6a
--- /dev/null
+++ b/src/components/code-snippet/languages/dbml-language.ts
@@ -0,0 +1,54 @@
+import type { Monaco } from '@monaco-editor/react';
+import { dataTypes } from '@/lib/data/data-types/data-types';
+
+export const setupDBMLLanguage = (monaco: Monaco) => {
+ monaco.languages.register({ id: 'dbml' });
+
+ // Define themes for DBML
+ monaco.editor.defineTheme('dbml-dark', {
+ base: 'vs-dark',
+ inherit: true,
+ rules: [
+ { token: 'keyword', foreground: '569CD6' }, // Table, Ref keywords
+ { token: 'string', foreground: 'CE9178' }, // Strings
+ { token: 'annotation', foreground: '9CDCFE' }, // [annotations]
+ { token: 'delimiter', foreground: 'D4D4D4' }, // Braces {}
+ { token: 'operator', foreground: 'D4D4D4' }, // Operators
+ { token: 'datatype', foreground: '4EC9B0' }, // Data types
+ ],
+ colors: {},
+ });
+
+ monaco.editor.defineTheme('dbml-light', {
+ base: 'vs',
+ inherit: true,
+ rules: [
+ { token: 'keyword', foreground: '0000FF' }, // Table, Ref keywords
+ { token: 'string', foreground: 'A31515' }, // Strings
+ { token: 'annotation', foreground: '001080' }, // [annotations]
+ { token: 'delimiter', foreground: '000000' }, // Braces {}
+ { token: 'operator', foreground: '000000' }, // Operators
+ { token: 'type', foreground: '267F99' }, // Data types
+ ],
+ colors: {},
+ });
+
+ const dataTypesNames = dataTypes.map((dt) => dt.name);
+ const datatypePattern = dataTypesNames.join('|');
+
+ monaco.languages.setMonarchTokensProvider('dbml', {
+ keywords: ['Table', 'Ref', 'Indexes'],
+ datatypes: dataTypesNames,
+ tokenizer: {
+ root: [
+ [/\b(Table|Ref|Indexes)\b/, 'keyword'],
+ [/\[.*?\]/, 'annotation'],
+ [/".*?"/, 'string'],
+ [/'.*?'/, 'string'],
+ [/[{}]/, 'delimiter'],
+ [/[<>]/, 'operator'],
+ [new RegExp(`\\b(${datatypePattern})\\b`, 'i'), 'type'], // Added 'i' flag for case-insensitive matching
+ ],
+ },
+ });
+};
diff --git a/src/context/canvas-context/canvas-context.tsx b/src/context/canvas-context/canvas-context.tsx
new file mode 100644
index 00000000..994c71fa
--- /dev/null
+++ b/src/context/canvas-context/canvas-context.tsx
@@ -0,0 +1,22 @@
+import { createContext } from 'react';
+import { emptyFn } from '@/lib/utils';
+import type { Graph } from '@/lib/graph';
+import { createGraph } from '@/lib/graph';
+
+export interface CanvasContext {
+ reorderTables: (options?: { updateHistory?: boolean }) => void;
+ fitView: (options?: {
+ duration?: number;
+ padding?: number;
+ maxZoom?: number;
+ }) => void;
+ setOverlapGraph: (graph: Graph<string>) => void;
+ overlapGraph: Graph<string>;
+}
+
+export const canvasContext = createContext<CanvasContext>({
+ reorderTables: emptyFn,
+ fitView: emptyFn,
+ setOverlapGraph: emptyFn,
+ overlapGraph: createGraph(),
+});
diff --git a/src/context/canvas-context/canvas-provider.tsx b/src/context/canvas-context/canvas-provider.tsx
new file mode 100644
index 00000000..56cb89cd
--- /dev/null
+++ b/src/context/canvas-context/canvas-provider.tsx
@@ -0,0 +1,85 @@
+import React, { type ReactNode, useCallback, useState } from 'react';
+import { canvasContext } from './canvas-context';
+import { useChartDB } from '@/hooks/use-chartdb';
+import {
+ adjustTablePositions,
+ shouldShowTablesBySchemaFilter,
+} from '@/lib/domain/db-table';
+import { useReactFlow } from '@xyflow/react';
+import { findOverlappingTables } from '@/pages/editor-page/canvas/canvas-utils';
+import type { Graph } from '@/lib/graph';
+import { createGraph } from '@/lib/graph';
+
+interface CanvasProviderProps {
+ children: ReactNode;
+}
+
+export const CanvasProvider = ({ children }: CanvasProviderProps) => {
+ const { tables, relationships, updateTablesState, filteredSchemas } =
+ useChartDB();
+ const { fitView } = useReactFlow();
+ const [overlapGraph, setOverlapGraph] =
+ useState<Graph<string>>(createGraph());
+
+ const reorderTables = useCallback(
+ (
+ options: { updateHistory?: boolean } = {
+ updateHistory: true,
+ }
+ ) => {
+ const newTables = adjustTablePositions({
+ relationships,
+ tables: tables.filter((table) =>
+ shouldShowTablesBySchemaFilter(table, filteredSchemas)
+ ),
+ mode: 'all', // Use 'all' mode for manual reordering
+ });
+
+ const updatedOverlapGraph = findOverlappingTables({
+ tables: newTables,
+ });
+
+ updateTablesState(
+ (currentTables) =>
+ currentTables.map((table) => {
+ const newTable = newTables.find(
+ (t) => t.id === table.id
+ );
+ return {
+ id: table.id,
+ x: newTable?.x ?? table.x,
+ y: newTable?.y ?? table.y,
+ };
+ }),
+ {
+ updateHistory: options.updateHistory ?? true,
+ forceOverride: false,
+ }
+ );
+
+ setOverlapGraph(updatedOverlapGraph);
+
+ setTimeout(() => {
+ fitView({
+ duration: 500,
+ padding: 0.2,
+ maxZoom: 0.8,
+ });
+ }, 500);
+ },
+ [filteredSchemas, relationships, tables, updateTablesState, fitView]
+ );
+
+ return (
+ <canvasContext.Provider
+ value={{
+ reorderTables,
+ fitView,
+ setOverlapGraph,
+ overlapGraph,
+ }}
+ >
+ {children}
+ </canvasContext.Provider>
+ );
+};
diff --git a/src/context/dialog-context/dialog-context.tsx b/src/context/dialog-context/dialog-context.tsx
index 52f3b91d..b50a2fe7 100644
--- a/src/context/dialog-context/dialog-context.tsx
+++ b/src/context/dialog-context/dialog-context.tsx
@@ -61,6 +61,10 @@ export interface DialogContext {
params: Omit<ImportDiagramDialogProps, 'dialog'>
) => void;
closeImportDiagramDialog: () => void;
+
+ // Import DBML dialog
+ openImportDBMLDialog: () => void;
+ closeImportDBMLDialog: () => void;
}
export const dialogContext = createContext<DialogContext>({
@@ -86,4 +90,6 @@ export const dialogContext = createContext<DialogContext>({
closeImportDiagramDialog: emptyFn,
openBuckleDialog: emptyFn,
closeBuckleDialog: emptyFn,
+ openImportDBMLDialog: emptyFn,
+ closeImportDBMLDialog: emptyFn,
});
diff --git a/src/context/dialog-context/dialog-provider.tsx b/src/context/dialog-context/dialog-provider.tsx
index 1a1f1bbb..f4b409dd 100644
--- a/src/context/dialog-context/dialog-provider.tsx
+++ b/src/context/dialog-context/dialog-provider.tsx
@@ -18,6 +18,7 @@ import { ExportImageDialog } from '@/dialogs/export-image-dialog/export-image-di
import { ExportDiagramDialog } from '@/dialogs/export-diagram-dialog/export-diagram-dialog';
import { ImportDiagramDialog } from '@/dialogs/import-diagram-dialog/import-diagram-dialog';
import { BuckleDialog } from '@/dialogs/buckle-dialog/buckle-dialog';
+import { ImportDBMLDialog } from '@/dialogs/import-dbml-dialog/import-dbml-dialog';
export const DialogProvider: React.FC<React.PropsWithChildren> = ({
children,
@@ -88,7 +89,7 @@ export const DialogProvider: React.FC<React.PropsWithChildren> = ({
[setOpenTableSchemaDialog]
);
- // Export image dialog
+ // Export diagram dialog
const [openExportDiagramDialog, setOpenExportDiagramDialog] =
useState(false);
@@ -96,6 +97,9 @@ export const DialogProvider: React.FC<React.PropsWithChildren> = ({
const [openImportDiagramDialog, setOpenImportDiagramDialog] =
useState(false);
+ // Import DBML dialog
+ const [openImportDBMLDialog, setOpenImportDBMLDialog] = useState(false);
+
return (
<dialogContext.Provider
value={{
@@ -126,6 +130,8 @@ export const DialogProvider: React.FC<React.PropsWithChildren> = ({
openImportDiagramDialog: () => setOpenImportDiagramDialog(true),
closeImportDiagramDialog: () =>
setOpenImportDiagramDialog(false),
+ openImportDBMLDialog: () => setOpenImportDBMLDialog(true),
+ closeImportDBMLDialog: () => setOpenImportDBMLDialog(false),
}}
>
{children}
@@ -154,6 +160,7 @@ export const DialogProvider: React.FC<React.PropsWithChildren> = ({
<ExportDiagramDialog dialog={{ open: openExportDiagramDialog }} />
<ImportDiagramDialog dialog={{ open: openImportDiagramDialog }} />
<BuckleDialog dialog={{ open: openBuckleDialog }} />
+ <ImportDBMLDialog dialog={{ open: openImportDBMLDialog }} />
</dialogContext.Provider>
);
};
diff --git a/src/dialogs/import-dbml-dialog/import-dbml-dialog.tsx b/src/dialogs/import-dbml-dialog/import-dbml-dialog.tsx
new file mode 100644
index 00000000..5611a33d
--- /dev/null
+++ b/src/dialogs/import-dbml-dialog/import-dbml-dialog.tsx
@@ -0,0 +1,279 @@
+import React, { useCallback, useEffect, useState } from 'react';
+import { useDialog } from '@/hooks/use-dialog';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogInternalContent,
+ DialogTitle,
+} from '@/components/dialog/dialog';
+import { Button } from '@/components/button/button';
+import type { BaseDialogProps } from '../common/base-dialog-props';
+import { useTranslation } from 'react-i18next';
+import { Editor } from '@/components/code-snippet/code-editor';
+import { useTheme } from '@/hooks/use-theme';
+import { AlertCircle } from 'lucide-react';
+import { importDBMLToDiagram } from '@/lib/dbml-import';
+import { useChartDB } from '@/hooks/use-chartdb';
+import { Parser } from '@dbml/core';
+import { useCanvas } from '@/hooks/use-canvas';
+import { setupDBMLLanguage } from '@/components/code-snippet/languages/dbml-language';
+import { useToast } from '@/components/toast/use-toast';
+
+export interface ImportDBMLDialogProps extends BaseDialogProps {}
+
+export const ImportDBMLDialog: React.FC<ImportDBMLDialogProps> = ({
+ dialog,
+}) => {
+ const { t } = useTranslation();
+ const initialDBML = `// Use DBML to define your database structure
+// Simple Blog System with Comments Example
+
+Table users {
+ id integer [primary key]
+ name varchar
+ email varchar
+}
+
+Table posts {
+ id integer [primary key]
+ title varchar
+ content text
+ user_id integer
+ created_at timestamp
+}
+
+Table comments {
+ id integer [primary key]
+ content text
+ post_id integer
+ user_id integer
+ created_at timestamp
+}
+
+// Relationships
+Ref: posts.user_id > users.id // Each post belongs to one user
+Ref: comments.post_id > posts.id // Each comment belongs to one post
+Ref: comments.user_id > users.id // Each comment is written by one user`;
+
+ const [dbmlContent, setDBMLContent] = useState<string>(initialDBML);
+ const { closeImportDBMLDialog } = useDialog();
+ const [errorMessage, setErrorMessage] = useState<string | undefined>();
+ const { effectiveTheme } = useTheme();
+ const { toast } = useToast();
+ const {
+ addTables,
+ addRelationships,
+ tables,
+ relationships,
+ removeTables,
+ removeRelationships,
+ } = useChartDB();
+ const { reorderTables } = useCanvas();
+ const [reorder, setReorder] = useState(false);
+
+ useEffect(() => {
+ if (reorder) {
+ reorderTables({
+ updateHistory: false,
+ });
+ setReorder(false);
+ }
+ }, [reorder, reorderTables]);
+
+ useEffect(() => {
+ if (!dialog.open) return;
+ setErrorMessage(undefined);
+ setDBMLContent(initialDBML);
+ }, [dialog.open, initialDBML]);
+
+ useEffect(() => {
+ const validateDBML = async () => {
+ if (!dbmlContent.trim()) {
+ setErrorMessage(undefined);
+ return;
+ }
+
+ try {
+ const parser = new Parser();
+ parser.parse(dbmlContent, 'dbml');
+ setErrorMessage(undefined);
+ } catch (e) {
+ setErrorMessage(
+ e instanceof Error
+ ? e.message
+ : t('import_dbml_dialog.error.description')
+ );
+ }
+ };
+
+ validateDBML();
+ }, [dbmlContent, t]);
+
+ const handleImport = useCallback(async () => {
+ if (!dbmlContent.trim() || errorMessage) return;
+
+ try {
+ const importedDiagram = await importDBMLToDiagram(dbmlContent);
+ const tableIdsToRemove = tables
+ .filter((table) =>
+ importedDiagram.tables?.some(
+ (t) =>
+ t.name === table.name && t.schema === table.schema
+ )
+ )
+ .map((table) => table.id);
+ // Find relationships that need to be removed
+ const relationshipIdsToRemove = relationships
+ .filter((relationship) => {
+ const sourceTable = tables.find(
+ (table) => table.id === relationship.sourceTableId
+ );
+ const targetTable = tables.find(
+ (table) => table.id === relationship.targetTableId
+ );
+ if (!sourceTable || !targetTable) return true;
+ const replacementSourceTable = importedDiagram.tables?.find(
+ (table) =>
+ table.name === sourceTable.name &&
+ table.schema === sourceTable.schema
+ );
+ const replacementTargetTable = importedDiagram.tables?.find(
+ (table) =>
+ table.name === targetTable.name &&
+ table.schema === targetTable.schema
+ );
+ return replacementSourceTable || replacementTargetTable;
+ })
+ .map((relationship) => relationship.id);
+
+ // Remove existing items
+ await Promise.all([
+ removeTables(tableIdsToRemove, { updateHistory: false }),
+ removeRelationships(relationshipIdsToRemove, {
+ updateHistory: false,
+ }),
+ ]);
+
+ // Add new items
+ await Promise.all([
+ addTables(importedDiagram.tables ?? [], {
+ updateHistory: false,
+ }),
+ addRelationships(importedDiagram.relationships ?? [], {
+ updateHistory: false,
+ }),
+ ]);
+ setReorder(true);
+ closeImportDBMLDialog();
+ } catch (e) {
+ toast({
+ title: t('import_dbml_dialog.error.title'),
+ variant: 'destructive',
+ description: (
+ <>
+ <div>{t('import_dbml_dialog.error.description')}</div>
+ {e instanceof Error ? <div>{e.message}</div> : null}
+ </>
+ ),
+ });
+ }
+ }, [
+ dbmlContent,
+ closeImportDBMLDialog,
+ tables,
+ relationships,
+ removeTables,
+ removeRelationships,
+ addTables,
+ addRelationships,
+ errorMessage,
+ toast,
+ setReorder,
+ t,
+ ]);
+
+ return (
+ <Dialog
+ {...dialog}
+ onOpenChange={(open) => {
+ if (!open) {
+ closeImportDBMLDialog();
+ }
+ }}
+ >
+ <DialogContent
+ className="flex h-[80vh] max-h-screen flex-col"
+ showClose
+ >
+ <DialogHeader>
+ <DialogTitle>{t('import_dbml_dialog.title')}</DialogTitle>
+ <DialogDescription>
+ {t('import_dbml_dialog.description')}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogInternalContent className="flex-1">
+ <div className="flex h-full flex-col gap-4">
+ <div className="relative size-full min-h-[400px]">
+ <Editor
+ value={dbmlContent}
+ onChange={(value) =>
+ setDBMLContent(value || '')
+ }
+ language="dbml"
+ theme={
+ effectiveTheme === 'dark'
+ ? 'dbml-dark'
+ : 'dbml-light'
+ }
+ beforeMount={setupDBMLLanguage}
+ options={{
+ minimap: { enabled: false },
+ scrollBeyondLastLine: false,
+ automaticLayout: true,
+ scrollbar: {
+ vertical: 'visible',
+ horizontal: 'visible',
+ },
+ }}
+ className="size-full"
+ />
+ </div>
+ </div>
+ </DialogInternalContent>
+ <DialogFooter>
+ <div className="flex w-full items-center justify-between">
+ <div className="flex items-center gap-4">
+ <DialogClose asChild>
+ <Button variant="secondary">
+ {t('import_dbml_dialog.cancel')}
+ </Button>
+ </DialogClose>
+ {errorMessage ? (
+ <div className="flex items-center gap-1">
+ <AlertCircle className="size-4 text-destructive" />
+
+ <span className="text-xs text-destructive">
+ {errorMessage ||
+ t(
+ 'import_dbml_dialog.error.description'
+ )}
+ </span>
+ </div>
+ ) : null}
+ </div>
+ <Button
+ onClick={handleImport}
+ disabled={!dbmlContent.trim() || !!errorMessage}
+ >
+ {t('import_dbml_dialog.import')}
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/src/hooks/use-canvas.ts b/src/hooks/use-canvas.ts
new file mode 100644
index 00000000..254e68bc
--- /dev/null
+++ b/src/hooks/use-canvas.ts
@@ -0,0 +1,4 @@
+import { useContext } from 'react';
+import { canvasContext } from '@/context/canvas-context/canvas-context';
+
+export const useCanvas = () => useContext(canvasContext);
diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts
index 68bc9657..87cc5446 100644
--- a/src/i18n/locales/ar.ts
+++ b/src/i18n/locales/ar.ts
@@ -8,7 +8,7 @@ export const ar: LanguageTranslation = {
new: 'جديد',
open: 'فتح',
save: 'حفظ',
- import_database: 'استيراد قاعدة بيانات',
+ import: 'استيراد قاعدة بيانات',
export_sql: 'SQL تصدير',
export_as: 'تصدير كـ',
delete_diagram: 'حذف الرسم البياني',
@@ -364,7 +364,6 @@ export const ar: LanguageTranslation = {
'[email protected] حدث خطأ ما. هل تحتاج إلى مساعدة؟',
},
},
-
import_diagram_dialog: {
title: 'استيراد الرسم البياني',
description: ':للرسم البياني ادناه JSON قم بلصق',
@@ -376,6 +375,17 @@ export const ar: LanguageTranslation = {
'[email protected] و المحاولة مرة اخرى. هل تحتاج إلى المساعدة؟ JSON غير صالح. يرجى التحقق من JSON الرسم البياني',
},
},
+ import_dbml_dialog: {
+ // TODO: Translate
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'واحد إلى واحد',
one_to_many: 'واحد إلى متعدد',
diff --git a/src/i18n/locales/bn.ts b/src/i18n/locales/bn.ts
index 42bcae13..07cb239a 100644
--- a/src/i18n/locales/bn.ts
+++ b/src/i18n/locales/bn.ts
@@ -8,7 +8,7 @@ export const bn: LanguageTranslation = {
new: 'নতুন',
open: 'খুলুন',
save: 'সংরক্ষণ করুন',
- import_database: 'ডাটাবেস আমদানি করুন',
+ import: 'ডাটাবেস আমদানি করুন',
export_sql: 'SQL রপ্তানি করুন',
export_as: 'রূপে রপ্তানি করুন',
delete_diagram: 'ডায়াগ্রাম মুছুন',
@@ -379,6 +379,17 @@ export const bn: LanguageTranslation = {
'ডায়াগ্রাম JSON অবৈধ। অনুগ্রহ করে JSON পরীক্ষা করুন এবং আবার চেষ্টা করুন। সাহায্যের প্রয়োজন? [email protected]এ যোগাযোগ করুন।',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'এক থেকে এক',
one_to_many: 'এক থেকে অনেক',
diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts
index 2d3ad169..6a4685c5 100644
--- a/src/i18n/locales/de.ts
+++ b/src/i18n/locales/de.ts
@@ -8,7 +8,7 @@ export const de: LanguageTranslation = {
new: 'Neu',
open: 'Öffnen',
save: 'Speichern',
- import_database: 'Datenbank importieren',
+ import: 'Datenbank importieren',
export_sql: 'SQL exportieren',
export_as: 'Exportieren als',
delete_diagram: 'Diagramm löschen',
@@ -382,6 +382,17 @@ export const de: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Ein zu Eins (1:1)',
one_to_many: 'Ein zu Viele (1:n)',
diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts
index cd2fbda6..a739ff5f 100644
--- a/src/i18n/locales/en.ts
+++ b/src/i18n/locales/en.ts
@@ -8,7 +8,7 @@ export const en = {
new: 'New',
open: 'Open',
save: 'Save',
- import_database: 'Import Database',
+ import: 'Import',
export_sql: 'Export SQL',
export_as: 'Export as',
delete_diagram: 'Delete Diagram',
@@ -365,7 +365,7 @@ export const en = {
import_diagram_dialog: {
title: 'Import Diagram',
- description: 'Paste the diagram JSON below:',
+ description: 'Import a diagram from a JSON file.',
cancel: 'Cancel',
import: 'Import',
error: {
@@ -374,6 +374,17 @@ export const en = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error importing DBML',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'One to One',
one_to_many: 'One to Many',
diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts
index f3a7d6ca..ef356899 100644
--- a/src/i18n/locales/es.ts
+++ b/src/i18n/locales/es.ts
@@ -8,7 +8,7 @@ export const es: LanguageTranslation = {
new: 'Nuevo',
open: 'Abrir',
save: 'Guardar',
- import_database: 'Importar Base de Datos',
+ import: 'Importar Base de Datos',
export_sql: 'Exportar SQL',
export_as: 'Exportar como',
delete_diagram: 'Eliminar Diagrama',
@@ -381,6 +381,17 @@ export const es: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Uno a Uno',
one_to_many: 'Uno a Muchos',
diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts
index 1f23b7f8..a02a5302 100644
--- a/src/i18n/locales/fr.ts
+++ b/src/i18n/locales/fr.ts
@@ -8,7 +8,7 @@ export const fr: LanguageTranslation = {
new: 'Nouveau',
open: 'Ouvrir',
save: 'Enregistrer',
- import_database: 'Importer Base de Données',
+ import: 'Importer Base de Données',
export_sql: 'Exporter SQL',
export_as: 'Exporter en tant que',
delete_diagram: 'Supprimer le Diagramme',
@@ -383,6 +383,17 @@ export const fr: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Un à Un',
one_to_many: 'Un à Plusieurs',
diff --git a/src/i18n/locales/gu.ts b/src/i18n/locales/gu.ts
index c9c150c5..33c1bbea 100644
--- a/src/i18n/locales/gu.ts
+++ b/src/i18n/locales/gu.ts
@@ -8,7 +8,7 @@ export const gu: LanguageTranslation = {
new: 'નવું',
open: 'ખોલો',
save: 'સાચવો',
- import_database: 'ડેટાબેસ આયાત કરો',
+ import: 'ડેટાબેસ આયાત કરો',
export_sql: 'SQL નિકાસ કરો',
export_as: 'રૂપે નિકાસ કરો',
delete_diagram: 'ડાયાગ્રામ કાઢી નાખો',
@@ -379,6 +379,17 @@ export const gu: LanguageTranslation = {
'ડાયાગ્રામ JSON અમાન્ય છે. કૃપા કરીને JSON તપાસો અને ફરી પ્રયાસ કરો. મદદ જોઈએ? [email protected] પર સંપર્ક કરો.',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'એકથી એક',
one_to_many: 'એકથી ઘણા',
diff --git a/src/i18n/locales/hi.ts b/src/i18n/locales/hi.ts
index 08f2be27..7c2e5b95 100644
--- a/src/i18n/locales/hi.ts
+++ b/src/i18n/locales/hi.ts
@@ -8,7 +8,7 @@ export const hi: LanguageTranslation = {
new: 'नया',
open: 'खोलें',
save: 'सहेजें',
- import_database: 'डेटाबेस आयात करें',
+ import: 'डेटाबेस आयात करें',
export_sql: 'SQL निर्यात करें',
export_as: 'के रूप में निर्यात करें',
delete_diagram: 'आरेख हटाएँ',
@@ -383,6 +383,17 @@ export const hi: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'एक से एक',
one_to_many: 'एक से कई',
diff --git a/src/i18n/locales/id_ID.ts b/src/i18n/locales/id_ID.ts
index ce4c3c73..a8d90795 100644
--- a/src/i18n/locales/id_ID.ts
+++ b/src/i18n/locales/id_ID.ts
@@ -8,7 +8,7 @@ export const id_ID: LanguageTranslation = {
new: 'Buat Baru',
open: 'Buka',
save: 'Simpan',
- import_database: 'Impor Database',
+ import: 'Impor Database',
export_sql: 'Ekspor SQL',
export_as: 'Ekspor Sebagai',
delete_diagram: 'Hapus Diagram',
@@ -377,6 +377,17 @@ export const id_ID: LanguageTranslation = {
'Diagram JSON tidak valid. Silakan cek JSON dan coba lagi. Butuh bantuan? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Satu ke Satu',
diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts
index 128b057c..1864952f 100644
--- a/src/i18n/locales/ja.ts
+++ b/src/i18n/locales/ja.ts
@@ -8,7 +8,7 @@ export const ja: LanguageTranslation = {
new: '新規',
open: '開く',
save: '保存',
- import_database: 'データベースをインポート',
+ import: 'データベースをインポート',
export_sql: 'SQLをエクスポート',
export_as: '形式を指定してエクスポート',
delete_diagram: 'ダイアグラムを削除',
@@ -386,6 +386,17 @@ export const ja: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: '1対1',
one_to_many: '1対多',
diff --git a/src/i18n/locales/ko_KR.ts b/src/i18n/locales/ko_KR.ts
index 3f22fe63..93e709cd 100644
--- a/src/i18n/locales/ko_KR.ts
+++ b/src/i18n/locales/ko_KR.ts
@@ -8,7 +8,7 @@ export const ko_KR: LanguageTranslation = {
new: '새 다이어그램',
open: '열기',
save: '저장',
- import_database: '데이터베이스 가져오기',
+ import: '데이터베이스 가져오기',
export_sql: 'SQL로 저장',
export_as: '다른 형식으로 저장',
delete_diagram: '다이어그램 삭제',
@@ -375,6 +375,17 @@ export const ko_KR: LanguageTranslation = {
'다이어그램 JSON이 유효하지 않습니다. JSON이 올바른 형식인지 확인해주세요. 도움이 필요하신 경우 [email protected]으로 연락해주세요.',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: '일대일 (1:1)',
one_to_many: '일대다 (1:N)',
diff --git a/src/i18n/locales/mr.ts b/src/i18n/locales/mr.ts
index bf98e2c6..3e541773 100644
--- a/src/i18n/locales/mr.ts
+++ b/src/i18n/locales/mr.ts
@@ -8,7 +8,7 @@ export const mr: LanguageTranslation = {
new: 'नवीन',
open: 'उघडा',
save: 'जतन करा',
- import_database: 'डेटाबेस इम्पोर्ट करा',
+ import: 'डेटाबेस इम्पोर्ट करा',
export_sql: 'SQL एक्स्पोर्ट करा',
export_as: 'म्हणून एक्स्पोर्ट करा',
delete_diagram: 'आरेख हटवा',
@@ -387,6 +387,17 @@ export const mr: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'एक ते एक',
diff --git a/src/i18n/locales/ne.ts b/src/i18n/locales/ne.ts
index cf4b8e45..dee85ad1 100644
--- a/src/i18n/locales/ne.ts
+++ b/src/i18n/locales/ne.ts
@@ -8,7 +8,7 @@ export const ne: LanguageTranslation = {
new: 'नयाँ',
open: 'खोल्नुहोस्',
save: 'सुरक्षित गर्नुहोस्',
- import_database: 'डाटाबेस आयात गर्नुहोस्',
+ import: 'डाटाबेस आयात गर्नुहोस्',
export_sql: 'SQL निर्यात गर्नुहोस्',
export_as: 'निर्यात गर्नुहोस्',
delete_diagram: 'डायाग्राम हटाउनुहोस्',
@@ -380,6 +380,17 @@ export const ne: LanguageTranslation = {
'डायाग्राम JSON अमान्य छ। कृपया JSON जाँच गर्नुहोस् र पुन: प्रयास गर्नुहोस्। मद्दत चाहिन्छ? [email protected] मा सम्पर्क गर्नुहोस्',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'एक देखि एक',
diff --git a/src/i18n/locales/pt_BR.ts b/src/i18n/locales/pt_BR.ts
index 9ff01212..979448ad 100644
--- a/src/i18n/locales/pt_BR.ts
+++ b/src/i18n/locales/pt_BR.ts
@@ -8,7 +8,7 @@ export const pt_BR: LanguageTranslation = {
new: 'Novo',
open: 'Abrir',
save: 'Salvar',
- import_database: 'Importar Banco de Dados',
+ import: 'Importar Banco de Dados',
export_sql: 'Exportar SQL',
export_as: 'Exportar como',
delete_diagram: 'Excluir Diagrama',
@@ -380,6 +380,17 @@ export const pt_BR: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Um para Um',
one_to_many: 'Um para Muitos',
diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts
index 1c65ddb2..bba34a8d 100644
--- a/src/i18n/locales/ru.ts
+++ b/src/i18n/locales/ru.ts
@@ -8,7 +8,7 @@ export const ru: LanguageTranslation = {
new: 'Создать',
open: 'Открыть',
save: 'Сохранить',
- import_database: 'Импортировать базу данных',
+ import: 'Импортировать базу данных',
export_sql: 'Экспорт SQL',
export_as: 'Экспортировать как',
delete_diagram: 'Удалить диаграмму',
@@ -376,6 +376,17 @@ export const ru: LanguageTranslation = {
'Код JSON диаграммы некорректен. Проверьте, пожалуйста, код и попробуйте снова. Проблема не решается? Напишите нам: [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Один к одному',
one_to_many: 'Один ко многим',
diff --git a/src/i18n/locales/te.ts b/src/i18n/locales/te.ts
index 6fff0f10..6862fede 100644
--- a/src/i18n/locales/te.ts
+++ b/src/i18n/locales/te.ts
@@ -8,7 +8,7 @@ export const te: LanguageTranslation = {
new: 'కొత్తది',
open: 'తెరవు',
save: 'సేవ్',
- import_database: 'డేటాబేస్‌ను దిగుమతి చేసుకోండి',
+ import: 'డేటాబేస్‌ను దిగుమతి చేసుకోండి',
export_sql: 'SQL ఎగుమతి',
export_as: 'వగా ఎగుమతి చేయండి',
delete_diagram: 'చిత్రాన్ని తొలగించండి',
@@ -383,6 +383,17 @@ export const te: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'ఒకటి_కీ_ఒకటి',
diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts
index 9676bd19..e5e2f0a8 100644
--- a/src/i18n/locales/tr.ts
+++ b/src/i18n/locales/tr.ts
@@ -8,7 +8,7 @@ export const tr: LanguageTranslation = {
new: 'Yeni',
open: 'Aç',
save: 'Kaydet',
- import_database: 'Veritabanı İçe Aktar',
+ import: 'Veritabanı İçe Aktar',
export_sql: 'SQL Olarak Dışa Aktar',
export_as: 'Olarak Dışa Aktar',
delete_diagram: 'Diyagramı Sil',
@@ -370,6 +370,17 @@ export const tr: LanguageTranslation = {
'The diagram JSON is invalid. Please check the JSON and try again. Need help? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Bir Bir',
one_to_many: 'Bir Çok',
diff --git a/src/i18n/locales/uk.ts b/src/i18n/locales/uk.ts
index 6316c01f..ea7eba70 100644
--- a/src/i18n/locales/uk.ts
+++ b/src/i18n/locales/uk.ts
@@ -8,7 +8,7 @@ export const uk: LanguageTranslation = {
new: 'Новий',
open: 'Відкрити',
save: 'Зберегти',
- import_database: 'Імпорт бази даних',
+ import: 'Імпорт бази даних',
export_sql: 'Експорт SQL',
export_as: 'Експортувати як',
delete_diagram: 'Видалити діаграму',
@@ -375,6 +375,17 @@ export const uk: LanguageTranslation = {
'JSON діаграми є неправильним. Будь ласка, перевірте JSON і спробуйте ще раз. Потрібна допомога? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Один до Одного',
one_to_many: 'Один до Багатьох',
diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts
index 74dfe94c..d53cc888 100644
--- a/src/i18n/locales/vi.ts
+++ b/src/i18n/locales/vi.ts
@@ -8,7 +8,7 @@ export const vi: LanguageTranslation = {
new: 'Tạo mới',
open: 'Mở',
save: 'Lưu',
- import_database: 'Nhập cơ sở dữ liệu',
+ import: 'Nhập cơ sở dữ liệu',
export_sql: 'Xuất SQL',
export_as: 'Xuất thành',
delete_diagram: 'Xóa sơ đồ',
@@ -376,6 +376,17 @@ export const vi: LanguageTranslation = {
'Sơ đồ ở dạng JSON không hợp lệ. Vui lòng kiểm tra JSON và thử lại. Bạn cần trợ giúp? [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: 'Quan hệ một-một',
one_to_many: 'Quan hệ một-nhiều',
diff --git a/src/i18n/locales/zh_CN.ts b/src/i18n/locales/zh_CN.ts
index 939c56b1..e9d6daef 100644
--- a/src/i18n/locales/zh_CN.ts
+++ b/src/i18n/locales/zh_CN.ts
@@ -8,7 +8,7 @@ export const zh_CN: LanguageTranslation = {
new: '新建',
open: '打开',
save: '保存',
- import_database: '导入数据库',
+ import: '导入数据库',
export_sql: '导出 SQL 语句',
export_as: '导出为',
delete_diagram: '删除关系图',
@@ -372,6 +372,17 @@ export const zh_CN: LanguageTranslation = {
'关系图 JSON 无效,请检查 JSON 后重试。需要帮助? 联系 [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: '一对一',
one_to_many: '一对多',
diff --git a/src/i18n/locales/zh_TW.ts b/src/i18n/locales/zh_TW.ts
index ed116cbe..2ccb4429 100644
--- a/src/i18n/locales/zh_TW.ts
+++ b/src/i18n/locales/zh_TW.ts
@@ -8,7 +8,7 @@ export const zh_TW: LanguageTranslation = {
new: '新增',
open: '開啟',
save: '儲存',
- import_database: '匯入資料庫',
+ import: '匯入資料庫',
export_sql: '匯出 SQL',
export_as: '匯出為特定格式',
delete_diagram: '刪除圖表',
@@ -371,6 +371,17 @@ export const zh_TW: LanguageTranslation = {
'圖表的 JSON 無效。請檢查 JSON 並再試一次。如需幫助,請聯繫 [email protected]',
},
},
+ // TODO: Translate
+ import_dbml_dialog: {
+ title: 'Import DBML',
+ description: 'Import a database schema from DBML format.',
+ import: 'Import',
+ cancel: 'Cancel',
+ error: {
+ title: 'Error',
+ description: 'Failed to import DBML. Please check the syntax.',
+ },
+ },
relationship_type: {
one_to_one: '一對一',
one_to_many: '一對多',
diff --git a/src/lib/dbml-import.ts b/src/lib/dbml-import.ts
new file mode 100644
index 00000000..2f59d8af
--- /dev/null
+++ b/src/lib/dbml-import.ts
@@ -0,0 +1,221 @@
+import { Parser } from '@dbml/core';
+import type { Diagram } from '@/lib/domain/diagram';
+import { generateDiagramId, generateId } from '@/lib/utils';
+import type { DBTable } from '@/lib/domain/db-table';
+import type { Cardinality, DBRelationship } from '@/lib/domain/db-relationship';
+import type { DBField } from '@/lib/domain/db-field';
+import type { DataType } from '@/lib/data/data-types/data-types';
+import { genericDataTypes } from '@/lib/data/data-types/generic-data-types';
+import { randomColor } from '@/lib/colors';
+import { DatabaseType } from '@/lib/domain/database-type';
+
+interface DBMLTypeArgs {
+ length?: number;
+ precision?: number;
+ scale?: number;
+ values?: string[]; // For enum types
+}
+
+interface DBMLField {
+ name: string;
+ type: {
+ type_name: string;
+ args?: DBMLTypeArgs;
+ };
+ unique?: boolean;
+ pk?: boolean;
+ not_null?: boolean;
+ increment?: boolean;
+}
+
+interface DBMLTable {
+ name: string;
+ schema?: string | { name: string };
+ fields: DBMLField[];
+}
+
+interface DBMLEndpoint {
+ tableName: string;
+ fieldNames: string[];
+ relation: string;
+}
+
+interface DBMLRef {
+ endpoints: [DBMLEndpoint, DBMLEndpoint];
+}
+
+const mapDBMLTypeToGenericType = (dbmlType: string): DataType => {
+ const normalizedType = dbmlType.toLowerCase().replace(/\(.*\)/, '');
+ const matchedType = genericDataTypes.find((t) => t.id === normalizedType);
+ if (matchedType) return matchedType;
+ const typeMap: Record<string, string> = {
+ int: 'integer',
+ varchar: 'varchar',
+ bool: 'boolean',
+ number: 'numeric',
+ string: 'varchar',
+ text: 'text',
+ timestamp: 'timestamp',
+ datetime: 'timestamp',
+ float: 'float',
+ double: 'double',
+ decimal: 'decimal',
+ bigint: 'bigint',
+ smallint: 'smallint',
+ char: 'char',
+ };
+ const mappedType = typeMap[normalizedType];
+ if (mappedType) {
+ const foundType = genericDataTypes.find((t) => t.id === mappedType);
+ if (foundType) return foundType;
+ }
+ return genericDataTypes.find((t) => t.id === 'varchar')!;
+};
+
+const determineCardinality = (
+ field: DBField,
+ referencedField: DBField
+): { sourceCardinality: string; targetCardinality: string } => {
+ const isSourceUnique = field.unique || field.primaryKey;
+ const isTargetUnique = referencedField.unique || referencedField.primaryKey;
+ if (isSourceUnique && isTargetUnique) {
+ return { sourceCardinality: 'one', targetCardinality: 'one' };
+ } else if (isSourceUnique) {
+ return { sourceCardinality: 'one', targetCardinality: 'many' };
+ } else if (isTargetUnique) {
+ return { sourceCardinality: 'many', targetCardinality: 'one' };
+ } else {
+ return { sourceCardinality: 'many', targetCardinality: 'many' };
+ }
+};
+
+export const importDBMLToDiagram = async (
+ dbmlContent: string
+): Promise<Diagram> => {
+ try {
+ const parser = new Parser();
+ const parsedData = parser.parse(dbmlContent, 'dbml');
+ const dbmlData = parsedData.schemas[0];
+
+ // Extract only the necessary data from the parsed DBML
+ const extractedData = {
+ tables: dbmlData.tables.map((table: DBMLTable) => ({
+ name: table.name,
+ schema: table.schema,
+ fields: table.fields.map((field: DBMLField) => ({
+ name: field.name,
+ type: field.type,
+ unique: field.unique,
+ pk: field.pk,
+ not_null: field.not_null,
+ increment: field.increment,
+ })),
+ })),
+ refs: (dbmlData.refs as unknown as DBMLRef[]).map((ref) => ({
+ endpoints: (ref.endpoints as [DBMLEndpoint, DBMLEndpoint]).map(
+ (endpoint) => ({
+ tableName: endpoint.tableName,
+ fieldNames: endpoint.fieldNames,
+ relation: endpoint.relation,
+ })
+ ),
+ })),
+ };
+
+ // Convert DBML tables to ChartDB table objects
+ const tables: DBTable[] = extractedData.tables.map((table, index) => {
+ const row = Math.floor(index / 4);
+ const col = index % 4;
+ const tableSpacing = 300; // Increased spacing between tables
+
+ return {
+ id: generateId(),
+ name: table.name.replace(/['"]/g, ''),
+ schema:
+ typeof table.schema === 'string'
+ ? table.schema
+ : table.schema?.name || '',
+ order: index,
+ fields: table.fields.map((field) => ({
+ id: generateId(),
+ name: field.name.replace(/['"]/g, ''),
+ type: mapDBMLTypeToGenericType(field.type.type_name),
+ nullable: !field.not_null,
+ primaryKey: field.pk || false,
+ unique: field.unique || false,
+ createdAt: Date.now(),
+ })),
+ x: col * tableSpacing,
+ y: row * tableSpacing,
+ indexes: [],
+ color: randomColor(),
+ isView: false,
+ createdAt: Date.now(),
+ };
+ });
+
+ // Create relationships using the refs
+ const relationships: DBRelationship[] = extractedData.refs.map(
+ (ref) => {
+ const [source, target] = ref.endpoints;
+ const sourceTable = tables.find(
+ (t) =>
+ t.name === source.tableName.replace(/['"]/g, '') &&
+ (!source.tableName.includes('.') ||
+ t.schema === source.tableName.split('.')[0])
+ );
+ const targetTable = tables.find(
+ (t) =>
+ t.name === target.tableName.replace(/['"]/g, '') &&
+ (!target.tableName.includes('.') ||
+ t.schema === target.tableName.split('.')[0])
+ );
+
+ if (!sourceTable || !targetTable) {
+ throw new Error('Invalid relationship: tables not found');
+ }
+
+ const sourceField = sourceTable.fields.find(
+ (f) => f.name === source.fieldNames[0].replace(/['"]/g, '')
+ );
+ const targetField = targetTable.fields.find(
+ (f) => f.name === target.fieldNames[0].replace(/['"]/g, '')
+ );
+
+ if (!sourceField || !targetField) {
+ throw new Error('Invalid relationship: fields not found');
+ }
+
+ const { sourceCardinality, targetCardinality } =
+ determineCardinality(sourceField, targetField);
+
+ return {
+ id: generateId(),
+ name: `${sourceTable.name}_${sourceField.name}_${targetTable.name}_${targetField.name}`,
+ sourceSchema: sourceTable.schema,
+ targetSchema: targetTable.schema,
+ sourceTableId: sourceTable.id,
+ targetTableId: targetTable.id,
+ sourceFieldId: sourceField.id,
+ targetFieldId: targetField.id,
+ sourceCardinality: sourceCardinality as Cardinality,
+ targetCardinality: targetCardinality as Cardinality,
+ createdAt: Date.now(),
+ };
+ }
+ );
+
+ return {
+ id: generateDiagramId(),
+ name: 'DBML Import',
+ databaseType: DatabaseType.GENERIC,
+ tables,
+ relationships,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+ } catch (error) {
+ console.error('DBML parsing error:', error);
+ throw error;
+ }
+};
diff --git a/src/pages/editor-page/canvas/canvas.tsx b/src/pages/editor-page/canvas/canvas.tsx
index 819dee9c..dbe4894e 100644
--- a/src/pages/editor-page/canvas/canvas.tsx
+++ b/src/pages/editor-page/canvas/canvas.tsx
@@ -45,10 +45,7 @@ import { Badge } from '@/components/badge/badge';
import { useTheme } from '@/hooks/use-theme';
import { useTranslation } from 'react-i18next';
import type { DBTable } from '@/lib/domain/db-table';
-import {
- adjustTablePositions,
- shouldShowTablesBySchemaFilter,
-} from '@/lib/domain/db-table';
+import { shouldShowTablesBySchemaFilter } from '@/lib/domain/db-table';
import { useLocalConfig } from '@/hooks/use-local-config';
import {
Tooltip,
@@ -64,7 +61,7 @@ import {
findTableOverlapping,
} from './canvas-utils';
import type { Graph } from '@/lib/graph';
-import { createGraph, removeVertex } from '@/lib/graph';
+import { removeVertex } from '@/lib/graph';
import type { ChartDBEvent } from '@/context/chartdb-context/chartdb-context';
import { cn, debounce, getOperatingSystem } from '@/lib/utils';
import type { DependencyEdgeType } from './dependency-edge';
@@ -76,6 +73,7 @@ import {
} from './table-node/table-node-dependency-indicator';
import { DatabaseType } from '@/lib/domain/database-type';
import { useAlert } from '@/context/alert-context/alert-context';
+import { useCanvas } from '@/hooks/use-canvas';
export type EdgeType = RelationshipEdgeType | DependencyEdgeType;
@@ -109,8 +107,7 @@ export interface CanvasProps {
}
export const Canvas: React.FC<CanvasProps> = ({ initialTables, readonly }) => {
- const { getEdge, getInternalNode, fitView, getEdges, getNode } =
- useReactFlow();
+ const { getEdge, getInternalNode, getEdges, getNode } = useReactFlow();
const [selectedTableIds, setSelectedTableIds] = useState<string[]>([]);
const [selectedRelationshipIds, setSelectedRelationshipIds] = useState<
string[]
@@ -140,10 +137,10 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables, readonly }) => {
const nodeTypes = useMemo(() => ({ table: TableNode }), []);
const [highlightOverlappingTables, setHighlightOverlappingTables] =
useState(false);
+ const { reorderTables, fitView, setOverlapGraph, overlapGraph } =
+ useCanvas();
const [isInitialLoadingNodes, setIsInitialLoadingNodes] = useState(true);
- const [overlapGraph, setOverlapGraph] =
- useState<Graph<string>>(createGraph());
const [nodes, setNodes, onNodesChange] = useNodesState<TableNodeType>(
initialTables.map((table) => tableToTableNode(table, filteredSchemas))
@@ -345,7 +342,7 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables, readonly }) => {
}, 500)();
prevFilteredSchemas.current = filteredSchemas;
}
- }, [filteredSchemas, fitView, tables]);
+ }, [filteredSchemas, fitView, tables, setOverlapGraph]);
const onConnectHandler = useCallback(
async (params: AddEdgeParams) => {
@@ -657,33 +654,6 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables, readonly }) => {
const isLoadingDOM =
tables.length > 0 ? !getInternalNode(tables[0].id) : false;
- const reorderTables = useCallback(() => {
- const newTables = adjustTablePositions({
- relationships,
- tables: tables.filter((table) =>
- shouldShowTablesBySchemaFilter(table, filteredSchemas)
- ),
- mode: 'all', // Use 'all' mode for manual reordering
- });
-
- const updatedOverlapGraph = findOverlappingTables({
- tables: newTables,
- });
-
- updateTablesState((currentTables) =>
- currentTables.map((table) => {
- const newTable = newTables.find((t) => t.id === table.id);
- return {
- id: table.id,
- x: newTable?.x ?? table.x,
- y: newTable?.y ?? table.y,
- };
- })
- );
-
- setOverlapGraph(updatedOverlapGraph);
- }, [filteredSchemas, relationships, tables, updateTablesState]);
-
const showReorderConfirmation = useCallback(() => {
showAlert({
title: t('reorder_diagram_alert.title'),
diff --git a/src/pages/editor-page/editor-page.tsx b/src/pages/editor-page/editor-page.tsx
index eb65e6ca..61b71db3 100644
--- a/src/pages/editor-page/editor-page.tsx
+++ b/src/pages/editor-page/editor-page.tsx
@@ -37,6 +37,7 @@ import { Spinner } from '@/components/spinner/spinner';
import { Helmet } from 'react-helmet-async';
import { useStorage } from '@/hooks/use-storage';
import { AlertProvider } from '@/context/alert-context/alert-provider';
+import { CanvasProvider } from '@/context/canvas-context/canvas-provider';
const OPEN_STAR_US_AFTER_SECONDS = 30;
const SHOW_STAR_US_AGAIN_AFTER_DAYS = 1;
@@ -315,15 +316,17 @@ export const EditorPage: React.FC = () => (
<ChartDBProvider>
<HistoryProvider>
<ReactFlowProvider>
- <ExportImageProvider>
- <AlertProvider>
- <DialogProvider>
- <KeyboardShortcutsProvider>
- <EditorPageComponent />
- </KeyboardShortcutsProvider>
- </DialogProvider>
- </AlertProvider>
- </ExportImageProvider>
+ <CanvasProvider>
+ <ExportImageProvider>
+ <AlertProvider>
+ <DialogProvider>
+ <KeyboardShortcutsProvider>
+ <EditorPageComponent />
+ </KeyboardShortcutsProvider>
+ </DialogProvider>
+ </AlertProvider>
+ </ExportImageProvider>
+ </CanvasProvider>
</ReactFlowProvider>
</HistoryProvider>
</ChartDBProvider>
diff --git a/src/pages/editor-page/side-panel/tables-section/table-dbml/table-dbml.tsx b/src/pages/editor-page/side-panel/tables-section/table-dbml/table-dbml.tsx
index b0f9f2be..c1d21ce4 100644
--- a/src/pages/editor-page/side-panel/tables-section/table-dbml/table-dbml.tsx
+++ b/src/pages/editor-page/side-panel/tables-section/table-dbml/table-dbml.tsx
@@ -1,72 +1,19 @@
import React, { useMemo } from 'react';
-import type { Monaco } from '@monaco-editor/react';
import type { DBTable } from '@/lib/domain/db-table';
import { useChartDB } from '@/hooks/use-chartdb';
import { useTheme } from '@/hooks/use-theme';
import { CodeSnippet } from '@/components/code-snippet/code-snippet';
-import { dataTypes } from '@/lib/data/data-types/data-types';
import type { EffectiveTheme } from '@/context/theme-context/theme-context';
import { importer } from '@dbml/core';
import { exportBaseSQL } from '@/lib/data/export-metadata/export-sql-script';
import type { Diagram } from '@/lib/domain/diagram';
import { useToast } from '@/components/toast/use-toast';
+import { setupDBMLLanguage } from '@/components/code-snippet/languages/dbml-language';
export interface TableDBMLProps {
filteredTables: DBTable[];
}
-const setupDBMLLanguage = (monaco: Monaco) => {
- monaco.languages.register({ id: 'dbml' });
-
- // Define themes for DBML
- monaco.editor.defineTheme('dbml-dark', {
- base: 'vs-dark',
- inherit: true,
- rules: [
- { token: 'keyword', foreground: '569CD6' }, // Table, Ref keywords
- { token: 'string', foreground: 'CE9178' }, // Strings
- { token: 'annotation', foreground: '9CDCFE' }, // [annotations]
- { token: 'delimiter', foreground: 'D4D4D4' }, // Braces {}
- { token: 'operator', foreground: 'D4D4D4' }, // Operators
- { token: 'datatype', foreground: '4EC9B0' }, // Data types
- ],
- colors: {},
- });
-
- monaco.editor.defineTheme('dbml-light', {
- base: 'vs',
- inherit: true,
- rules: [
- { token: 'keyword', foreground: '0000FF' }, // Table, Ref keywords
- { token: 'string', foreground: 'A31515' }, // Strings
- { token: 'annotation', foreground: '001080' }, // [annotations]
- { token: 'delimiter', foreground: '000000' }, // Braces {}
- { token: 'operator', foreground: '000000' }, // Operators
- { token: 'type', foreground: '267F99' }, // Data types
- ],
- colors: {},
- });
-
- const dataTypesNames = dataTypes.map((dt) => dt.name);
- const datatypePattern = dataTypesNames.join('|');
-
- monaco.languages.setMonarchTokensProvider('dbml', {
- keywords: ['Table', 'Ref', 'Indexes'],
- datatypes: dataTypesNames,
- tokenizer: {
- root: [
- [/\b(Table|Ref|Indexes)\b/, 'keyword'],
- [/\[.*?\]/, 'annotation'],
- [/".*?"/, 'string'],
- [/'.*?'/, 'string'],
- [/[{}]/, 'delimiter'],
- [/[<>]/, 'operator'],
- [new RegExp(`\\b(${datatypePattern})\\b`, 'i'), 'type'], // Added 'i' flag for case-insensitive matching
- ],
- },
- });
-};
-
const getEditorTheme = (theme: EffectiveTheme) => {
return theme === 'dark' ? 'dbml-dark' : 'dbml-light';
};
diff --git a/src/pages/editor-page/top-navbar/menu/menu.tsx b/src/pages/editor-page/top-navbar/menu/menu.tsx
index 18196673..bbb2abca 100644
--- a/src/pages/editor-page/top-navbar/menu/menu.tsx
+++ b/src/pages/editor-page/top-navbar/menu/menu.tsx
@@ -48,6 +48,7 @@ export const Menu: React.FC<MenuProps> = () => {
openExportImageDialog,
openExportDiagramDialog,
openImportDiagramDialog,
+ openImportDBMLDialog,
} = useDialog();
const { showAlert } = useAlert();
const { setTheme, theme } = useTheme();
@@ -221,9 +222,13 @@ export const Menu: React.FC<MenuProps> = () => {
<MenubarSeparator />
<MenubarSub>
<MenubarSubTrigger>
- {t('menu.file.import_database')}
+ {t('menu.file.import')}
</MenubarSubTrigger>
<MenubarSubContent>
+ <MenubarItem onClick={() => openImportDBMLDialog()}>
+ .dbml
+ </MenubarItem>
+ <MenubarSeparator />
<MenubarItem
onClick={() =>
openImportDatabaseDialog({