Skip to content

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

fix: support index comments in DBML and SQL export (#1098)

Jonathan Fishnerce95f83ff531
diff --git a/src/lib/data/sql-export/export-per-type/postgresql.ts b/src/lib/data/sql-export/export-per-type/postgresql.ts
index bf22dcb5..5352de59 100644
--- a/src/lib/data/sql-export/export-per-type/postgresql.ts
+++ b/src/lib/data/sql-export/export-per-type/postgresql.ts
@@ -13,6 +13,21 @@ import type { DBRelationship } from '@/lib/domain/db-relationship';
import type { DBCustomType } from '@/lib/domain/db-custom-type';
import { DBCustomTypeKind } from '@/lib/domain/db-custom-type';
+// Build a unique, safe index name from table and index names,
+// respecting PostgreSQL's 63-character identifier limit
+function buildIndexName(tableName: string, indexName: string): string {
+ const safeTableName = tableName.replace(/[^a-zA-Z0-9_]/g, '_');
+ const safeIndexName = indexName.replace(/[^a-zA-Z0-9_]/g, '_');
+ let combinedName = `${safeTableName}_${safeIndexName}`;
+ if (combinedName.length > 60) {
+ combinedName =
+ safeIndexName.length > 60
+ ? safeIndexName.substring(0, 60)
+ : safeIndexName;
+ }
+ return combinedName;
+}
+
function parsePostgresDefault(field: DBField): string {
if (!field.default || typeof field.default !== 'string') {
return '';
@@ -403,27 +418,10 @@ export function exportPostgreSQL({
return '';
}
- // Create unique index name using table name and index name
- // This ensures index names are unique across the database
- const safeTableName = table.name.replace(
- /[^a-zA-Z0-9_]/g,
- '_'
- );
- const safeIndexName = index.name.replace(
- /[^a-zA-Z0-9_]/g,
- '_'
+ const combinedName = buildIndexName(
+ table.name,
+ index.name
);
-
- // Limit index name length to avoid PostgreSQL's 63-character identifier limit
- let combinedName = `${safeTableName}_${safeIndexName}`;
- if (combinedName.length > 60) {
- // If too long, use just the index name or a truncated version
- combinedName =
- safeIndexName.length > 60
- ? safeIndexName.substring(0, 60)
- : safeIndexName;
- }
-
const indexName = `"${combinedName}"`;
// Get the properly quoted field names
@@ -440,9 +438,27 @@ export function exportPostgreSQL({
.filter(Boolean)
.sort((a, b) => a.localeCompare(b)); // Sort for consistent output
- return validIndexes.length > 0
- ? `\n-- Indexes\n${validIndexes.join('\n')}`
- : '';
+ const indexComments = table.indexes
+ .filter((index) => index.comments)
+ .map((index) => {
+ const combinedName = buildIndexName(
+ table.name,
+ index.name
+ );
+ return `COMMENT ON INDEX "${combinedName}" IS '${escapeSQLComment(index.comments!)}';`;
+ })
+ .filter(Boolean);
+
+ const indexSection =
+ validIndexes.length > 0
+ ? `\n-- Indexes\n${validIndexes.join('\n')}`
+ : '';
+ const indexCommentSection =
+ indexComments.length > 0
+ ? `\n${indexComments.join('\n')}`
+ : '';
+
+ return indexSection + indexCommentSection;
})()
}\n`;
})
diff --git a/src/lib/dbml/dbml-export/dbml-export.ts b/src/lib/dbml/dbml-export/dbml-export.ts
index 86a04094..73bfc8ef 100644
--- a/src/lib/dbml/dbml-export/dbml-export.ts
+++ b/src/lib/dbml/dbml-export/dbml-export.ts
@@ -230,6 +230,12 @@ export const sanitizeSQLforDBML = (sql: string): string => {
'DEFAULT NOW()'
);
+ // Strip COMMENT ON INDEX statements before @dbml/core parsing.
+ // @dbml/core doesn't support COMMENT ON INDEX, so these are restored
+ // afterwards by restoreIndexNotes(). Table/column comments are left
+ // intact since @dbml/core handles them natively with proper escaping.
+ sanitized = sanitized.replace(/^COMMENT ON INDEX .+;$/gm, '');
+
// Replace any remaining problematic characters
sanitized = sanitized.replace(/\?\?/g, '__');
@@ -777,6 +783,17 @@ const restoreCheckConstraints = (dbml: string, tables: DBTable[]): string => {
return result;
};
+// Helper function to escape comments for DBML note attributes
+const escapeDBMLComment = (comment: string): string => {
+ return comment
+ .replace(/\r?\n/g, ' ') // Replace newlines with spaces
+ .replace(/\s+/g, ' ') // Normalize multiple spaces
+ .trim() // Remove leading/trailing whitespace
+ .replace(/\\/g, '\\\\')
+ .replace(/'/g, "\\'")
+ .replace(/"/g, '\\"');
+};
+
// Restore table and field notes/comments that may have been lost during DBML export
// This handles databases where @dbml/core doesn't recognize the comment syntax
// (e.g., MySQL's inline COMMENT syntax). For databases like PostgreSQL where
@@ -786,17 +803,6 @@ const restoreNotes = (dbml: string, tables: DBTable[]): string => {
let result = dbml;
- // Helper function to escape comments for DBML
- const escapeComment = (comment: string): string => {
- return comment
- .replace(/\r?\n/g, ' ') // Replace newlines with spaces
- .replace(/\s+/g, ' ') // Normalize multiple spaces
- .trim() // Remove leading/trailing whitespace
- .replace(/\\/g, '\\\\')
- .replace(/'/g, "\\'")
- .replace(/"/g, '\\"');
- };
-
tables.forEach((table) => {
// Build the table identifier pattern once for this table
const tableIdentifier = table.schema
@@ -805,7 +811,7 @@ const restoreNotes = (dbml: string, tables: DBTable[]): string => {
// Restore table-level notes
if (table.comments) {
- const escapedComment = escapeComment(table.comments);
+ const escapedComment = escapeDBMLComment(table.comments);
// Pattern to match the entire table block
const tableBlockPattern = new RegExp(
@@ -839,7 +845,7 @@ const restoreNotes = (dbml: string, tables: DBTable[]): string => {
);
// Escape the comment text for use in the replacement
- const escapedComment = escapeComment(field.comments!);
+ const escapedComment = escapeDBMLComment(field.comments!);
// Pattern to match the field line
// We need to match the complete field definition including array types
@@ -998,6 +1004,84 @@ const restoreIndexTypes = (dbml: string, tables: DBTable[]): string => {
return result;
};
+// Restore index notes/comments that are lost during SQL to DBML conversion
+// The @dbml/core importer doesn't support COMMENT ON INDEX, so we add note: attributes directly
+const restoreIndexNotes = (dbml: string, tables: DBTable[]): string => {
+ if (!tables || tables.length === 0) return dbml;
+
+ let result = dbml;
+
+ tables.forEach((table) => {
+ // Find indexes with comments
+ const indexesWithComments = table.indexes.filter(
+ (idx) => idx.comments && !idx.isPrimaryKey
+ );
+
+ if (indexesWithComments.length === 0) return;
+
+ // Build the table identifier pattern
+ const tableIdentifier = table.schema
+ ? `"${table.schema.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"\\."${table.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`
+ : `"${table.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`;
+
+ indexesWithComments.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 (same approach as restoreIndexTypes)
+ let indexColumnPattern: string;
+ if (fieldNames.length === 1) {
+ indexColumnPattern = fieldNames[0].replace(
+ /[.*+?^${}()|[\]\\]/g,
+ '\\$&'
+ );
+ } else {
+ const escapedFields = fieldNames
+ .map((f) => f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+ .join(',\\s*');
+ indexColumnPattern = `\\(${escapedFields}\\)`;
+ }
+
+ // Pattern to match the index line with its attributes
+ const indexLinePattern = new RegExp(
+ `(Table ${tableIdentifier} \\{[\\s\\S]*?Indexes \\{[\\s\\S]*?)(${indexColumnPattern})\\s*\\[([^\\]]*name:\\s*"${escapedIndexName}"[^\\]]*)\\]`,
+ 'g'
+ );
+
+ const escapedComment = escapeDBMLComment(index.comments!);
+
+ result = result.replace(
+ indexLinePattern,
+ (match, prefix, columns, attributes) => {
+ // Check if note is already present
+ if (/note:\s*'/.test(attributes)) {
+ return match;
+ }
+
+ // Append note at the end of attributes
+ const newAttributes = `${attributes}, note: '${escapedComment}'`;
+ 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;
@@ -1420,6 +1504,9 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {
// Restore index types (like GIN) that are lost during SQL to DBML conversion
standard = restoreIndexTypes(standard, tablesWithFields);
+ // Restore index notes/comments that are lost during SQL to DBML conversion
+ standard = restoreIndexNotes(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(
diff --git a/src/lib/dbml/dbml-import/dbml-import.ts b/src/lib/dbml/dbml-import/dbml-import.ts
index af3961b4..d412f0e2 100644
--- a/src/lib/dbml/dbml-import/dbml-import.ts
+++ b/src/lib/dbml/dbml-import/dbml-import.ts
@@ -294,6 +294,7 @@ interface DBMLIndex {
name?: string;
pk?: boolean; // Primary key index flag
type?: string; // Index type (e.g., 'gin', 'btree', 'hash')
+ note?: string | { value: string } | null;
}
interface DBMLTable {
@@ -628,6 +629,7 @@ export const importDBMLToDiagram = async (
name: indexName,
pk: Boolean(dbmlIndex.pk) || false,
type: dbmlIndex.type,
+ note: dbmlIndex.note,
};
}) || [],
});
@@ -840,6 +842,18 @@ export const importDBMLToDiagram = async (
? (dbmlIndex.type.toLowerCase() as IndexType)
: undefined;
+ let indexComment: string | undefined;
+ if (dbmlIndex.note) {
+ if (typeof dbmlIndex.note === 'string') {
+ indexComment = dbmlIndex.note;
+ } else if (
+ typeof dbmlIndex.note === 'object' &&
+ 'value' in dbmlIndex.note
+ ) {
+ indexComment = dbmlIndex.note.value;
+ }
+ }
+
return {
id: generateId(),
name:
@@ -849,6 +863,7 @@ export const importDBMLToDiagram = async (
unique: dbmlIndex.unique || false,
createdAt: Date.now(),
...(indexType ? { type: indexType } : {}),
+ ...(indexComment ? { comments: indexComment } : {}),
};
}) || [];
diff --git a/src/lib/domain/db-index.ts b/src/lib/domain/db-index.ts
index 1f047611..b03a4819 100644
--- a/src/lib/domain/db-index.ts
+++ b/src/lib/domain/db-index.ts
@@ -30,6 +30,7 @@ export interface DBIndex {
createdAt: number;
type?: IndexType | null;
isPrimaryKey?: boolean | null;
+ comments?: string | null;
}
export const dbIndexSchema: z.ZodType<DBIndex> = z.object({
@@ -40,6 +41,7 @@ export const dbIndexSchema: z.ZodType<DBIndex> = z.object({
createdAt: z.number(),
type: z.enum(INDEX_TYPES).optional(),
isPrimaryKey: z.boolean().or(z.null()).optional(),
+ comments: z.string().or(z.null()).optional(),
});
export const databaseIndexTypes: Record<DatabaseType, IndexType[] | undefined> =
diff --git a/src/lib/domain/diff/diff-check/diff-check.ts b/src/lib/domain/diff/diff-check/diff-check.ts
index 6c3e3421..5a9edd01 100644
--- a/src/lib/domain/diff/diff-check/diff-check.ts
+++ b/src/lib/domain/diff/diff-check/diff-check.ts
@@ -1088,6 +1088,7 @@ function compareIndexProperties({
'unique',
'fieldIds',
'type',
+ 'comments',
];
const changedAttributes: IndexDiffAttribute[] = [];
@@ -1122,6 +1123,13 @@ function compareIndexProperties({
}
}
+ if (
+ attributesToCheck.includes('comments') &&
+ (oldIndex.comments ?? null) !== (newIndex.comments ?? null)
+ ) {
+ changedAttributes.push('comments');
+ }
+
if (changedAttributes.length > 0) {
// Track which attributes should trigger adding to changed maps
const attributesThatTriggerChange = changedAttributes.filter((attr) =>
diff --git a/src/lib/domain/diff/index-diff.ts b/src/lib/domain/diff/index-diff.ts
index 50a542a6..2092afff 100644
--- a/src/lib/domain/diff/index-diff.ts
+++ b/src/lib/domain/diff/index-diff.ts
@@ -1,13 +1,19 @@
import { z } from 'zod';
import type { DBIndex, IndexType } from '../db-index';
-export type IndexDiffAttribute = 'name' | 'unique' | 'fieldIds' | 'type';
+export type IndexDiffAttribute =
+ | 'name'
+ | 'unique'
+ | 'fieldIds'
+ | 'type'
+ | 'comments';
export const indexDiffAttributeSchema: z.ZodType<IndexDiffAttribute> = z.union([
z.literal('name'),
z.literal('unique'),
z.literal('fieldIds'),
z.literal('type'),
+ z.literal('comments'),
]);
export interface IndexDiffAdded<T = DBIndex> {
diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-index/table-index.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-index/table-index.tsx
index 3c6d3c98..b1bbc430 100644
--- a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-index/table-index.tsx
+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-index/table-index.tsx
@@ -18,6 +18,7 @@ import { Separator } from '@/components/separator/separator';
import { Checkbox } from '@/components/checkbox/checkbox';
import { Label } from '@/components/label/label';
import { Input } from '@/components/input/input';
+import { Textarea } from '@/components/textarea/textarea';
import { useTranslation } from 'react-i18next';
import { SelectBox } from '@/components/select-box/select-box';
import { TableIndexToggle } from './table-index-toggle';
@@ -122,7 +123,24 @@ export const TableIndex: React.FC<TableIndexProps> = ({
'Select type';
return (
- <div className="flex flex-1 flex-row justify-between gap-2 p-1">
+ <div className="relative flex flex-1 flex-row justify-between gap-2 p-1">
+ {index.comments ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="absolute right-0 top-0 size-0 border-l-[10px] border-t-[10px] border-l-transparent border-t-pink-500" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ <div>
+ <div className="font-normal text-white/70 dark:text-black/70">
+ Comment:
+ </div>
+ <div className="whitespace-pre-wrap break-words">
+ {index.comments}
+ </div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
<SelectBox
className="flex h-8 min-h-8 min-w-0 flex-1"
multiple
@@ -245,6 +263,26 @@ export const TableIndex: React.FC<TableIndexProps> = ({
t={t}
/>
)}
+ <div className="flex flex-col gap-2">
+ <Label
+ htmlFor="width"
+ className="text-subtitle"
+ >
+ Comments
+ </Label>
+ <Textarea
+ value={index.comments ?? ''}
+ onChange={(e) =>
+ updateIndex({
+ comments:
+ e.target.value || null,
+ })
+ }
+ placeholder="No comments"
+ className="w-full rounded-md bg-muted text-sm"
+ readOnly={readonly}
+ />
+ </div>
{!readonly && (
<>
<Separator orientation="horizontal" />