Skip to content

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

fix: preserve GIN index type in DBML export (#1075)

Jonathan Fishner0b73295922f8
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.ts
index d7ad4be8..15a3061b 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
@@ -1655,4 +1655,148 @@ Ref "fk_0_table_2_id_fk":"table_2"."id" - "table_1"."id"
(result.inlineDbml.match(/}/g) || []).length;
expect(braceBalance).toBe(0);
});
+
+ it('should export GIN index type in DBML', () => {
+ const diagram: Diagram = {
+ id: 'test-diagram',
+ name: 'Test',
+ databaseType: DatabaseType.POSTGRESQL,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ tables: [
+ {
+ id: 'table1',
+ name: 'test',
+ schema: 'public',
+ x: 0,
+ y: 0,
+ fields: [
+ {
+ id: 'field1',
+ name: 'id',
+ type: { id: 'bigint', name: 'bigint' },
+ primaryKey: true,
+ nullable: false,
+ unique: true,
+ createdAt: Date.now(),
+ },
+ {
+ id: 'field2',
+ name: 'ginsss',
+ type: { id: 'int[]', name: 'int[]' },
+ primaryKey: false,
+ nullable: true,
+ unique: false,
+ isArray: true,
+ createdAt: Date.now(),
+ },
+ ],
+ indexes: [
+ {
+ id: 'idx1',
+ name: 'test_index_2',
+ fieldIds: ['field2'],
+ unique: false,
+ type: 'gin',
+ createdAt: Date.now(),
+ },
+ ],
+ color: 'blue',
+ isView: false,
+ createdAt: Date.now(),
+ },
+ ],
+ relationships: [],
+ };
+
+ const result = generateDBMLFromDiagram(diagram);
+
+ // The index should include type: gin
+ expect(result.standardDbml).toContain('type: gin');
+ expect(result.standardDbml).toContain('test_index_2');
+ });
+
+ it('should export composite GIN index type in DBML', () => {
+ const diagram: Diagram = {
+ id: 'test-diagram',
+ name: 'Test',
+ databaseType: DatabaseType.POSTGRESQL,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ tables: [
+ {
+ id: 'table1',
+ name: 'merchants',
+ schema: 'public',
+ x: 0,
+ y: 0,
+ fields: [
+ {
+ id: 'field1',
+ name: 'id',
+ type: { id: 'bigint', name: 'bigint' },
+ primaryKey: true,
+ nullable: false,
+ unique: true,
+ createdAt: Date.now(),
+ },
+ {
+ id: 'field2',
+ name: 'supported_licenses',
+ type: { id: 'text[]', name: 'text[]' },
+ primaryKey: false,
+ nullable: true,
+ unique: false,
+ isArray: true,
+ createdAt: Date.now(),
+ },
+ {
+ id: 'field3',
+ name: 'supported_countries',
+ type: { id: 'text[]', name: 'text[]' },
+ primaryKey: false,
+ nullable: true,
+ unique: false,
+ isArray: true,
+ createdAt: Date.now(),
+ },
+ {
+ id: 'field4',
+ name: 'supported_currencies',
+ type: { id: 'text[]', name: 'text[]' },
+ primaryKey: false,
+ nullable: true,
+ unique: false,
+ isArray: true,
+ createdAt: Date.now(),
+ },
+ ],
+ indexes: [
+ {
+ id: 'idx1',
+ name: 'index_4',
+ fieldIds: ['field2', 'field3', 'field4'],
+ unique: false,
+ type: 'gin',
+ createdAt: Date.now(),
+ },
+ ],
+ color: 'blue',
+ isView: false,
+ createdAt: Date.now(),
+ },
+ ],
+ relationships: [],
+ };
+
+ const result = generateDBMLFromDiagram(diagram);
+
+ // The composite index should include type: gin
+ expect(result.standardDbml).toContain('type: gin');
+ expect(result.standardDbml).toContain('index_4');
+ // Should have the composite format (col1, col2, col3)
+ expect(result.standardDbml).toContain(
+ 'supported_licenses, supported_countries, supported_currencies'
+ );
+ });
});
diff --git a/src/lib/dbml/dbml-export/dbml-export.ts b/src/lib/dbml/dbml-export/dbml-export.ts
index f81bf606..fb3495f0 100644
--- a/src/lib/dbml/dbml-export/dbml-export.ts
+++ b/src/lib/dbml/dbml-export/dbml-export.ts
@@ -901,6 +901,87 @@ const restoreCompositePKNames = (dbml: string, tables: DBTable[]): string => {
return result;
};
+// Restore index types (like GIN) that are lost during SQL to DBML conversion
+// The @dbml/core importer doesn't preserve the USING clause from CREATE INDEX statements
+const restoreIndexTypes = (dbml: string, tables: DBTable[]): string => {
+ if (!tables || tables.length === 0) return dbml;
+
+ let result = dbml;
+
+ tables.forEach((table) => {
+ // Find indexes with non-default types (not btree, and not null/undefined)
+ const indexesWithType = table.indexes.filter(
+ (idx) => idx.type && idx.type !== 'btree' && !idx.isPrimaryKey // PK indexes don't need type restoration
+ );
+
+ if (indexesWithType.length === 0) return;
+
+ // Build the table identifier pattern
+ const tableIdentifier = table.schema
+ ? `"${table.schema.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"\\."${table.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`
+ : `"${table.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`;
+
+ indexesWithType.forEach((index) => {
+ // Get the field names for this index
+ const fieldNames = index.fieldIds
+ .map((fieldId) => {
+ const field = table.fields.find((f) => f.id === fieldId);
+ return field ? field.name : null;
+ })
+ .filter((name): name is string => name !== null);
+
+ if (fieldNames.length === 0) return;
+
+ // Escape the index name for regex
+ const escapedIndexName = index.name.replace(
+ /[.*+?^${}()|[\]\\]/g,
+ '\\$&'
+ );
+
+ // Build pattern to match index line in DBML
+ // For single column: field_name [name: "index_name"] or field_name [unique, name: "index_name"]
+ // For composite: (field1, field2) [name: "index_name"]
+ let indexColumnPattern: string;
+ if (fieldNames.length === 1) {
+ // Single column index
+ indexColumnPattern = fieldNames[0].replace(
+ /[.*+?^${}()|[\]\\]/g,
+ '\\$&'
+ );
+ } else {
+ // Composite index: (col1, col2, ...)
+ const escapedFields = fieldNames
+ .map((f) => f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+ .join(',\\s*');
+ indexColumnPattern = `\\(${escapedFields}\\)`;
+ }
+
+ // Pattern to match the index line with its attributes
+ // Captures: 1) the column(s), 2) optional unique/pk attributes, 3) rest of attributes including name
+ const indexLinePattern = new RegExp(
+ `(Table ${tableIdentifier} \\{[\\s\\S]*?Indexes \\{[\\s\\S]*?)(${indexColumnPattern})\\s*\\[([^\\]]*name:\\s*"${escapedIndexName}"[^\\]]*)\\]`,
+ 'g'
+ );
+
+ result = result.replace(
+ indexLinePattern,
+ (match, prefix, columns, attributes) => {
+ // Check if type is already present
+ if (/type:\s*\w+/.test(attributes)) {
+ return match;
+ }
+
+ // Add type at the beginning of attributes
+ const newAttributes = `type: ${index.type}, ${attributes}`;
+ return `${prefix}${columns} [${newAttributes}]`;
+ }
+ );
+ });
+ });
+
+ return result;
+};
+
// Restore schema information that may have been stripped by the DBML importer
const restoreTableSchemas = (dbml: string, tables: DBTable[]): string => {
if (!tables || tables.length === 0) return dbml;
@@ -1320,6 +1401,9 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {
// Restore check constraints that may have been lost during DBML export
standard = restoreCheckConstraints(standard, tablesWithFields);
+ // Restore index types (like GIN) that are lost during SQL to DBML conversion
+ standard = restoreIndexTypes(standard, tablesWithFields);
+
// Generate cardinality-aware Ref statements from the diagram relationships
// (FK generation is skipped in SQL, so @dbml/core doesn't generate any Refs)
const cardinalityAwareRefs = generateRelationshipsDbmlFromDiagram(