Skip to content

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

fix: add Oracle database support for SQL import (#1005)

Guy Ben-Aharon9ac99d928c5d
diff --git a/src/context/chartdb-context/chartdb-provider.tsx b/src/context/chartdb-context/chartdb-provider.tsx
index c748740e..b5a733d8 100644
--- a/src/context/chartdb-context/chartdb-provider.tsx
+++ b/src/context/chartdb-context/chartdb-provider.tsx
@@ -32,6 +32,7 @@ import {
DBCustomTypeKind,
type DBCustomType,
} from '@/lib/domain/db-custom-type';
+import { getDefaultPrimaryKeyType } from '@/lib/data/data-types/data-types';
export interface ChartDBProviderProps {
diagram?: Diagram;
@@ -342,10 +343,7 @@ export const ChartDBProvider: React.FC<
{
id: generateId(),
name: 'id',
- type:
- databaseType === DatabaseType.SQLITE
- ? { id: 'integer', name: 'integer' }
- : { id: 'bigint', name: 'bigint' },
+ type: getDefaultPrimaryKeyType(databaseType),
unique: true,
nullable: false,
primaryKey: true,
@@ -865,10 +863,7 @@ export const ChartDBProvider: React.FC<
const field: DBField = {
id: generateId(),
name: `field_${(table?.fields?.length ?? 0) + 1}`,
- type:
- databaseType === DatabaseType.SQLITE
- ? { id: 'integer', name: 'integer' }
- : { id: 'bigint', name: 'bigint' },
+ type: getDefaultPrimaryKeyType(databaseType),
unique: false,
nullable: true,
primaryKey: false,
diff --git a/src/lib/data/data-types/data-types.ts b/src/lib/data/data-types/data-types.ts
index 0f099bd0..e8b6734c 100644
--- a/src/lib/data/data-types/data-types.ts
+++ b/src/lib/data/data-types/data-types.ts
@@ -240,3 +240,39 @@ export const getPreferredSynonym = (
return null;
};
+
+/**
+ * Returns the default primary key data type for a given database type.
+ *
+ * Different databases have different conventions for auto-increment primary key types:
+ * - SQLite: INTEGER (required for AUTOINCREMENT)
+ * - Oracle: NUMBER (Oracle doesn't have bigint - uses NUMBER for all numeric types)
+ * - Others: BIGINT (PostgreSQL, MySQL, SQL Server, MariaDB, etc.)
+ *
+ * @param databaseType - The database type
+ * @returns The DataType object with id and name for the default primary key type
+ *
+ * @example
+ * ```ts
+ * getDefaultPrimaryKeyType(DatabaseType.SQLITE)
+ * // Returns: { id: 'integer', name: 'integer' }
+ *
+ * getDefaultPrimaryKeyType(DatabaseType.ORACLE)
+ * // Returns: { id: 'number', name: 'number' }
+ *
+ * getDefaultPrimaryKeyType(DatabaseType.POSTGRESQL)
+ * // Returns: { id: 'bigint', name: 'bigint' }
+ * ```
+ */
+export const getDefaultPrimaryKeyType = (
+ databaseType: DatabaseType
+): DataType => {
+ switch (databaseType) {
+ case DatabaseType.SQLITE:
+ return { id: 'integer', name: 'integer' };
+ case DatabaseType.ORACLE:
+ return { id: 'number', name: 'number' };
+ default:
+ return { id: 'bigint', name: 'bigint' };
+ }
+};
diff --git a/src/lib/data/sql-import/common.ts b/src/lib/data/sql-import/common.ts
index 7eb143c0..4beaa344 100644
--- a/src/lib/data/sql-import/common.ts
+++ b/src/lib/data/sql-import/common.ts
@@ -540,13 +540,40 @@ export const typeAffinity: Record<string, Record<string, string>> = {
},
[DatabaseType.ORACLE]: {
// Oracle data types (all lowercase for consistency)
+ // Character types
varchar2: 'varchar',
nvarchar2: 'varchar',
+ char: 'char',
+ nchar: 'char',
+ clob: 'text',
+ nclob: 'text',
+ long: 'text',
+ // Numeric types
number: 'numeric',
+ integer: 'integer',
+ int: 'integer',
+ smallint: 'smallint',
+ float: 'float',
+ real: 'real',
+ binary_float: 'float',
+ binary_double: 'double',
+ // Date/Time types
date: 'date',
timestamp: 'timestamp',
- clob: 'text',
+ 'timestamp with time zone': 'timestamp',
+ 'timestamp with local time zone': 'timestamp',
+ interval: 'interval',
+ // Binary types
blob: 'blob',
+ raw: 'blob',
+ 'long raw': 'blob',
+ bfile: 'blob',
+ // Other types
+ rowid: 'varchar',
+ urowid: 'varchar',
+ xmltype: 'text',
+ json: 'json',
+ boolean: 'boolean',
},
[DatabaseType.GENERIC]: {
// Generic fallback types (all lowercase for consistency)
diff --git a/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-core.test.ts b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-core.test.ts
new file mode 100644
index 00000000..aa340795
--- /dev/null
+++ b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-core.test.ts
@@ -0,0 +1,305 @@
+import { describe, it, expect } from 'vitest';
+import { fromOracle } from '../oracle';
+
+describe('Oracle Core Parser Tests', () => {
+ it('should parse basic tables', async () => {
+ const sql = `
+ CREATE TABLE employees (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(255) NOT NULL
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ expect(result.tables[0].name).toBe('employees');
+ expect(result.tables[0].columns).toHaveLength(2);
+ });
+
+ it('should parse tables with schemas', async () => {
+ const sql = `
+ CREATE TABLE hr.departments (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL,
+ location VARCHAR2(200)
+ );
+
+ CREATE TABLE sales.orders (
+ id NUMBER(10) PRIMARY KEY,
+ order_date DATE NOT NULL
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(2);
+ expect(
+ result.tables.find((t) => t.name === 'departments')
+ ).toBeDefined();
+ expect(
+ result.tables.find((t) => t.name === 'departments')?.schema
+ ).toBe('hr');
+ expect(result.tables.find((t) => t.name === 'orders')?.schema).toBe(
+ 'sales'
+ );
+ });
+
+ it('should parse foreign key relationships', async () => {
+ const sql = `
+ CREATE TABLE departments (id NUMBER(10) PRIMARY KEY);
+ CREATE TABLE employees (
+ id NUMBER(10) PRIMARY KEY,
+ department_id NUMBER(10) REFERENCES departments(id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(2);
+ expect(result.relationships).toHaveLength(1);
+ expect(result.relationships[0].sourceTable).toBe('employees');
+ expect(result.relationships[0].targetTable).toBe('departments');
+ expect(result.relationships[0].sourceColumn).toBe('department_id');
+ expect(result.relationships[0].targetColumn).toBe('id');
+ });
+
+ it('should parse foreign keys with schema references', async () => {
+ const sql = `
+ CREATE TABLE hr.departments (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL
+ );
+
+ CREATE TABLE hr.employees (
+ id NUMBER(10) PRIMARY KEY,
+ department_id NUMBER(10) NOT NULL,
+ name VARCHAR2(100) NOT NULL,
+ CONSTRAINT FK_emp_dept FOREIGN KEY (department_id) REFERENCES hr.departments(id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(2);
+ expect(result.relationships).toHaveLength(1);
+ expect(result.relationships[0].sourceTable).toBe('employees');
+ expect(result.relationships[0].targetTable).toBe('departments');
+ expect(result.relationships[0].sourceSchema).toBe('hr');
+ expect(result.relationships[0].targetSchema).toBe('hr');
+ });
+
+ it('should handle Oracle-specific data types correctly', async () => {
+ const sql = `
+ CREATE TABLE data_types_test (
+ id NUMBER(10) NOT NULL,
+ name VARCHAR2(255) NOT NULL,
+ description CLOB,
+ amount NUMBER(18, 2) NOT NULL,
+ is_active NUMBER(1) NOT NULL,
+ created_at TIMESTAMP NOT NULL,
+ birth_date DATE,
+ photo BLOB,
+ small_number INTEGER,
+ precise_value BINARY_DOUBLE,
+ xml_data XMLTYPE,
+ PRIMARY KEY (id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'id')?.type).toBe('number');
+ expect(columns.find((c) => c.name === 'name')?.type).toBe('varchar2');
+ expect(columns.find((c) => c.name === 'description')?.type).toBe(
+ 'clob'
+ );
+ expect(columns.find((c) => c.name === 'amount')?.type).toBe('number');
+ expect(columns.find((c) => c.name === 'is_active')?.type).toBe(
+ 'number'
+ );
+ expect(columns.find((c) => c.name === 'created_at')?.type).toBe(
+ 'timestamp'
+ );
+ expect(columns.find((c) => c.name === 'birth_date')?.type).toBe('date');
+ expect(columns.find((c) => c.name === 'photo')?.type).toBe('blob');
+ expect(columns.find((c) => c.name === 'small_number')?.type).toBe(
+ 'integer'
+ );
+ expect(columns.find((c) => c.name === 'precise_value')?.type).toBe(
+ 'binary_double'
+ );
+ expect(columns.find((c) => c.name === 'xml_data')?.type).toBe(
+ 'xmltype'
+ );
+ });
+
+ it('should handle GENERATED AS IDENTITY columns', async () => {
+ const sql = `
+ CREATE TABLE products (
+ id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL,
+ price NUMBER(10, 2) NOT NULL
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const idColumn = result.tables[0].columns.find((c) => c.name === 'id');
+ expect(idColumn?.increment).toBe(true);
+ });
+
+ it('should parse composite primary keys', async () => {
+ const sql = `
+ CREATE TABLE order_items (
+ order_id NUMBER(10) NOT NULL,
+ product_id NUMBER(10) NOT NULL,
+ quantity NUMBER(10) NOT NULL,
+ CONSTRAINT pk_order_items PRIMARY KEY (order_id, product_id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const table = result.tables[0];
+ expect(table.columns.filter((c) => c.primaryKey)).toHaveLength(2);
+ expect(
+ table.columns.find((c) => c.name === 'order_id')?.primaryKey
+ ).toBe(true);
+ expect(
+ table.columns.find((c) => c.name === 'product_id')?.primaryKey
+ ).toBe(true);
+ });
+
+ it('should handle unique constraints', async () => {
+ const sql = `
+ CREATE TABLE users (
+ id NUMBER(10) NOT NULL PRIMARY KEY,
+ email VARCHAR2(255) NOT NULL,
+ username VARCHAR2(50) NOT NULL,
+ CONSTRAINT uq_users_email UNIQUE (email)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ expect(result.tables[0].indexes).toHaveLength(1);
+ expect(result.tables[0].indexes[0].name).toBe('uq_users_email');
+ expect(result.tables[0].indexes[0].unique).toBe(true);
+ expect(result.tables[0].indexes[0].columns).toContain('email');
+ });
+
+ it('should handle default values', async () => {
+ const sql = `
+ CREATE TABLE audit_log (
+ id NUMBER(10) NOT NULL,
+ action VARCHAR2(100) NOT NULL,
+ is_active NUMBER(1) DEFAULT 1,
+ created_at TIMESTAMP DEFAULT SYSTIMESTAMP,
+ updated_at DATE DEFAULT SYSDATE,
+ status VARCHAR2(20) DEFAULT 'pending',
+ PRIMARY KEY (id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'is_active')?.default).toBe('1');
+ expect(
+ columns.find((c) => c.name === 'created_at')?.default
+ ).toBeDefined();
+ expect(
+ columns.find((c) => c.name === 'updated_at')?.default
+ ).toBeDefined();
+ expect(columns.find((c) => c.name === 'status')?.default).toBe(
+ "'pending'"
+ );
+ });
+
+ it('should parse indexes created separately', async () => {
+ const sql = `
+ CREATE TABLE customers (
+ id NUMBER(10) NOT NULL PRIMARY KEY,
+ first_name VARCHAR2(100) NOT NULL,
+ last_name VARCHAR2(100) NOT NULL,
+ email VARCHAR2(255) NOT NULL
+ );
+
+ CREATE INDEX idx_customers_name ON customers (last_name, first_name);
+ CREATE UNIQUE INDEX idx_customers_email ON customers (email);
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ expect(result.tables[0].indexes).toHaveLength(2);
+
+ const nameIndex = result.tables[0].indexes.find(
+ (i) => i.name === 'idx_customers_name'
+ );
+ expect(nameIndex?.unique).toBe(false);
+ expect(nameIndex?.columns).toContain('last_name');
+ expect(nameIndex?.columns).toContain('first_name');
+
+ const emailIndex = result.tables[0].indexes.find(
+ (i) => i.name === 'idx_customers_email'
+ );
+ expect(emailIndex?.unique).toBe(true);
+ expect(emailIndex?.columns).toContain('email');
+ });
+
+ it('should handle nullable and not null columns correctly', async () => {
+ const sql = `
+ CREATE TABLE test_nullability (
+ id NUMBER(10) NOT NULL PRIMARY KEY,
+ required_field VARCHAR2(100) NOT NULL,
+ optional_field VARCHAR2(100),
+ another_optional CLOB
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'id')?.nullable).toBe(false);
+ expect(columns.find((c) => c.name === 'required_field')?.nullable).toBe(
+ false
+ );
+ expect(columns.find((c) => c.name === 'optional_field')?.nullable).toBe(
+ true
+ );
+ expect(
+ columns.find((c) => c.name === 'another_optional')?.nullable
+ ).toBe(true);
+ });
+
+ it('should handle quoted identifiers', async () => {
+ const sql = `
+ CREATE TABLE "Order" (
+ "Id" NUMBER(10) NOT NULL PRIMARY KEY,
+ "Order Date" DATE NOT NULL,
+ "Customer ID" NUMBER(10) NOT NULL
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ expect(result.tables[0].name).toBe('Order');
+ expect(result.tables[0].columns).toHaveLength(3);
+ expect(
+ result.tables[0].columns.find((c) => c.name === 'Id')
+ ).toBeDefined();
+ });
+});
diff --git a/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-data-types.test.ts b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-data-types.test.ts
new file mode 100644
index 00000000..05e741f9
--- /dev/null
+++ b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-data-types.test.ts
@@ -0,0 +1,227 @@
+import { describe, it, expect } from 'vitest';
+import { fromOracle } from '../oracle';
+
+describe('Oracle Data Types Tests', () => {
+ it('should parse character data types', async () => {
+ const sql = `
+ CREATE TABLE char_types (
+ id NUMBER(10) PRIMARY KEY,
+ var_char VARCHAR2(100),
+ n_var_char NVARCHAR2(100),
+ fixed_char CHAR(10),
+ n_fixed_char NCHAR(10),
+ large_text CLOB,
+ n_large_text NCLOB,
+ legacy_text LONG
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'var_char')?.type).toBe(
+ 'varchar2'
+ );
+ expect(columns.find((c) => c.name === 'n_var_char')?.type).toBe(
+ 'nvarchar2'
+ );
+ expect(columns.find((c) => c.name === 'fixed_char')?.type).toBe('char');
+ expect(columns.find((c) => c.name === 'n_fixed_char')?.type).toBe(
+ 'nchar'
+ );
+ expect(columns.find((c) => c.name === 'large_text')?.type).toBe('clob');
+ expect(columns.find((c) => c.name === 'n_large_text')?.type).toBe(
+ 'nclob'
+ );
+ expect(columns.find((c) => c.name === 'legacy_text')?.type).toBe(
+ 'long'
+ );
+ });
+
+ it('should parse numeric data types', async () => {
+ const sql = `
+ CREATE TABLE numeric_types (
+ id NUMBER(10) PRIMARY KEY,
+ plain_number NUMBER,
+ precise_number NUMBER(18, 2),
+ int_val INTEGER,
+ small_int SMALLINT,
+ float_val FLOAT,
+ real_val REAL,
+ bin_float BINARY_FLOAT,
+ bin_double BINARY_DOUBLE
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'plain_number')?.type).toBe(
+ 'number'
+ );
+ expect(columns.find((c) => c.name === 'precise_number')?.type).toBe(
+ 'number'
+ );
+ expect(columns.find((c) => c.name === 'int_val')?.type).toBe('integer');
+ expect(columns.find((c) => c.name === 'small_int')?.type).toBe(
+ 'smallint'
+ );
+ expect(columns.find((c) => c.name === 'float_val')?.type).toBe('float');
+ expect(columns.find((c) => c.name === 'real_val')?.type).toBe('real');
+ expect(columns.find((c) => c.name === 'bin_float')?.type).toBe(
+ 'binary_float'
+ );
+ expect(columns.find((c) => c.name === 'bin_double')?.type).toBe(
+ 'binary_double'
+ );
+ });
+
+ it('should parse date and time data types', async () => {
+ const sql = `
+ CREATE TABLE datetime_types (
+ id NUMBER(10) PRIMARY KEY,
+ simple_date DATE,
+ time_stamp TIMESTAMP,
+ time_stamp_tz TIMESTAMP,
+ created_at TIMESTAMP NOT NULL
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'simple_date')?.type).toBe(
+ 'date'
+ );
+ expect(columns.find((c) => c.name === 'time_stamp')?.type).toBe(
+ 'timestamp'
+ );
+ expect(columns.find((c) => c.name === 'created_at')?.type).toBe(
+ 'timestamp'
+ );
+ });
+
+ it('should parse binary data types', async () => {
+ const sql = `
+ CREATE TABLE binary_types (
+ id NUMBER(10) PRIMARY KEY,
+ binary_data BLOB,
+ raw_data RAW(100),
+ file_ref BFILE
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'binary_data')?.type).toBe(
+ 'blob'
+ );
+ expect(columns.find((c) => c.name === 'raw_data')?.type).toBe('raw');
+ expect(columns.find((c) => c.name === 'file_ref')?.type).toBe('bfile');
+ });
+
+ it('should parse special Oracle data types', async () => {
+ const sql = `
+ CREATE TABLE special_types (
+ id NUMBER(10) PRIMARY KEY,
+ row_identifier ROWID,
+ xml_content XMLTYPE,
+ json_content JSON
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ expect(columns.find((c) => c.name === 'row_identifier')?.type).toBe(
+ 'rowid'
+ );
+ expect(columns.find((c) => c.name === 'xml_content')?.type).toBe(
+ 'xmltype'
+ );
+ expect(columns.find((c) => c.name === 'json_content')?.type).toBe(
+ 'json'
+ );
+ });
+
+ it('should preserve type arguments for NUMBER types', async () => {
+ const sql = `
+ CREATE TABLE number_precision (
+ id NUMBER(10) PRIMARY KEY,
+ amount NUMBER(18, 2) NOT NULL,
+ percentage NUMBER(5, 4) NOT NULL,
+ quantity NUMBER(10) NOT NULL
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ const amountCol = columns.find((c) => c.name === 'amount');
+ expect(amountCol?.typeArgs).toBeDefined();
+ if (
+ typeof amountCol?.typeArgs === 'object' &&
+ !Array.isArray(amountCol.typeArgs)
+ ) {
+ expect(amountCol.typeArgs.precision).toBe(18);
+ expect(amountCol.typeArgs.scale).toBe(2);
+ }
+
+ const percentCol = columns.find((c) => c.name === 'percentage');
+ expect(percentCol?.typeArgs).toBeDefined();
+ if (
+ typeof percentCol?.typeArgs === 'object' &&
+ !Array.isArray(percentCol.typeArgs)
+ ) {
+ expect(percentCol.typeArgs.precision).toBe(5);
+ expect(percentCol.typeArgs.scale).toBe(4);
+ }
+ });
+
+ it('should preserve type arguments for VARCHAR2 types', async () => {
+ const sql = `
+ CREATE TABLE varchar_lengths (
+ id NUMBER(10) PRIMARY KEY,
+ short_text VARCHAR2(50) NOT NULL,
+ medium_text VARCHAR2(255) NOT NULL,
+ long_text VARCHAR2(4000)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(1);
+ const columns = result.tables[0].columns;
+
+ const shortCol = columns.find((c) => c.name === 'short_text');
+ expect(shortCol?.typeArgs).toBeDefined();
+ if (
+ typeof shortCol?.typeArgs === 'object' &&
+ !Array.isArray(shortCol.typeArgs)
+ ) {
+ expect(shortCol.typeArgs.length).toBe(50);
+ }
+
+ const longCol = columns.find((c) => c.name === 'long_text');
+ expect(longCol?.typeArgs).toBeDefined();
+ if (
+ typeof longCol?.typeArgs === 'object' &&
+ !Array.isArray(longCol.typeArgs)
+ ) {
+ expect(longCol.typeArgs.length).toBe(4000);
+ }
+ });
+});
diff --git a/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-examples.test.ts b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-examples.test.ts
new file mode 100644
index 00000000..08590e9f
--- /dev/null
+++ b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-examples.test.ts
@@ -0,0 +1,324 @@
+import { describe, it, expect } from 'vitest';
+import { fromOracle } from '../oracle';
+
+describe('Oracle Real-World Examples Tests', () => {
+ it('should parse a typical HR schema', async () => {
+ const sql = `
+ -- Regions table
+ CREATE TABLE hr.regions (
+ region_id NUMBER(10) PRIMARY KEY,
+ region_name VARCHAR2(25)
+ );
+
+ -- Countries table
+ CREATE TABLE hr.countries (
+ country_id CHAR(2) PRIMARY KEY,
+ country_name VARCHAR2(40),
+ region_id NUMBER(10),
+ CONSTRAINT fk_country_region FOREIGN KEY (region_id) REFERENCES hr.regions(region_id)
+ );
+
+ -- Locations table
+ CREATE TABLE hr.locations (
+ location_id NUMBER(10) PRIMARY KEY,
+ street_address VARCHAR2(40),
+ postal_code VARCHAR2(12),
+ city VARCHAR2(30) NOT NULL,
+ state_province VARCHAR2(25),
+ country_id CHAR(2),
+ CONSTRAINT fk_loc_country FOREIGN KEY (country_id) REFERENCES hr.countries(country_id)
+ );
+
+ -- Departments table
+ CREATE TABLE hr.departments (
+ department_id NUMBER(10) PRIMARY KEY,
+ department_name VARCHAR2(30) NOT NULL,
+ manager_id NUMBER(10),
+ location_id NUMBER(10),
+ CONSTRAINT fk_dept_loc FOREIGN KEY (location_id) REFERENCES hr.locations(location_id)
+ );
+
+ -- Jobs table
+ CREATE TABLE hr.jobs (
+ job_id VARCHAR2(10) PRIMARY KEY,
+ job_title VARCHAR2(35) NOT NULL,
+ min_salary NUMBER(10),
+ max_salary NUMBER(10)
+ );
+
+ -- Employees table
+ CREATE TABLE hr.employees (
+ employee_id NUMBER(10) PRIMARY KEY,
+ first_name VARCHAR2(20),
+ last_name VARCHAR2(25) NOT NULL,
+ email VARCHAR2(25) NOT NULL,
+ phone_number VARCHAR2(20),
+ hire_date DATE NOT NULL,
+ job_id VARCHAR2(10) NOT NULL,
+ salary NUMBER(10, 2),
+ commission_pct NUMBER(2, 2),
+ manager_id NUMBER(10),
+ department_id NUMBER(10),
+ CONSTRAINT fk_emp_job FOREIGN KEY (job_id) REFERENCES hr.jobs(job_id),
+ CONSTRAINT fk_emp_dept FOREIGN KEY (department_id) REFERENCES hr.departments(department_id),
+ CONSTRAINT fk_emp_mgr FOREIGN KEY (manager_id) REFERENCES hr.employees(employee_id)
+ );
+
+ -- Job history table
+ CREATE TABLE hr.job_history (
+ employee_id NUMBER(10) NOT NULL,
+ start_date DATE NOT NULL,
+ end_date DATE NOT NULL,
+ job_id VARCHAR2(10) NOT NULL,
+ department_id NUMBER(10),
+ CONSTRAINT pk_job_history PRIMARY KEY (employee_id, start_date),
+ CONSTRAINT fk_jh_emp FOREIGN KEY (employee_id) REFERENCES hr.employees(employee_id),
+ CONSTRAINT fk_jh_job FOREIGN KEY (job_id) REFERENCES hr.jobs(job_id),
+ CONSTRAINT fk_jh_dept FOREIGN KEY (department_id) REFERENCES hr.departments(department_id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(7);
+ expect(result.relationships.length).toBeGreaterThanOrEqual(8);
+
+ // Verify all tables exist
+ expect(result.tables.find((t) => t.name === 'regions')).toBeDefined();
+ expect(result.tables.find((t) => t.name === 'countries')).toBeDefined();
+ expect(result.tables.find((t) => t.name === 'locations')).toBeDefined();
+ expect(
+ result.tables.find((t) => t.name === 'departments')
+ ).toBeDefined();
+ expect(result.tables.find((t) => t.name === 'jobs')).toBeDefined();
+ expect(result.tables.find((t) => t.name === 'employees')).toBeDefined();
+ expect(
+ result.tables.find((t) => t.name === 'job_history')
+ ).toBeDefined();
+
+ // Verify schema is set
+ result.tables.forEach((t) => {
+ expect(t.schema).toBe('hr');
+ });
+
+ // Verify self-referencing relationship exists
+ const selfRefRel = result.relationships.find(
+ (r) =>
+ r.sourceTable === 'employees' && r.targetTable === 'employees'
+ );
+ expect(selfRefRel).toBeDefined();
+ });
+
+ it('should parse an e-commerce schema', async () => {
+ const sql = `
+ -- Customers
+ CREATE TABLE ecom.customers (
+ customer_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ email VARCHAR2(255) NOT NULL UNIQUE,
+ password_hash VARCHAR2(255) NOT NULL,
+ first_name VARCHAR2(100) NOT NULL,
+ last_name VARCHAR2(100) NOT NULL,
+ phone VARCHAR2(20),
+ created_at TIMESTAMP DEFAULT SYSTIMESTAMP,
+ updated_at TIMESTAMP DEFAULT SYSTIMESTAMP
+ );
+
+ -- Addresses
+ CREATE TABLE ecom.addresses (
+ address_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ customer_id NUMBER(10) NOT NULL,
+ address_type VARCHAR2(20) NOT NULL,
+ street_address VARCHAR2(255) NOT NULL,
+ city VARCHAR2(100) NOT NULL,
+ state VARCHAR2(100),
+ postal_code VARCHAR2(20),
+ country VARCHAR2(100) NOT NULL,
+ is_default NUMBER(1) DEFAULT 0,
+ CONSTRAINT fk_addr_customer FOREIGN KEY (customer_id) REFERENCES ecom.customers(customer_id)
+ );
+
+ -- Categories with self-reference for hierarchy
+ CREATE TABLE ecom.categories (
+ category_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ parent_category_id NUMBER(10),
+ name VARCHAR2(100) NOT NULL,
+ description CLOB,
+ image_url VARCHAR2(500),
+ is_active NUMBER(1) DEFAULT 1,
+ CONSTRAINT fk_cat_parent FOREIGN KEY (parent_category_id) REFERENCES ecom.categories(category_id)
+ );
+
+ -- Products
+ CREATE TABLE ecom.products (
+ product_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ category_id NUMBER(10) NOT NULL,
+ sku VARCHAR2(50) NOT NULL UNIQUE,
+ name VARCHAR2(255) NOT NULL,
+ description CLOB,
+ price NUMBER(10, 2) NOT NULL,
+ cost_price NUMBER(10, 2),
+ stock_quantity NUMBER(10) DEFAULT 0,
+ weight NUMBER(10, 3),
+ is_active NUMBER(1) DEFAULT 1,
+ created_at TIMESTAMP DEFAULT SYSTIMESTAMP,
+ CONSTRAINT fk_prod_category FOREIGN KEY (category_id) REFERENCES ecom.categories(category_id)
+ );
+
+ -- Orders
+ CREATE TABLE ecom.orders (
+ order_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ customer_id NUMBER(10) NOT NULL,
+ shipping_address_id NUMBER(10) NOT NULL,
+ billing_address_id NUMBER(10) NOT NULL,
+ order_status VARCHAR2(20) DEFAULT 'pending',
+ order_date TIMESTAMP DEFAULT SYSTIMESTAMP,
+ shipped_date TIMESTAMP,
+ total_amount NUMBER(12, 2) NOT NULL,
+ notes CLOB,
+ CONSTRAINT fk_order_customer FOREIGN KEY (customer_id) REFERENCES ecom.customers(customer_id),
+ CONSTRAINT fk_order_ship_addr FOREIGN KEY (shipping_address_id) REFERENCES ecom.addresses(address_id),
+ CONSTRAINT fk_order_bill_addr FOREIGN KEY (billing_address_id) REFERENCES ecom.addresses(address_id)
+ );
+
+ -- Order items
+ CREATE TABLE ecom.order_items (
+ order_item_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ order_id NUMBER(10) NOT NULL,
+ product_id NUMBER(10) NOT NULL,
+ quantity NUMBER(10) NOT NULL,
+ unit_price NUMBER(10, 2) NOT NULL,
+ discount_amount NUMBER(10, 2) DEFAULT 0,
+ CONSTRAINT fk_oi_order FOREIGN KEY (order_id) REFERENCES ecom.orders(order_id),
+ CONSTRAINT fk_oi_product FOREIGN KEY (product_id) REFERENCES ecom.products(product_id)
+ );
+
+ -- Reviews
+ CREATE TABLE ecom.reviews (
+ review_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ product_id NUMBER(10) NOT NULL,
+ customer_id NUMBER(10) NOT NULL,
+ rating NUMBER(1) NOT NULL,
+ title VARCHAR2(200),
+ content CLOB,
+ created_at TIMESTAMP DEFAULT SYSTIMESTAMP,
+ is_verified NUMBER(1) DEFAULT 0,
+ CONSTRAINT fk_review_product FOREIGN KEY (product_id) REFERENCES ecom.products(product_id),
+ CONSTRAINT fk_review_customer FOREIGN KEY (customer_id) REFERENCES ecom.customers(customer_id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(7);
+ expect(result.relationships.length).toBeGreaterThanOrEqual(9);
+
+ // Verify customers table structure
+ const customersTable = result.tables.find(
+ (t) => t.name === 'customers'
+ );
+ expect(customersTable).toBeDefined();
+ expect(customersTable!.columns.length).toBe(8);
+
+ // Verify identity columns
+ const customerIdCol = customersTable!.columns.find(
+ (c) => c.name === 'customer_id'
+ );
+ expect(customerIdCol?.increment).toBe(true);
+
+ // Verify category self-reference
+ const catSelfRef = result.relationships.find(
+ (r) =>
+ r.sourceTable === 'categories' && r.targetTable === 'categories'
+ );
+ expect(catSelfRef).toBeDefined();
+
+ // Verify order has multiple address references
+ const orderAddressRels = result.relationships.filter(
+ (r) => r.sourceTable === 'orders' && r.targetTable === 'addresses'
+ );
+ expect(orderAddressRels.length).toBe(2);
+ });
+
+ it('should parse a financial services schema with complex relationships', async () => {
+ const sql = `
+ -- Account types
+ CREATE TABLE fin.account_types (
+ type_id NUMBER(10) PRIMARY KEY,
+ type_name VARCHAR2(50) NOT NULL,
+ description VARCHAR2(500),
+ min_balance NUMBER(12, 2) DEFAULT 0,
+ interest_rate NUMBER(5, 4) DEFAULT 0
+ );
+
+ -- Accounts
+ CREATE TABLE fin.accounts (
+ account_id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ account_number VARCHAR2(20) NOT NULL UNIQUE,
+ account_type_id NUMBER(10) NOT NULL,
+ customer_id NUMBER(10) NOT NULL,
+ balance NUMBER(15, 2) DEFAULT 0,
+ status VARCHAR2(20) DEFAULT 'active',
+ opened_date DATE DEFAULT SYSDATE,
+ closed_date DATE,
+ CONSTRAINT fk_acc_type FOREIGN KEY (account_type_id) REFERENCES fin.account_types(type_id)
+ );
+
+ -- Transactions
+ CREATE TABLE fin.transactions (
+ transaction_id NUMBER(15) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ from_account_id NUMBER(10),
+ to_account_id NUMBER(10),
+ transaction_type VARCHAR2(20) NOT NULL,
+ amount NUMBER(15, 2) NOT NULL,
+ currency CHAR(3) DEFAULT 'USD',
+ transaction_date TIMESTAMP DEFAULT SYSTIMESTAMP,
+ description VARCHAR2(500),
+ reference_number VARCHAR2(50),
+ status VARCHAR2(20) DEFAULT 'completed',
+ CONSTRAINT fk_trans_from FOREIGN KEY (from_account_id) REFERENCES fin.accounts(account_id),
+ CONSTRAINT fk_trans_to FOREIGN KEY (to_account_id) REFERENCES fin.accounts(account_id)
+ );
+
+ -- Audit log
+ CREATE TABLE fin.audit_log (
+ log_id NUMBER(15) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ table_name VARCHAR2(100) NOT NULL,
+ record_id NUMBER(15) NOT NULL,
+ action VARCHAR2(20) NOT NULL,
+ old_values CLOB,
+ new_values CLOB,
+ changed_by VARCHAR2(100) NOT NULL,
+ changed_at TIMESTAMP DEFAULT SYSTIMESTAMP
+ );
+
+ -- Indexes
+ CREATE INDEX fin.idx_acc_customer ON fin.accounts(customer_id);
+ CREATE INDEX fin.idx_acc_type ON fin.accounts(account_type_id);
+ CREATE INDEX fin.idx_trans_from ON fin.transactions(from_account_id);
+ CREATE INDEX fin.idx_trans_to ON fin.transactions(to_account_id);
+ CREATE INDEX fin.idx_trans_date ON fin.transactions(transaction_date);
+ CREATE INDEX fin.idx_audit_table ON fin.audit_log(table_name, record_id);
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(4);
+ expect(result.relationships).toHaveLength(3);
+
+ // Verify transaction has two account references
+ const transAccountRels = result.relationships.filter(
+ (r) =>
+ r.sourceTable === 'transactions' && r.targetTable === 'accounts'
+ );
+ expect(transAccountRels.length).toBe(2);
+
+ // Verify indexes were parsed
+ const accountsTable = result.tables.find((t) => t.name === 'accounts');
+ expect(accountsTable?.indexes.length).toBeGreaterThanOrEqual(1);
+
+ const transactionsTable = result.tables.find(
+ (t) => t.name === 'transactions'
+ );
+ expect(transactionsTable?.indexes.length).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-full-flow.test.ts b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-full-flow.test.ts
new file mode 100644
index 00000000..9079e443
--- /dev/null
+++ b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-full-flow.test.ts
@@ -0,0 +1,278 @@
+import { describe, it, expect } from 'vitest';
+import { sqlImportToDiagram, detectDatabaseType } from '../../../index';
+import { DatabaseType } from '@/lib/domain/database-type';
+
+describe('Oracle Full Flow Tests', () => {
+ it('should detect Oracle database type from SQL content', () => {
+ const sql = `
+ CREATE TABLE employees (
+ id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ name VARCHAR2(255) NOT NULL,
+ hire_date DATE DEFAULT SYSDATE
+ );
+ `;
+
+ const detectedType = detectDatabaseType(sql);
+ expect(detectedType).toBe(DatabaseType.ORACLE);
+ });
+
+ it('should detect Oracle from VARCHAR2 type', () => {
+ const sql = `
+ CREATE TABLE test (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100)
+ );
+ `;
+
+ const detectedType = detectDatabaseType(sql);
+ expect(detectedType).toBe(DatabaseType.ORACLE);
+ });
+
+ it('should detect Oracle from SYSDATE usage', () => {
+ const sql = `
+ CREATE TABLE audit_log (
+ id INTEGER PRIMARY KEY,
+ created_at DATE DEFAULT SYSDATE
+ );
+ `;
+
+ const detectedType = detectDatabaseType(sql);
+ expect(detectedType).toBe(DatabaseType.ORACLE);
+ });
+
+ it('should detect Oracle from GENERATED AS IDENTITY', () => {
+ const sql = `
+ CREATE TABLE products (
+ id NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
+ name VARCHAR(100)
+ );
+ `;
+
+ const detectedType = detectDatabaseType(sql);
+ expect(detectedType).toBe(DatabaseType.ORACLE);
+ });
+
+ it('should import Oracle SQL to diagram with correct table structure', async () => {
+ const sql = `
+ CREATE TABLE departments (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL,
+ budget NUMBER(12, 2)
+ );
+
+ CREATE TABLE employees (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL,
+ department_id NUMBER(10),
+ hire_date DATE DEFAULT SYSDATE,
+ CONSTRAINT fk_emp_dept FOREIGN KEY (department_id) REFERENCES departments(id)
+ );
+ `;
+
+ const diagram = await sqlImportToDiagram({
+ sqlContent: sql,
+ sourceDatabaseType: DatabaseType.ORACLE,
+ targetDatabaseType: DatabaseType.ORACLE,
+ });
+
+ expect(diagram).toBeDefined();
+ expect(diagram.tables).toBeDefined();
+ expect(diagram.tables!).toHaveLength(2);
+ expect(diagram.relationships).toBeDefined();
+ expect(diagram.relationships!).toHaveLength(1);
+
+ // Check table names
+ const deptTable = diagram.tables!.find((t) => t.name === 'departments');
+ const empTable = diagram.tables!.find((t) => t.name === 'employees');
+
+ expect(deptTable).toBeDefined();
+ expect(empTable).toBeDefined();
+
+ // Check fields
+ expect(deptTable!.fields).toHaveLength(3);
+ expect(empTable!.fields).toHaveLength(4);
+
+ // Check relationship
+ expect(diagram.relationships![0].sourceTableId).toBe(deptTable!.id);
+ expect(diagram.relationships![0].targetTableId).toBe(empTable!.id);
+ });
+
+ it('should handle Oracle with auto-detection when source type is GENERIC', async () => {
+ const sql = `
+ CREATE TABLE products (
+ id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ name VARCHAR2(200) NOT NULL,
+ price NUMBER(10, 2) NOT NULL,
+ created_at TIMESTAMP DEFAULT SYSTIMESTAMP
+ );
+ `;
+
+ const diagram = await sqlImportToDiagram({
+ sqlContent: sql,
+ sourceDatabaseType: DatabaseType.GENERIC,
+ targetDatabaseType: DatabaseType.GENERIC,
+ });
+
+ expect(diagram).toBeDefined();
+ expect(diagram.tables).toBeDefined();
+ expect(diagram.tables!).toHaveLength(1);
+ expect(diagram.tables![0].name).toBe('products');
+ expect(diagram.tables![0].fields).toHaveLength(4);
+ });
+
+ it('should import complex Oracle schema with multiple tables and relationships', async () => {
+ const sql = `
+ -- Categories table
+ CREATE TABLE categories (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL,
+ description CLOB
+ );
+
+ -- Products table
+ CREATE TABLE products (
+ id NUMBER(10) PRIMARY KEY,
+ category_id NUMBER(10) NOT NULL,
+ name VARCHAR2(200) NOT NULL,
+ price NUMBER(10, 2) NOT NULL,
+ stock_quantity NUMBER(10) DEFAULT 0
+ );
+
+ -- Customers table
+ CREATE TABLE customers (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL,
+ email VARCHAR2(255) UNIQUE,
+ phone VARCHAR2(20)
+ );
+
+ -- Orders table
+ CREATE TABLE orders (
+ id NUMBER(10) PRIMARY KEY,
+ customer_id NUMBER(10) NOT NULL,
+ order_date DATE DEFAULT SYSDATE,
+ total_amount NUMBER(12, 2)
+ );
+
+ -- Order items table
+ CREATE TABLE order_items (
+ id NUMBER(10) PRIMARY KEY,
+ order_id NUMBER(10) NOT NULL,
+ product_id NUMBER(10) NOT NULL,
+ quantity NUMBER(10) NOT NULL,
+ unit_price NUMBER(10, 2) NOT NULL
+ );
+
+ -- Foreign key constraints
+ ALTER TABLE products ADD CONSTRAINT fk_prod_cat FOREIGN KEY (category_id) REFERENCES categories(id);
+ ALTER TABLE orders ADD CONSTRAINT fk_ord_cust FOREIGN KEY (customer_id) REFERENCES customers(id);
+ ALTER TABLE order_items ADD CONSTRAINT fk_oi_order FOREIGN KEY (order_id) REFERENCES orders(id);
+ ALTER TABLE order_items ADD CONSTRAINT fk_oi_product FOREIGN KEY (product_id) REFERENCES products(id);
+
+ -- Indexes
+ CREATE INDEX idx_products_category ON products(category_id);
+ CREATE INDEX idx_orders_customer ON orders(customer_id);
+ CREATE INDEX idx_order_items_order ON order_items(order_id);
+ CREATE INDEX idx_order_items_product ON order_items(product_id);
+ `;
+
+ const diagram = await sqlImportToDiagram({
+ sqlContent: sql,
+ sourceDatabaseType: DatabaseType.ORACLE,
+ targetDatabaseType: DatabaseType.ORACLE,
+ });
+
+ expect(diagram).toBeDefined();
+ expect(diagram.tables).toBeDefined();
+ expect(diagram.tables!).toHaveLength(5);
+ expect(diagram.relationships).toBeDefined();
+ expect(diagram.relationships!).toHaveLength(4);
+
+ // Verify all tables exist
+ expect(
+ diagram.tables!.find((t) => t.name === 'categories')
+ ).toBeDefined();
+ expect(
+ diagram.tables!.find((t) => t.name === 'products')
+ ).toBeDefined();
+ expect(
+ diagram.tables!.find((t) => t.name === 'customers')
+ ).toBeDefined();
+ expect(diagram.tables!.find((t) => t.name === 'orders')).toBeDefined();
+ expect(
+ diagram.tables!.find((t) => t.name === 'order_items')
+ ).toBeDefined();
+
+ // Verify indexes were parsed
+ const productsTable = diagram.tables!.find(
+ (t) => t.name === 'products'
+ );
+ expect(productsTable?.indexes?.length).toBeGreaterThanOrEqual(1);
+ });
+
+ it('should handle Oracle-specific syntax without errors', async () => {
+ const sql = `
+ SET DEFINE OFF;
+ SPOOL output.log
+
+ CREATE TABLE test_table (
+ id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT SYSTIMESTAMP,
+ updated_at DATE DEFAULT SYSDATE
+ )
+ TABLESPACE users
+ STORAGE (INITIAL 64K NEXT 64K);
+
+ CREATE INDEX idx_test_name ON test_table(name)
+ TABLESPACE users_idx;
+
+ SPOOL OFF;
+ `;
+
+ const diagram = await sqlImportToDiagram({
+ sqlContent: sql,
+ sourceDatabaseType: DatabaseType.ORACLE,
+ targetDatabaseType: DatabaseType.ORACLE,
+ });
+
+ expect(diagram).toBeDefined();
+ expect(diagram.tables).toBeDefined();
+ expect(diagram.tables!).toHaveLength(1);
+ expect(diagram.tables![0].name).toBe('test_table');
+ });
+
+ it('should preserve field types correctly when target is Oracle', async () => {
+ const sql = `
+ CREATE TABLE data_preservation_test (
+ id NUMBER(10) PRIMARY KEY,
+ amount NUMBER(18, 4) NOT NULL,
+ description VARCHAR2(500),
+ created_at TIMESTAMP,
+ is_active NUMBER(1),
+ xml_data XMLTYPE,
+ binary_data BLOB
+ );
+ `;
+
+ const diagram = await sqlImportToDiagram({
+ sqlContent: sql,
+ sourceDatabaseType: DatabaseType.ORACLE,
+ targetDatabaseType: DatabaseType.ORACLE,
+ });
+
+ expect(diagram).toBeDefined();
+ expect(diagram.tables).toBeDefined();
+ const fields = diagram.tables![0].fields;
+
+ // Verify types are preserved or mapped appropriately
+ expect(fields.find((f) => f.name === 'id')?.type.id).toBeDefined();
+ expect(fields.find((f) => f.name === 'amount')?.type.id).toBeDefined();
+ expect(
+ fields.find((f) => f.name === 'description')?.type.id
+ ).toBeDefined();
+ expect(
+ fields.find((f) => f.name === 'created_at')?.type.id
+ ).toBeDefined();
+ });
+});
diff --git a/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-relationships.test.ts b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-relationships.test.ts
new file mode 100644
index 00000000..ee8edff2
--- /dev/null
+++ b/src/lib/data/sql-import/dialect-importers/oracle/__tests__/oracle-relationships.test.ts
@@ -0,0 +1,323 @@
+import { describe, it, expect } from 'vitest';
+import { fromOracle } from '../oracle';
+
+describe('Oracle Foreign Key Relationship Tests', () => {
+ it('should properly link foreign key relationships with correct table IDs', async () => {
+ const sql = `
+ CREATE TABLE hr.departments (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL
+ );
+
+ CREATE TABLE hr.employees (
+ id NUMBER(10) PRIMARY KEY,
+ department_id NUMBER(10) NOT NULL,
+ name VARCHAR2(100) NOT NULL
+ );
+
+ ALTER TABLE hr.employees ADD CONSTRAINT fk_emp_dept
+ FOREIGN KEY (department_id) REFERENCES hr.departments(id);
+ `;
+
+ const result = await fromOracle(sql);
+
+ // Check tables are parsed
+ expect(result.tables).toHaveLength(2);
+ const deptTable = result.tables.find((t) => t.name === 'departments');
+ const empTable = result.tables.find((t) => t.name === 'employees');
+ expect(deptTable).toBeDefined();
+ expect(empTable).toBeDefined();
+
+ // Check relationship is parsed
+ expect(result.relationships).toHaveLength(1);
+ const rel = result.relationships[0];
+
+ // Verify the relationship has proper table IDs
+ expect(rel.sourceTableId).toBe(empTable!.id);
+ expect(rel.targetTableId).toBe(deptTable!.id);
+
+ // Verify other relationship properties
+ expect(rel.sourceTable).toBe('employees');
+ expect(rel.targetTable).toBe('departments');
+ expect(rel.sourceColumn).toBe('department_id');
+ expect(rel.targetColumn).toBe('id');
+ expect(rel.sourceSchema).toBe('hr');
+ expect(rel.targetSchema).toBe('hr');
+ });
+
+ it('should handle cross-schema foreign key relationships', async () => {
+ const sql = `
+ CREATE TABLE finance.accounts (
+ id NUMBER(10) PRIMARY KEY,
+ account_number VARCHAR2(50) NOT NULL
+ );
+
+ CREATE TABLE sales.transactions (
+ id NUMBER(10) PRIMARY KEY,
+ account_id NUMBER(10) NOT NULL
+ );
+
+ ALTER TABLE sales.transactions ADD CONSTRAINT fk_trans_account
+ FOREIGN KEY (account_id) REFERENCES finance.accounts(id);
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(2);
+ expect(result.relationships).toHaveLength(1);
+
+ const rel = result.relationships[0];
+ const accountsTable = result.tables.find(
+ (t) => t.name === 'accounts' && t.schema === 'finance'
+ );
+ const transactionsTable = result.tables.find(
+ (t) => t.name === 'transactions' && t.schema === 'sales'
+ );
+
+ // Verify cross-schema relationship IDs are properly linked
+ expect(rel.sourceTableId).toBe(transactionsTable!.id);
+ expect(rel.targetTableId).toBe(accountsTable!.id);
+ });
+
+ it('should parse complex foreign keys from enterprise database with proper table IDs', async () => {
+ const sql = `
+ -- Inventory schema
+ CREATE TABLE inventory.products (
+ id NUMBER(10) NOT NULL,
+ name VARCHAR2(255) NOT NULL,
+ category VARCHAR2(100) NOT NULL,
+ price NUMBER(10, 2) NOT NULL,
+ description CLOB,
+ CONSTRAINT pk_products PRIMARY KEY (id)
+ );
+
+ -- Purchase orders
+ CREATE TABLE inventory.purchase_orders (
+ id NUMBER(10) NOT NULL,
+ product_id NUMBER(10) NOT NULL,
+ supplier_id NUMBER(10) NOT NULL,
+ order_date DATE NOT NULL,
+ quantity NUMBER(10) NOT NULL,
+ total_amount NUMBER(12, 2) NOT NULL,
+ CONSTRAINT pk_purchase_orders PRIMARY KEY (id)
+ );
+
+ -- Suppliers schema
+ CREATE TABLE suppliers.suppliers (
+ id NUMBER(10) NOT NULL,
+ name VARCHAR2(255) NOT NULL,
+ contact_name VARCHAR2(100),
+ email VARCHAR2(255),
+ CONSTRAINT pk_suppliers PRIMARY KEY (id)
+ );
+
+ -- Employee purchases
+ CREATE TABLE hr.employee_purchases (
+ id NUMBER(10) NOT NULL,
+ employee_id NUMBER(10) NOT NULL,
+ manager_id NUMBER(10) NOT NULL,
+ purchase_date DATE NOT NULL,
+ CONSTRAINT pk_employee_purchases PRIMARY KEY (id)
+ );
+
+ -- HR employees
+ CREATE TABLE hr.employees (
+ id NUMBER(10) NOT NULL,
+ name VARCHAR2(255) NOT NULL,
+ title VARCHAR2(100),
+ hire_date DATE NOT NULL,
+ CONSTRAINT pk_employees PRIMARY KEY (id)
+ );
+
+ -- Add foreign key constraints
+ ALTER TABLE inventory.purchase_orders
+ ADD CONSTRAINT fk_po_product
+ FOREIGN KEY (product_id)
+ REFERENCES inventory.products(id);
+
+ ALTER TABLE inventory.purchase_orders
+ ADD CONSTRAINT fk_po_supplier
+ FOREIGN KEY (supplier_id)
+ REFERENCES suppliers.suppliers(id);
+
+ ALTER TABLE hr.employee_purchases
+ ADD CONSTRAINT fk_ep_employee
+ FOREIGN KEY (employee_id)
+ REFERENCES hr.employees(id);
+
+ ALTER TABLE hr.employee_purchases
+ ADD CONSTRAINT fk_ep_manager
+ FOREIGN KEY (manager_id)
+ REFERENCES hr.employees(id);
+ `;
+
+ const result = await fromOracle(sql);
+
+ // Check if we have the expected number of tables and relationships
+ expect(result.tables).toHaveLength(5);
+ expect(result.relationships).toHaveLength(4);
+
+ // Check a specific relationship we know should exist
+ const poProductRel = result.relationships.find(
+ (r) =>
+ r.sourceTable === 'purchase_orders' &&
+ r.targetTable === 'products' &&
+ r.sourceColumn === 'product_id'
+ );
+
+ expect(poProductRel).toBeDefined();
+
+ // Find the corresponding tables
+ const productsTable = result.tables.find(
+ (t) => t.name === 'products' && t.schema === 'inventory'
+ );
+ const poTable = result.tables.find(
+ (t) => t.name === 'purchase_orders' && t.schema === 'inventory'
+ );
+
+ // Verify the IDs are properly linked
+ expect(poProductRel!.sourceTableId).toBeTruthy();
+ expect(poProductRel!.targetTableId).toBeTruthy();
+ expect(poProductRel!.sourceTableId).toBe(poTable!.id);
+ expect(poProductRel!.targetTableId).toBe(productsTable!.id);
+
+ // Check the employee self-referencing relationships
+ const epEmployeeRel = result.relationships.find(
+ (r) =>
+ r.sourceTable === 'employee_purchases' &&
+ r.targetTable === 'employees' &&
+ r.sourceColumn === 'employee_id'
+ );
+
+ const epManagerRel = result.relationships.find(
+ (r) =>
+ r.sourceTable === 'employee_purchases' &&
+ r.targetTable === 'employees' &&
+ r.sourceColumn === 'manager_id'
+ );
+
+ expect(epEmployeeRel).toBeDefined();
+ expect(epManagerRel).toBeDefined();
+
+ // Check that all relationships have valid table IDs
+ const relationshipsWithMissingIds = result.relationships.filter(
+ (r) =>
+ !r.sourceTableId ||
+ !r.targetTableId ||
+ r.sourceTableId === '' ||
+ r.targetTableId === ''
+ );
+
+ expect(relationshipsWithMissingIds).toHaveLength(0);
+ });
+
+ it('should handle inline foreign key references', async () => {
+ const sql = `
+ CREATE TABLE categories (
+ id NUMBER(10) PRIMARY KEY,
+ name VARCHAR2(100) NOT NULL
+ );
+
+ CREATE TABLE products (
+ id NUMBER(10) PRIMARY KEY,
+ category_id NUMBER(10) REFERENCES categories(id),
+ name VARCHAR2(100) NOT NULL
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(2);
+ expect(result.relationships).toHaveLength(1);
+
+ const rel = result.relationships[0];
+ expect(rel.sourceTable).toBe('products');
+ expect(rel.targetTable).toBe('categories');
+ expect(rel.sourceColumn).toBe('category_id');
+ expect(rel.targetColumn).toBe('id');
+ });
+
+ it('should handle multiple foreign keys in a single table', async () => {
+ const sql = `
+ CREATE TABLE users (id NUMBER(10) PRIMARY KEY, name VARCHAR2(100));
+ CREATE TABLE products (id NUMBER(10) PRIMARY KEY, name VARCHAR2(100));
+
+ CREATE TABLE reviews (
+ id NUMBER(10) PRIMARY KEY,
+ user_id NUMBER(10) NOT NULL,
+ product_id NUMBER(10) NOT NULL,
+ rating NUMBER(1) NOT NULL,
+ CONSTRAINT fk_review_user FOREIGN KEY (user_id) REFERENCES users(id),
+ CONSTRAINT fk_review_product FOREIGN KEY (product_id) REFERENCES products(id)
+ );
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(3);
+ expect(result.relationships).toHaveLength(2);
+
+ const userRel = result.relationships.find(
+ (r) => r.targetTable === 'users'
+ );
+ const productRel = result.relationships.find(
+ (r) => r.targetTable === 'products'
+ );
+
+ expect(userRel).toBeDefined();
+ expect(productRel).toBeDefined();
+ expect(userRel!.sourceTable).toBe('reviews');
+ expect(productRel!.sourceTable).toBe('reviews');
+ });
+
+ it('should handle ALTER TABLE with quoted identifiers', async () => {
+ const sql = `
+ CREATE TABLE "table_1" (
+ "id" number NOT NULL,
+ "field_2" number,
+ "field_3" number,
+ CONSTRAINT "pk_table_1_id" PRIMARY KEY ("id")
+ );
+
+ CREATE TABLE "table_2" (
+ "id" number NOT NULL,
+ "field_2" number,
+ "field_3" number,
+ CONSTRAINT "pk_table_2_id" PRIMARY KEY ("id")
+ );
+
+ ALTER TABLE "table_1" ADD CONSTRAINT "fk_table_1_id_table_2_field_3" FOREIGN KEY("id") REFERENCES "table_2"("field_3");
+ `;
+
+ const result = await fromOracle(sql);
+
+ expect(result.tables).toHaveLength(2);
+ const table1 = result.tables.find((t) => t.name === 'table_1');
+ const table2 = result.tables.find((t) => t.name === 'table_2');
+ expect(table1).toBeDefined();
+ expect(table2).toBeDefined();
+
+ // Check primary key columns for table_1
+ const table1IdCol = table1!.columns.find((c) => c.name === 'id');
+ expect(table1IdCol).toBeDefined();
+ expect(table1IdCol!.primaryKey).toBe(true);
+ expect(table1IdCol!.nullable).toBe(false);
+
+ // Check primary key columns for table_2
+ const table2IdCol = table2!.columns.find((c) => c.name === 'id');
+ expect(table2IdCol).toBeDefined();
+ expect(table2IdCol!.primaryKey).toBe(true);
+ expect(table2IdCol!.nullable).toBe(false);
+
+ // Check relationship
+ expect(result.relationships).toHaveLength(1);
+ const rel = result.relationships[0];
+
+ expect(rel.sourceTable).toBe('table_1');
+ expect(rel.targetTable).toBe('table_2');
+ expect(rel.sourceColumn).toBe('id');
+ expect(rel.targetColumn).toBe('field_3');
+ expect(rel.sourceTableId).toBe(table1!.id);
+ expect(rel.targetTableId).toBe(table2!.id);
+ });
+});
diff --git a/src/lib/data/sql-import/dialect-importers/oracle/oracle-common.ts b/src/lib/data/sql-import/dialect-importers/oracle/oracle-common.ts
new file mode 100644
index 00000000..94c1475f
--- /dev/null
+++ b/src/lib/data/sql-import/dialect-importers/oracle/oracle-common.ts
@@ -0,0 +1,186 @@
+import type { SQLASTNode } from '../../common';
+
+// Set up the SQL parser with Oracle/PL-SQL dialect
+export const parserOpts = {
+ database: 'plsql',
+};
+
+// Type definitions for Oracle AST
+export interface TableReference {
+ db?: string;
+ schema?: string;
+ table: string;
+ as?: string;
+}
+
+export interface ColumnReference {
+ type: 'column_ref';
+ table?: string;
+ column: string;
+}
+
+export interface CreateTableStatement extends SQLASTNode {
+ type: 'create';
+ keyword: 'table';
+ table: TableReference | TableReference[];
+ create_definitions: (ColumnDefinition | ConstraintDefinition)[];
+ table_options?: Record<string, unknown>[];
+ if_not_exists?: boolean;
+}
+
+export interface CreateIndexStatement extends SQLASTNode {
+ type: 'create';
+ keyword: 'index';
+ index: string;
+ table: TableReference | TableReference[];
+ columns: ColumnReference[];
+ constraint?: string;
+ index_using?: string;
+ index_options?: Record<string, unknown>[];
+}
+
+export interface AlterTableStatement extends SQLASTNode {
+ type: 'alter';
+ keyword: 'table';
+ table: TableReference | TableReference[];
+ expr: AlterTableExprItem[];
+}
+
+export interface AlterTableExprItem {
+ action: string;
+ column?: ColumnReference | string;
+ definition?: Record<string, unknown>;
+ resource?: string;
+ [key: string]: unknown;
+}
+
+export interface ColumnDefinition {
+ column: ColumnReference | string;
+ definition?: {
+ dataType: string;
+ length?: number | string;
+ width?: number | string;
+ scale?: number;
+ precision?: number;
+ parentheses?: boolean;
+ suffix?: string[];
+ constraint?: string;
+ [key: string]: unknown;
+ };
+ nullable?: { type: string };
+ primary_key?: string;
+ unique?: string;
+ default_val?: unknown;
+ auto_increment?: string;
+ comment?: string;
+ reference?: Record<string, unknown>;
+ resource: string;
+ [key: string]: unknown;
+}
+
+export interface ConstraintDefinition {
+ constraint_type: string;
+ constraint?: string;
+ definition?: Array<unknown> | Record<string, unknown>;
+ resource: string;
+ reference?: {
+ table: TableReference;
+ columns: ColumnReference[];
+ on_delete?: string;
+ on_update?: string;
+ };
+ [key: string]: unknown;
+}
+
+/**
+ * Extract column name from a column reference
+ */
+export function extractColumnName(columnRef: ColumnReference | string): string {
+ if (typeof columnRef === 'string') {
+ // Remove double quotes if present (Oracle quoted identifiers)
+ return columnRef.replace(/^"|"$/g, '');
+ }
+
+ if (columnRef.type === 'column_ref') {
+ return columnRef.column.replace(/^"|"$/g, '');
+ }
+
+ return '';
+}
+
+/**
+ * Extract type arguments such as length, precision, scale
+ */
+export function getTypeArgs(
+ definition?: ColumnDefinition['definition']
+): { length?: number; precision?: number; scale?: number } | undefined {
+ if (!definition) return undefined;
+
+ const result: { length?: number; precision?: number; scale?: number } = {};
+
+ // Check if length/width is present
+ if (definition.length !== undefined) {
+ result.length = Number(definition.length);
+ } else if (definition.width !== undefined) {
+ result.length = Number(definition.width);
+ }
+
+ // Check if precision is present
+ if (definition.precision !== undefined) {
+ result.precision = Number(definition.precision);
+ }
+
+ // Check if scale is present
+ if (definition.scale !== undefined) {
+ result.scale = Number(definition.scale);
+ }
+
+ return Object.keys(result).length > 0 ? result : undefined;
+}
+
+/**
+ * Find a table in the tables array with schema support
+ */
+export function findTableWithSchemaSupport(
+ tables: Array<{ id: string; name: string; schema?: string }>,
+ tableName: string,
+ schemaName?: string
+): { id: string; name: string; schema?: string } | undefined {
+ // Normalize names (Oracle is case-insensitive by default, uppercase)
+ const normalizedTableName = tableName.toUpperCase();
+ const normalizedSchemaName = schemaName?.toUpperCase();
+
+ // If schema is provided, search for exact match
+ if (normalizedSchemaName) {
+ return tables.find(
+ (t) =>
+ t.name.toUpperCase() === normalizedTableName &&
+ t.schema?.toUpperCase() === normalizedSchemaName
+ );
+ }
+
+ // No schema provided, first try to find exact match without schema
+ const exactMatch = tables.find(
+ (t) => t.name.toUpperCase() === normalizedTableName && !t.schema
+ );
+ if (exactMatch) return exactMatch;
+
+ // Finally, look for any table with matching name regardless of schema
+ return tables.find((t) => t.name.toUpperCase() === normalizedTableName);
+}
+
+/**
+ * Normalize Oracle identifier (remove quotes, handle case)
+ */
+export function normalizeOracleIdentifier(identifier: string): string {
+ if (!identifier) return '';
+
+ // If quoted with double quotes, preserve case and remove quotes
+ if (identifier.startsWith('"') && identifier.endsWith('"')) {
+ return identifier.slice(1, -1);
+ }
+
+ // Unquoted identifiers in Oracle are case-insensitive
+ // We preserve the original case for display purposes
+ return identifier;
+}
diff --git a/src/lib/data/sql-import/dialect-importers/oracle/oracle.ts b/src/lib/data/sql-import/dialect-importers/oracle/oracle.ts
new file mode 100644
index 00000000..0221f548
--- /dev/null
+++ b/src/lib/data/sql-import/dialect-importers/oracle/oracle.ts
@@ -0,0 +1,1079 @@
+import { generateId } from '@/lib/utils';
+import type {
+ SQLParserResult,
+ SQLTable,
+ SQLColumn,
+ SQLIndex,
+ SQLForeignKey,
+ SQLASTNode,
+} from '../../common';
+import type {
+ TableReference,
+ ColumnReference,
+ ConstraintDefinition,
+ CreateIndexStatement,
+ AlterTableStatement,
+} from './oracle-common';
+import {
+ parserOpts,
+ extractColumnName,
+ findTableWithSchemaSupport,
+ normalizeOracleIdentifier,
+} from './oracle-common';
+
+/**
+ * Preprocess Oracle SQL script to remove or modify parts that the parser can't handle
+ */
+function preprocessOracleScript(sqlContent: string): string {
+ // 1. Remove Oracle-specific SET commands
+ sqlContent = sqlContent.replace(
+ /SET\s+(DEFINE|ECHO|FEEDBACK|HEADING|LINESIZE|PAGESIZE|SERVEROUTPUT|TERMOUT|TIMING|VERIFY)\s+\w+\s*;?/gi,
+ ''
+ );
+
+ // 2. Remove WHENEVER commands
+ sqlContent = sqlContent.replace(/WHENEVER\s+\w+\s+[^;]*;?/gi, '');
+
+ // 3. Remove PROMPT commands
+ sqlContent = sqlContent.replace(/PROMPT\s+[^;]*;?/gi, '');
+
+ // 4. Remove SPOOL commands
+ sqlContent = sqlContent.replace(/SPOOL\s+[^;]*;?/gi, '');
+
+ // 5. Remove EXIT/QUIT commands
+ sqlContent = sqlContent.replace(/\b(EXIT|QUIT)\b\s*;?/gi, '');
+
+ // 6. Remove REM (remark) comments
+ sqlContent = sqlContent.replace(/^REM\s+.*$/gim, '');
+
+ // 7. Remove slash command (Oracle script delimiter)
+ sqlContent = sqlContent.replace(/^\s*\/\s*$/gm, '');
+
+ // 8. Remove PL/SQL blocks (CREATE OR REPLACE PROCEDURE/FUNCTION/PACKAGE/TRIGGER)
+ sqlContent = sqlContent.replace(
+ /CREATE\s+(?:OR\s+REPLACE\s+)?(?:PROCEDURE|FUNCTION|PACKAGE(?:\s+BODY)?|TRIGGER)\s+[\s\S]*?(?:END\s*;|END\s+\w+\s*;)/gi,
+ ''
+ );
+
+ // 9. Remove EXECUTE IMMEDIATE and dynamic SQL
+ sqlContent = sqlContent.replace(/EXECUTE\s+IMMEDIATE\s+[^;]+;/gi, '');
+
+ // 10. Handle Oracle GENERATED ALWAYS AS IDENTITY
+ sqlContent = sqlContent.replace(
+ /GENERATED\s+(?:ALWAYS|BY\s+DEFAULT)\s+AS\s+IDENTITY(?:\s*\([^)]*\))?/gi,
+ 'AUTO_INCREMENT'
+ );
+
+ // 11. Handle Oracle sequences with NEXTVAL for default values
+ sqlContent = sqlContent.replace(
+ /DEFAULT\s+(\w+)\.NEXTVAL/gi,
+ "DEFAULT 'sequence'"
+ );
+
+ // 12. Remove STORAGE clauses
+ sqlContent = sqlContent.replace(/STORAGE\s*\([^)]*\)/gi, '');
+
+ // 13. Remove TABLESPACE clauses
+ sqlContent = sqlContent.replace(/TABLESPACE\s+\w+/gi, '');
+
+ // 14. Remove PCTFREE, PCTUSED, INITRANS, MAXTRANS clauses
+ sqlContent = sqlContent.replace(
+ /\b(PCTFREE|PCTUSED|INITRANS|MAXTRANS)\s+\d+/gi,
+ ''
+ );
+
+ // 15. Remove LOGGING/NOLOGGING
+ sqlContent = sqlContent.replace(/\b(LOGGING|NOLOGGING)\b/gi, '');
+
+ // 16. Remove COMPRESS/NOCOMPRESS
+ sqlContent = sqlContent.replace(/\b(COMPRESS|NOCOMPRESS)(?:\s+\d+)?/gi, '');
+
+ // 17. Remove PARALLEL clause
+ sqlContent = sqlContent.replace(
+ /PARALLEL\s*(?:\(\s*DEGREE\s+\d+\s*\)|\d+)?/gi,
+ ''
+ );
+
+ // 18. Remove ENABLE/DISABLE keywords for constraints
+ sqlContent = sqlContent.replace(
+ /\b(ENABLE|DISABLE)(?:\s+VALIDATE|\s+NOVALIDATE)?\b/gi,
+ ''
+ );
+
+ // 19. Remove USING INDEX clause
+ sqlContent = sqlContent.replace(
+ /USING\s+INDEX\s*(?:\([^)]*\)|[\w."]+)?/gi,
+ ''
+ );
+
+ // 20. Handle CHECK constraints - simplify them
+ sqlContent = sqlContent.replace(
+ /CHECK\s*\([^)]+\)/gi,
+ '/* CHECK CONSTRAINT */'
+ );
+
+ // 21. Handle Oracle-specific default functions
+ sqlContent = sqlContent.replace(/DEFAULT\s+SYSDATE/gi, "DEFAULT 'sysdate'");
+ sqlContent = sqlContent.replace(
+ /DEFAULT\s+SYSTIMESTAMP/gi,
+ "DEFAULT 'systimestamp'"
+ );
+ sqlContent = sqlContent.replace(
+ /DEFAULT\s+SYS_GUID\(\)/gi,
+ "DEFAULT 'sys_guid'"
+ );
+ sqlContent = sqlContent.replace(/DEFAULT\s+USER/gi, "DEFAULT 'user'");
+ sqlContent = sqlContent.replace(
+ /DEFAULT\s+CURRENT_TIMESTAMP/gi,
+ "DEFAULT 'current_timestamp'"
+ );
+ sqlContent = sqlContent.replace(
+ /DEFAULT\s+CURRENT_DATE/gi,
+ "DEFAULT 'current_date'"
+ );
+
+ // 22. Remove LOB storage clauses
+ sqlContent = sqlContent.replace(
+ /LOB\s*\([^)]+\)\s*STORE\s+AS\s*(?:\([^)]*\)|[^,)]+)/gi,
+ ''
+ );
+
+ // 23. Remove SUPPLEMENTAL LOG clauses
+ sqlContent = sqlContent.replace(/SUPPLEMENTAL\s+LOG\s+[^;]+;?/gi, '');
+
+ // 24. Split into individual statements
+ const statements = sqlContent
+ .split(';')
+ .filter((stmt) => stmt.trim().length > 0);
+
+ // Filter to keep only CREATE TABLE, CREATE INDEX, and ALTER TABLE statements
+ const filteredStatements = statements.filter((stmt) => {
+ const trimmedStmt = stmt.trim().toUpperCase();
+ return (
+ trimmedStmt.includes('CREATE TABLE') ||
+ trimmedStmt.includes('CREATE UNIQUE INDEX') ||
+ trimmedStmt.includes('CREATE INDEX') ||
+ trimmedStmt.includes('ALTER TABLE')
+ );
+ });
+
+ return filteredStatements.join(';\n') + ';';
+}
+
+/**
+ * Manual parsing of ALTER TABLE ADD CONSTRAINT statements for Oracle
+ */
+function parseAlterTableAddConstraint(statements: string[]): SQLForeignKey[] {
+ const fkData: SQLForeignKey[] = [];
+
+ // Oracle ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY pattern
+ const alterTableRegex =
+ /ALTER\s+TABLE\s+"?(\w+)"?(?:\."?(\w+)"?)?\s+ADD\s+CONSTRAINT\s+"?(\w+)"?\s+FOREIGN\s+KEY\s*\("?([^")]+)"?\)\s*REFERENCES\s+"?(\w+)"?(?:\."?(\w+)"?)?\s*\("?([^")]+)"?\)/i;
+
+ for (const stmt of statements) {
+ const match = stmt.match(alterTableRegex);
+ if (match) {
+ const [
+ ,
+ sourceSchemaOrTable,
+ sourceTableIfSchema,
+ constraintName,
+ sourceColumn,
+ targetSchemaOrTable,
+ targetTableIfSchema,
+ targetColumn,
+ ] = match;
+
+ // Handle both schema.table and just table formats
+ let sourceSchema = '';
+ let sourceTable = '';
+ let targetSchema = '';
+ let targetTable = '';
+
+ // If second group is empty, first group is the table name
+ if (!sourceTableIfSchema) {
+ sourceTable = sourceSchemaOrTable;
+ } else {
+ sourceSchema = sourceSchemaOrTable;
+ sourceTable = sourceTableIfSchema;
+ }
+
+ if (!targetTableIfSchema) {
+ targetTable = targetSchemaOrTable;
+ } else {
+ targetSchema = targetSchemaOrTable;
+ targetTable = targetTableIfSchema;
+ }
+
+ fkData.push({
+ name: normalizeOracleIdentifier(constraintName),
+ sourceTable: normalizeOracleIdentifier(sourceTable),
+ sourceSchema: normalizeOracleIdentifier(sourceSchema),
+ sourceColumn: normalizeOracleIdentifier(sourceColumn),
+ targetTable: normalizeOracleIdentifier(targetTable),
+ targetSchema: normalizeOracleIdentifier(targetSchema),
+ targetColumn: normalizeOracleIdentifier(targetColumn),
+ sourceTableId: '', // Will be filled by linkRelationships
+ targetTableId: '', // Will be filled by linkRelationships
+ });
+ }
+ }
+
+ return fkData;
+}
+
+/**
+ * Map Oracle data type strings to normalized types
+ */
+function normalizeOracleDataType(dataType: string): string {
+ const lowerType = dataType.toLowerCase().trim();
+
+ switch (lowerType) {
+ // Character types
+ case 'varchar2':
+ case 'varchar':
+ return 'varchar2';
+ case 'nvarchar2':
+ return 'nvarchar2';
+ case 'char':
+ return 'char';
+ case 'nchar':
+ return 'nchar';
+ case 'clob':
+ return 'clob';
+ case 'nclob':
+ return 'nclob';
+ case 'long':
+ return 'long';
+
+ // Numeric types
+ case 'number':
+ case 'numeric':
+ case 'decimal':
+ return 'number';
+ case 'integer':
+ case 'int':
+ return 'integer';
+ case 'smallint':
+ return 'smallint';
+ case 'float':
+ return 'float';
+ case 'binary_float':
+ return 'binary_float';
+ case 'binary_double':
+ return 'binary_double';
+ case 'real':
+ return 'real';
+
+ // Date/Time types
+ case 'date':
+ return 'date';
+ case 'timestamp':
+ return 'timestamp';
+ case 'timestamp with time zone':
+ case 'timestamp with local time zone':
+ return 'timestamp';
+ case 'interval year to month':
+ case 'interval day to second':
+ return 'interval';
+
+ // Binary types
+ case 'blob':
+ return 'blob';
+ case 'raw':
+ return 'raw';
+ case 'long raw':
+ return 'long raw';
+ case 'bfile':
+ return 'bfile';
+
+ // Other types
+ case 'rowid':
+ return 'rowid';
+ case 'urowid':
+ return 'urowid';
+ case 'xmltype':
+ return 'xmltype';
+ case 'json':
+ return 'json';
+ case 'boolean':
+ return 'boolean';
+
+ default:
+ return dataType;
+ }
+}
+
+/**
+ * Manual parsing of CREATE TABLE statements when node-sql-parser fails
+ */
+function parseCreateTableManually(
+ statement: string,
+ tables: SQLTable[],
+ tableMap: Record<string, string>,
+ relationships: SQLForeignKey[]
+): void {
+ // Extract table name and schema (handling quoted identifiers)
+ const tableMatch = statement.match(
+ /CREATE\s+TABLE\s+"?(\w+)"?(?:\."?(\w+)"?)?\s*\(/i
+ );
+ if (!tableMatch) return;
+
+ let schema = '';
+ let tableName = '';
+
+ // If we have two captures, first is schema, second is table
+ if (tableMatch[2]) {
+ schema = normalizeOracleIdentifier(tableMatch[1]);
+ tableName = normalizeOracleIdentifier(tableMatch[2]);
+ } else {
+ tableName = normalizeOracleIdentifier(tableMatch[1]);
+ }
+
+ // Generate table ID
+ const tableId = generateId();
+ const tableKey = schema ? `${schema}.${tableName}` : tableName;
+ tableMap[tableKey] = tableId;
+ tableMap[tableName] = tableId; // Also map by table name only
+
+ // Extract column definitions
+ const columns: SQLColumn[] = [];
+ const indexes: SQLIndex[] = [];
+
+ // Find the content between the parentheses
+ const tableContentMatch = statement.match(
+ /CREATE\s+TABLE\s+[^(]+\(([\s\S]*)\)\s*(?:TABLESPACE|STORAGE|PCTFREE|$)/i
+ );
+ if (!tableContentMatch) return;
+
+ const tableContent = tableContentMatch[1];
+
+ // Split table content by commas but not within parentheses
+ const parts = [];
+ let current = '';
+ let parenDepth = 0;
+
+ for (let i = 0; i < tableContent.length; i++) {
+ const char = tableContent[i];
+ if (char === '(') parenDepth++;
+ else if (char === ')') parenDepth--;
+ else if (char === ',' && parenDepth === 0) {
+ parts.push(current.trim());
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ if (current.trim()) parts.push(current.trim());
+
+ // Process each part (column or constraint)
+ for (const part of parts) {
+ // Handle standalone FOREIGN KEY definitions (without CONSTRAINT keyword)
+ if (part.match(/^\s*FOREIGN\s+KEY/i)) {
+ const fkMatch = part.match(
+ /FOREIGN\s+KEY\s*\("?([^")]+)"?\)\s+REFERENCES\s+"?(\w+)"?(?:\."?(\w+)"?)?\s*\("?([^")]+)"?\)/i
+ );
+ if (fkMatch) {
+ const [
+ ,
+ sourceCol,
+ targetSchemaOrTable,
+ targetTableIfSchema,
+ targetCol,
+ ] = fkMatch;
+ relationships.push({
+ name: `FK_${tableName}_${normalizeOracleIdentifier(sourceCol)}`,
+ sourceTable: tableName,
+ sourceSchema: schema,
+ sourceColumn: normalizeOracleIdentifier(sourceCol),
+ targetTable: normalizeOracleIdentifier(
+ targetTableIfSchema || targetSchemaOrTable
+ ),
+ targetSchema: targetTableIfSchema
+ ? normalizeOracleIdentifier(targetSchemaOrTable)
+ : '',
+ targetColumn: normalizeOracleIdentifier(targetCol),
+ sourceTableId: tableId,
+ targetTableId: '', // Will be filled later
+ });
+ }
+ continue;
+ }
+
+ // Handle standalone PRIMARY KEY definitions
+ if (part.match(/^\s*PRIMARY\s+KEY/i)) {
+ const pkColumnsMatch = part.match(
+ /PRIMARY\s+KEY\s*\(([\s\S]+?)\)/i
+ );
+ if (pkColumnsMatch) {
+ const pkColumns = pkColumnsMatch[1]
+ .split(',')
+ .map((c) => normalizeOracleIdentifier(c.trim()));
+ pkColumns.forEach((col) => {
+ const column = columns.find(
+ (c) => c.name.toUpperCase() === col.toUpperCase()
+ );
+ if (column) column.primaryKey = true;
+ });
+ }
+ continue;
+ }
+
+ // Handle constraint definitions
+ if (part.match(/^\s*CONSTRAINT/i)) {
+ const constraintMatch = part.match(
+ /CONSTRAINT\s+"?(\w+)"?\s+(PRIMARY\s+KEY|UNIQUE|FOREIGN\s+KEY)/i
+ );
+ if (constraintMatch) {
+ const [, constraintName, constraintType] = constraintMatch;
+
+ if (constraintType.match(/PRIMARY\s+KEY/i)) {
+ // Extract columns from PRIMARY KEY constraint
+ const pkColumnsMatch = part.match(
+ /PRIMARY\s+KEY\s*\(([\s\S]+?)\)/i
+ );
+ if (pkColumnsMatch) {
+ const pkColumns = pkColumnsMatch[1]
+ .split(',')
+ .map((c) => normalizeOracleIdentifier(c.trim()));
+ pkColumns.forEach((col) => {
+ const column = columns.find(
+ (c) =>
+ c.name.toUpperCase() === col.toUpperCase()
+ );
+ if (column) column.primaryKey = true;
+ });
+ }
+ } else if (constraintType === 'UNIQUE') {
+ // Extract columns from UNIQUE constraint
+ const uniqueColumnsMatch = part.match(
+ /UNIQUE\s*\(([\s\S]+?)\)/i
+ );
+ if (uniqueColumnsMatch) {
+ const uniqueColumns = uniqueColumnsMatch[1]
+ .split(',')
+ .map((c) => normalizeOracleIdentifier(c.trim()));
+ indexes.push({
+ name: normalizeOracleIdentifier(constraintName),
+ columns: uniqueColumns,
+ unique: true,
+ });
+ }
+ } else if (constraintType.match(/FOREIGN\s+KEY/i)) {
+ // Parse foreign key constraint
+ const fkMatch = part.match(
+ /FOREIGN\s+KEY\s*\("?([^")]+)"?\)\s+REFERENCES\s+"?(\w+)"?(?:\."?(\w+)"?)?\s*\("?([^")]+)"?\)/i
+ );
+ if (fkMatch) {
+ const [
+ ,
+ sourceCol,
+ targetSchemaOrTable,
+ targetTableIfSchema,
+ targetCol,
+ ] = fkMatch;
+ relationships.push({
+ name: normalizeOracleIdentifier(constraintName),
+ sourceTable: tableName,
+ sourceSchema: schema,
+ sourceColumn: normalizeOracleIdentifier(sourceCol),
+ targetTable: normalizeOracleIdentifier(
+ targetTableIfSchema || targetSchemaOrTable
+ ),
+ targetSchema: targetTableIfSchema
+ ? normalizeOracleIdentifier(targetSchemaOrTable)
+ : '',
+ targetColumn: normalizeOracleIdentifier(targetCol),
+ sourceTableId: tableId,
+ targetTableId: '', // Will be filled later
+ });
+ }
+ }
+ }
+ continue;
+ }
+
+ // Parse column definition
+ // Handle Oracle format: column_name datatype(args) [constraints]
+ const columnMatch = part.match(
+ /^\s*"?(\w+)"?\s+(\w+)(?:\s*\(\s*(\d+(?:\s*,\s*\d+)?)\s*\))?(.*)$/i
+ );
+
+ if (columnMatch) {
+ const [, colName, baseType, typeArgs, rest] = columnMatch;
+
+ if (
+ colName &&
+ !colName.match(/^(PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT)$/i)
+ ) {
+ // Check for inline foreign key
+ const inlineFkMatch = rest?.match(
+ /REFERENCES\s+"?(\w+)"?(?:\."?(\w+)"?)?\s*\("?([^")]+)"?\)/i
+ );
+
+ if (inlineFkMatch) {
+ const [
+ ,
+ targetSchemaOrTable,
+ targetTableIfSchema,
+ targetCol,
+ ] = inlineFkMatch;
+ relationships.push({
+ name: `FK_${tableName}_${normalizeOracleIdentifier(colName)}`,
+ sourceTable: tableName,
+ sourceSchema: schema,
+ sourceColumn: normalizeOracleIdentifier(colName),
+ targetTable: normalizeOracleIdentifier(
+ targetTableIfSchema || targetSchemaOrTable
+ ),
+ targetSchema: targetTableIfSchema
+ ? normalizeOracleIdentifier(targetSchemaOrTable)
+ : '',
+ targetColumn: normalizeOracleIdentifier(targetCol),
+ sourceTableId: tableId,
+ targetTableId: '', // Will be filled later
+ });
+ }
+
+ const isPrimaryKey = !!rest?.match(/PRIMARY\s+KEY/i);
+ const isNotNull = !!rest?.match(/NOT\s+NULL/i);
+ const isIdentity =
+ !!rest?.match(
+ /GENERATED\s+(?:ALWAYS|BY\s+DEFAULT)\s+AS\s+IDENTITY/i
+ ) || !!rest?.match(/AUTO_INCREMENT/i);
+ const isUnique = !!rest?.match(/UNIQUE/i);
+ const defaultMatch = rest?.match(/DEFAULT\s+([^,\s]+)/i);
+
+ // Parse type arguments
+ let parsedTypeArgs:
+ | { length?: number; precision?: number; scale?: number }
+ | undefined;
+ if (typeArgs) {
+ const args = typeArgs
+ .split(',')
+ .map((a) => parseInt(a.trim()));
+ if (args.length === 1) {
+ parsedTypeArgs = { length: args[0] };
+ } else if (args.length >= 2) {
+ parsedTypeArgs = { precision: args[0], scale: args[1] };
+ }
+ }
+
+ const column: SQLColumn = {
+ name: normalizeOracleIdentifier(colName),
+ type: normalizeOracleDataType(baseType.trim()),
+ nullable: !isNotNull && !isPrimaryKey,
+ primaryKey: isPrimaryKey,
+ unique: isUnique,
+ increment: isIdentity,
+ default: defaultMatch ? defaultMatch[1].trim() : undefined,
+ };
+
+ if (parsedTypeArgs) {
+ column.typeArgs = parsedTypeArgs;
+ }
+
+ columns.push(column);
+ }
+ }
+ }
+
+ // Add the table
+ tables.push({
+ id: tableId,
+ name: tableName,
+ schema: schema || undefined,
+ columns,
+ indexes,
+ order: tables.length,
+ });
+}
+
+/**
+ * Parse Oracle DDL scripts and extract database structure
+ * @param sqlContent Oracle DDL content as string
+ * @returns Parsed structure including tables, columns, and relationships
+ */
+export async function fromOracle(sqlContent: string): Promise<SQLParserResult> {
+ const tables: SQLTable[] = [];
+ const relationships: SQLForeignKey[] = [];
+ const tableMap: Record<string, string> = {}; // Maps table name to its ID
+
+ try {
+ // First, split by semicolon for Oracle
+ const statements = sqlContent
+ .split(';')
+ .filter((stmt) => stmt.trim().length > 0);
+
+ // Handle ALTER TABLE statements for foreign keys
+ const alterTableStatements = statements.filter(
+ (stmt) =>
+ stmt.trim().toUpperCase().includes('ALTER TABLE') &&
+ stmt.toUpperCase().includes('FOREIGN KEY')
+ );
+
+ if (alterTableStatements.length > 0) {
+ const fkData = parseAlterTableAddConstraint(alterTableStatements);
+ relationships.push(...fkData);
+ }
+
+ // Parse CREATE TABLE statements manually first
+ const createTableStatements = statements.filter((stmt) =>
+ stmt.trim().toUpperCase().includes('CREATE TABLE')
+ );
+
+ for (const stmt of createTableStatements) {
+ parseCreateTableManually(stmt, tables, tableMap, relationships);
+ }
+
+ // Preprocess the SQL content for node-sql-parser
+ const preprocessedSQL = preprocessOracleScript(sqlContent);
+
+ // Try to use node-sql-parser for additional parsing
+ try {
+ const { Parser } = await import('node-sql-parser');
+ const parser = new Parser();
+ let ast;
+ try {
+ ast = parser.astify(preprocessedSQL, parserOpts);
+ } catch {
+ // Fallback: Try to parse each statement individually
+ const stmts = preprocessedSQL
+ .split(';')
+ .filter((stmt) => stmt.trim().length > 0);
+ ast = [];
+
+ for (const stmt of stmts) {
+ try {
+ const stmtAst = parser.astify(stmt + ';', parserOpts);
+ if (Array.isArray(stmtAst)) {
+ ast.push(...stmtAst);
+ } else if (stmtAst) {
+ ast.push(stmtAst);
+ }
+ } catch {
+ // Skip statements that can't be parsed
+ }
+ }
+ }
+
+ if (Array.isArray(ast) && ast.length > 0) {
+ // Process each statement
+ (ast as unknown as SQLASTNode[]).forEach((stmt) => {
+ // Process CREATE INDEX statements
+ if (stmt.type === 'create' && stmt.keyword === 'index') {
+ processCreateIndex(
+ stmt as CreateIndexStatement,
+ tables
+ );
+ }
+ // Process ALTER TABLE statements for non-FK constraints
+ else if (
+ stmt.type === 'alter' &&
+ stmt.keyword === 'table'
+ ) {
+ processAlterTable(
+ stmt as AlterTableStatement,
+ tables,
+ relationships
+ );
+ }
+ });
+ }
+ } catch (parserError) {
+ // If parser fails completely, continue with manual parsing results
+ console.warn(
+ 'node-sql-parser failed, using manual parsing only:',
+ parserError
+ );
+ }
+
+ // Parse CREATE INDEX statements manually
+ const createIndexStatements = statements.filter(
+ (stmt) =>
+ stmt.trim().toUpperCase().includes('CREATE') &&
+ stmt.trim().toUpperCase().includes('INDEX') &&
+ !stmt.trim().toUpperCase().includes('CREATE TABLE')
+ );
+
+ for (const stmt of createIndexStatements) {
+ // Handle both schema-qualified and non-qualified index names
+ // Format: CREATE [UNIQUE] INDEX [schema.]index_name ON [schema.]table_name(columns)
+ const indexMatch = stmt.match(
+ /CREATE\s+(UNIQUE\s+)?INDEX\s+(?:"?(\w+)"?\.)?"?(\w+)"?\s+ON\s+"?(\w+)"?(?:\."?(\w+)"?)?\s*\(([^)]+)\)/i
+ );
+ if (indexMatch) {
+ const [
+ ,
+ unique,
+ ,
+ indexName,
+ schemaOrTable,
+ tableIfSchema,
+ columnsStr,
+ ] = indexMatch;
+
+ const targetTable = tableIfSchema || schemaOrTable;
+ const targetSchema = tableIfSchema ? schemaOrTable : '';
+
+ const table = tables.find(
+ (t) =>
+ t.name.toUpperCase() === targetTable.toUpperCase() &&
+ (!targetSchema ||
+ t.schema?.toUpperCase() ===
+ targetSchema.toUpperCase())
+ );
+
+ if (table) {
+ const columns = columnsStr
+ .split(',')
+ .map((c) => normalizeOracleIdentifier(c.trim()));
+
+ // Check if this index already exists
+ const existingIndex = table.indexes.find(
+ (i) =>
+ i.name.toUpperCase() ===
+ normalizeOracleIdentifier(indexName).toUpperCase()
+ );
+ if (!existingIndex) {
+ table.indexes.push({
+ name: normalizeOracleIdentifier(indexName),
+ columns,
+ unique: !!unique,
+ });
+ }
+ }
+ }
+ }
+
+ // Link relationships to ensure all targetTableId and sourceTableId fields are filled
+ const validRelationships = linkRelationships(
+ tables,
+ relationships,
+ tableMap
+ );
+
+ // Sort tables by order
+ const sortedTables = [...tables];
+ sortedTables.sort((a, b) => a.order - b.order);
+
+ return {
+ tables: sortedTables,
+ relationships: validRelationships,
+ };
+ } catch (error) {
+ console.error('Error parsing Oracle DDL:', error);
+ throw new Error(`Error parsing Oracle DDL: ${error}`);
+ }
+}
+
+/**
+ * Process a CREATE INDEX statement
+ */
+function processCreateIndex(
+ stmt: CreateIndexStatement,
+ tables: SQLTable[]
+): void {
+ if (!stmt.table || !stmt.columns || stmt.columns.length === 0) {
+ return;
+ }
+
+ // Extract table name and schema
+ let tableName = '';
+ let schemaName = '';
+
+ if (typeof stmt.table === 'object') {
+ if (Array.isArray(stmt.table) && stmt.table.length > 0) {
+ const tableObj = stmt.table[0];
+ tableName = tableObj.table || '';
+ schemaName = tableObj.schema || tableObj.db || '';
+ } else {
+ const tableObj = stmt.table as TableReference;
+ tableName = tableObj.table || '';
+ schemaName = tableObj.schema || tableObj.db || '';
+ }
+ }
+
+ if (!tableName) {
+ return;
+ }
+
+ // Find the table
+ const table = findTableWithSchemaSupport(tables, tableName, schemaName);
+ if (!table) {
+ return;
+ }
+
+ // Extract column names from the index definition
+ const indexColumns = stmt.columns.map((col) => extractColumnName(col));
+ if (indexColumns.length === 0) {
+ return;
+ }
+
+ // Create the index
+ const indexName =
+ stmt.index || `idx_${tableName}_${indexColumns.join('_')}`;
+ const isUnique = stmt.constraint === 'unique';
+
+ // Add index to the table if it doesn't already exist
+ const tableObj = tables.find((t) => t.id === table.id);
+ if (tableObj) {
+ const existingIndex = tableObj.indexes.find(
+ (i) => i.name.toUpperCase() === indexName.toUpperCase()
+ );
+ if (!existingIndex) {
+ tableObj.indexes.push({
+ name: indexName,
+ columns: indexColumns,
+ unique: isUnique,
+ });
+ }
+ }
+}
+
+/**
+ * Process an ALTER TABLE statement
+ */
+function processAlterTable(
+ stmt: AlterTableStatement,
+ tables: SQLTable[],
+ relationships: SQLForeignKey[]
+): void {
+ if (!stmt.table || !stmt.expr || !Array.isArray(stmt.expr)) {
+ return;
+ }
+
+ // Extract table name and schema
+ let tableName = '';
+ let schemaName = '';
+
+ if (typeof stmt.table === 'object') {
+ if (Array.isArray(stmt.table) && stmt.table.length > 0) {
+ const tableObj = stmt.table[0];
+ tableName = tableObj.table || '';
+ schemaName = tableObj.schema || tableObj.db || '';
+ } else {
+ const tableObj = stmt.table as TableReference;
+ tableName = tableObj.table || '';
+ schemaName = tableObj.schema || tableObj.db || '';
+ }
+ }
+
+ if (!tableName) {
+ return;
+ }
+
+ // Find the table
+ const table = findTableWithSchemaSupport(tables, tableName, schemaName);
+ if (!table) {
+ return;
+ }
+
+ // Process each expression in the ALTER TABLE statement
+ for (const expr of stmt.expr) {
+ const action = expr.action;
+
+ // Handle ADD CONSTRAINT for foreign keys
+ if (action === 'add' && expr.resource === 'constraint') {
+ const constraintDef = expr as unknown as ConstraintDefinition;
+
+ if (
+ constraintDef.constraint_type === 'foreign key' &&
+ constraintDef.reference
+ ) {
+ const reference = constraintDef.reference;
+ if (
+ reference &&
+ reference.table &&
+ reference.columns &&
+ reference.columns.length > 0
+ ) {
+ // Extract target table info
+ const targetTable = reference.table as TableReference;
+ const targetTableName = targetTable.table;
+ const targetSchemaName =
+ targetTable.schema || targetTable.db || '';
+
+ // Extract source column
+ let sourceColumnName = '';
+ if (
+ Array.isArray(constraintDef.definition) &&
+ constraintDef.definition.length > 0
+ ) {
+ const sourceColDef = constraintDef.definition[0];
+ if (
+ sourceColDef &&
+ typeof sourceColDef === 'object' &&
+ 'type' in sourceColDef &&
+ (sourceColDef as { type: string }).type ===
+ 'column_ref'
+ ) {
+ sourceColumnName = extractColumnName(
+ sourceColDef as ColumnReference
+ );
+ }
+ }
+
+ // Extract target column
+ const targetColumnName = extractColumnName(
+ reference.columns[0]
+ );
+
+ if (
+ sourceColumnName &&
+ targetTableName &&
+ targetColumnName
+ ) {
+ // Check if this relationship already exists
+ const existingRel = relationships.find(
+ (r) =>
+ r.sourceTable.toUpperCase() ===
+ tableName.toUpperCase() &&
+ r.sourceColumn.toUpperCase() ===
+ sourceColumnName.toUpperCase() &&
+ r.targetTable.toUpperCase() ===
+ targetTableName.toUpperCase()
+ );
+
+ if (!existingRel) {
+ relationships.push({
+ name:
+ constraintDef.constraint ||
+ `fk_${tableName}_${sourceColumnName}`,
+ sourceTable: tableName,
+ sourceSchema: schemaName,
+ sourceColumn: sourceColumnName,
+ targetTable: targetTableName,
+ targetSchema: targetSchemaName,
+ targetColumn: targetColumnName,
+ sourceTableId: table.id,
+ targetTableId: '', // Will be filled later
+ updateAction: reference.on_update,
+ deleteAction: reference.on_delete,
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Post-process the tables and relationships to ensure all targetTableId and sourceTableId fields are filled
+ */
+function linkRelationships(
+ tables: SQLTable[],
+ relationships: SQLForeignKey[],
+ tableMap: Record<string, string>
+): SQLForeignKey[] {
+ // First, ensure all table keys are normalized
+ const normalizedTableMap: Record<string, string> = {};
+ for (const [key, id] of Object.entries(tableMap)) {
+ normalizedTableMap[key.toUpperCase()] = id;
+
+ // Also add without schema for fallback
+ if (key.includes('.')) {
+ const tableName = key.split('.')[1];
+ normalizedTableMap[tableName.toUpperCase()] = id;
+ }
+ }
+
+ // Add all tables to the normalized map
+ for (const table of tables) {
+ if (table.schema) {
+ const tableKey = `${table.schema}.${table.name}`;
+ normalizedTableMap[tableKey.toUpperCase()] = table.id;
+ }
+ normalizedTableMap[table.name.toUpperCase()] = table.id;
+ }
+
+ // Process all relationships
+ const validRelationships = relationships.filter((rel) => {
+ // Normalize keys for lookup
+ const sourceTableKey = rel.sourceSchema
+ ? `${rel.sourceSchema}.${rel.sourceTable}`
+ : rel.sourceTable;
+ const targetTableKey = rel.targetSchema
+ ? `${rel.targetSchema}.${rel.targetTable}`
+ : rel.targetTable;
+
+ // Get the source table ID if it's not already set
+ if (!rel.sourceTableId || rel.sourceTableId === '') {
+ const sourceId =
+ normalizedTableMap[sourceTableKey.toUpperCase()] ||
+ normalizedTableMap[rel.sourceTable.toUpperCase()];
+
+ if (sourceId) {
+ rel.sourceTableId = sourceId;
+ } else {
+ return false;
+ }
+ }
+
+ // Get the target table ID
+ if (!rel.targetTableId || rel.targetTableId === '') {
+ const targetId =
+ normalizedTableMap[targetTableKey.toUpperCase()] ||
+ normalizedTableMap[rel.targetTable.toUpperCase()];
+
+ if (targetId) {
+ rel.targetTableId = targetId;
+ } else {
+ return false;
+ }
+ }
+
+ return true;
+ });
+
+ return validRelationships;
+}
+
+/**
+ * Detect if SQL content is from Oracle format
+ * @param sqlContent SQL content as string
+ * @returns boolean indicating if the SQL is likely from Oracle
+ */
+export function isOracleFormat(sqlContent: string): boolean {
+ const oracleMarkers = [
+ 'VARCHAR2',
+ 'NUMBER(',
+ 'SYSDATE',
+ 'SYSTIMESTAMP',
+ 'SYS_GUID',
+ 'GENERATED ALWAYS AS IDENTITY',
+ 'GENERATED BY DEFAULT AS IDENTITY',
+ '.NEXTVAL',
+ 'TABLESPACE',
+ 'PCTFREE',
+ 'STORAGE (',
+ 'NVARCHAR2',
+ 'CLOB',
+ 'NCLOB',
+ 'BLOB',
+ 'BFILE',
+ 'BINARY_FLOAT',
+ 'BINARY_DOUBLE',
+ 'ROWID',
+ 'XMLTYPE',
+ 'CREATE SEQUENCE',
+ 'CREATE OR REPLACE',
+ 'CONSTRAINT .* PRIMARY KEY.*ENABLE',
+ ];
+
+ // Check for specific Oracle patterns
+ for (const marker of oracleMarkers) {
+ if (marker.includes('.*')) {
+ // Handle regex patterns
+ const regex = new RegExp(marker, 'i');
+ if (regex.test(sqlContent)) {
+ return true;
+ }
+ } else if (sqlContent.toUpperCase().includes(marker.toUpperCase())) {
+ return true;
+ }
+ }
+
+ return false;
+}
diff --git a/src/lib/data/sql-import/index.ts b/src/lib/data/sql-import/index.ts
index 47b38798..be2b8b81 100644
--- a/src/lib/data/sql-import/index.ts
+++ b/src/lib/data/sql-import/index.ts
@@ -5,6 +5,7 @@ import { fromPostgresDump } from './dialect-importers/postgresql/postgresql-dump
import { fromSQLServer } from './dialect-importers/sqlserver/sqlserver';
import { fromSQLite } from './dialect-importers/sqlite/sqlite';
+import { fromOracle, isOracleFormat } from './dialect-importers/oracle/oracle';
import type { SQLParserResult } from './common';
import { convertToChartDBDiagram } from './common';
import { adjustTablePositions } from '@/lib/domain/db-table';
@@ -137,6 +138,11 @@ export function detectDatabaseType(sqlContent: string): DatabaseType | null {
return DatabaseType.SQLITE;
}
+ // Check for Oracle format
+ if (isOracleFormat(sqlContent)) {
+ return DatabaseType.ORACLE;
+ }
+
// Look for database-specific keywords
if (
sqlContent.includes('SERIAL PRIMARY KEY') ||
@@ -209,6 +215,9 @@ export async function sqlImportToDiagram({
case DatabaseType.SQLITE:
parserResult = await fromSQLite(sqlContent);
break;
+ case DatabaseType.ORACLE:
+ parserResult = await fromOracle(sqlContent);
+ break;
default:
throw new Error(`Unsupported database type: ${sourceDatabaseType}`);
}
@@ -283,7 +292,10 @@ export async function parseSQLError({
// SQLite validation
await fromSQLite(sqlContent);
break;
- // Add more database types here
+ case DatabaseType.ORACLE:
+ // Oracle validation
+ await fromOracle(sqlContent);
+ break;
default:
throw new Error(
`Unsupported database type: ${sourceDatabaseType}`
diff --git a/src/lib/data/sql-import/sql-validator.ts b/src/lib/data/sql-import/sql-validator.ts
index 83d7dace..a7e02ef4 100644
--- a/src/lib/data/sql-import/sql-validator.ts
+++ b/src/lib/data/sql-import/sql-validator.ts
@@ -13,6 +13,7 @@ import {
import { validateMySQLDialect } from './validators/mysql-validator';
import { validateSQLServerDialect } from './validators/sqlserver-validator';
import { validateSQLiteDialect } from './validators/sqlite-validator';
+import { validateOracleDialect } from './validators/oracle-validator';
// Re-export types for backward compatibility
export type { ValidationResult, ValidationError, ValidationWarning };
@@ -44,6 +45,9 @@ export function validateSQL(
// MariaDB uses MySQL validator
return validateMySQLDialect(sql);
+ case DatabaseType.ORACLE:
+ return validateOracleDialect(sql);
+
default:
return {
isValid: false,
diff --git a/src/lib/data/sql-import/validators/oracle-validator.ts b/src/lib/data/sql-import/validators/oracle-validator.ts
new file mode 100644
index 00000000..fcc068bc
--- /dev/null
+++ b/src/lib/data/sql-import/validators/oracle-validator.ts
@@ -0,0 +1,137 @@
+/**
+ * Oracle SQL Validator
+ * Validates Oracle SQL syntax and provides helpful error messages
+ */
+
+import type {
+ ValidationResult,
+ ValidationError,
+ ValidationWarning,
+} from './postgresql-validator';
+
+/**
+ * Validates Oracle SQL syntax
+ * @param sql - The Oracle SQL to validate
+ * @returns ValidationResult with errors, warnings, and optional fixed SQL
+ */
+export function validateOracleDialect(sql: string): ValidationResult {
+ const errors: ValidationError[] = [];
+ const warnings: ValidationWarning[] = [];
+
+ // First check if the SQL is empty or just whitespace
+ if (!sql || !sql.trim()) {
+ errors.push({
+ line: 1,
+ message: 'SQL script is empty',
+ type: 'syntax',
+ suggestion: 'Add CREATE TABLE statements to import',
+ });
+ return {
+ isValid: false,
+ errors,
+ warnings,
+ tableCount: 0,
+ };
+ }
+
+ // Check for common Oracle syntax patterns
+ const lines = sql.split('\n');
+ let tableCount = 0;
+
+ lines.forEach((line, index) => {
+ const trimmedLine = line.trim();
+
+ // Count CREATE TABLE statements
+ if (trimmedLine.match(/^\s*CREATE\s+TABLE/i)) {
+ tableCount++;
+ }
+
+ // Check for syntax from other databases that won't work in Oracle
+ if (trimmedLine.includes('AUTO_INCREMENT')) {
+ warnings.push({
+ message: `Line ${index + 1}: AUTO_INCREMENT is MySQL syntax. Use GENERATED AS IDENTITY in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+
+ if (trimmedLine.includes('SERIAL')) {
+ warnings.push({
+ message: `Line ${index + 1}: SERIAL is PostgreSQL syntax. Use GENERATED AS IDENTITY in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+
+ if (trimmedLine.match(/\bIDENTITY\s*\(\s*\d+\s*,\s*\d+\s*\)/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: IDENTITY(seed, increment) is SQL Server syntax. Use GENERATED AS IDENTITY in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+
+ // Check for MySQL-specific types
+ if (trimmedLine.match(/\bTINYINT\b/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: TINYINT is not an Oracle type. Consider using NUMBER(3) instead.`,
+ type: 'compatibility',
+ });
+ }
+
+ if (trimmedLine.match(/\bMEDIUMINT\b/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: MEDIUMINT is not an Oracle type. Consider using NUMBER(7) instead.`,
+ type: 'compatibility',
+ });
+ }
+
+ // Check for SQL Server-specific types
+ if (trimmedLine.match(/\bNVARCHAR\s*\(\s*max\s*\)/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: NVARCHAR(max) is SQL Server syntax. Use NCLOB in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+
+ if (trimmedLine.match(/\bVARCHAR\s*\(\s*max\s*\)/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: VARCHAR(max) is SQL Server syntax. Use CLOB in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+
+ if (trimmedLine.match(/\bUNIQUEIDENTIFIER\b/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: UNIQUEIDENTIFIER is SQL Server syntax. Use RAW(16) or SYS_GUID() in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+
+ if (trimmedLine.match(/\bDATETIME2\b/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: DATETIME2 is SQL Server syntax. Use TIMESTAMP in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+
+ // Check for PostgreSQL-specific syntax
+ if (trimmedLine.match(/\bJSONB\b/i)) {
+ warnings.push({
+ message: `Line ${index + 1}: JSONB is PostgreSQL syntax. Use JSON in Oracle 21c+ or CLOB for older versions.`,
+ type: 'compatibility',
+ });
+ }
+
+ if (trimmedLine.match(/::/)) {
+ warnings.push({
+ message: `Line ${index + 1}: :: cast syntax is PostgreSQL specific. Use CAST() in Oracle.`,
+ type: 'compatibility',
+ });
+ }
+ });
+
+ return {
+ isValid: errors.length === 0,
+ errors,
+ warnings,
+ tableCount,
+ };
+}