|
| 1 | +import { ForeignKeyDS } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/data-structures/foreign-key.ds.js'; |
| 2 | +import { PrimaryKeyDS } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/data-structures/primary-key.ds.js'; |
| 3 | +import { TableStructureDS } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/data-structures/table-structure.ds.js'; |
| 4 | + |
| 5 | +export interface MermaidTableInput { |
| 6 | + tableName: string; |
| 7 | + structure: Array<TableStructureDS>; |
| 8 | + primaryColumns: Array<PrimaryKeyDS>; |
| 9 | + foreignKeys: Array<ForeignKeyDS>; |
| 10 | +} |
| 11 | + |
| 12 | +export interface MermaidDiagramResult { |
| 13 | + diagram: string; |
| 14 | + description: string; |
| 15 | +} |
| 16 | + |
| 17 | +export function buildMermaidErDiagram( |
| 18 | + databaseName: string | null, |
| 19 | + tables: Array<MermaidTableInput>, |
| 20 | +): MermaidDiagramResult { |
| 21 | + const aliasByTable = new Map<string, string>(); |
| 22 | + const usedAliases = new Set<string>(); |
| 23 | + for (const t of tables) { |
| 24 | + aliasByTable.set(t.tableName, makeUniqueAlias(t.tableName, usedAliases)); |
| 25 | + } |
| 26 | + |
| 27 | + const lines: Array<string> = ['erDiagram']; |
| 28 | + |
| 29 | + for (const table of tables) { |
| 30 | + const alias = aliasByTable.get(table.tableName)!; |
| 31 | + const pkColumnNames = new Set(table.primaryColumns.map((p) => p.column_name)); |
| 32 | + const fkColumnNames = new Set(table.foreignKeys.map((fk) => fk.column_name)); |
| 33 | + |
| 34 | + const aliasDiffersFromOriginal = alias !== table.tableName; |
| 35 | + const header = aliasDiffersFromOriginal ? ` ${alias}["${escapeQuotes(table.tableName)}"] {` : ` ${alias} {`; |
| 36 | + lines.push(header); |
| 37 | + |
| 38 | + if (table.structure.length === 0) { |
| 39 | + lines.push(' string _empty_ "no columns"'); |
| 40 | + } else { |
| 41 | + for (const column of table.structure) { |
| 42 | + const dataType = sanitizeIdentifier(column.data_type || column.udt_name || 'unknown'); |
| 43 | + const colName = sanitizeIdentifier(column.column_name); |
| 44 | + const markers: Array<string> = []; |
| 45 | + if (pkColumnNames.has(column.column_name)) markers.push('PK'); |
| 46 | + if (fkColumnNames.has(column.column_name)) markers.push('FK'); |
| 47 | + const comment = buildColumnComment(column); |
| 48 | + const tail = [markers.join(','), comment].filter((p) => p && p.length > 0).join(' '); |
| 49 | + lines.push(` ${dataType} ${colName}${tail ? ' ' + tail : ''}`); |
| 50 | + } |
| 51 | + } |
| 52 | + lines.push(' }'); |
| 53 | + } |
| 54 | + |
| 55 | + let relationshipCount = 0; |
| 56 | + for (const table of tables) { |
| 57 | + const sourceAlias = aliasByTable.get(table.tableName)!; |
| 58 | + for (const fk of table.foreignKeys) { |
| 59 | + const targetAlias = aliasByTable.get(fk.referenced_table_name); |
| 60 | + if (!targetAlias) continue; |
| 61 | + const label = `"${escapeQuotes(fk.column_name)} -> ${escapeQuotes(fk.referenced_column_name)}"`; |
| 62 | + lines.push(` ${sourceAlias} }o--|| ${targetAlias} : ${label}`); |
| 63 | + relationshipCount++; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + const diagram = lines.join('\n'); |
| 68 | + const description = buildDescription(databaseName, tables, relationshipCount); |
| 69 | + return { diagram, description }; |
| 70 | +} |
| 71 | + |
| 72 | +function buildDescription( |
| 73 | + databaseName: string | null, |
| 74 | + tables: Array<MermaidTableInput>, |
| 75 | + relationshipCount: number, |
| 76 | +): string { |
| 77 | + const dbLabel = databaseName ? `Database "${databaseName}"` : 'Database'; |
| 78 | + const tablesPart = `${tables.length} ${pluralize(tables.length, 'table', 'tables')}`; |
| 79 | + const relsPart = `${relationshipCount} ${pluralize(relationshipCount, 'foreign key relationship', 'foreign key relationships')}`; |
| 80 | + const header = `${dbLabel} contains ${tablesPart} and ${relsPart}.`; |
| 81 | + |
| 82 | + if (tables.length === 0) { |
| 83 | + return header; |
| 84 | + } |
| 85 | + |
| 86 | + const tableSummaries = tables.map((t) => { |
| 87 | + const pkNames = t.primaryColumns.map((p) => p.column_name); |
| 88 | + const pkPart = pkNames.length > 0 ? `PK: ${pkNames.join(', ')}` : 'no primary key'; |
| 89 | + const fkPart = |
| 90 | + t.foreignKeys.length > 0 |
| 91 | + ? `FKs: ${t.foreignKeys.map((fk) => `${fk.column_name}->${fk.referenced_table_name}.${fk.referenced_column_name}`).join(', ')}` |
| 92 | + : 'no foreign keys'; |
| 93 | + return `- ${t.tableName} (${t.structure.length} ${pluralize(t.structure.length, 'column', 'columns')}; ${pkPart}; ${fkPart})`; |
| 94 | + }); |
| 95 | + |
| 96 | + return [header, 'Tables:', ...tableSummaries].join('\n'); |
| 97 | +} |
| 98 | + |
| 99 | +function pluralize(n: number, singular: string, plural: string): string { |
| 100 | + return n === 1 ? singular : plural; |
| 101 | +} |
| 102 | + |
| 103 | +function buildColumnComment(column: TableStructureDS): string { |
| 104 | + const parts: Array<string> = []; |
| 105 | + if (column.column_default !== null && column.column_default !== undefined && column.column_default !== '') { |
| 106 | + parts.push(`default: ${String(column.column_default)}`); |
| 107 | + } |
| 108 | + parts.push(column.allow_null ? 'nullable' : 'not null'); |
| 109 | + if (column.character_maximum_length) { |
| 110 | + parts.push(`max length: ${column.character_maximum_length}`); |
| 111 | + } |
| 112 | + const text = parts.join('; '); |
| 113 | + return text ? `"${escapeQuotes(text)}"` : ''; |
| 114 | +} |
| 115 | + |
| 116 | +function makeUniqueAlias(name: string, used: Set<string>): string { |
| 117 | + let base = sanitizeIdentifier(name); |
| 118 | + if (base.length === 0 || /^[0-9]/.test(base)) base = `t_${base}`; |
| 119 | + let candidate = base; |
| 120 | + let suffix = 1; |
| 121 | + while (used.has(candidate)) { |
| 122 | + candidate = `${base}_${suffix++}`; |
| 123 | + } |
| 124 | + used.add(candidate); |
| 125 | + return candidate; |
| 126 | +} |
| 127 | + |
| 128 | +function sanitizeIdentifier(value: string): string { |
| 129 | + return value.replace(/[^A-Za-z0-9_]/g, '_'); |
| 130 | +} |
| 131 | + |
| 132 | +function escapeQuotes(value: string): string { |
| 133 | + return value.replace(/"/g, "'"); |
| 134 | +} |
0 commit comments