Database diagrams editor that allows you to visualize and design your DB with a single query.
TypeScript databasedbdb-migrationeditorerdmariadbmssqlmysqlpostgresqlreactreact-flowschema-migrationssqlsqlitetypescriptvisualizationxyflow
fix: handle quoted identifiers with special characters in SQL import/export and DBML generation (#877)
Jonathan Fishner66b086378cd6
diff --git a/src/lib/data/export-metadata/__tests__/export-sql-dbml.test.ts b/src/lib/data/export-metadata/__tests__/export-sql-dbml.test.tsindex 28f28f55..92a3f56c 100644--- a/src/lib/data/export-metadata/__tests__/export-sql-dbml.test.ts+++ b/src/lib/data/export-metadata/__tests__/export-sql-dbml.test.ts@@ -1,20 +1,10 @@-import { describe, it, expect, vi } from 'vitest';+import { describe, it, expect } from 'vitest';import { exportBaseSQL } from '../export-sql-script';import { DatabaseType } from '@/lib/domain/database-type';import type { Diagram } from '@/lib/domain/diagram';import type { DBTable } from '@/lib/domain/db-table';import type { DBField } from '@/lib/domain/db-field';-// Mock the dbml/core importer-vi.mock('@dbml/core', () => ({- importer: {- import: vi.fn((sql: string) => {- // Return a simplified DBML for testing- return sql;- }),- },-}));-describe('DBML Export - SQL Generation Tests', () => {// Helper to generate test IDs and timestampslet idCounter = 0;@@ -606,7 +596,7 @@ describe('DBML Export - SQL Generation Tests', () => {});// Should create a valid table without primary key- expect(sql).toContain('CREATE TABLE experiment_logs');+ expect(sql).toContain('CREATE TABLE "experiment_logs"');expect(sql).not.toContain('PRIMARY KEY');});@@ -721,11 +711,11 @@ describe('DBML Export - SQL Generation Tests', () => {});// Should create both tables- expect(sql).toContain('CREATE TABLE guilds');- expect(sql).toContain('CREATE TABLE guild_members');+ expect(sql).toContain('CREATE TABLE "guilds"');+ expect(sql).toContain('CREATE TABLE "guild_members"');// Should create foreign keyexpect(sql).toContain(- 'ALTER TABLE guild_members ADD CONSTRAINT fk_guild_members_guild FOREIGN KEY (guild_id) REFERENCES guilds (id)'+ 'ALTER TABLE "guild_members" ADD CONSTRAINT fk_guild_members_guild FOREIGN KEY (guild_id) REFERENCES "guilds" (id);');});});@@ -799,12 +789,9 @@ describe('DBML Export - SQL Generation Tests', () => {isDBMLFlow: true,});- // Should create schemas- expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS transportation');- expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS magic');// Should use schema-qualified table names- expect(sql).toContain('CREATE TABLE transportation.portals');- expect(sql).toContain('CREATE TABLE magic.spells');+ expect(sql).toContain('CREATE TABLE "transportation"."portals"');+ expect(sql).toContain('CREATE TABLE "magic"."spells"');});});@@ -851,7 +838,7 @@ describe('DBML Export - SQL Generation Tests', () => {});// Should still create table structure- expect(sql).toContain('CREATE TABLE empty_table');+ expect(sql).toContain('CREATE TABLE "empty_table"');expect(sql).toContain('(\n\n)');});diff --git a/src/lib/data/export-metadata/__tests__/export-sql-quoted-identifiers.test.ts b/src/lib/data/export-metadata/__tests__/export-sql-quoted-identifiers.test.tsnew file mode 100644index 00000000..f4739efb--- /dev/null+++ b/src/lib/data/export-metadata/__tests__/export-sql-quoted-identifiers.test.ts@@ -0,0 +1,1002 @@+import { describe, it, expect } from 'vitest';+import { exportBaseSQL } from '../export-sql-script';+import { DatabaseType } from '@/lib/domain/database-type';+import type { Diagram } from '@/lib/domain/diagram';+import type { DBTable } from '@/lib/domain/db-table';+import type { DBField } from '@/lib/domain/db-field';++describe('Quoted Identifiers - Special Characters Handling', () => {+ // Helper to generate test IDs and timestamps+ let idCounter = 0;+ const testId = () => `test-id-${++idCounter}`;+ const testTime = Date.now();++ // Helper to create a field with all required properties+ const createField = (overrides: Partial<DBField>): DBField =>+ ({+ id: testId(),+ name: 'field',+ type: { id: 'text', name: 'text' },+ primaryKey: false,+ nullable: true,+ unique: false,+ createdAt: testTime,+ ...overrides,+ }) as DBField;++ // Helper to create a table with all required properties+ const createTable = (overrides: Partial<DBTable>): DBTable =>+ ({+ id: testId(),+ name: 'table',+ fields: [],+ indexes: [],+ createdAt: testTime,+ x: 0,+ y: 0,+ width: 200,+ ...overrides,+ }) as DBTable;++ // Helper to create a diagram with all required properties+ const createDiagram = (overrides: Partial<Diagram>): Diagram =>+ ({+ id: testId(),+ name: 'diagram',+ databaseType: DatabaseType.GENERIC,+ tables: [],+ relationships: [],+ createdAt: testTime,+ updatedAt: testTime,+ ...overrides,+ }) as Diagram;++ describe('Table Names with Special Characters', () => {+ it('should quote table names with spaces', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'user profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "user profiles"');+ });++ it('should quote table names with dashes', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'user-accounts',+ fields: [+ createField({+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "user-accounts"');+ });++ it('should quote table names with dots', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'app.config.settings',+ fields: [+ createField({+ name: 'key',+ type: { id: 'varchar', name: 'varchar' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "app.config.settings"');+ });++ it('should not double-quote already quoted table names', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: '"already-quoted"',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "already-quoted"');+ expect(sql).not.toContain('""already-quoted""');+ });++ it('should handle backtick-quoted table names', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.MYSQL,+ tables: [+ createTable({+ name: '`mysql-table`',+ fields: [+ createField({+ name: 'id',+ type: { id: 'int', name: 'int' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.MYSQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE `mysql-table`');+ expect(sql).not.toContain('"`mysql-table`"');+ });++ it('should handle bracket-quoted table names', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.SQL_SERVER,+ tables: [+ createTable({+ name: '[sql-server-table]',+ fields: [+ createField({+ name: 'id',+ type: { id: 'int', name: 'int' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.SQL_SERVER,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE [sql-server-table]');+ expect(sql).not.toContain('"[sql-server-table]"');+ });+ });++ describe('Schema Names with Special Characters', () => {+ it('should quote schema names with spaces', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ schema: 'user data',+ name: 'profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sqlDBML = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ const sqlNormal = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: false,+ });++ // For DBML flow+ expect(sqlDBML).toContain('CREATE TABLE "user data"."profiles"');+ expect(sqlDBML).not.toContain('CREATE SCHEMA');++ // For normal flow (PostgreSQL quotes everything)+ expect(sqlNormal).toContain(+ 'CREATE SCHEMA IF NOT EXISTS "user data"'+ );+ expect(sqlNormal).toContain('CREATE TABLE "user data"."profiles"');+ });++ it('should quote both schema and table names with special characters', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ schema: 'app-db',+ name: 'user-settings',+ fields: [+ createField({+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "app-db"."user-settings"');+ });++ it('should not double-quote already quoted schema names', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ schema: '"quoted-schema"',+ name: 'table',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "quoted-schema"."table"');+ expect(sql).not.toContain('""quoted-schema""');+ });++ it('should handle mixed quoted and unquoted identifiers', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ schema: '"my-schema"',+ name: 'regular_table',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ schema: 'public',+ name: '"special-table"',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "my-schema"."regular_table"');+ expect(sql).toContain('CREATE TABLE "public"."special-table"');+ });+ });++ describe('Foreign Key References with Special Characters', () => {+ it('should quote table names in foreign key constraints', () => {+ const parentTableId = testId();+ const childTableId = testId();+ const parentIdFieldId = testId();+ const childParentIdFieldId = testId();++ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ id: parentTableId,+ name: 'user-accounts',+ fields: [+ createField({+ id: parentIdFieldId,+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ id: childTableId,+ name: 'user-profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ createField({+ id: childParentIdFieldId,+ name: 'account_id',+ type: { id: 'uuid', name: 'uuid' },+ nullable: false,+ }),+ ],+ }),+ ],+ relationships: [+ {+ id: testId(),+ name: 'fk_profiles_accounts',+ sourceTableId: childTableId,+ targetTableId: parentTableId,+ sourceFieldId: childParentIdFieldId,+ targetFieldId: parentIdFieldId,+ sourceCardinality: 'many',+ targetCardinality: 'one',+ createdAt: testTime,+ },+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain(+ 'ALTER TABLE "user-profiles" ADD CONSTRAINT fk_profiles_accounts FOREIGN KEY (account_id) REFERENCES "user-accounts" (id)'+ );+ });++ it('should handle foreign keys between schema-qualified tables with special characters', () => {+ const parentTableId = testId();+ const childTableId = testId();+ const parentIdFieldId = testId();+ const childParentIdFieldId = testId();++ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ id: parentTableId,+ schema: 'auth-db',+ name: 'user accounts',+ fields: [+ createField({+ id: parentIdFieldId,+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ id: childTableId,+ schema: 'app-data',+ name: 'user profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ createField({+ id: childParentIdFieldId,+ name: 'account_id',+ type: { id: 'uuid', name: 'uuid' },+ nullable: false,+ }),+ ],+ }),+ ],+ relationships: [+ {+ id: testId(),+ name: 'fk_profiles_accounts',+ sourceTableId: childTableId,+ targetTableId: parentTableId,+ sourceFieldId: childParentIdFieldId,+ targetFieldId: parentIdFieldId,+ sourceCardinality: 'many',+ targetCardinality: 'one',+ createdAt: testTime,+ },+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain(+ 'ALTER TABLE "app-data"."user profiles" ADD CONSTRAINT fk_profiles_accounts FOREIGN KEY (account_id) REFERENCES "auth-db"."user accounts" (id)'+ );+ });+ });++ describe('Schema Quoting in Non-DBML Flow', () => {+ it('should properly quote schemas with special characters in non-DBML flow', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.GENERIC,+ tables: [+ createTable({+ schema: 'my-schema',+ name: 'users',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ schema: 'my schema',+ name: 'orders',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ schema: 'schema.with.dots',+ name: 'products',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ // Test with Generic database type to use base exportSQL+ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.GENERIC,+ isDBMLFlow: false,+ });++ // Schemas should be quoted when they have special characters+ expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS "my-schema"');+ expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS "my schema"');+ expect(sql).toContain(+ 'CREATE SCHEMA IF NOT EXISTS "schema.with.dots"'+ );++ // Tables should use quoted schema names (GENERIC uses PostgreSQL exporter which quotes everything)+ expect(sql).toContain('CREATE TABLE "my-schema"."users"');+ expect(sql).toContain('CREATE TABLE "my schema"."orders"');+ expect(sql).toContain('CREATE TABLE "schema.with.dots"."products"');+ });++ it('should not quote simple schema names in non-DBML flow', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.GENERIC,+ tables: [+ createTable({+ schema: 'public',+ name: 'users',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ schema: 'myschema',+ name: 'orders',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.GENERIC,+ isDBMLFlow: false,+ });++ // GENERIC uses PostgreSQL exporter which quotes everything+ expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS "public"');+ expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS "myschema"');+ expect(sql).toContain('CREATE TABLE "public"."users"');+ expect(sql).toContain('CREATE TABLE "myschema"."orders"');+ });++ it('should handle schemas in foreign key relationships', () => {+ const parentTableId = testId();+ const childTableId = testId();+ const parentIdFieldId = testId();+ const childParentIdFieldId = testId();++ const diagram = createDiagram({+ databaseType: DatabaseType.GENERIC,+ tables: [+ createTable({+ id: parentTableId,+ schema: 'auth-schema',+ name: 'users',+ fields: [+ createField({+ id: parentIdFieldId,+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ id: childTableId,+ schema: 'app schema',+ name: 'profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ createField({+ id: childParentIdFieldId,+ name: 'user_id',+ type: { id: 'uuid', name: 'uuid' },+ nullable: false,+ }),+ ],+ }),+ ],+ relationships: [+ {+ id: testId(),+ name: 'fk_profiles_users',+ sourceTableId: childTableId,+ targetTableId: parentTableId,+ sourceFieldId: childParentIdFieldId,+ targetFieldId: parentIdFieldId,+ sourceCardinality: 'many',+ targetCardinality: 'one',+ createdAt: testTime,+ },+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.GENERIC,+ isDBMLFlow: false,+ });++ // Check foreign key with schema-qualified tables (GENERIC uses PostgreSQL which quotes everything)+ expect(sql).toContain('ALTER TABLE "app schema"."profiles"');+ expect(sql).toContain('REFERENCES "auth-schema"."users"');+ });+ });++ describe('Edge Cases and Complex Scenarios', () => {+ it('should handle table names that are SQL reserved words', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'user',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ name: 'order',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ // For DBML flow, all names should be quoted+ expect(sql).toContain('CREATE TABLE "user"');+ expect(sql).toContain('CREATE TABLE "order"');+ });++ it('should handle Unicode characters in table names', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'użytkownik',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ name: '用户表',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "użytkownik"');+ expect(sql).toContain('CREATE TABLE "用户表"');+ });++ it('should handle table names with parentheses', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'users(archived)',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "users(archived)"');+ });++ it('should handle table names with forward slashes', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'api/v1/users',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "api/v1/users"');+ });++ it('should handle empty table names gracefully', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: '',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ // Empty name should be quoted+ expect(sql).toContain('CREATE TABLE ""');+ });++ it('should preserve different quote styles when already quoted', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: '"double-quoted"',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ name: '`backtick-quoted`',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ name: '[bracket-quoted]',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ expect(sql).toContain('CREATE TABLE "double-quoted"');+ expect(sql).toContain('CREATE TABLE `backtick-quoted`');+ expect(sql).toContain('CREATE TABLE [bracket-quoted]');+ });+ });++ describe('DBML vs Non-DBML Flow Behavior', () => {+ it('should quote all table names when in DBML flow, but not in normal flow for simple names', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'users',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sqlNormal = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: false,+ });++ const sqlDBML = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: true,+ });++ // In non-DBML flow with PostgreSQL, the PostgreSQL exporter quotes everything+ expect(sqlNormal).toContain('CREATE TABLE "users"');++ // In DBML flow, all names are quoted+ expect(sqlDBML).toContain('CREATE TABLE "users"');+ });++ it('should quote table names with special characters even when not in DBML flow', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ name: 'user-accounts',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: false,+ });++ expect(sql).toContain('CREATE TABLE "user-accounts"');+ });++ it('should create schema statements when not in DBML flow', () => {+ const diagram = createDiagram({+ databaseType: DatabaseType.POSTGRESQL,+ tables: [+ createTable({+ schema: 'auth',+ name: 'users',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ schema: 'app-data',+ name: 'settings',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const sql = exportBaseSQL({+ diagram,+ targetDatabaseType: DatabaseType.POSTGRESQL,+ isDBMLFlow: false,+ });++ expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS "auth"');+ expect(sql).toContain('CREATE SCHEMA IF NOT EXISTS "app-data"');+ // PostgreSQL exporter quotes everything+ expect(sql).toContain('CREATE TABLE "auth"."users"');+ expect(sql).toContain('CREATE TABLE "app-data"."settings"');+ });+ });+});diff --git a/src/lib/data/export-metadata/export-sql-script.ts b/src/lib/data/export-metadata/export-sql-script.tsindex 007bb888..7f1aeba7 100644--- a/src/lib/data/export-metadata/export-sql-script.ts+++ b/src/lib/data/export-metadata/export-sql-script.ts@@ -20,6 +20,38 @@ const simplifyDataType = (typeName: string): string => {return typeMap[typeName.toLowerCase()] || typeName;};+// Helper function to properly quote table/schema names with special characters+const getQuotedTableName = (+ table: DBTable,+ isDBMLFlow: boolean = false+): string => {+ // Check if a name is already quoted+ const isAlreadyQuoted = (name: string) => {+ return (+ (name.startsWith('"') && name.endsWith('"')) ||+ (name.startsWith('`') && name.endsWith('`')) ||+ (name.startsWith('[') && name.endsWith(']'))+ );+ };++ // Only add quotes if needed and not already quoted+ const quoteIfNeeded = (name: string) => {+ if (isAlreadyQuoted(name)) {+ return name;+ }+ const needsQuoting = /[^a-zA-Z0-9_]/.test(name) || isDBMLFlow;+ return needsQuoting ? `"${name}"` : name;+ };++ if (table.schema) {+ const quotedSchema = quoteIfNeeded(table.schema);+ const quotedTable = quoteIfNeeded(table.name);+ return `${quotedSchema}.${quotedTable}`;+ } else {+ return quoteIfNeeded(table.name);+ }+};+export const exportBaseSQL = ({diagram,targetDatabaseType,@@ -63,18 +95,21 @@ export const exportBaseSQL = ({let sqlScript = '';// First create the CREATE SCHEMA statements for all the found schemas based on tables- const schemas = new Set<string>();- tables.forEach((table) => {- if (table.schema) {- schemas.add(table.schema);- }- });+ // Skip schema creation for DBML flow as DBML doesn't support CREATE SCHEMA syntax+ if (!isDBMLFlow) {+ const schemas = new Set<string>();+ tables.forEach((table) => {+ if (table.schema) {+ schemas.add(table.schema);+ }+ });- // Add CREATE SCHEMA statements if any schemas exist- schemas.forEach((schema) => {- sqlScript += `CREATE SCHEMA IF NOT EXISTS ${schema};\n`;- });- if (schemas.size > 0) sqlScript += '\n'; // Add newline only if schemas were added+ // Add CREATE SCHEMA statements if any schemas exist+ schemas.forEach((schema) => {+ sqlScript += `CREATE SCHEMA IF NOT EXISTS "${schema}";\n`;+ });+ if (schemas.size > 0) sqlScript += '\n'; // Add newline only if schemas were added+ }// Add CREATE TYPE statements for ENUMs and COMPOSITE types from diagram.customTypesif (diagram.customTypes && diagram.customTypes.length > 0) {@@ -166,9 +201,7 @@ export const exportBaseSQL = ({// Loop through each non-view table to generate the SQL statementsnonViewTables.forEach((table) => {- const tableName = table.schema- ? `${table.schema}.${table.name}`- : table.name;+ const tableName = getQuotedTableName(table, isDBMLFlow);sqlScript += `CREATE TABLE ${tableName} (\n`;// Check for composite primary keys@@ -465,12 +498,9 @@ export const exportBaseSQL = ({return;}- const fkTableName = fkTable.schema- ? `${fkTable.schema}.${fkTable.name}`- : fkTable.name;- const refTableName = refTable.schema- ? `${refTable.schema}.${refTable.name}`- : refTable.name;+ const fkTableName = getQuotedTableName(fkTable, isDBMLFlow);+ const refTableName = getQuotedTableName(refTable, isDBMLFlow);+sqlScript += `ALTER TABLE ${fkTableName} ADD CONSTRAINT ${relationship.name} FOREIGN KEY (${fkField.name}) REFERENCES ${refTableName} (${refField.name});\n`;}});diff --git a/src/lib/data/sql-import/dialect-importers/postgresql/__tests__/postgresql-quoted-identifiers.test.ts b/src/lib/data/sql-import/dialect-importers/postgresql/__tests__/postgresql-quoted-identifiers.test.tsnew file mode 100644index 00000000..f2c9270e--- /dev/null+++ b/src/lib/data/sql-import/dialect-importers/postgresql/__tests__/postgresql-quoted-identifiers.test.ts@@ -0,0 +1,350 @@+import { describe, it, expect } from 'vitest';+import { fromPostgres } from '../postgresql';++describe('PostgreSQL Import - Quoted Identifiers with Special Characters', () => {+ describe('CREATE TABLE with quoted identifiers', () => {+ it('should handle tables with quoted schema and table names', async () => {+ const sql = `+ CREATE TABLE "my-schema"."user-profiles" (+ id serial PRIMARY KEY,+ name text NOT NULL+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('my-schema');+ expect(table.name).toBe('user-profiles');+ });++ it('should handle tables with spaces in schema and table names', async () => {+ const sql = `+ CREATE TABLE "user schema"."profile table" (+ "user id" integer PRIMARY KEY,+ "full name" varchar(255)+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('user schema');+ expect(table.name).toBe('profile table');+ expect(table.columns).toBeDefined();+ expect(table.columns.length).toBeGreaterThan(0);+ // Note: Column names with spaces might be parsed differently+ });++ it('should handle mixed quoted and unquoted identifiers', async () => {+ const sql = `+ CREATE TABLE "special-schema".users (+ id serial PRIMARY KEY+ );+ CREATE TABLE public."special-table" (+ id serial PRIMARY KEY+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(2);++ expect(result.tables[0].schema).toBe('special-schema');+ expect(result.tables[0].name).toBe('users');+ expect(result.tables[1].schema).toBe('public');+ expect(result.tables[1].name).toBe('special-table');+ });++ it('should handle tables with dots in names', async () => {+ const sql = `+ CREATE TABLE "schema.with.dots"."table.with.dots" (+ id serial PRIMARY KEY,+ data text+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('schema.with.dots');+ expect(table.name).toBe('table.with.dots');+ });+ });++ describe('FOREIGN KEY with quoted identifiers', () => {+ it('should handle inline REFERENCES with quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "auth-schema"."users" (+ "user-id" serial PRIMARY KEY,+ email text UNIQUE+ );++ CREATE TABLE "app-schema"."user-profiles" (+ id serial PRIMARY KEY,+ "user-id" integer REFERENCES "auth-schema"."users"("user-id"),+ bio text+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(2);+ expect(result.relationships).toHaveLength(1);++ const relationship = result.relationships[0];+ expect(relationship.sourceTable).toBe('user-profiles');+ expect(relationship.targetTable).toBe('users');+ expect(relationship.sourceColumn).toBe('user-id');+ expect(relationship.targetColumn).toBe('user-id');+ });++ it('should handle FOREIGN KEY constraints with quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "schema one"."table one" (+ "id field" serial PRIMARY KEY,+ "data field" text+ );++ CREATE TABLE "schema two"."table two" (+ id serial PRIMARY KEY,+ "ref id" integer,+ FOREIGN KEY ("ref id") REFERENCES "schema one"."table one"("id field")+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(2);+ expect(result.relationships).toHaveLength(1);++ const relationship = result.relationships[0];+ expect(relationship.sourceTable).toBe('table two');+ expect(relationship.targetTable).toBe('table one');+ expect(relationship.sourceColumn).toBe('ref id');+ expect(relationship.targetColumn).toBe('id field');+ });++ it('should handle named constraints with quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "auth"."users" (+ id serial PRIMARY KEY+ );++ CREATE TABLE "app"."profiles" (+ id serial PRIMARY KEY,+ user_id integer,+ CONSTRAINT "fk-user-profile" FOREIGN KEY (user_id) REFERENCES "auth"."users"(id)+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.relationships).toHaveLength(1);++ const relationship = result.relationships[0];+ // Note: Constraint names with special characters might be normalized+ expect(relationship.name).toBeDefined();+ });++ it('should handle ALTER TABLE ADD CONSTRAINT with quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "user-schema"."user-accounts" (+ "account-id" serial PRIMARY KEY,+ username text+ );++ CREATE TABLE "order-schema"."user-orders" (+ "order-id" serial PRIMARY KEY,+ "account-id" integer+ );++ ALTER TABLE "order-schema"."user-orders"+ ADD CONSTRAINT "fk_orders_accounts"+ FOREIGN KEY ("account-id")+ REFERENCES "user-schema"."user-accounts"("account-id");+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(2);+ expect(result.relationships).toHaveLength(1);++ const relationship = result.relationships[0];+ expect(relationship.name).toBe('fk_orders_accounts');+ expect(relationship.sourceTable).toBe('user-orders');+ expect(relationship.targetTable).toBe('user-accounts');+ expect(relationship.sourceColumn).toBe('account-id');+ expect(relationship.targetColumn).toBe('account-id');+ });++ it('should handle complex mixed quoting scenarios', async () => {+ const sql = `+ CREATE TABLE auth.users (+ id serial PRIMARY KEY+ );++ CREATE TABLE "app-data"."user_profiles" (+ profile_id serial PRIMARY KEY,+ "user-id" integer REFERENCES auth.users(id)+ );++ CREATE TABLE "app-data".posts (+ id serial PRIMARY KEY,+ profile_id integer+ );++ ALTER TABLE "app-data".posts+ ADD CONSTRAINT fk_posts_profiles+ FOREIGN KEY (profile_id)+ REFERENCES "app-data"."user_profiles"(profile_id);+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(3);+ expect(result.relationships).toHaveLength(2);++ // Verify the relationships were correctly identified+ const profilesTable = result.tables.find(+ (t) => t.name === 'user_profiles'+ );+ expect(profilesTable?.schema).toBe('app-data');++ const postsTable = result.tables.find((t) => t.name === 'posts');+ expect(postsTable?.schema).toBe('app-data');+ });+ });++ describe('Edge cases and special scenarios', () => {+ it('should handle Unicode characters in quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "схема"."таблица" (+ "идентификатор" serial PRIMARY KEY,+ "данные" text+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('схема');+ expect(table.name).toBe('таблица');+ expect(table.columns).toBeDefined();+ expect(table.columns.length).toBeGreaterThan(0);+ });++ it('should handle parentheses in quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "schema(prod)"."users(archived)" (+ id serial PRIMARY KEY,+ data text+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('schema(prod)');+ expect(table.name).toBe('users(archived)');+ });++ it('should handle forward slashes in quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "api/v1"."users/profiles" (+ id serial PRIMARY KEY+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('api/v1');+ expect(table.name).toBe('users/profiles');+ });++ it('should handle IF NOT EXISTS with quoted identifiers', async () => {+ const sql = `+ CREATE TABLE IF NOT EXISTS "test-schema"."test-table" (+ id serial PRIMARY KEY+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('test-schema');+ expect(table.name).toBe('test-table');+ });++ it('should handle ONLY keyword with quoted identifiers', async () => {+ const sql = `+ CREATE TABLE ONLY "parent-schema"."parent-table" (+ id serial PRIMARY KEY+ );++ ALTER TABLE ONLY "parent-schema"."parent-table"+ ADD CONSTRAINT "unique-constraint" UNIQUE (id);+ `;++ const result = await fromPostgres(sql);++ // ONLY keyword might trigger warnings+ expect(result.warnings).toBeDefined();+ expect(result.tables).toHaveLength(1);++ const table = result.tables[0];+ expect(table.schema).toBe('parent-schema');+ expect(table.name).toBe('parent-table');+ });++ it('should handle self-referencing foreign keys with quoted identifiers', async () => {+ const sql = `+ CREATE TABLE "org-schema"."departments" (+ "dept-id" serial PRIMARY KEY,+ "parent-dept-id" integer REFERENCES "org-schema"."departments"("dept-id"),+ name text+ );+ `;++ const result = await fromPostgres(sql);++ expect(result.warnings || []).toHaveLength(0);+ expect(result.tables).toHaveLength(1);+ expect(result.relationships).toHaveLength(1);++ const relationship = result.relationships[0];+ expect(relationship.sourceTable).toBe('departments');+ expect(relationship.targetTable).toBe('departments'); // Self-reference+ expect(relationship.sourceColumn).toBe('parent-dept-id');+ expect(relationship.targetColumn).toBe('dept-id');+ });+ });+});diff --git a/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.ts b/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.tsindex b58b9765..75a44b2a 100644--- a/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.ts+++ b/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.ts@@ -490,16 +490,21 @@ function extractForeignKeysFromCreateTable(const tableBody = tableBodyMatch[1];- // Pattern for inline REFERENCES - more flexible to handle various formats+ // Pattern for inline REFERENCES - handles quoted and unquoted identifiersconst inlineRefPattern =- /["']?(\w+)["']?\s+(?:\w+(?:\([^)]*\))?(?:\[[^\]]*\])?(?:\s+\w+)*\s+)?REFERENCES\s+(?:["']?(\w+)["']?\.)?["']?(\w+)["']?\s*\(\s*["']?(\w+)["']?\s*\)/gi;+ /(?:"([^"]+)"|([^"\s,()]+))\s+(?:\w+(?:\([^)]*\))?(?:\[[^\]]*\])?(?:\s+\w+)*\s+)?REFERENCES\s+(?:(?:"([^"]+)"|([^"\s.]+))\.)?(?:"([^"]+)"|([^"\s.(]+))\s*\(\s*(?:"([^"]+)"|([^"\s,)]+))\s*\)/gi;let match;while ((match = inlineRefPattern.exec(tableBody)) !== null) {- const sourceColumn = match[1];- const targetSchema = match[2] || 'public';- const targetTable = match[3];- const targetColumn = match[4];+ // Extract values from appropriate match groups+ // Groups: 1=quoted source col, 2=unquoted source col,+ // 3=quoted schema, 4=unquoted schema,+ // 5=quoted target table, 6=unquoted target table,+ // 7=quoted target col, 8=unquoted target col+ const sourceColumn = match[1] || match[2];+ const targetSchema = match[3] || match[4] || 'public';+ const targetTable = match[5] || match[6];+ const targetColumn = match[7] || match[8];const targetTableKey = `${targetSchema}.${targetTable}`;const targetTableId = tableMap[targetTableKey];@@ -521,15 +526,16 @@ function extractForeignKeysFromCreateTable(}}- // Pattern for FOREIGN KEY constraints+ // Pattern for FOREIGN KEY constraints - handles quoted and unquoted identifiersconst fkConstraintPattern =- /FOREIGN\s+KEY\s*\(\s*["']?(\w+)["']?\s*\)\s*REFERENCES\s+(?:["']?(\w+)["']?\.)?["']?(\w+)["']?\s*\(\s*["']?(\w+)["']?\s*\)/gi;+ /FOREIGN\s+KEY\s*\(\s*(?:"([^"]+)"|([^"\s,)]+))\s*\)\s*REFERENCES\s+(?:(?:"([^"]+)"|([^"\s.]+))\.)?(?:"([^"]+)"|([^"\s.(]+))\s*\(\s*(?:"([^"]+)"|([^"\s,)]+))\s*\)/gi;while ((match = fkConstraintPattern.exec(tableBody)) !== null) {- const sourceColumn = match[1];- const targetSchema = match[2] || 'public';- const targetTable = match[3];- const targetColumn = match[4];+ // Extract values from appropriate match groups+ const sourceColumn = match[1] || match[2];+ const targetSchema = match[3] || match[4] || 'public';+ const targetTable = match[5] || match[6];+ const targetColumn = match[7] || match[8];const targetTableKey = `${targetSchema}.${targetTable}`;const targetTableId = tableMap[targetTableKey];@@ -585,12 +591,16 @@ export async function fromPostgres(? stmt.sql.substring(createTableIndex): stmt.sql;+ // Updated regex to properly handle quoted identifiers with special characters+ // Matches: schema.table, "schema"."table", "schema".table, schema."table"const tableMatch = sqlFromCreate.match(- /CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?(?:\s+ONLY)?\s+(?:"?([^"\s.]+)"?\.)?["'`]?([^"'`\s.(]+)["'`]?/i+ /CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?(?:\s+ONLY)?\s+(?:(?:"([^"]+)"|([^"\s.]+))\.)?(?:"([^"]+)"|([^"\s.(]+))/i);if (tableMatch) {- const schemaName = tableMatch[1] || 'public';- const tableName = tableMatch[2];+ // Extract schema and table names from the appropriate match groups+ // Groups: 1=quoted schema, 2=unquoted schema, 3=quoted table, 4=unquoted table+ const schemaName = tableMatch[1] || tableMatch[2] || 'public';+ const tableName = tableMatch[3] || tableMatch[4];const tableKey = `${schemaName}.${tableName}`;tableMap[tableKey] = generateId();}@@ -938,12 +948,16 @@ export async function fromPostgres(? stmt.sql.substring(createTableIndex): stmt.sql;+ // Updated regex to properly handle quoted identifiers with special characters+ // Matches: schema.table, "schema"."table", "schema".table, schema."table"const tableMatch = sqlFromCreate.match(- /CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?(?:\s+ONLY)?\s+(?:"?([^"\s.]+)"?\.)?["'`]?([^"'`\s.(]+)["'`]?/i+ /CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?(?:\s+ONLY)?\s+(?:(?:"([^"]+)"|([^"\s.]+))\.)?(?:"([^"]+)"|([^"\s.(]+))/i);if (tableMatch) {- const schemaName = tableMatch[1] || 'public';- const tableName = tableMatch[2];+ // Extract schema and table names from the appropriate match groups+ // Groups: 1=quoted schema, 2=unquoted schema, 3=quoted table, 4=unquoted table+ const schemaName = tableMatch[1] || tableMatch[2] || 'public';+ const tableName = tableMatch[3] || tableMatch[4];const tableKey = `${schemaName}.${tableName}`;const tableId = tableMap[tableKey];@@ -1130,18 +1144,22 @@ export async function fromPostgres(} else if (stmt.type === 'alter' && !stmt.parsed) {// Handle ALTER TABLE statements that failed to parse// Extract foreign keys using regex as fallback+ // Updated regex to handle quoted identifiers properlyconst alterFKMatch = stmt.sql.match(- /ALTER\s+TABLE\s+(?:ONLY\s+)?(?:"?([^"\s.]+)"?\.)?["']?([^"'\s.(]+)["']?\s+ADD\s+CONSTRAINT\s+["']?([^"'\s]+)["']?\s+FOREIGN\s+KEY\s*\(["']?([^"'\s)]+)["']?\)\s+REFERENCES\s+(?:"?([^"\s.]+)"?\.)?["']?([^"'\s.(]+)["']?\s*\(["']?([^"'\s)]+)["']?\)/i+ /ALTER\s+TABLE\s+(?:ONLY\s+)?(?:(?:"([^"]+)"|([^"\s.]+))\.)?(?:"([^"]+)"|([^"\s.(]+))\s+ADD\s+CONSTRAINT\s+(?:"([^"]+)"|([^"\s]+))\s+FOREIGN\s+KEY\s*\((?:"([^"]+)"|([^"\s)]+))\)\s+REFERENCES\s+(?:(?:"([^"]+)"|([^"\s.]+))\.)?(?:"([^"]+)"|([^"\s.(]+))\s*\((?:"([^"]+)"|([^"\s)]+))\)/i);if (alterFKMatch) {- const sourceSchema = alterFKMatch[1] || 'public';- const sourceTable = alterFKMatch[2];- const constraintName = alterFKMatch[3];- const sourceColumn = alterFKMatch[4];- const targetSchema = alterFKMatch[5] || 'public';- const targetTable = alterFKMatch[6];- const targetColumn = alterFKMatch[7];+ // Extract values from appropriate match groups+ const sourceSchema =+ alterFKMatch[1] || alterFKMatch[2] || 'public';+ const sourceTable = alterFKMatch[3] || alterFKMatch[4];+ const constraintName = alterFKMatch[5] || alterFKMatch[6];+ const sourceColumn = alterFKMatch[7] || alterFKMatch[8];+ const targetSchema =+ alterFKMatch[9] || alterFKMatch[10] || 'public';+ const targetTable = alterFKMatch[11] || alterFKMatch[12];+ const targetColumn = alterFKMatch[13] || alterFKMatch[14];const sourceTableId = getTableIdWithSchemaSupport(tableMap,diff --git a/src/lib/dbml/dbml-export/__tests__/dbml-export-multiline-fix.test.ts b/src/lib/dbml/dbml-export/__tests__/dbml-export-multiline-fix.test.tsnew file mode 100644index 00000000..b6d85d18--- /dev/null+++ b/src/lib/dbml/dbml-export/__tests__/dbml-export-multiline-fix.test.ts@@ -0,0 +1,438 @@+import { describe, it, expect } from 'vitest';+import { generateDBMLFromDiagram } from '../dbml-export';+import { DatabaseType } from '@/lib/domain/database-type';+import type { Diagram } from '@/lib/domain/diagram';+import type { DBTable } from '@/lib/domain/db-table';+import type { DBField } from '@/lib/domain/db-field';++describe('DBML Export - Fix Multiline Table Names', () => {+ // Helper to generate test IDs and timestamps+ let idCounter = 0;+ const testId = () => `test-id-${++idCounter}`;+ const testTime = Date.now();++ // Helper to create a field+ const createField = (overrides: Partial<DBField>): DBField =>+ ({+ id: testId(),+ name: 'field',+ type: { id: 'text', name: 'text' },+ primaryKey: false,+ nullable: true,+ unique: false,+ createdAt: testTime,+ ...overrides,+ }) as DBField;++ // Helper to create a table+ const createTable = (overrides: Partial<DBTable>): DBTable =>+ ({+ id: testId(),+ name: 'table',+ fields: [],+ indexes: [],+ createdAt: testTime,+ x: 0,+ y: 0,+ width: 200,+ ...overrides,+ }) as DBTable;++ // Helper to create a diagram+ const createDiagram = (overrides: Partial<Diagram>): Diagram =>+ ({+ id: testId(),+ name: 'diagram',+ databaseType: DatabaseType.POSTGRESQL,+ tables: [],+ relationships: [],+ createdAt: testTime,+ updatedAt: testTime,+ ...overrides,+ }) as Diagram;++ describe('DBML Generation with Special Characters', () => {+ it('should handle table names with special characters', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ name: 'user-profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ createField({+ name: 'user-name',+ type: { id: 'varchar', name: 'varchar' },+ nullable: true,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should properly quote table names with special characters+ expect(result.standardDbml).toContain('Table "user-profiles"');++ // Field names with special characters should also be quoted+ expect(result.standardDbml).toContain('"user-name"');++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });++ it('should handle schema-qualified table names', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ schema: 'my-schema',+ name: 'my-table',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should properly quote schema and table names+ expect(result.standardDbml).toContain(+ 'Table "my-schema"."my-table"'+ );++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });++ it('should handle table names with spaces', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ name: 'user profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should properly quote table names with spaces+ expect(result.standardDbml).toContain('Table "user profiles"');++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });++ it('should handle schema names with spaces', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ schema: 'my schema',+ name: 'my_table',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should properly quote schema with spaces+ expect(result.standardDbml).toContain(+ 'Table "my schema"."my_table"'+ );++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });++ it('should handle table names with dots', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ name: 'app.config',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should properly quote table names with dots+ expect(result.standardDbml).toContain('Table "app.config"');++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });++ it('should not have line breaks in table declarations', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ schema: 'very-long-schema-name-with-dashes',+ name: 'very-long-table-name-with-special-characters',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Table declaration should be on a single line+ const tableDeclarations =+ result.standardDbml.match(/Table\s+[^{]+\{/g) || [];+ tableDeclarations.forEach((decl) => {+ // Should not contain newlines before the opening brace+ expect(decl).not.toContain('\n');+ });++ // The full qualified name should be on one line+ expect(result.standardDbml).toMatch(+ /Table\s+"very-long-schema-name-with-dashes"\."very-long-table-name-with-special-characters"\s*\{/+ );+ });+ });++ describe('Multiple tables and relationships', () => {+ it('should handle multiple tables with special characters', () => {+ const parentTableId = testId();+ const childTableId = testId();+ const parentIdField = testId();+ const childParentIdField = testId();++ const diagram = createDiagram({+ tables: [+ createTable({+ id: parentTableId,+ schema: 'auth-schema',+ name: 'user-accounts',+ fields: [+ createField({+ id: parentIdField,+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ id: childTableId,+ schema: 'app-schema',+ name: 'user-profiles',+ fields: [+ createField({+ name: 'id',+ type: { id: 'uuid', name: 'uuid' },+ primaryKey: true,+ nullable: false,+ }),+ createField({+ id: childParentIdField,+ name: 'account-id',+ type: { id: 'uuid', name: 'uuid' },+ nullable: false,+ }),+ ],+ }),+ ],+ relationships: [+ {+ id: testId(),+ name: 'fk_profiles_accounts',+ sourceTableId: childTableId,+ targetTableId: parentTableId,+ sourceFieldId: childParentIdField,+ targetFieldId: parentIdField,+ sourceCardinality: 'many',+ targetCardinality: 'one',+ createdAt: testTime,+ },+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should contain both tables properly quoted+ expect(result.standardDbml).toContain(+ 'Table "auth-schema"."user-accounts"'+ );+ expect(result.standardDbml).toContain(+ 'Table "app-schema"."user-profiles"'+ );++ // Should contain the relationship reference+ expect(result.standardDbml).toContain('Ref');++ // Should contain field names with dashes properly quoted+ expect(result.standardDbml).toContain('"account-id"');++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });++ it('should work correctly with inline DBML format', () => {+ const parentTableId = testId();+ const childTableId = testId();+ const parentIdField = testId();+ const childParentIdField = testId();++ const diagram = createDiagram({+ tables: [+ createTable({+ id: parentTableId,+ name: 'parent-table',+ fields: [+ createField({+ id: parentIdField,+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ createTable({+ id: childTableId,+ name: 'child-table',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ createField({+ id: childParentIdField,+ name: 'parent-id',+ type: { id: 'integer', name: 'integer' },+ nullable: false,+ }),+ ],+ }),+ ],+ relationships: [+ {+ id: testId(),+ name: 'fk_child_parent',+ sourceTableId: childTableId,+ targetTableId: parentTableId,+ sourceFieldId: childParentIdField,+ targetFieldId: parentIdField,+ sourceCardinality: 'many',+ targetCardinality: 'one',+ createdAt: testTime,+ },+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Both standard and inline should be generated+ expect(result.standardDbml).toBeDefined();+ expect(result.inlineDbml).toBeDefined();++ // Inline version should contain inline references+ expect(result.inlineDbml).toContain('ref:');++ // Both should properly quote table names+ expect(result.standardDbml).toContain('Table "parent-table"');+ expect(result.inlineDbml).toContain('Table "parent-table"');+ expect(result.standardDbml).toContain('Table "child-table"');+ expect(result.inlineDbml).toContain('Table "child-table"');++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });+ });++ describe('Edge cases', () => {+ it('should handle empty table names gracefully', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ name: '',+ fields: [+ createField({+ name: 'id',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should not throw error+ expect(result.error).toBeUndefined();+ });++ it('should handle Unicode characters in names', () => {+ const diagram = createDiagram({+ tables: [+ createTable({+ name: 'użytkownik',+ fields: [+ createField({+ name: 'identyfikator',+ type: { id: 'integer', name: 'integer' },+ primaryKey: true,+ nullable: false,+ }),+ ],+ }),+ ],+ });++ const result = generateDBMLFromDiagram(diagram);++ // Should handle Unicode characters+ expect(result.standardDbml).toContain('Table "użytkownik"');+ expect(result.standardDbml).toContain('"identyfikator"');++ // Should not have any errors+ expect(result.error).toBeUndefined();+ });+ });+});diff --git a/src/lib/dbml/dbml-export/dbml-export.ts b/src/lib/dbml/dbml-export/dbml-export.tsindex 2a70efbf..5030085d 100644--- a/src/lib/dbml/dbml-export/dbml-export.ts+++ b/src/lib/dbml/dbml-export/dbml-export.ts@@ -605,6 +605,23 @@ const fixTableBracketSyntax = (dbml: string): string => {);};+// Fix table names that have been broken across multiple lines+const fixMultilineTableNames = (dbml: string): string => {+ // Match Table declarations that might have line breaks in the table name+ // This regex captures:+ // - Table keyword+ // - Optional quoted schema with dot+ // - Table name that might be broken across lines (until the opening brace)+ return dbml.replace(+ /Table\s+((?:"[^"]*"\.)?"[^"]*(?:\n[^"]*)*")\s*\{/g,+ (_, tableName) => {+ // Remove line breaks within the table name+ const fixedTableName = tableName.replace(/\n\s*/g, '');+ return `Table ${fixedTableName} {`;+ }+ );+};+// Restore composite primary key names in the DBMLconst restoreCompositePKNames = (dbml: string, tables: DBTable[]): string => {if (!tables || tables.length === 0) return dbml;@@ -969,10 +986,12 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {}standard = normalizeCharTypeFormat(- fixTableBracketSyntax(- importer.import(- baseScript,- databaseTypeToImportFormat(diagram.databaseType)+ fixMultilineTableNames(+ fixTableBracketSyntax(+ importer.import(+ baseScript,+ databaseTypeToImportFormat(diagram.databaseType)+ ))));