From b3e7e0b5ed54b3b5c7899ac158b8308f77ba213a Mon Sep 17 00:00:00 2001 From: Jingchao Di Date: Thu, 2 May 2024 22:53:14 +0800 Subject: [PATCH] feat: dbml parse to er works --- src/pages/index.tsx | 9 +++-- src/parser/parser.ts | 80 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 src/parser/parser.ts diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 036a14b..d4bcec1 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -7,6 +7,7 @@ import { debounce } from 'lodash-es'; import { useEffect, useRef, useState } from 'react'; import MonacoEditor from 'react-monaco-editor'; +import parseDatabaseToER from '@/parser/parser'; import './index.less'; const CustomComponent = ({ node }: { node: Node }) => { @@ -278,6 +279,7 @@ export default () => { email varchar }`; const [code, setCode] = useState(initCode); + const [models, setModels] = useState(data); const containerRef = useRef(null); const parser = new Parser(); @@ -291,10 +293,10 @@ export default () => { }, }); - graph.fromJSON(data); + graph.fromJSON(models); graph.centerContent(); } - }, []); + }, [models]); // editorDidMount const editorDidMount = (editor: any, monaco: any) => { @@ -305,6 +307,9 @@ export default () => { const onChange = (newValue: any, e: any) => { const database = parser.parse(newValue, 'dbmlv2'); console.log(database); + let models = parseDatabaseToER(database); + console.log(models); + setModels(models); }; const debouncedOnChange = debounce(onChange, 500); diff --git a/src/parser/parser.ts b/src/parser/parser.ts new file mode 100644 index 0000000..c2fee6c --- /dev/null +++ b/src/parser/parser.ts @@ -0,0 +1,80 @@ +import Database from '@dbml/core/types/model_structure/database'; + +function parseDatabaseToER(database: Database): any { + const a = { + id: '1', + shape: 'er-rect', + label: '学生', + width: 150, + height: 24, + ports: [ + { + id: '1-1', + group: 'list', + attrs: { + portNameLabel: { + text: 'ID', + }, + portTypeLabel: { + text: 'STRING', + }, + }, + }, + { + id: '1-2', + group: 'list', + attrs: { + portNameLabel: { + text: 'Name', + }, + portTypeLabel: { + text: 'STRING', + }, + }, + }, + { + id: '1-3', + group: 'list', + attrs: { + portNameLabel: { + text: 'Class', + }, + portTypeLabel: { + text: 'NUMBER', + }, + }, + }, + { + id: '1-4', + group: 'list', + attrs: { + portNameLabel: { + text: 'Gender', + }, + portTypeLabel: { + text: 'BOOLEAN', + }, + }, + }, + ], + }; + + let models: any[] = []; + for (let i = 0; i < database.schemas.length; i++) { + for (let j = 0; j < database.schemas[i].tables.length; j++) { + const table = database.schemas[i].tables[j]; + const model = { + id: '1', + shape: 'er-rect', + label: table.name, + width: 150, + height: 24, + ports: [], + }; + models.push(model); + } + } + return models; +} + +export default parseDatabaseToER;