Database diagrams editor that allows you to visualize and design your DB with a single query.
TypeScript databasedbdb-migrationeditorerdmariadbmssqlmysqlpostgresqlreactreact-flowschema-migrationssqlsqlitetypescriptvisualizationxyflow
fix(dbml): dbml indentation (#829)
Guy Ben-Aharon16f9f4671e01
diff --git a/src/lib/dbml/dbml-export/__tests__/dbml-export-issue-fix.test.ts b/src/lib/dbml/dbml-export/__tests__/dbml-export-issue-fix.test.tsindex 31e114b0..7b4f4815 100644--- a/src/lib/dbml/dbml-export/__tests__/dbml-export-issue-fix.test.ts+++ b/src/lib/dbml/dbml-export/__tests__/dbml-export-issue-fix.test.ts@@ -1299,4 +1299,120 @@ Ref "fk_0_table_2_id_fk":"table_1"."id" < "table_2"."id"// Ensure no closing brace appears on the same line as a field with inline refsexpect(result.inlineDbml).not.toMatch(/\[.*ref:.*\]\}/);});++ it('should properly format closing brace when table has both indexes and inline refs', () => {+ const diagram: Diagram = {+ id: 'test-diagram',+ name: 'Test',+ databaseType: DatabaseType.POSTGRESQL,+ createdAt: new Date(),+ updatedAt: new Date(),+ tables: [+ {+ id: 'table1',+ name: 'table_1',+ x: 0,+ y: 0,+ fields: [+ {+ id: 'field1',+ name: 'id',+ type: { id: 'bigint', name: 'bigint' },+ primaryKey: true,+ nullable: false,+ unique: false,+ collation: null,+ default: null,+ characterMaximumLength: null,+ createdAt: Date.now(),+ },+ ],+ indexes: [+ {+ id: 'index1',+ name: 'index_1',+ unique: false,+ fieldIds: ['field1'],+ createdAt: Date.now(),+ },+ ],+ color: 'blue',+ isView: false,+ createdAt: Date.now(),+ },+ {+ id: 'table2',+ name: 'table_2',+ x: 0,+ y: 0,+ fields: [+ {+ id: 'field2',+ name: 'id',+ type: { id: 'bigint', name: 'bigint' },+ primaryKey: true,+ nullable: false,+ unique: false,+ collation: null,+ default: null,+ characterMaximumLength: null,+ createdAt: Date.now(),+ },+ ],+ indexes: [],+ color: 'blue',+ isView: false,+ createdAt: Date.now(),+ },+ ],+ relationships: [+ {+ id: 'rel1',+ name: 'table2_id_fkey',+ sourceTableId: 'table2',+ sourceFieldId: 'field2',+ targetTableId: 'table1',+ targetFieldId: 'field1',+ sourceCardinality: 'many',+ targetCardinality: 'one',+ createdAt: Date.now(),+ },+ ],+ };++ const result = generateDBMLFromDiagram(diagram);++ // Check that the inline DBML has proper indentation+ expect(result.inlineDbml).toContain(`Table "table_1" {+ "id" bigint [pk, not null]++ Indexes {+ id [name: "index_1"]+ }+}`);++ expect(result.inlineDbml).toContain(`Table "table_2" {+ "id" bigint [pk, not null, ref: < "table_1"."id"]+}`);++ // The issue was that it would generate:+ // Table "table_1" {+ // "id" bigint [pk, not null]+ //+ // Indexes {+ // id [name: "index_1"]+ //+ // }+ // }++ // Make sure there's no malformed closing brace+ expect(result.inlineDbml).not.toMatch(/\n\s*\n\s*}\s*\n}/);+ expect(result.inlineDbml).not.toMatch(/\s+\n}/);++ // Ensure there's no extra closing brace+ const braceBalance =+ (result.inlineDbml.match(/{/g) || []).length -+ (result.inlineDbml.match(/}/g) || []).length;+ expect(braceBalance).toBe(0);+ });});diff --git a/src/lib/dbml/dbml-export/dbml-export.ts b/src/lib/dbml/dbml-export/dbml-export.tsindex 1992e7c6..36d42bdf 100644--- a/src/lib/dbml/dbml-export/dbml-export.ts+++ b/src/lib/dbml/dbml-export/dbml-export.ts@@ -248,34 +248,67 @@ const convertToInlineRefs = (dbml: string): string => {fullMatch: string;};} = {};- // Updated pattern to handle various table name formats including schema.table- const tablePattern =- /Table\s+(?:"([^"]+)"(?:\."([^"]+)")?|(\[?[^\s[]+\]?\.\[?[^\s\]]+\]?)|(\[?[^\s[{]+\]?))\s*{([^}]*)}/gs;- let tableMatch;- while ((tableMatch = tablePattern.exec(dbml)) !== null) {- // Extract table name - handle schema.table format+ // Use a more sophisticated approach to handle nested braces+ let currentPos = 0;+ while (currentPos < dbml.length) {+ // Find the next table definition+ const tableStartPattern =+ /Table\s+(?:"([^"]+)"(?:\."([^"]+)")?|(\[?[^\s[]+\]?\.\[?[^\s\]]+\]?)|(\[?[^\s[{]+\]?))\s*{/g;+ tableStartPattern.lastIndex = currentPos;+ const tableStartMatch = tableStartPattern.exec(dbml);++ if (!tableStartMatch) break;++ // Extract table namelet tableName;- if (tableMatch[1] && tableMatch[2]) {- // Format: "schema"."table"- tableName = `${tableMatch[1]}.${tableMatch[2]}`;- } else if (tableMatch[1]) {- // Format: "table" (no schema)- tableName = tableMatch[1];+ if (tableStartMatch[1] && tableStartMatch[2]) {+ tableName = `${tableStartMatch[1]}.${tableStartMatch[2]}`;+ } else if (tableStartMatch[1]) {+ tableName = tableStartMatch[1];} else {- // Other formats- tableName = tableMatch[3] || tableMatch[4];+ tableName = tableStartMatch[3] || tableStartMatch[4];}// Clean up any bracket syntax from table namesconst cleanTableName = tableName.replace(/\[([^\]]+)\]/g, '$1');- tables[cleanTableName] = {- start: tableMatch.index,- end: tableMatch.index + tableMatch[0].length,- content: tableMatch[5],- fullMatch: tableMatch[0],- };+ // Find the matching closing brace by counting nested braces+ const openBracePos =+ tableStartMatch.index + tableStartMatch[0].length - 1;+ let braceCount = 1;+ const contentStart = openBracePos + 1;+ let contentEnd = contentStart;++ for (let i = contentStart; i < dbml.length && braceCount > 0; i++) {+ if (dbml[i] === '{') braceCount++;+ else if (dbml[i] === '}') {+ braceCount--;+ if (braceCount === 0) {+ contentEnd = i;+ }+ }+ }++ if (braceCount === 0) {+ const content = dbml.substring(contentStart, contentEnd);+ const fullMatch = dbml.substring(+ tableStartMatch.index,+ contentEnd + 1+ );++ tables[cleanTableName] = {+ start: tableStartMatch.index,+ end: contentEnd + 1,+ content: content,+ fullMatch: fullMatch,+ };++ currentPos = contentEnd + 1;+ } else {+ // Malformed DBML, skip this table+ currentPos = tableStartMatch.index + tableStartMatch[0].length;+ }}if (refs.length === 0 || Object.keys(tables).length === 0) {@@ -396,15 +429,48 @@ const convertToInlineRefs = (dbml: string): string => {reconstructedDbml += dbml.substring(lastIndex, tableData.start);// Preserve the original table definition format but with updated contentconst originalTableDef = tableData.fullMatch;- // Ensure content ends with a newline before the closing bracelet formattedContent = tableData.content;++ // Clean up content formatting:+ // 1. Split into lines to handle each line individually+ const lines = formattedContent.split('\n');++ // 2. Process lines to ensure proper formatting+ const processedLines = [];+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const trimmedLine = line.trimEnd();++ // Skip empty lines at the end if followed by a closing brace+ if (trimmedLine === '' && i === lines.length - 1) {+ continue;+ }++ // Skip empty lines before a closing brace+ if (+ trimmedLine === '' &&+ i < lines.length - 1 &&+ lines[i + 1].trim().startsWith('}')+ ) {+ continue;+ }++ processedLines.push(line);+ }++ formattedContent = processedLines.join('\n');++ // Ensure content ends with a newline before the table's closing braceif (!formattedContent.endsWith('\n')) {formattedContent = formattedContent + '\n';}- const updatedTableDef = originalTableDef.replace(- /{[^}]*}/s,- `{${formattedContent}}`++ // Since we properly extracted content with nested braces, we need to rebuild the table definition+ const tableHeader = originalTableDef.substring(+ 0,+ originalTableDef.indexOf('{') + 1);+ const updatedTableDef = `${tableHeader}${formattedContent}}`;reconstructedDbml += updatedTableDef;lastIndex = tableData.end;}