Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

test(schema): drop testcontainer from the schema plugin (#21415)

Danny Xu47baed4f5d2b
diff --git a/AGENTS.md b/AGENTS.md
index 41f561d8a2..27af00b9a8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -11,6 +11,7 @@ Bytebase is the standard for database development. Every product and engineering
- Before exploring domain behavior, read [domain guidance](docs/agents/domain.md).
- For frontend work, read [frontend/AGENTS.md](frontend/AGENTS.md); before changing UI, also read the [UX contract](docs/agents/frontend-ux.md).
- Before adding or modifying metadata SQL, pagination, or multi-row transactions anywhere in the repo, read [backend/store/AGENTS.md](backend/store/AGENTS.md). This includes CEL-to-SQL filters and raw reads in tests.
+- Before changing metadata/DDL conversions or their golden fixtures, read [backend/plugin/schema/AGENTS.md](backend/plugin/schema/AGENTS.md). It covers what these packages test and the `record` process for regenerating fixtures.
- For issue operations, read [issue-tracker.md](docs/agents/issue-tracker.md). Linear is the tracker; agent-created issues go to team `BOT`. For triage, also read [triage-labels.md](docs/agents/triage-labels.md).
- Before creating a PR, complete [docs/pre-pr-checklist.md](docs/pre-pr-checklist.md).
- `AGENTS.md` files are the instruction source of truth; `CLAUDE.md` files import them.
diff --git a/backend/plugin/schema/AGENTS.md b/backend/plugin/schema/AGENTS.md
new file mode 100644
index 0000000000..66f85232e9
--- /dev/null
+++ b/backend/plugin/schema/AGENTS.md
@@ -0,0 +1,71 @@
+# Bytebase schema plugin
+
+Additional guidance for `./backend/plugin/schema/`, the per-engine conversions
+between database metadata and DDL. Follow `../../../AGENTS.md` first; this file
+adds to it.
+
+## What these packages test
+
+Each engine package owns three conversions, and a test covers exactly one:
+
+- `GetDatabaseMetadata` — schema text to metadata.
+- `GetDatabaseDefinition` — metadata to DDL.
+- `schema.GetDatabaseSchemaDiff` plus the package's `generateMigration`.
+
+Do not call `driver.SyncDBSchema` here, and never use a live server's answer as
+the expected value: whether our output matches what an engine stores is engine
+conformance, and it belongs in omni. No test in these packages starts a
+container.
+
+A metadata-to-DDL test takes metadata as its input, not a schema text. Deriving
+it by parsing caps the test at whatever the parser extracts, so any generator
+branch nothing feeds goes untested.
+
+## The record process
+
+Fixtures live in `testdata/` as a YAML list of cases, one file per test, named
+after the source file it covers. Each test carries the path and a `record`
+constant:
+
+```go
+const (
+ record = false
+ filepath = "testdata/get_database_definition.yaml"
+)
+```
+
+To regenerate, set `record` to `true`, run that one test, and set it back:
+
+```bash
+go test ./backend/plugin/schema/tidb/ -run '^TestGetDatabaseDefinition$' -count=1
+```
+
+- Commit the fixture and the restored `record = false` together. A `record = true`
+ left in the tree overwrites the goldens on every run, so the test always passes.
+- Read the fixture diff. A re-record captures current behavior, bugs included.
+- Recording only rewrites the output field. Changing a fixture's input means
+ editing the metadata blob, or re-seeding it.
+
+## Fixture gotchas
+
+- YAML block scalars cannot carry tabs, trailing whitespace, or a leading
+ newline. A value with any of them is stored as one unreadable quoted line.
+ Indent fixture SQL with spaces; trim a leading newline before comparing, as
+ the PostgreSQL definition test does. Trailing whitespace usually arrives from
+ a `definition`/`body` field, not the generator — strip it in the fixture.
+- yaml.v3 escapes astral-plane characters, so a golden containing an emoji is
+ always a quoted line. Two are, deliberately: they cover 4-byte UTF-8.
+- Generated DDL must be byte-stable before it can be pinned. Walk maps in sorted
+ key order in the generators.
+
+## Two deviations
+
+Oracle's migration inputs are `oldMetadata`/`newMetadata`, protojson captured
+from a real Oracle, where every other engine's are `oldSchema`/`newSchema`
+schema text. Converting them would rewrite all 34 cases: a metadata/DDL/metadata
+round trip is lossless for 0 of its 68 blobs.
+
+PostgreSQL registers neither `GenerateMigration` nor `GetDatabaseMetadata`, so it
+has no fixture for either. Its migration generation is covered by
+`metadata_migration_test.go`, whose hand-written assertions carry intent a golden
+cannot. Do not convert those.
diff --git a/backend/plugin/schema/mssql/generate_migration_test.go b/backend/plugin/schema/mssql/generate_migration_test.go
index 11aef06380..50be7f7e33 100644
--- a/backend/plugin/schema/mssql/generate_migration_test.go
+++ b/backend/plugin/schema/mssql/generate_migration_test.go
@@ -1,40 +1,35 @@
package mssql
import (
- "context"
- "fmt"
"io"
"os"
- "path/filepath"
- "slices"
- "strings"
"testing"
- // Import MSSQL driver
- "github.com/google/go-cmp/cmp"
- "github.com/google/uuid"
_ "github.com/microsoft/go-mssqldb"
- "github.com/pkg/errors"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/testing/protocmp"
"gopkg.in/yaml.v3"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
)
-type MigrationTestData struct {
+type generateMigrationCase struct {
Description string `yaml:"description"`
OldSchema string `yaml:"oldSchema"`
NewSchema string `yaml:"newSchema"`
Expected string `yaml:"expected"`
}
-func runMigrationTest(t *testing.T, file string) {
- var tests []MigrationTestData
- filepath := filepath.Join("test-data", file)
+// TestGenerateMigration pins the DDL that takes oldSchema to newSchema.
+func TestGenerateMigration(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/generate_migration.yaml"
+ )
+
+ var tests []generateMigrationCase
yamlFile, err := os.Open(filepath)
require.NoError(t, err)
defer yamlFile.Close()
@@ -99,2513 +94,16 @@ func runMigrationTest(t *testing.T, file string) {
migration, err := generateMigration(diff)
require.NoErrorf(t, err, "Failed to generate migration for test case [%02d]: %s", i+1, test.Description)
- require.Equalf(t, test.Expected, migration, "Test case [%02d] failed: %s", i+1, test.Description)
- })
- }
-}
-
-func TestGenerateMigration_Tables(t *testing.T) {
- runMigrationTest(t, "test_migration_tables.yaml")
-}
-
-func TestGenerateMigration_Indexes(t *testing.T) {
- runMigrationTest(t, "test_migration_indexes.yaml")
-}
-
-func TestGenerateMigration_Constraints(t *testing.T) {
- runMigrationTest(t, "test_migration_constraints.yaml")
-}
-
-func TestGenerateMigration_Functions(t *testing.T) {
- runMigrationTest(t, "test_migration_functions.yaml")
-}
-
-func TestGenerateMigration_Procedures(t *testing.T) {
- runMigrationTest(t, "test_migration_procedures.yaml")
-}
-
-func TestGenerateMigration_Views(t *testing.T) {
- runMigrationTest(t, "test_migration_views.yaml")
-}
-
-func TestGenerateMigration_SafeOrder(t *testing.T) {
- runMigrationTest(t, "test_migration_safe_order.yaml")
-}
-
-// TestGenerateMigrationWithTestcontainer tests the generate migration function
-// by applying migrations and rollback to verify the schema can be restored.
-//
-//nolint:tparallel
-func TestGenerateMigrationWithTestcontainer(t *testing.T) {
- if testing.Short() {
- t.Skip("Skipping MSSQL testcontainer test in short mode")
- }
-
- ctx := context.Background()
-
- // Start shared MSSQL container for all subtests
- container := testcontainer.SharedMSSQLContainer(t)
-
- // Test cases with various schema changes
- testCases := []struct {
- name string
- initialSchema string
- migrationDDL string
- description string
- }{
- {
- name: "basic_table_operations",
- initialSchema: `
-CREATE SCHEMA [app];
-GO
-
-CREATE TABLE [app].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [created_at] DATETIME2,
- CONSTRAINT [uk_users_email] UNIQUE ([email])
-);
-
-CREATE INDEX [idx_users_username] ON [app].[users] ([username]);
-
-CREATE TABLE [app].[posts] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [title] NVARCHAR(200) NOT NULL,
- [content] NTEXT,
- [published_at] DATETIME2,
- CONSTRAINT [fk_posts_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]) ON DELETE CASCADE
-);
-
-CREATE INDEX [idx_posts_user_id] ON [app].[posts] ([user_id]);
-`,
- migrationDDL: `
--- Add new column
-ALTER TABLE [app].[users] ADD [status] NVARCHAR(20);
-
--- Add new table
-CREATE TABLE [app].[comments] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [post_id] INT NOT NULL,
- [user_id] INT NOT NULL,
- [content] NTEXT NOT NULL,
- [created_at] DATETIME2,
- CONSTRAINT [fk_comments_post] FOREIGN KEY ([post_id]) REFERENCES [app].[posts]([id]) ON DELETE CASCADE,
- CONSTRAINT [fk_comments_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id])
-);
-
--- Add index
-CREATE INDEX [idx_comments_post_id] ON [app].[comments] ([post_id]);
-
--- Add check constraint
-ALTER TABLE [app].[users] ADD CONSTRAINT [ck_users_status] CHECK ([status] IN ('active', 'inactive', 'suspended'));
-`,
- description: "Basic table operations with foreign keys, indexes, and constraints",
- },
- {
- name: "schema_operations",
- initialSchema: `
-CREATE SCHEMA [sales];
-GO
-
-CREATE TABLE [sales].[customers] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [email] NVARCHAR(100)
-);
-
-CREATE TABLE [sales].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [customer_id] INT NOT NULL,
- [order_date] DATE,
- [total] DECIMAL(10,2),
- CONSTRAINT [fk_orders_customer] FOREIGN KEY ([customer_id]) REFERENCES [sales].[customers]([id])
-);
-`,
- migrationDDL: `
--- Create new schema
-CREATE SCHEMA [inventory];
-GO
-
--- Create table in new schema
-CREATE TABLE [inventory].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [category_id] INT,
- CONSTRAINT [ck_products_price] CHECK ([price] > 0)
-);
-
--- Add reference to new table from existing schema
-ALTER TABLE [sales].[orders] ADD [product_id] INT;
-ALTER TABLE [sales].[orders] ADD CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [inventory].[products]([id]);
-`,
- description: "Cross-schema operations with new schema creation",
- },
- {
- name: "view_operations",
- initialSchema: `
-CREATE SCHEMA [reporting];
-GO
-
-CREATE TABLE [reporting].[sales_data] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [product_name] NVARCHAR(100) NOT NULL,
- [quantity] INT NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [sale_date] DATE
-);
-
-CREATE TABLE [reporting].[customers] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [region] NVARCHAR(50)
-);
-`,
- migrationDDL: `
--- Create basic view
-CREATE VIEW [reporting].[product_summary] AS
-SELECT
- [product_name],
- COUNT(*) as [sale_count],
- SUM([quantity]) as [total_quantity],
- AVG([price]) as [avg_price]
-FROM [reporting].[sales_data]
-GROUP BY [product_name];
-GO
-
--- Create dependent view
-CREATE VIEW [reporting].[top_products] AS
-SELECT TOP 10
- [product_name],
- [total_quantity]
-FROM [reporting].[product_summary]
-WHERE [total_quantity] > 100
-ORDER BY [total_quantity] DESC;
-GO
-`,
- description: "View creation with dependencies",
- },
- {
- name: "function_and_procedure_operations",
- initialSchema: `
-CREATE SCHEMA [calc];
-GO
-
-CREATE TABLE [calc].[numbers] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [value] INT NOT NULL,
- [category] NVARCHAR(20)
-);
-`,
- migrationDDL: `
--- Create scalar function
-CREATE FUNCTION [calc].[square](@input INT)
-RETURNS INT
-AS
-BEGIN
- RETURN @input * @input;
-END;
-GO
-
--- Create table-valued function
-CREATE FUNCTION [calc].[get_numbers_by_category](@category NVARCHAR(20))
-RETURNS TABLE
-AS
-RETURN (
- SELECT [id], [value], [category]
- FROM [calc].[numbers]
- WHERE [category] = @category
-);
-GO
-
--- Create stored procedure
-CREATE PROCEDURE [calc].[add_number]
- @value INT,
- @category NVARCHAR(20)
-AS
-BEGIN
- INSERT INTO [calc].[numbers] ([value], [category])
- VALUES (@value, @category);
-END;
-GO
-`,
- description: "Functions and procedures creation",
- },
- {
- name: "index_operations",
- initialSchema: `
-CREATE SCHEMA [perf];
-GO
-
-CREATE TABLE [perf].[events] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [event_name] NVARCHAR(100) NOT NULL,
- [event_data] NVARCHAR(MAX),
- [timestamp] DATETIME2,
- [user_id] INT,
- [category] NVARCHAR(50)
-);
-`,
- migrationDDL: `
--- Add various index types
-CREATE INDEX [idx_events_timestamp] ON [perf].[events] ([timestamp]);
-CREATE INDEX [idx_events_user_category] ON [perf].[events] ([user_id], [category]);
-CREATE UNIQUE INDEX [idx_events_name_timestamp] ON [perf].[events] ([event_name], [timestamp]);
-
--- Add filtered index (using deterministic date)
-CREATE INDEX [idx_events_recent] ON [perf].[events] ([event_name])
-WHERE [timestamp] >= '2023-01-01';
-
--- Add computed column first
-ALTER TABLE [perf].[events] ADD [event_month] AS DATEPART(MONTH, [timestamp]);
-
--- Add index on computed column
-CREATE INDEX [idx_events_month] ON [perf].[events] ([event_month]);
-`,
- description: "Various index types including filtered and computed column indexes",
- },
- {
- name: "complex_constraints",
- initialSchema: `
-CREATE SCHEMA [finance];
-GO
-
-CREATE TABLE [finance].[accounts] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [account_number] NVARCHAR(20) NOT NULL,
- [balance] DECIMAL(15,2),
- [account_type] NVARCHAR(20) NOT NULL,
- [created_at] DATETIME2 DEFAULT GETDATE()
-);
-`,
- migrationDDL: `
--- Add multiple check constraints
-ALTER TABLE [finance].[accounts] ADD CONSTRAINT [ck_accounts_balance] CHECK ([balance] >= 0);
-ALTER TABLE [finance].[accounts] ADD CONSTRAINT [ck_accounts_type] CHECK ([account_type] IN ('CHECKING', 'SAVINGS', 'CREDIT'));
-
--- Add unique constraint
-ALTER TABLE [finance].[accounts] ADD CONSTRAINT [uk_accounts_number] UNIQUE ([account_number]);
-
--- Create related table with foreign key
-CREATE TABLE [finance].[transactions] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [account_id] INT NOT NULL,
- [amount] DECIMAL(15,2) NOT NULL,
- [transaction_type] NVARCHAR(20) NOT NULL,
- [transaction_date] DATETIME2,
- CONSTRAINT [fk_transactions_account] FOREIGN KEY ([account_id]) REFERENCES [finance].[accounts]([id]),
- CONSTRAINT [ck_transactions_amount] CHECK ([amount] != 0),
- CONSTRAINT [ck_transactions_type] CHECK ([transaction_type] IN ('DEBIT', 'CREDIT'))
-);
-`,
- description: "Complex constraints with multiple check constraints and foreign keys",
- },
- {
- name: "column_modifications",
- initialSchema: `
-CREATE SCHEMA [hr];
-GO
-
-CREATE TABLE [hr].[employees] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [first_name] NVARCHAR(50),
- [last_name] NVARCHAR(50),
- [email] NVARCHAR(100),
- [phone] VARCHAR(20),
- [hire_date] DATE,
- [salary] DECIMAL(10,2)
-);
-`,
- migrationDDL: `
--- Add new columns
-ALTER TABLE [hr].[employees] ADD [department_id] INT;
-ALTER TABLE [hr].[employees] ADD [manager_id] INT;
-ALTER TABLE [hr].[employees] ADD [status] NVARCHAR(20);
-
--- Create department table
-CREATE TABLE [hr].[departments] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [budget] DECIMAL(15,2)
-);
-
--- Add foreign key constraints
-ALTER TABLE [hr].[employees] ADD CONSTRAINT [fk_employees_department] FOREIGN KEY ([department_id]) REFERENCES [hr].[departments]([id]);
-ALTER TABLE [hr].[employees] ADD CONSTRAINT [fk_employees_manager] FOREIGN KEY ([manager_id]) REFERENCES [hr].[employees]([id]);
-
--- Add check constraints
-ALTER TABLE [hr].[employees] ADD CONSTRAINT [ck_employees_salary] CHECK ([salary] > 0);
-ALTER TABLE [hr].[employees] ADD CONSTRAINT [ck_employees_status] CHECK ([status] IN ('ACTIVE', 'INACTIVE', 'TERMINATED'));
-`,
- description: "Column additions and self-referencing foreign keys",
- },
- {
- name: "multiple_schema_dependencies",
- initialSchema: `
-CREATE SCHEMA [core];
-GO
-CREATE SCHEMA [app];
-GO
-
-CREATE TABLE [core].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL
-);
-
-CREATE TABLE [core].[roles] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(50) NOT NULL
-);
-`,
- migrationDDL: `
--- Create user_roles junction table in core schema
-CREATE TABLE [core].[user_roles] (
- [user_id] INT NOT NULL,
- [role_id] INT NOT NULL,
- [assigned_at] DATETIME2,
- CONSTRAINT [pk_user_roles] PRIMARY KEY ([user_id], [role_id]),
- CONSTRAINT [fk_user_roles_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE,
- CONSTRAINT [fk_user_roles_role] FOREIGN KEY ([role_id]) REFERENCES [core].[roles]([id]) ON DELETE CASCADE
-);
-
--- Create application tables that reference core schema
-CREATE TABLE [app].[sessions] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [token] NVARCHAR(255) NOT NULL,
- [expires_at] DATETIME2 NOT NULL,
- CONSTRAINT [fk_sessions_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE
-);
-
-CREATE TABLE [app].[audit_log] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT,
- [action] NVARCHAR(100) NOT NULL,
- [timestamp] DATETIME2,
- [details] NVARCHAR(MAX),
- CONSTRAINT [fk_audit_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id])
-);
-`,
- description: "Multiple schema dependencies with cross-schema foreign keys",
- },
- {
- name: "computed_columns_and_triggers",
- initialSchema: `
-CREATE SCHEMA [ecommerce];
-GO
-
-CREATE TABLE [ecommerce].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [tax_rate] DECIMAL(5,4)
-);
-`,
- migrationDDL: `
--- Add computed columns
-ALTER TABLE [ecommerce].[products] ADD [price_with_tax] AS ([price] * (1 + [tax_rate]));
-GO
-
-ALTER TABLE [ecommerce].[products] ADD [price_category] AS (
- CASE
- WHEN [price] < 10 THEN 'Budget'
- WHEN [price] < 100 THEN 'Standard'
- ELSE 'Premium'
- END
-);
-GO
-
--- Create order table
-CREATE TABLE [ecommerce].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [product_id] INT NOT NULL,
- [quantity] INT NOT NULL,
- [unit_price] DECIMAL(10,2) NOT NULL,
- [total] DECIMAL(15,2),
- [order_date] DATETIME2,
- CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [ecommerce].[products]([id])
-);
-GO
-
--- Add computed column for total
-ALTER TABLE [ecommerce].[orders] ADD [computed_total] AS ([quantity] * [unit_price]);
-GO
-
--- Add indexes on computed columns
-CREATE INDEX [idx_products_price_category] ON [ecommerce].[products] ([price_category]);
-CREATE INDEX [idx_products_price_with_tax] ON [ecommerce].[products] ([price_with_tax]);
-`,
- description: "Computed columns with indexes",
- },
- {
- name: "create_tables_with_fk",
- initialSchema: `
-CREATE SCHEMA [test];
-GO
-
-CREATE TABLE [test].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [created_at] DATETIME2,
- CONSTRAINT [uk_email] UNIQUE ([email])
-);
-
-CREATE INDEX [idx_username] ON [test].[users] ([username]);
-
-CREATE TABLE [test].[posts] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [title] NVARCHAR(200) NOT NULL,
- [content] NVARCHAR(MAX),
- [published_at] DATETIME2,
- CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE CASCADE
-);
-
-CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);
-`,
- migrationDDL: `
-DROP TABLE [test].[posts];
-DROP TABLE [test].[users];
-DROP SCHEMA [test];`,
- description: "Create tables with foreign key constraints",
- },
- {
- name: "multiple_foreign_keys",
- initialSchema: `
-CREATE SCHEMA [test];
-GO
-
-CREATE TABLE [test].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [created_at] DATETIME2,
- CONSTRAINT [uk_email] UNIQUE ([email])
-);
-GO
-
-CREATE INDEX [idx_username] ON [test].[users] ([username]);
-GO
-
-CREATE TABLE [test].[posts] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [title] NVARCHAR(200) NOT NULL,
- [content] NVARCHAR(MAX),
- [published_at] DATETIME2,
- CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE CASCADE
-);
-GO
-
-CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);
-GO
-`,
- migrationDDL: `
--- Add new column
-ALTER TABLE [test].[users] ADD [is_active] BIT;
-GO
-
--- Create new table with multiple foreign keys
-CREATE TABLE [test].[comments] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [post_id] INT NOT NULL,
- [user_id] INT NOT NULL,
- [content] NVARCHAR(MAX) NOT NULL,
- [created_at] DATETIME2,
- CONSTRAINT [fk_comment_post] FOREIGN KEY ([post_id]) REFERENCES [test].[posts]([id]) ON DELETE CASCADE,
- CONSTRAINT [fk_comment_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE NO ACTION
-);
-GO
-
-CREATE INDEX [idx_post_user] ON [test].[comments] ([post_id], [user_id]);
-
--- Add new index
-CREATE INDEX [idx_email_active] ON [test].[users] ([email], [is_active]);
-
--- Add check constraint
-ALTER TABLE [test].[posts] ADD CONSTRAINT [chk_title_length] CHECK (LEN([title]) > 0);
-`,
- description: "Tables with multiple foreign key constraints",
- },
- {
- name: "drop_and_recreate_fk_constraints",
- initialSchema: `
-CREATE SCHEMA [library];
-GO
-
-CREATE TABLE [library].[authors] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [email] NVARCHAR(100),
- CONSTRAINT [uk_email] UNIQUE ([email])
-);
-
-CREATE TABLE [library].[books] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [title] NVARCHAR(200) NOT NULL,
- [author_id] INT NOT NULL,
- [isbn] NVARCHAR(20),
- [published_year] INT,
- [price] DECIMAL(8, 2),
- CONSTRAINT [fk_author] FOREIGN KEY ([author_id]) REFERENCES [library].[authors]([id]),
- CONSTRAINT [chk_year_valid] CHECK ([published_year] >= 1000 AND [published_year] <= 2100),
- CONSTRAINT [chk_price_positive] CHECK ([price] > 0),
- CONSTRAINT [uk_isbn] UNIQUE ([isbn])
-);
-
-CREATE INDEX [idx_author] ON [library].[books] ([author_id]);
-CREATE INDEX [idx_year] ON [library].[books] ([published_year]);
-`,
- migrationDDL: `
--- Drop and recreate foreign key with different options
-ALTER TABLE [library].[books] DROP CONSTRAINT [fk_author];
-ALTER TABLE [library].[books] ADD CONSTRAINT [fk_author_new] FOREIGN KEY ([author_id]) REFERENCES [library].[authors]([id]) ON DELETE CASCADE ON UPDATE CASCADE;
-
--- Drop and modify check constraints
-ALTER TABLE [library].[books] DROP CONSTRAINT [chk_year_valid];
-ALTER TABLE [library].[books] ADD CONSTRAINT [chk_year_extended] CHECK ([published_year] >= 1000 AND [published_year] <= 2030);
-
--- Add new constraints
-ALTER TABLE [library].[books] ADD CONSTRAINT [chk_title_length] CHECK (LEN([title]) >= 3);
-`,
- description: "Drop and recreate foreign key constraints with different options",
- },
- {
- name: "self_referencing_foreign_keys",
- initialSchema: `
-CREATE SCHEMA [company];
-GO
-
-CREATE TABLE [company].[departments] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [manager_id] INT
-);
-
-CREATE TABLE [company].[employees] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [department_id] INT,
- [salary] DECIMAL(10, 2),
- [hire_date] DATE,
- CONSTRAINT [fk_dept] FOREIGN KEY ([department_id]) REFERENCES [company].[departments]([id])
-);
-
-CREATE INDEX [idx_dept] ON [company].[employees] ([department_id]);
-
--- Add self-referencing foreign key
-ALTER TABLE [company].[departments] ADD CONSTRAINT [fk_manager] FOREIGN KEY ([manager_id]) REFERENCES [company].[employees]([id]);
-`,
- migrationDDL: `
--- Create base view
-CREATE VIEW [company].[dept_employee_count] AS
-SELECT d.[id] AS dept_id, d.[name] AS dept_name, COUNT(e.[id]) AS emp_count
-FROM [company].[departments] d
-LEFT JOIN [company].[employees] e ON d.[id] = e.[department_id]
-GROUP BY d.[id], d.[name];
-GO
-
--- Create dependent view
-CREATE VIEW [company].[dept_summary] AS
-SELECT
- dept_id,
- dept_name,
- emp_count,
- 0 AS avg_salary,
- 0 AS max_salary,
- 0 AS min_salary
-FROM [company].[dept_employee_count];
-GO
-
--- Create highly dependent view
-CREATE VIEW [company].[dept_manager_summary] AS
-SELECT
- ds.dept_id,
- ds.dept_name,
- ds.emp_count,
- ds.avg_salary,
- m.[name] AS manager_name
-FROM [company].[dept_summary] ds
-JOIN [company].[departments] d ON ds.dept_id = d.[id]
-LEFT JOIN [company].[employees] m ON d.[manager_id] = m.[id];
-GO
-
--- Create stored procedure using views
-CREATE PROCEDURE [company].[GetDepartmentReport]
- @dept_name_pattern NVARCHAR(100)
-AS
-BEGIN
- SELECT * FROM [company].[dept_manager_summary]
- WHERE dept_name LIKE '%' + @dept_name_pattern + '%';
-END;
-`,
- description: "Self-referencing foreign keys and complex view dependencies",
- },
- {
- name: "table_and_column_comments",
- initialSchema: `
-CREATE SCHEMA [app];
-GO
-
-CREATE TABLE [app].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [created_at] DATETIME2,
- [status] NVARCHAR(20)
-);
-
-CREATE TABLE [app].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [category] NVARCHAR(50)
-);
-
-CREATE INDEX [idx_users_email] ON [app].[users] ([email]);
-CREATE INDEX [idx_products_category] ON [app].[products] ([category]);
-`,
- migrationDDL: `
--- Add table comments using extended properties
-EXEC sp_addextendedproperty 'MS_Description', 'User accounts and profile information', 'SCHEMA', 'app', 'TABLE', 'users';
-EXEC sp_addextendedproperty 'MS_Description', 'Product catalog with pricing information', 'SCHEMA', 'app', 'TABLE', 'products';
-GO
-
--- Add column comments for users table
-EXEC sp_addextendedproperty 'MS_Description', 'Unique identifier for each user', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Unique username for login authentication', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';
-EXEC sp_addextendedproperty 'MS_Description', 'User email address for notifications', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';
-EXEC sp_addextendedproperty 'MS_Description', 'Timestamp when the user account was created', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';
-EXEC sp_addextendedproperty 'MS_Description', 'Current status: active, inactive, or suspended', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';
-GO
-
--- Add column comments for products table
-EXEC sp_addextendedproperty 'MS_Description', 'Unique product identifier', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Product display name', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';
-EXEC sp_addextendedproperty 'MS_Description', 'Product price in USD', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';
-EXEC sp_addextendedproperty 'MS_Description', 'Product category classification', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';
-GO
-
--- Create new table and add comments immediately
-CREATE TABLE [app].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [product_id] INT NOT NULL,
- [quantity] INT NOT NULL,
- [order_date] DATETIME2,
- CONSTRAINT [fk_orders_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]),
- CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [app].[products]([id])
-);
-GO
-
--- Add comments to the new table
-EXEC sp_addextendedproperty 'MS_Description', 'Customer orders tracking system', 'SCHEMA', 'app', 'TABLE', 'orders';
-EXEC sp_addextendedproperty 'MS_Description', 'Unique order identifier', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Reference to the user who placed the order', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';
-EXEC sp_addextendedproperty 'MS_Description', 'Reference to the ordered product', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';
-EXEC sp_addextendedproperty 'MS_Description', 'Number of items ordered', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';
-EXEC sp_addextendedproperty 'MS_Description', 'When the order was placed', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';
-`,
- description: "Adding comments to tables and columns using SQL Server extended properties",
- },
- {
- name: "modify_and_drop_comments",
- initialSchema: `
-CREATE SCHEMA [test];
-GO
-
-CREATE TABLE [test].[customers] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [email] NVARCHAR(100),
- [phone] NVARCHAR(20),
- [created_at] DATETIME2 DEFAULT GETDATE()
-);
-GO
-
--- Add initial comments
-EXEC sp_addextendedproperty 'MS_Description', 'Customer information database', 'SCHEMA', 'test', 'TABLE', 'customers';
-EXEC sp_addextendedproperty 'MS_Description', 'Customer unique ID', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Customer full name', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'name';
-EXEC sp_addextendedproperty 'MS_Description', 'Customer email for marketing', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'email';
-EXEC sp_addextendedproperty 'MS_Description', 'Customer contact number', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'phone';
-GO
-
-CREATE TABLE [test].[invoices] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [customer_id] INT NOT NULL,
- [amount] DECIMAL(10,2) NOT NULL,
- [invoice_date] DATE,
- CONSTRAINT [fk_invoices_customer] FOREIGN KEY ([customer_id]) REFERENCES [test].[customers]([id])
-);
-GO
-
--- Add comments to invoices table
-EXEC sp_addextendedproperty 'MS_Description', 'Invoice records for billing', 'SCHEMA', 'test', 'TABLE', 'invoices';
-EXEC sp_addextendedproperty 'MS_Description', 'Invoice number', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Link to customer', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'customer_id';
-`,
- migrationDDL: `
--- Update existing table comment
-EXEC sp_updateextendedproperty 'MS_Description', 'Complete customer database with contact details and preferences', 'SCHEMA', 'test', 'TABLE', 'customers';
-GO
-
--- Update existing column comments
-EXEC sp_updateextendedproperty 'MS_Description', 'Primary key - auto-generated customer identifier', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'id';
-EXEC sp_updateextendedproperty 'MS_Description', 'Customer business or personal name', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'name';
-EXEC sp_updateextendedproperty 'MS_Description', 'Primary email address for communications and billing', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'email';
-GO
-
--- Drop specific column comment
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'phone';
-GO
-
--- Add new comment to column that didn't have one
-EXEC sp_addextendedproperty 'MS_Description', 'Account creation timestamp for auditing', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'created_at';
-GO
-
--- Update invoice table comment
-EXEC sp_updateextendedproperty 'MS_Description', 'Financial invoice tracking and billing system', 'SCHEMA', 'test', 'TABLE', 'invoices';
-GO
-
--- Drop invoice column comments
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'id';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'customer_id';
-GO
-
--- Add new column with comment
-ALTER TABLE [test].[invoices] ADD [payment_status] NVARCHAR(20);
-GO
-
-EXEC sp_addextendedproperty 'MS_Description', 'Current payment status: pending, paid, overdue, cancelled', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'payment_status';
-`,
- description: "Modifying existing comments and removing comments using extended properties",
- },
- {
- name: "comments_with_special_characters",
- initialSchema: `
-CREATE SCHEMA [special];
-GO
-
-CREATE TABLE [special].[documents] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [title] NVARCHAR(200) NOT NULL,
- [content] NVARCHAR(MAX),
- [author] NVARCHAR(100),
- [created_date] DATETIME2,
- [metadata] NVARCHAR(500)
-);
-
-CREATE TABLE [special].[translations] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [document_id] INT NOT NULL,
- [lang_code] NVARCHAR(10) NOT NULL,
- [translated_title] NVARCHAR(200),
- [translated_content] NVARCHAR(MAX),
- CONSTRAINT [fk_translations_doc] FOREIGN KEY ([document_id]) REFERENCES [special].[documents]([id])
-);
-`,
- migrationDDL: `
--- Add table comments with special characters and quotes
-EXEC sp_addextendedproperty 'MS_Description', 'Document storage system - handles files, "metadata", & special chars: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'documents';
-GO
-
--- Add multiline comment with special formatting
-EXEC sp_addextendedproperty 'MS_Description',
-'Translation table for international support:
-- Supports Unicode characters: αβγδε, 中文, العربية, русский
-- Handles quotes: "double quotes" and ''single quotes''
-- Special symbols: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'translations';
-GO
-
--- Column comments with various special cases
-EXEC sp_addextendedproperty 'MS_Description', 'Primary key (auto-increment) - unique ID for each document', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Document title - may contain "quotes", ''apostrophes'', and symbols: @#$%', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';
-GO
-
--- Multiline comment with technical details
-EXEC sp_addextendedproperty 'MS_Description',
-'Document content field:
- • Supports rich text formatting
- • HTML tags like <p>, <div>, <span>
- • Special characters: © ® ™ § ¶ † ‡ • ‰ ′ ″
- • Mathematical: ± × ÷ ≠ ≤ ≥ ∞ ∑ ∏ ∫
- • Currency: $ € £ ¥ ₹ ₽
- • Arrows: ← → ↑ ↓ ↔ ⇐ ⇒ ⇔', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';
-GO
-
--- Comment with SQL injection attempt (should be safely handled)
-EXEC sp_addextendedproperty 'MS_Description', 'Author name field - prevents SQL injection like ''; DROP TABLE users; --', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';
-GO
-
--- Comment with JSON-like structure
-EXEC sp_addextendedproperty 'MS_Description', 'Metadata JSON: {"version": "1.0", "tags": ["important", "draft"], "settings": {"public": false}}', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';
-GO
-
--- Unicode characters in comments
-EXEC sp_addextendedproperty 'MS_Description', 'Language code: en-US, fr-FR, de-DE, ja-JP, zh-CN, ar-SA, ru-RU, hi-IN, 한국어, ไทย', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';
-GO
-
--- Comment with URLs and file paths
-EXEC sp_addextendedproperty 'MS_Description', 'Translated content - may reference URLs like https://example.com/path?param=value&other=123 or file paths C:\Users\Name\Documents\file.txt', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';
-GO
-
--- Create new table with extreme comment case
-CREATE TABLE [special].[test_extreme] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [data] NVARCHAR(MAX)
-);
-GO
-
--- Extremely long comment to test limits
-EXEC sp_addextendedproperty 'MS_Description',
-'This is an extremely long comment designed to test the limits of extended property storage in SQL Server. It contains multiple lines of text with various formatting, special characters, and technical information. The purpose is to verify that the migration system can properly handle, store, and retrieve complex comment data without truncation or corruption. This comment includes: numbers (123456789), symbols (!@#$%^&*()_+-={}[]|\:";''<>?,./ ), Unicode characters (αβγδε中文العربيةрусский한국어), and structured data like JSON {"key": "value", "array": [1, 2, 3], "nested": {"deep": true}}. Additionally, it tests SQL-like syntax: SELECT * FROM table WHERE column = ''value'' AND other_column IN (1, 2, 3); as well as HTML markup: <html><body><p class="test">Content</p></body></html> and XML: <?xml version="1.0"?><root><item id="1">Test</item></root>. The comment system should preserve all these characters and structures exactly as written, demonstrating robust handling of complex metadata in database schema documentation.', 'SCHEMA', 'special', 'TABLE', 'test_extreme';
-`,
- description: "Comments with special characters, quotes, multiline text, and Unicode",
- },
- {
- name: "default_constraint_operations",
- initialSchema: `
-CREATE SCHEMA [defaults];
-GO
-
-CREATE TABLE [defaults].[employees] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [hire_date] DATE NOT NULL DEFAULT GETDATE(),
- [status] NVARCHAR(20) NOT NULL DEFAULT 'active',
- [is_active] BIT NOT NULL DEFAULT 1,
- [salary] DECIMAL(10,2) DEFAULT 50000.00,
- [department_id] INT DEFAULT 1,
- [created_at] DATETIME2 DEFAULT SYSDATETIME(),
- [updated_at] DATETIME2
-);
-
-CREATE TABLE [defaults].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- [stock] INT NOT NULL DEFAULT 0,
- [is_available] BIT DEFAULT 1
-);
-`,
- migrationDDL: `
--- Add column with default
-ALTER TABLE [defaults].[employees] ADD [vacation_days] INT NOT NULL DEFAULT 15;
-
--- Remove default constraint (by adding new column without default)
-ALTER TABLE [defaults].[products] ADD [cost] DECIMAL(10,2) NOT NULL;
-
--- Modify existing default value
--- First drop the existing constraint
-DECLARE @constraint_name NVARCHAR(256);
-SELECT @constraint_name = dc.name
-FROM sys.default_constraints dc
-JOIN sys.columns c ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id
-WHERE OBJECT_NAME(dc.parent_object_id) = 'employees'
-AND c.name = 'status'
-AND OBJECT_SCHEMA_NAME(dc.parent_object_id) = 'defaults';
-IF @constraint_name IS NOT NULL
- EXEC('ALTER TABLE [defaults].[employees] DROP CONSTRAINT [' + @constraint_name + ']');
-GO
-
--- Add new default
-ALTER TABLE [defaults].[employees] ADD CONSTRAINT [DF_employees_status_new] DEFAULT 'pending' FOR [status];
-
--- Add default with expression
-ALTER TABLE [defaults].[employees] ADD [bonus_percentage] DECIMAL(5,2) DEFAULT (CASE WHEN MONTH(GETDATE()) = 12 THEN 10.0 ELSE 5.0 END);
-
--- Create new table with various defaults
-CREATE TABLE [defaults].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [order_number] NVARCHAR(50) NOT NULL DEFAULT CONCAT('ORD-', YEAR(GETDATE()), '-', FORMAT(GETDATE(), 'MMdd')),
- [order_date] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
- [status] NVARCHAR(20) NOT NULL DEFAULT 'pending',
- [total] DECIMAL(10,2) NOT NULL DEFAULT 0,
- [discount] DECIMAL(5,2) DEFAULT NULL,
- [is_paid] BIT NOT NULL DEFAULT 0,
- [notes] NVARCHAR(MAX) DEFAULT 'No notes'
-);
-`,
- description: "Default constraint operations including add, remove, modify with various data types and expressions",
- },
- {
- name: "complex_default_expressions",
- initialSchema: `
-CREATE SCHEMA [complex];
-GO
-
-CREATE TABLE [complex].[audit_log] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [event_type] NVARCHAR(50) NOT NULL,
- [user_name] NVARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,
- [event_time] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
- [ip_address] NVARCHAR(45),
- [session_id] UNIQUEIDENTIFIER DEFAULT NEWID()
-);
-
-CREATE TABLE [complex].[documents] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [title] NVARCHAR(200) NOT NULL,
- [content] NVARCHAR(MAX),
- [version] INT NOT NULL DEFAULT 1,
- [created_date] DATE DEFAULT CAST(GETDATE() AS DATE),
- [expiry_date] DATE DEFAULT DATEADD(YEAR, 1, CAST(GETDATE() AS DATE))
-);
-`,
- migrationDDL: `
--- Add columns with complex default expressions
-ALTER TABLE [complex].[audit_log] ADD [server_name] NVARCHAR(100) DEFAULT @@SERVERNAME;
-ALTER TABLE [complex].[audit_log] ADD [database_name] NVARCHAR(100) DEFAULT DB_NAME();
-ALTER TABLE [complex].[audit_log] ADD [schema_name] NVARCHAR(100) DEFAULT SCHEMA_NAME();
-
--- Add computed default based on other columns
-ALTER TABLE [complex].[documents] ADD [document_code] NVARCHAR(50) DEFAULT CONCAT('DOC-', FORMAT(GETDATE(), 'yyyyMMdd'), '-', NEWID());
-
--- Create table with function-based defaults
-CREATE TABLE [complex].[calculations] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [value1] DECIMAL(10,2) NOT NULL,
- [value2] DECIMAL(10,2) NOT NULL,
- [pi_value] DECIMAL(10,8) DEFAULT PI(),
- [random_value] FLOAT DEFAULT RAND(),
- [checksum_value] INT DEFAULT CHECKSUM(NEWID()),
- [created_at] DATETIME2 DEFAULT SYSDATETIME(),
- [created_offset] DATETIMEOFFSET DEFAULT SYSDATETIMEOFFSET()
-);
-
--- Add default with CASE expression
-ALTER TABLE [complex].[documents] ADD [priority] INT DEFAULT
- CASE
- WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 1
- WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 2
- ELSE 3
- END;
-`,
- description: "Complex default expressions using system functions, variables, and conditional logic",
- },
- {
- name: "default_constraint_edge_cases",
- initialSchema: `
-CREATE SCHEMA [edge];
-GO
-
-CREATE TABLE [edge].[test_defaults] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [nullable_with_default] INT DEFAULT 42,
- [string_default] NVARCHAR(50) DEFAULT N'Default''s value',
- [empty_string] NVARCHAR(50) DEFAULT '',
- [zero_default] INT DEFAULT 0,
- [negative_default] INT DEFAULT -1,
- [decimal_precision] DECIMAL(18,6) DEFAULT 123.456789
-);
-`,
- migrationDDL: `
--- Test dropping and re-adding defaults with different names
-DECLARE @constraint_name NVARCHAR(256);
--- Drop nullable_with_default's constraint
-SELECT @constraint_name = dc.name
-FROM sys.default_constraints dc
-JOIN sys.columns c ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id
-WHERE OBJECT_NAME(dc.parent_object_id) = 'test_defaults'
-AND c.name = 'nullable_with_default'
-AND OBJECT_SCHEMA_NAME(dc.parent_object_id) = 'edge';
-IF @constraint_name IS NOT NULL
- EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name + ']');
-GO
-
--- Add it back with a new value
-ALTER TABLE [edge].[test_defaults] ADD CONSTRAINT [DF_test_defaults_nullable_new] DEFAULT 84 FOR [nullable_with_default];
-
--- Add column with special characters in default
-ALTER TABLE [edge].[test_defaults] ADD [special_chars] NVARCHAR(100) DEFAULT N'Line1' + CHAR(13) + CHAR(10) + N'Line2';
-
--- Add column with unicode default
-ALTER TABLE [edge].[test_defaults] ADD [unicode_default] NVARCHAR(100) DEFAULT N'你好世界 🌍';
-
--- Add column with max value defaults
-ALTER TABLE [edge].[test_defaults] ADD [max_int] BIGINT DEFAULT 9223372036854775807;
-ALTER TABLE [edge].[test_defaults] ADD [min_int] BIGINT DEFAULT -9223372036854775808;
-
--- Create table with bit field defaults
-CREATE TABLE [edge].[flags] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [is_enabled] BIT NOT NULL DEFAULT 1,
- [is_deleted] BIT NOT NULL DEFAULT 0,
- [is_visible] BIT DEFAULT 1,
- [is_archived] BIT DEFAULT 0
-);
-
--- Add JSON default (for NVARCHAR storing JSON)
-ALTER TABLE [edge].[test_defaults] ADD [json_config] NVARCHAR(MAX) DEFAULT N'{"enabled": true, "count": 0}';
-`,
- description: "Edge cases for default constraints including special characters, unicode, extreme values",
- },
- {
- name: "reverse_basic_table_operations",
- initialSchema: `
-CREATE SCHEMA [app];
-GO
-
-CREATE TABLE [app].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [created_at] DATETIME2,
- [status] NVARCHAR(20),
- CONSTRAINT [uk_users_email] UNIQUE ([email]),
- CONSTRAINT [ck_users_status] CHECK ([status] IN ('active', 'inactive', 'suspended'))
-);
-
-CREATE INDEX [idx_users_username] ON [app].[users] ([username]);
-
-CREATE TABLE [app].[posts] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [title] NVARCHAR(200) NOT NULL,
- [content] NTEXT,
- [published_at] DATETIME2,
- CONSTRAINT [fk_posts_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]) ON DELETE CASCADE
-);
-
-CREATE INDEX [idx_posts_user_id] ON [app].[posts] ([user_id]);
-
-CREATE TABLE [app].[comments] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [post_id] INT NOT NULL,
- [user_id] INT NOT NULL,
- [content] NTEXT NOT NULL,
- [created_at] DATETIME2,
- CONSTRAINT [fk_comments_post] FOREIGN KEY ([post_id]) REFERENCES [app].[posts]([id]) ON DELETE CASCADE,
- CONSTRAINT [fk_comments_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id])
-);
-
-CREATE INDEX [idx_comments_post_id] ON [app].[comments] ([post_id]);
-`,
- migrationDDL: `
--- Drop index
-DROP INDEX [idx_comments_post_id] ON [app].[comments];
-
--- Drop check constraint
-ALTER TABLE [app].[users] DROP CONSTRAINT [ck_users_status];
-
--- Drop table (must drop in correct order due to foreign keys)
-DROP TABLE [app].[comments];
-
--- Drop column
-ALTER TABLE [app].[users] DROP COLUMN [status];
-`,
- description: "Reverse of basic table operations - dropping column, table, index, and constraint",
- },
- {
- name: "reverse_schema_operations",
- initialSchema: `
-CREATE SCHEMA [sales];
-GO
-
-CREATE SCHEMA [inventory];
-GO
-
-CREATE TABLE [sales].[customers] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [email] NVARCHAR(100)
-);
-
-CREATE TABLE [sales].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [customer_id] INT NOT NULL,
- [order_date] DATE,
- [total] DECIMAL(10,2),
- [product_id] INT,
- CONSTRAINT [fk_orders_customer] FOREIGN KEY ([customer_id]) REFERENCES [sales].[customers]([id])
-);
-
-CREATE TABLE [inventory].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [category_id] INT,
- CONSTRAINT [ck_products_price] CHECK ([price] > 0)
-);
-
-ALTER TABLE [sales].[orders] ADD CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [inventory].[products]([id]);
-`,
- migrationDDL: `
--- Drop foreign key referencing table in different schema
-ALTER TABLE [sales].[orders] DROP CONSTRAINT [fk_orders_product];
-
--- Drop column referencing another schema
-ALTER TABLE [sales].[orders] DROP COLUMN [product_id];
-
--- Drop table in inventory schema
-DROP TABLE [inventory].[products];
-
--- Drop the inventory schema
-DROP SCHEMA [inventory];
-`,
- description: "Reverse of schema operations - dropping cross-schema foreign key, table, and schema",
- },
- {
- name: "reverse_view_operations",
- initialSchema: `
-CREATE SCHEMA [reporting];
-GO
-
-CREATE TABLE [reporting].[sales_data] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [product_name] NVARCHAR(100) NOT NULL,
- [quantity] INT NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [sale_date] DATE
-);
-
-CREATE TABLE [reporting].[customers] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [region] NVARCHAR(50)
-);
-GO
-
-CREATE VIEW [reporting].[product_summary] AS
-SELECT
- [product_name],
- COUNT(*) as [sale_count],
- SUM([quantity]) as [total_quantity],
- AVG([price]) as [avg_price]
-FROM [reporting].[sales_data]
-GROUP BY [product_name];
-GO
-
-CREATE VIEW [reporting].[top_products] AS
-SELECT TOP 10
- [product_name],
- [total_quantity]
-FROM [reporting].[product_summary]
-WHERE [total_quantity] > 100
-ORDER BY [total_quantity] DESC;
-GO
-`,
- migrationDDL: `
--- Drop dependent view first
-DROP VIEW [reporting].[top_products];
-GO
-
--- Drop base view
-DROP VIEW [reporting].[product_summary];
-GO
-`,
- description: "Reverse of view operations - dropping views in correct dependency order",
- },
- {
- name: "reverse_function_and_procedure_operations",
- initialSchema: `
-CREATE SCHEMA [calc];
-GO
-
-CREATE TABLE [calc].[numbers] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [value] INT NOT NULL,
- [category] NVARCHAR(20)
-);
-GO
-
-CREATE FUNCTION [calc].[square](@input INT)
-RETURNS INT
-AS
-BEGIN
- RETURN @input * @input;
-END;
-GO
-
-CREATE FUNCTION [calc].[get_numbers_by_category](@category NVARCHAR(20))
-RETURNS TABLE
-AS
-RETURN (
- SELECT [id], [value], [category]
- FROM [calc].[numbers]
- WHERE [category] = @category
-);
-GO
-
-CREATE PROCEDURE [calc].[add_number]
- @value INT,
- @category NVARCHAR(20)
-AS
-BEGIN
- INSERT INTO [calc].[numbers] ([value], [category])
- VALUES (@value, @category);
-END;
-GO
-`,
- migrationDDL: `
--- Drop stored procedure
-DROP PROCEDURE [calc].[add_number];
-GO
-
--- Drop table-valued function
-DROP FUNCTION [calc].[get_numbers_by_category];
-GO
-
--- Drop scalar function
-DROP FUNCTION [calc].[square];
-GO
-`,
- description: "Reverse of function and procedure operations - dropping procedures and functions",
- },
- {
- name: "reverse_index_operations",
- initialSchema: `
-CREATE SCHEMA [perf];
-GO
-
-CREATE TABLE [perf].[events] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [event_name] NVARCHAR(100) NOT NULL,
- [event_data] NVARCHAR(MAX),
- [timestamp] DATETIME2,
- [user_id] INT,
- [category] NVARCHAR(50),
- [event_month] AS DATEPART(MONTH, [timestamp])
-);
-
-CREATE INDEX [idx_events_timestamp] ON [perf].[events] ([timestamp]);
-CREATE INDEX [idx_events_user_category] ON [perf].[events] ([user_id], [category]);
-CREATE UNIQUE INDEX [idx_events_name_timestamp] ON [perf].[events] ([event_name], [timestamp]);
-
-CREATE INDEX [idx_events_recent] ON [perf].[events] ([event_name])
-WHERE [timestamp] >= '2023-01-01';
-
-CREATE INDEX [idx_events_month] ON [perf].[events] ([event_month]);
-`,
- migrationDDL: `
--- Drop index on computed column
-DROP INDEX [idx_events_month] ON [perf].[events];
-
--- Drop computed column
-ALTER TABLE [perf].[events] DROP COLUMN [event_month];
-
--- Drop filtered index
-DROP INDEX [idx_events_recent] ON [perf].[events];
-
--- Drop unique index
-DROP INDEX [idx_events_name_timestamp] ON [perf].[events];
-
--- Drop composite index
-DROP INDEX [idx_events_user_category] ON [perf].[events];
-
--- Drop simple index
-DROP INDEX [idx_events_timestamp] ON [perf].[events];
-`,
- description: "Reverse of index operations - dropping various index types including filtered and computed column indexes",
- },
- {
- name: "reverse_complex_constraints",
- initialSchema: `
-CREATE SCHEMA [finance];
-GO
-
-CREATE TABLE [finance].[accounts] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [account_number] NVARCHAR(20) NOT NULL,
- [balance] DECIMAL(15,2),
- [account_type] NVARCHAR(20) NOT NULL,
- [created_at] DATETIME2 DEFAULT GETDATE(),
- CONSTRAINT [ck_accounts_balance] CHECK ([balance] >= 0),
- CONSTRAINT [ck_accounts_type] CHECK ([account_type] IN ('CHECKING', 'SAVINGS', 'CREDIT')),
- CONSTRAINT [uk_accounts_number] UNIQUE ([account_number])
-);
-
-CREATE TABLE [finance].[transactions] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [account_id] INT NOT NULL,
- [amount] DECIMAL(15,2) NOT NULL,
- [transaction_type] NVARCHAR(20) NOT NULL,
- [transaction_date] DATETIME2,
- CONSTRAINT [fk_transactions_account] FOREIGN KEY ([account_id]) REFERENCES [finance].[accounts]([id]),
- CONSTRAINT [ck_transactions_amount] CHECK ([amount] != 0),
- CONSTRAINT [ck_transactions_type] CHECK ([transaction_type] IN ('DEBIT', 'CREDIT'))
-);
-`,
- migrationDDL: `
--- Drop table with foreign key and check constraints
-DROP TABLE [finance].[transactions];
-
--- Drop unique constraint
-ALTER TABLE [finance].[accounts] DROP CONSTRAINT [uk_accounts_number];
-
--- Drop check constraints
-ALTER TABLE [finance].[accounts] DROP CONSTRAINT [ck_accounts_type];
-ALTER TABLE [finance].[accounts] DROP CONSTRAINT [ck_accounts_balance];
-`,
- description: "Reverse of complex constraints - dropping tables with foreign keys and removing constraints",
- },
- {
- name: "reverse_column_modifications",
- initialSchema: `
-CREATE SCHEMA [hr];
-GO
-
-CREATE TABLE [hr].[departments] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [budget] DECIMAL(15,2)
-);
-
-CREATE TABLE [hr].[employees] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [first_name] NVARCHAR(50),
- [last_name] NVARCHAR(50),
- [email] NVARCHAR(100),
- [phone] VARCHAR(20),
- [hire_date] DATE,
- [salary] DECIMAL(10,2),
- [department_id] INT,
- [manager_id] INT,
- [status] NVARCHAR(20),
- CONSTRAINT [fk_employees_department] FOREIGN KEY ([department_id]) REFERENCES [hr].[departments]([id]),
- CONSTRAINT [fk_employees_manager] FOREIGN KEY ([manager_id]) REFERENCES [hr].[employees]([id]),
- CONSTRAINT [ck_employees_salary] CHECK ([salary] > 0),
- CONSTRAINT [ck_employees_status] CHECK ([status] IN ('ACTIVE', 'INACTIVE', 'TERMINATED'))
-);
-`,
- migrationDDL: `
--- Drop check constraints first
-ALTER TABLE [hr].[employees] DROP CONSTRAINT [ck_employees_status];
-ALTER TABLE [hr].[employees] DROP CONSTRAINT [ck_employees_salary];
-
--- Drop foreign key constraints before dropping columns
-ALTER TABLE [hr].[employees] DROP CONSTRAINT [fk_employees_manager];
-ALTER TABLE [hr].[employees] DROP CONSTRAINT [fk_employees_department];
-
--- Now safe to drop columns
-ALTER TABLE [hr].[employees] DROP COLUMN [status];
-ALTER TABLE [hr].[employees] DROP COLUMN [manager_id];
-ALTER TABLE [hr].[employees] DROP COLUMN [department_id];
-
--- Finally drop department table
-DROP TABLE [hr].[departments];
-`,
- description: "Reverse of column modifications - dropping columns, constraints, and related tables",
- },
- {
- name: "reverse_multiple_schema_dependencies",
- initialSchema: `
-CREATE SCHEMA [core];
-GO
-CREATE SCHEMA [app];
-GO
-
-CREATE TABLE [core].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL
-);
-
-CREATE TABLE [core].[roles] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(50) NOT NULL
-);
-
-CREATE TABLE [core].[user_roles] (
- [user_id] INT NOT NULL,
- [role_id] INT NOT NULL,
- [assigned_at] DATETIME2,
- CONSTRAINT [pk_user_roles] PRIMARY KEY ([user_id], [role_id]),
- CONSTRAINT [fk_user_roles_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE,
- CONSTRAINT [fk_user_roles_role] FOREIGN KEY ([role_id]) REFERENCES [core].[roles]([id]) ON DELETE CASCADE
-);
-
-CREATE TABLE [app].[sessions] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [token] NVARCHAR(255) NOT NULL,
- [expires_at] DATETIME2 NOT NULL,
- CONSTRAINT [fk_sessions_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE
-);
-
-CREATE TABLE [app].[audit_log] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT,
- [action] NVARCHAR(100) NOT NULL,
- [timestamp] DATETIME2,
- [details] NVARCHAR(MAX),
- CONSTRAINT [fk_audit_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id])
-);
-`,
- migrationDDL: `
--- Drop tables that reference core schema
-DROP TABLE [app].[audit_log];
-DROP TABLE [app].[sessions];
-
--- Drop junction table
-DROP TABLE [core].[user_roles];
-`,
- description: "Reverse of multiple schema dependencies - dropping cross-schema references",
- },
- {
- name: "reverse_computed_columns_and_triggers",
- initialSchema: `
-CREATE SCHEMA [ecommerce];
-GO
-
-CREATE TABLE [ecommerce].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [tax_rate] DECIMAL(5,4),
- [price_with_tax] AS ([price] * (1 + [tax_rate])),
- [price_category] AS (
- CASE
- WHEN [price] < 10 THEN 'Budget'
- WHEN [price] < 100 THEN 'Standard'
- ELSE 'Premium'
- END
- )
-);
-GO
-
-CREATE INDEX [idx_products_price_category] ON [ecommerce].[products] ([price_category]);
-CREATE INDEX [idx_products_price_with_tax] ON [ecommerce].[products] ([price_with_tax]);
-
-CREATE TABLE [ecommerce].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [product_id] INT NOT NULL,
- [quantity] INT NOT NULL,
- [unit_price] DECIMAL(10,2) NOT NULL,
- [total] DECIMAL(15,2),
- [order_date] DATETIME2,
- [computed_total] AS ([quantity] * [unit_price]),
- CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [ecommerce].[products]([id])
-);
-GO
-`,
- migrationDDL: `
--- Drop table with computed column
-DROP TABLE [ecommerce].[orders];
-GO
-
--- Drop indexes on computed columns
-DROP INDEX [idx_products_price_with_tax] ON [ecommerce].[products];
-DROP INDEX [idx_products_price_category] ON [ecommerce].[products];
-
--- Drop computed columns
-ALTER TABLE [ecommerce].[products] DROP COLUMN [price_category];
-GO
-
-ALTER TABLE [ecommerce].[products] DROP COLUMN [price_with_tax];
-GO
-`,
- description: "Reverse of computed columns - dropping indexes and computed columns",
- },
- {
- name: "reverse_temporal_tables",
- initialSchema: `
-CREATE SCHEMA [tracking];
-GO
-
-CREATE TABLE [tracking].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [last_modified] DATETIME2,
- [valid_from] DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
- [valid_to] DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
- PERIOD FOR SYSTEM_TIME ([valid_from], [valid_to])
-);
-
-CREATE TABLE [tracking].[products_history] (
- [id] INT NOT NULL,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [last_modified] DATETIME2,
- [valid_from] DATETIME2 NOT NULL,
- [valid_to] DATETIME2 NOT NULL
-);
-
-CREATE CLUSTERED INDEX [idx_products_history_period] ON [tracking].[products_history] ([valid_to], [valid_from]);
-
-ALTER TABLE [tracking].[products] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [tracking].[products_history]));
-`,
- migrationDDL: `
--- Disable system versioning first
-ALTER TABLE [tracking].[products] SET (SYSTEM_VERSIONING = OFF);
-
--- Drop history table (and its index will be dropped automatically)
-DROP TABLE [tracking].[products_history];
-
--- Drop period definition and system time columns
-ALTER TABLE [tracking].[products] DROP PERIOD FOR SYSTEM_TIME;
-ALTER TABLE [tracking].[products] DROP COLUMN [valid_to];
-ALTER TABLE [tracking].[products] DROP COLUMN [valid_from];
-`,
- description: "Reverse of temporal tables - disabling system versioning and dropping history",
- },
- {
- name: "reverse_table_and_column_comments",
- initialSchema: `
-CREATE SCHEMA [app];
-GO
-
-CREATE TABLE [app].[users] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [username] NVARCHAR(50) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [created_at] DATETIME2,
- [status] NVARCHAR(20)
-);
-
-CREATE TABLE [app].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL,
- [category] NVARCHAR(50)
-);
-
-CREATE INDEX [idx_users_email] ON [app].[users] ([email]);
-CREATE INDEX [idx_products_category] ON [app].[products] ([category]);
-
-CREATE TABLE [app].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [user_id] INT NOT NULL,
- [product_id] INT NOT NULL,
- [quantity] INT NOT NULL,
- [order_date] DATETIME2,
- CONSTRAINT [fk_orders_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]),
- CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [app].[products]([id])
-);
-GO
-
--- Add table comments using extended properties
-EXEC sp_addextendedproperty 'MS_Description', 'User accounts and profile information', 'SCHEMA', 'app', 'TABLE', 'users';
-EXEC sp_addextendedproperty 'MS_Description', 'Product catalog with pricing information', 'SCHEMA', 'app', 'TABLE', 'products';
-EXEC sp_addextendedproperty 'MS_Description', 'Customer orders tracking system', 'SCHEMA', 'app', 'TABLE', 'orders';
-GO
-
--- Add column comments for users table
-EXEC sp_addextendedproperty 'MS_Description', 'Unique identifier for each user', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Unique username for login authentication', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';
-EXEC sp_addextendedproperty 'MS_Description', 'User email address for notifications', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';
-EXEC sp_addextendedproperty 'MS_Description', 'Timestamp when the user account was created', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';
-EXEC sp_addextendedproperty 'MS_Description', 'Current status: active, inactive, or suspended', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';
-GO
-
--- Add column comments for products table
-EXEC sp_addextendedproperty 'MS_Description', 'Unique product identifier', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Product display name', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';
-EXEC sp_addextendedproperty 'MS_Description', 'Product price in USD', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';
-EXEC sp_addextendedproperty 'MS_Description', 'Product category classification', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';
-GO
-
--- Add comments to orders table
-EXEC sp_addextendedproperty 'MS_Description', 'Unique order identifier', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Reference to the user who placed the order', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';
-EXEC sp_addextendedproperty 'MS_Description', 'Reference to the ordered product', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';
-EXEC sp_addextendedproperty 'MS_Description', 'Number of items ordered', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';
-EXEC sp_addextendedproperty 'MS_Description', 'When the order was placed', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';
-`,
- migrationDDL: `
--- Drop column comments from orders table
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';
-GO
-
--- Drop table comment from orders
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders';
-GO
-
--- Drop the orders table
-DROP TABLE [app].[orders];
-GO
-
--- Drop column comments from products table
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';
-GO
-
--- Drop column comments from users table
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';
-GO
-
--- Drop table comments
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users';
-`,
- description: "Reverse of table and column comments - dropping extended properties",
- },
- {
- name: "reverse_default_constraint_operations",
- initialSchema: `
-CREATE SCHEMA [defaults];
-GO
-
-CREATE TABLE [defaults].[employees] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [email] NVARCHAR(100) NOT NULL,
- [hire_date] DATE NOT NULL DEFAULT GETDATE(),
- [status] NVARCHAR(20) NOT NULL CONSTRAINT [DF_employees_status_new] DEFAULT 'pending',
- [is_active] BIT NOT NULL DEFAULT 1,
- [salary] DECIMAL(10,2) DEFAULT 50000.00,
- [department_id] INT DEFAULT 1,
- [created_at] DATETIME2 DEFAULT SYSDATETIME(),
- [updated_at] DATETIME2,
- [vacation_days] INT NOT NULL DEFAULT 15,
- [bonus_percentage] DECIMAL(5,2) DEFAULT (CASE WHEN MONTH(GETDATE()) = 12 THEN 10.0 ELSE 5.0 END)
-);
-
-CREATE TABLE [defaults].[products] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- [stock] INT NOT NULL DEFAULT 0,
- [is_available] BIT DEFAULT 1,
- [cost] DECIMAL(10,2) NOT NULL
-);
-
-CREATE TABLE [defaults].[orders] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [order_number] NVARCHAR(50) NOT NULL DEFAULT CONCAT('ORD-', YEAR(GETDATE()), '-', FORMAT(GETDATE(), 'MMdd')),
- [order_date] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
- [status] NVARCHAR(20) NOT NULL DEFAULT 'pending',
- [total] DECIMAL(10,2) NOT NULL DEFAULT 0,
- [discount] DECIMAL(5,2) DEFAULT NULL,
- [is_paid] BIT NOT NULL DEFAULT 0,
- [notes] NVARCHAR(MAX) DEFAULT 'No notes'
-);
-`,
- migrationDDL: `
--- Drop orders table with all its defaults
-DROP TABLE [defaults].[orders];
-GO
-
--- Drop default constraint for bonus_percentage column
-DECLARE @constraint_name NVARCHAR(128);
-SELECT @constraint_name = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'defaults' AND t.name = 'employees' AND c.name = 'bonus_percentage';
-IF @constraint_name IS NOT NULL
- EXEC('ALTER TABLE [defaults].[employees] DROP CONSTRAINT [' + @constraint_name + ']');
-GO
-
--- Drop default constraint for vacation_days column
-DECLARE @constraint_name2 NVARCHAR(128);
-SELECT @constraint_name2 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'defaults' AND t.name = 'employees' AND c.name = 'vacation_days';
-IF @constraint_name2 IS NOT NULL
- EXEC('ALTER TABLE [defaults].[employees] DROP CONSTRAINT [' + @constraint_name2 + ']');
-GO
-
--- Now safe to drop columns
-ALTER TABLE [defaults].[employees] DROP COLUMN [bonus_percentage];
-ALTER TABLE [defaults].[employees] DROP COLUMN [vacation_days];
-
--- Remove default from status column (named constraint)
-ALTER TABLE [defaults].[employees] DROP CONSTRAINT [DF_employees_status_new];
-
--- Drop cost column (which has no default)
-ALTER TABLE [defaults].[products] DROP COLUMN [cost];
-`,
- description: "Reverse of default constraint operations - dropping tables, columns with defaults, and default constraints",
- },
- {
- name: "reverse_complex_default_expressions",
- initialSchema: `
-CREATE SCHEMA [complex];
-GO
-
-CREATE TABLE [complex].[audit_log] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [event_type] NVARCHAR(50) NOT NULL,
- [user_name] NVARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,
- [event_time] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
- [ip_address] NVARCHAR(45),
- [session_id] UNIQUEIDENTIFIER DEFAULT NEWID(),
- [server_name] NVARCHAR(100) DEFAULT @@SERVERNAME,
- [database_name] NVARCHAR(100) DEFAULT DB_NAME(),
- [schema_name] NVARCHAR(100) DEFAULT SCHEMA_NAME()
-);
-
-CREATE TABLE [complex].[documents] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [title] NVARCHAR(200) NOT NULL,
- [content] NVARCHAR(MAX),
- [version] INT NOT NULL DEFAULT 1,
- [created_date] DATE DEFAULT CAST(GETDATE() AS DATE),
- [expiry_date] DATE DEFAULT DATEADD(YEAR, 1, CAST(GETDATE() AS DATE)),
- [document_code] NVARCHAR(50) DEFAULT CONCAT('DOC-', FORMAT(GETDATE(), 'yyyyMMdd'), '-', NEWID()),
- [priority] INT DEFAULT
- CASE
- WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 1
- WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 2
- ELSE 3
- END
-);
-
-CREATE TABLE [complex].[calculations] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [value1] DECIMAL(10,2) NOT NULL,
- [value2] DECIMAL(10,2) NOT NULL,
- [pi_value] DECIMAL(10,8) DEFAULT PI(),
- [random_value] FLOAT DEFAULT RAND(),
- [checksum_value] INT DEFAULT CHECKSUM(NEWID()),
- [created_at] DATETIME2 DEFAULT SYSDATETIME(),
- [created_offset] DATETIMEOFFSET DEFAULT SYSDATETIMEOFFSET()
-);
-`,
- migrationDDL: `
--- Drop table with function-based defaults
-DROP TABLE [complex].[calculations];
-GO
-
--- Drop default constraint for priority column
-DECLARE @constraint_name NVARCHAR(128);
-SELECT @constraint_name = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'complex' AND t.name = 'documents' AND c.name = 'priority';
-IF @constraint_name IS NOT NULL
- EXEC('ALTER TABLE [complex].[documents] DROP CONSTRAINT [' + @constraint_name + ']');
-GO
-
--- Drop default constraint for document_code column
-DECLARE @constraint_name2 NVARCHAR(128);
-SELECT @constraint_name2 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'complex' AND t.name = 'documents' AND c.name = 'document_code';
-IF @constraint_name2 IS NOT NULL
- EXEC('ALTER TABLE [complex].[documents] DROP CONSTRAINT [' + @constraint_name2 + ']');
-GO
-
--- Drop default constraint for schema_name column
-DECLARE @constraint_name3 NVARCHAR(128);
-SELECT @constraint_name3 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'complex' AND t.name = 'audit_log' AND c.name = 'schema_name';
-IF @constraint_name3 IS NOT NULL
- EXEC('ALTER TABLE [complex].[audit_log] DROP CONSTRAINT [' + @constraint_name3 + ']');
-GO
-
--- Drop default constraint for database_name column
-DECLARE @constraint_name4 NVARCHAR(128);
-SELECT @constraint_name4 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'complex' AND t.name = 'audit_log' AND c.name = 'database_name';
-IF @constraint_name4 IS NOT NULL
- EXEC('ALTER TABLE [complex].[audit_log] DROP CONSTRAINT [' + @constraint_name4 + ']');
-GO
-
--- Drop default constraint for server_name column
-DECLARE @constraint_name5 NVARCHAR(128);
-SELECT @constraint_name5 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'complex' AND t.name = 'audit_log' AND c.name = 'server_name';
-IF @constraint_name5 IS NOT NULL
- EXEC('ALTER TABLE [complex].[audit_log] DROP CONSTRAINT [' + @constraint_name5 + ']');
-GO
-
--- Now safe to drop columns
-ALTER TABLE [complex].[documents] DROP COLUMN [priority];
-ALTER TABLE [complex].[documents] DROP COLUMN [document_code];
-ALTER TABLE [complex].[audit_log] DROP COLUMN [schema_name];
-ALTER TABLE [complex].[audit_log] DROP COLUMN [database_name];
-ALTER TABLE [complex].[audit_log] DROP COLUMN [server_name];
-`,
- description: "Reverse of complex default expressions - dropping columns with system functions and conditional defaults",
- },
- {
- name: "reverse_comments_with_special_characters",
- initialSchema: `
-CREATE SCHEMA [special];
-GO
-
-CREATE TABLE [special].[documents] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [title] NVARCHAR(200) NOT NULL,
- [content] NVARCHAR(MAX),
- [author] NVARCHAR(100),
- [created_date] DATETIME2,
- [metadata] NVARCHAR(500)
-);
-
-CREATE TABLE [special].[translations] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [document_id] INT NOT NULL,
- [lang_code] NVARCHAR(10) NOT NULL,
- [translated_title] NVARCHAR(200),
- [translated_content] NVARCHAR(MAX),
- CONSTRAINT [fk_translations_doc] FOREIGN KEY ([document_id]) REFERENCES [special].[documents]([id])
-);
-
-CREATE TABLE [special].[test_extreme] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [data] NVARCHAR(MAX)
-);
-GO
-
--- Add table comments with special characters and quotes
-EXEC sp_addextendedproperty 'MS_Description', 'Document storage system - handles files, "metadata", & special chars: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'documents';
-GO
-
--- Add multiline comment with special formatting
-EXEC sp_addextendedproperty 'MS_Description',
-'Translation table for international support:
-- Supports Unicode characters: αβγδε, 中文, العربية, русский
-- Handles quotes: "double quotes" and ''single quotes''
-- Special symbols: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'translations';
-GO
-
--- Column comments with various special cases
-EXEC sp_addextendedproperty 'MS_Description', 'Primary key (auto-increment) - unique ID for each document', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';
-EXEC sp_addextendedproperty 'MS_Description', 'Document title - may contain "quotes", ''apostrophes'', and symbols: @#$%', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';
-GO
-
--- Multiline comment with technical details
-EXEC sp_addextendedproperty 'MS_Description',
-'Document content field:
- • Supports rich text formatting
- • HTML tags like <p>, <div>, <span>
- • Special characters: © ® ™ § ¶ † ‡ • ‰ ′ ″
- • Mathematical: ± × ÷ ≠ ≤ ≥ ∞ ∑ ∏ ∫
- • Currency: $ € £ ¥ ₹ ₽
- • Arrows: ← → ↑ ↓ ↔ ⇐ ⇒ ⇔', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';
-GO
-
--- Comment with SQL injection attempt (should be safely handled)
-EXEC sp_addextendedproperty 'MS_Description', 'Author name field - prevents SQL injection like ''; DROP TABLE users; --', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';
-GO
-
--- Comment with JSON-like structure
-EXEC sp_addextendedproperty 'MS_Description', 'Metadata JSON: {"version": "1.0", "tags": ["important", "draft"], "settings": {"public": false}}', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';
-GO
-
--- Unicode characters in comments
-EXEC sp_addextendedproperty 'MS_Description', 'Language code: en-US, fr-FR, de-DE, ja-JP, zh-CN, ar-SA, ru-RU, hi-IN, 한국어, ไทย', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';
-GO
-
--- Comment with URLs and file paths
-EXEC sp_addextendedproperty 'MS_Description', 'Translated content - may reference URLs like https://example.com/path?param=value&other=123 or file paths C:\Users\Name\Documents\file.txt', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';
-GO
-
--- Extremely long comment to test limits
-EXEC sp_addextendedproperty 'MS_Description',
-'This is an extremely long comment designed to test the limits of extended property storage in SQL Server. It contains multiple lines of text with various formatting, special characters, and technical information. The purpose is to verify that the migration system can properly handle, store, and retrieve complex comment data without truncation or corruption. This comment includes: numbers (123456789), symbols (!@#$%^&*()_+-={}[]|\:";''<>?,./ ), Unicode characters (αβγδε中文العربيةрусский한국어), and structured data like JSON {"key": "value", "array": [1, 2, 3], "nested": {"deep": true}}. Additionally, it tests SQL-like syntax: SELECT * FROM table WHERE column = ''value'' AND other_column IN (1, 2, 3); as well as HTML markup: <html><body><p class="test">Content</p></body></html> and XML: <?xml version="1.0"?><root><item id="1">Test</item></root>. The comment system should preserve all these characters and structures exactly as written, demonstrating robust handling of complex metadata in database schema documentation.', 'SCHEMA', 'special', 'TABLE', 'test_extreme';
-`,
- migrationDDL: `
--- Drop extremely long comment
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'test_extreme';
-GO
-
--- Drop table with extreme comment
-DROP TABLE [special].[test_extreme];
-GO
-
--- Drop column comments with special characters
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';
-GO
-
--- Drop column comments from documents
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';
-GO
-
--- Drop table comments with special characters
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations';
-EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents';
-`,
- description: "Reverse of comments with special characters - dropping comments with quotes, unicode, and special formatting",
- },
- {
- name: "reverse_default_constraint_edge_cases",
- initialSchema: `
-CREATE SCHEMA [edge];
-GO
-
-CREATE TABLE [edge].[test_defaults] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [nullable_with_default] INT CONSTRAINT [DF_test_defaults_nullable_new] DEFAULT 84,
- [string_default] NVARCHAR(50) DEFAULT N'Default''s value',
- [empty_string] NVARCHAR(50) DEFAULT '',
- [zero_default] INT DEFAULT 0,
- [negative_default] INT DEFAULT -1,
- [decimal_precision] DECIMAL(18,6) DEFAULT 123.456789,
- [special_chars] NVARCHAR(100) DEFAULT N'Line1' + CHAR(13) + CHAR(10) + N'Line2',
- [unicode_default] NVARCHAR(100) DEFAULT N'你好世界 🌍',
- [max_int] BIGINT DEFAULT 9223372036854775807,
- [min_int] BIGINT DEFAULT -9223372036854775808,
- [json_config] NVARCHAR(MAX) DEFAULT N'{"enabled": true, "count": 0}'
-);
-
-CREATE TABLE [edge].[flags] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [is_enabled] BIT NOT NULL DEFAULT 1,
- [is_deleted] BIT NOT NULL DEFAULT 0,
- [is_visible] BIT DEFAULT 1,
- [is_archived] BIT DEFAULT 0
-);
-`,
- migrationDDL: `
--- Drop table with bit field defaults
-DROP TABLE [edge].[flags];
-
--- Drop default constraints before dropping columns
--- Drop default constraint for json_config column
-DECLARE @constraint_name NVARCHAR(128);
-SELECT @constraint_name = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'json_config';
-IF @constraint_name IS NOT NULL
- EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name + ']');
-GO
-
--- Drop default constraint for min_int column
-DECLARE @constraint_name2 NVARCHAR(128);
-SELECT @constraint_name2 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'min_int';
-IF @constraint_name2 IS NOT NULL
- EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name2 + ']');
-GO
-
--- Drop default constraint for max_int column
-DECLARE @constraint_name3 NVARCHAR(128);
-SELECT @constraint_name3 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'max_int';
-IF @constraint_name3 IS NOT NULL
- EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name3 + ']');
-GO
-
--- Drop default constraint for unicode_default column
-DECLARE @constraint_name4 NVARCHAR(128);
-SELECT @constraint_name4 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'unicode_default';
-IF @constraint_name4 IS NOT NULL
- EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name4 + ']');
-GO
-
--- Drop default constraint for special_chars column
-DECLARE @constraint_name5 NVARCHAR(128);
-SELECT @constraint_name5 = dc.name
-FROM sys.default_constraints dc
-INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id
-INNER JOIN sys.tables t ON c.object_id = t.object_id
-INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
-WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'special_chars';
-IF @constraint_name5 IS NOT NULL
- EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name5 + ']');
-GO
-
--- Now safe to drop columns
-ALTER TABLE [edge].[test_defaults] DROP COLUMN [json_config];
-ALTER TABLE [edge].[test_defaults] DROP COLUMN [min_int];
-ALTER TABLE [edge].[test_defaults] DROP COLUMN [max_int];
-ALTER TABLE [edge].[test_defaults] DROP COLUMN [unicode_default];
-ALTER TABLE [edge].[test_defaults] DROP COLUMN [special_chars];
-
--- Remove named default constraint
-ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [DF_test_defaults_nullable_new];
-`,
- description: "Reverse of edge case defaults - dropping special default constraints and columns",
- },
- {
- name: "spatial_index_operations",
- initialSchema: `
-CREATE SCHEMA [geo];
-GO
-
--- Enable spatial types
-CREATE TABLE [geo].[locations] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(200) NOT NULL,
- [geo_point] GEOMETRY NOT NULL,
- [geo_polygon] GEOMETRY NOT NULL,
- [geo_location] GEOGRAPHY NOT NULL,
- [description] NVARCHAR(MAX)
-);
-`,
- migrationDDL: `
--- Add spatial indexes with different configurations
-
--- GEOMETRY_GRID index with full parameters
-CREATE SPATIAL INDEX [idx_geo_point] ON [geo].[locations] ([geo_point])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-180, -90, 180, 90),
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 32,
- PAD_INDEX = ON,
- FILLFACTOR = 85,
- SORT_IN_TEMPDB = ON,
- ALLOW_ROW_LOCKS = ON,
- ALLOW_PAGE_LOCKS = ON,
- MAXDOP = 2,
- DATA_COMPRESSION = PAGE
-);
-
--- GEOMETRY_AUTO_GRID index (requires bounding box)
-CREATE SPATIAL INDEX [idx_geo_polygon] ON [geo].[locations] ([geo_polygon])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-1000, -1000, 1000, 1000),
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW)
-);
-
--- GEOGRAPHY_GRID index with specific grid levels
-CREATE SPATIAL INDEX [idx_geo_location] ON [geo].[locations] ([geo_location])
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 8,
- FILLFACTOR = 80
-);
-
--- Add another table with spatial columns
-CREATE TABLE [geo].[boundaries] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [boundary_name] NVARCHAR(100) NOT NULL,
- [boundary_shape] GEOMETRY NOT NULL,
- [center_point] GEOMETRY NOT NULL
-);
-
--- Add spatial index on new table
-CREATE SPATIAL INDEX [idx_boundary_shape] ON [geo].[boundaries] ([boundary_shape])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (0, 0, 1000, 1000),
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = LOW, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 64
-);
-`,
- description: "Spatial index operations with various tessellation schemes and parameters",
- },
- {
- name: "reverse_spatial_table_operations",
- initialSchema: `
-CREATE SCHEMA [geo];
-GO
-
--- Create table with spatial columns and indexes
-CREATE TABLE [geo].[locations] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(200) NOT NULL,
- [location] GEOGRAPHY NOT NULL,
- [area] GEOGRAPHY NOT NULL
-);
-GO
-
--- Create spatial indexes that will be dropped with the table
--- Using GEOGRAPHY_GRID which doesn't require BOUNDING_BOX
-CREATE SPATIAL INDEX [idx_location] ON [geo].[locations] ([location])
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 16
-);
-GO
-
-CREATE SPATIAL INDEX [idx_area] ON [geo].[locations] ([area])
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 8
-);
-GO
-
-CREATE TABLE [geo].[regions] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [region_name] NVARCHAR(100) NOT NULL,
- [boundary] GEOMETRY NOT NULL
-);
-GO
-`,
- migrationDDL: `
--- Drop entire table (this drops spatial indexes too)
-DROP TABLE [geo].[locations];
-
--- Add columns to remaining table
-ALTER TABLE [geo].[regions] ADD [population] INT;
-ALTER TABLE [geo].[regions] ADD [area_sqkm] FLOAT;
-`,
- description: "Reverse spatial table operations - dropping table with spatial indexes",
- },
- {
- name: "reverse_spatial_indexes",
- initialSchema: `
-CREATE SCHEMA [geo];
-GO
-
--- Create table with spatial columns and spatial indexes that can be preserved
-CREATE TABLE [geo].[locations] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(200) NOT NULL,
- [geo_point] GEOMETRY NOT NULL,
- [geo_polygon] GEOMETRY NOT NULL,
- [geo_location] GEOGRAPHY NOT NULL,
- [description] NVARCHAR(MAX)
-);
-GO
-
--- Create spatial indexes with basic configuration to avoid preservation issues
-CREATE SPATIAL INDEX [idx_geo_point] ON [geo].[locations] ([geo_point])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-180, -90, 180, 90),
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM)
-);
-GO
-
-CREATE SPATIAL INDEX [idx_geo_location] ON [geo].[locations] ([geo_location])
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM)
-);
-GO
-`,
- migrationDDL: `
--- Drop and recreate spatial indexes to test preservation
-DROP INDEX [idx_geo_point] ON [geo].[locations];
-DROP INDEX [idx_geo_location] ON [geo].[locations];
-
--- Recreate with same configuration (should work with DDL preservation)
-CREATE SPATIAL INDEX [idx_geo_point] ON [geo].[locations] ([geo_point])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-180, -90, 180, 90),
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM)
-);
-
-CREATE SPATIAL INDEX [idx_geo_location] ON [geo].[locations] ([geo_location])
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM)
-);
-`,
- description: "Reverse spatial index operations - dropping and recreating spatial indexes",
- },
- {
- name: "spatial_index_modifications",
- initialSchema: `
-CREATE SCHEMA [geo];
-GO
-
-CREATE TABLE [geo].[spatial_data] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [name] NVARCHAR(100) NOT NULL,
- [location] GEOMETRY NOT NULL,
- [region] GEOMETRY,
- [area] GEOGRAPHY
-);
-GO
-
--- Create initial spatial indexes
-CREATE SPATIAL INDEX [idx_location] ON [geo].[spatial_data] ([location])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-100, -100, 100, 100),
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 16
-);
-GO
-
-CREATE SPATIAL INDEX [idx_area] ON [geo].[spatial_data] ([area])
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 32
-);
-GO
-`,
- migrationDDL: `
--- Drop and recreate spatial index with different parameters
-DROP INDEX [idx_location] ON [geo].[spatial_data];
-GO
-
-CREATE SPATIAL INDEX [idx_location] ON [geo].[spatial_data] ([location])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-200, -200, 200, 200), -- Expanded bounding box
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW), -- Changed grid densities
- CELLS_PER_OBJECT = 64, -- Increased cells per object
- PAD_INDEX = ON,
- FILLFACTOR = 90,
- ALLOW_ROW_LOCKS = ON,
- ALLOW_PAGE_LOCKS = ON
-);
-GO
-
--- Add new spatial index on previously unindexed column
-CREATE SPATIAL INDEX [idx_region] ON [geo].[spatial_data] ([region])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-500, -500, 500, 500),
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 32
-);
-GO
-
--- Drop spatial index on geography column
-DROP INDEX [idx_area] ON [geo].[spatial_data];
-GO
-`,
- description: "Spatial index modifications - recreating with different parameters and adding/dropping indexes",
- },
- {
- name: "spatial_table_schema_changes",
- initialSchema: `
-CREATE SCHEMA [geo];
-GO
-
-CREATE TABLE [geo].[points] (
- [id] INT IDENTITY(1,1) PRIMARY KEY,
- [point_name] NVARCHAR(50) NOT NULL,
- [location] GEOMETRY NOT NULL
-);
-GO
-
-CREATE SPATIAL INDEX [idx_points_location] ON [geo].[points] ([location])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (0, 0, 100, 100),
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM)
-);
-GO
-`,
- migrationDDL: `
--- Add new spatial and non-spatial columns
-ALTER TABLE [geo].[points] ADD [altitude] FLOAT;
-ALTER TABLE [geo].[points] ADD [boundary] GEOMETRY;
-ALTER TABLE [geo].[points] ADD [geo_location] GEOGRAPHY;
-ALTER TABLE [geo].[points] ADD [created_at] DATETIME2 DEFAULT GETDATE();
-
--- Create spatial indexes on new columns
-CREATE SPATIAL INDEX [idx_points_boundary] ON [geo].[points] ([boundary])
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-50, -50, 150, 150),
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 8
-);
-GO
-
-CREATE SPATIAL INDEX [idx_points_geo_location] ON [geo].[points] ([geo_location])
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = HIGH, LEVEL_4 = HIGH),
- CELLS_PER_OBJECT = 16
-);
-GO
-
--- Modify existing column (rename)
-EXEC sp_rename '[geo].[points].[point_name]', 'name', 'COLUMN';
-GO
-`,
- description: "Spatial table schema changes - adding columns and indexes while preserving existing spatial indexes",
- },
- }
-
- // MSSQL Express in CI gets significantly slower when too many schema-heavy
- // subtests run at once against the same container. Keep bounded parallelism.
- const maxConcurrentSubtests = 4
- parallelGate := make(chan struct{}, maxConcurrentSubtests)
-
- for _, testCase := range testCases {
- t.Run(testCase.name, func(t *testing.T) {
- t.Parallel()
- parallelGate <- struct{}{}
- defer func() {
- <-parallelGate
- }()
-
- // Create test database with unique name
- testDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE [%s]", testDB))
- require.NoError(t, err, "failed to create test database")
-
- // Connect to test database
- driver, err := createMSSQLDriver(ctx, container.GetHost(), container.GetPort(), testDB)
- require.NoError(t, err, "failed to connect to test database")
- defer driver.Close(ctx)
-
- // Step 1: Initialize database schema and get schema result A
- err = executeSQL(ctx, driver, testCase.initialSchema)
- require.NoError(t, err, "failed to execute initial schema")
-
- schemaA, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err, "failed to sync schema A")
-
- // Step 2: Apply migration DDL and get schema result B
- err = executeSQL(ctx, driver, testCase.migrationDDL)
- require.NoError(t, err, "failed to execute migration DDL")
-
- schemaB, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err, "failed to sync schema B")
-
- // Step 3: Generate rollback DDL using generate_migration
- // Convert to model schemas for diff
- dbMetadataA := model.NewDatabaseMetadata(schemaA, nil, nil, storepb.Engine_MSSQL, false)
- dbMetadataB := model.NewDatabaseMetadata(schemaB, nil, nil, storepb.Engine_MSSQL, false)
-
- // Get diff from B to A (to generate rollback)
- diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_MSSQL, dbMetadataB, dbMetadataA)
- require.NoError(t, err, "failed to generate diff")
-
- rollbackDDL, err := schema.GenerateMigration(storepb.Engine_MSSQL, diff)
- require.NoError(t, err, "failed to generate rollback migration")
-
- // Only proceed if there's actual rollback DDL to execute
- if strings.TrimSpace(rollbackDDL) != "" {
- // Step 4: Execute rollback DDL and get schema result C
- err = executeSQL(ctx, driver, rollbackDDL)
- require.NoError(t, err, "failed to execute rollback DDL: %s", rollbackDDL)
-
- schemaC, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err, "failed to sync schema C")
-
- // Step 5: Compare schema results A and C
- err = compareSchemas(schemaA, schemaC)
- require.NoError(t, err, "schema comparison failed for test case: %s", testCase.description)
+ if record {
+ tests[i].Expected = migration
+ return
}
+ require.Equalf(t, test.Expected, migration, "Test case [%02d] failed: %s", i+1, test.Description)
})
}
-}
-
-// compareSchemas compares two database schemas and returns an error if they differ
-func compareSchemas(schemaA, schemaC *storepb.DatabaseSchemaMetadata) error {
- // Sort schemas for consistent comparison
- normalizeSchema(schemaA)
- normalizeSchema(schemaC)
-
- // Use protocmp for detailed comparison, ignoring DefaultConstraintName and Position fields
- // DefaultConstraintName is only populated when syncing from database, not when parsing SQL
- // Position must be ignored because:
- // - In SQL Server, column positions are determined by column_id (physical order)
- // - When a column is dropped and re-added, it gets a new column_id at the end
- // - Our migration generator uses DROP+ADD for column renames (doesn't use sp_rename)
- // - This causes legitimate position changes that don't affect functional equivalence
- // - Example: table with [id(1), name(2), email(3)] -> DROP name -> ADD name -> [id(1), email(3), name(4)]
- opts := cmp.Options{
- protocmp.Transform(),
- protocmp.IgnoreFields(&storepb.ColumnMetadata{}, "default_constraint_name", "position"),
- }
- if diff := cmp.Diff(schemaA, schemaC, opts); diff != "" {
- return errors.Errorf("schemas differ:\n%s", diff)
- }
-
- return nil
-}
-
-// normalizeSchema sorts elements within a schema for consistent comparison
-func normalizeSchema(schema *storepb.DatabaseSchemaMetadata) {
- if schema == nil {
- return
- }
-
- // Sort schemas
- slices.SortFunc(schema.Schemas, func(i, j *storepb.SchemaMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- for _, s := range schema.Schemas {
- // Sort tables
- slices.SortFunc(s.Tables, func(i, j *storepb.TableMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- // Sort views
- slices.SortFunc(s.Views, func(i, j *storepb.ViewMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- // Sort functions
- slices.SortFunc(s.Functions, func(i, j *storepb.FunctionMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- // Sort procedures
- slices.SortFunc(s.Procedures, func(i, j *storepb.ProcedureMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- // Sort table elements
- for _, table := range s.Tables {
- // Sort columns
- slices.SortFunc(table.Columns, func(i, j *storepb.ColumnMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- // Sort indexes
- slices.SortFunc(table.Indexes, func(i, j *storepb.IndexMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
- // Sort foreign keys
- slices.SortFunc(table.ForeignKeys, func(i, j *storepb.ForeignKeyMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- // Sort check constraints
- slices.SortFunc(table.CheckConstraints, func(i, j *storepb.CheckConstraintMetadata) int {
- return strings.Compare(i.Name, j.Name)
- })
-
- // Sort expressions within indexes
- for _, index := range table.Indexes {
- slices.Sort(index.Expressions)
- }
- }
+ if record {
+ yamltest.Record(t, filepath, tests)
}
}
diff --git a/backend/plugin/schema/mssql/get_database_definition_test.go b/backend/plugin/schema/mssql/get_database_definition_test.go
index 3cf46f2338..71ece9594d 100644
--- a/backend/plugin/schema/mssql/get_database_definition_test.go
+++ b/backend/plugin/schema/mssql/get_database_definition_test.go
@@ -1,595 +1,54 @@
package mssql
import (
- "context"
- "fmt"
- "io"
"os"
- "strings"
"testing"
- "github.com/google/uuid"
_ "github.com/microsoft/go-mssqldb"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
"github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/schema"
)
-type getDatabaseDefinitionTestCase struct {
- Input string `yaml:"input"`
- Output string `yaml:"output"`
+type getDatabaseDefinitionCase struct {
+ Description string `yaml:"description"`
+ Metadata string `yaml:"metadata"`
+ Expected string `yaml:"expected"`
}
+// TestGetDatabaseDefinition pins the DDL generated for each metadata input.
func TestGetDatabaseDefinition(t *testing.T) {
- tests := []getDatabaseDefinitionTestCase{}
const (
- record = false
+ record = false
+ filepath = "testdata/get_database_definition.yaml"
)
- var (
- filepath = "test-data/test_get_database_definition.yaml"
- )
-
- a := require.New(t)
- yamlFile, err := os.Open(filepath)
- a.NoError(err)
- defer yamlFile.Close()
- byteValue, err := io.ReadAll(yamlFile)
- a.NoError(err)
- a.NoError(yaml.Unmarshal(byteValue, &tests))
+ var tests []getDatabaseDefinitionCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
for i, tc := range tests {
- var metadata storepb.DatabaseSchemaMetadata
- err := common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Input), &metadata)
- a.NoError(err)
-
- result, err := GetDatabaseDefinition(schema.GetDefinitionContext{}, &metadata)
- a.NoError(err)
-
- if record {
- tests[i].Output = result
- } else {
- a.Equal(tc.Output, result, "Test case %d", i)
- }
- }
- if record {
- yamltest.Record(t, filepath, tests)
- }
-}
-
-//nolint:tparallel
-func TestGetDatabaseDefinitionWithTestcontainer(t *testing.T) {
- ctx := context.Background()
- container := testcontainer.SharedMSSQLContainer(t)
-
- testCases := []struct {
- name string
- setupSQL string
- wantMatch bool
- }{
- {
- name: "basic_tables_with_constraints",
- setupSQL: `
-CREATE SCHEMA test_schema;
-GO
-
-CREATE TABLE test_schema.users (
- id INT IDENTITY(1,1) PRIMARY KEY,
- email VARCHAR(255) NOT NULL UNIQUE,
- created_at DATETIME2 DEFAULT GETDATE(),
- is_active BIT DEFAULT 1,
- age INT CHECK (age >= 18),
- computed_column AS (id * 2) PERSISTED
-);
-GO
-
-CREATE TABLE test_schema.posts (
- id INT IDENTITY(1,1) PRIMARY KEY,
- user_id INT NOT NULL,
- title NVARCHAR(200) NOT NULL,
- content NVARCHAR(MAX),
- CONSTRAINT FK_posts_users FOREIGN KEY (user_id) REFERENCES test_schema.users(id) ON DELETE CASCADE
-);
-GO
-
-CREATE NONCLUSTERED INDEX idx_posts_user_id ON test_schema.posts(user_id);
-CREATE UNIQUE INDEX idx_posts_title ON test_schema.posts(title) WHERE title IS NOT NULL;
-GO
-`,
- wantMatch: true,
- },
- {
- name: "views_with_dependencies",
- setupSQL: `
-CREATE TABLE dbo.employees (
- emp_id INT PRIMARY KEY,
- emp_name VARCHAR(100),
- department VARCHAR(50),
- salary DECIMAL(10,2)
-);
-GO
-
-CREATE VIEW dbo.v_employee_summary AS
-SELECT department, COUNT(*) as emp_count, AVG(salary) as avg_salary
-FROM dbo.employees
-GROUP BY department;
-GO
-
-CREATE VIEW dbo.v_high_earners AS
-SELECT * FROM dbo.v_employee_summary
-WHERE avg_salary > 50000;
-GO
-`,
- wantMatch: true,
- },
- {
- name: "functions_and_procedures",
- setupSQL: `
-CREATE FUNCTION dbo.GetFullName(@FirstName NVARCHAR(50), @LastName NVARCHAR(50))
-RETURNS NVARCHAR(100)
-AS
-BEGIN
- RETURN @FirstName + ' ' + @LastName;
-END
-GO
-
-CREATE PROCEDURE dbo.UpdateSalary
- @EmployeeId INT,
- @NewSalary DECIMAL(10,2)
-AS
-BEGIN
- UPDATE employees SET salary = @NewSalary WHERE emp_id = @EmployeeId;
-END
-GO
-`,
- wantMatch: true,
- },
- {
- name: "complex_indexes",
- setupSQL: `
-CREATE TABLE dbo.sales (
- sale_id INT,
- product_id INT,
- sale_date DATE,
- amount DECIMAL(10,2),
- region VARCHAR(50)
-);
-GO
-
-CREATE CLUSTERED COLUMNSTORE INDEX cci_sales ON dbo.sales;
-GO
-
-CREATE TABLE dbo.products (
- product_id INT PRIMARY KEY,
- product_name VARCHAR(100),
- category VARCHAR(50)
-);
-GO
-
-CREATE NONCLUSTERED COLUMNSTORE INDEX ncci_products ON dbo.products(product_name, category);
-GO
-`,
- wantMatch: true,
- },
- {
- name: "temporal_tables",
- setupSQL: `
-CREATE TABLE dbo.temporal_test (
- id INT PRIMARY KEY,
- name VARCHAR(100),
- SysStartTime DATETIME2 GENERATED ALWAYS AS ROW START NOT NULL,
- SysEndTime DATETIME2 GENERATED ALWAYS AS ROW END NOT NULL,
- PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime)
-) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.temporal_test_history));
-GO
-`,
- wantMatch: true,
- },
- {
- name: "spatial_indexes_geography",
- setupSQL: `
-CREATE SCHEMA spatial_schema;
-GO
-
-CREATE TABLE spatial_schema.locations (
- id INT IDENTITY(1,1) PRIMARY KEY,
- name NVARCHAR(200) NOT NULL,
- location_point GEOGRAPHY NOT NULL,
- boundary_polygon GEOGRAPHY NOT NULL,
- route_line GEOGRAPHY,
- description NVARCHAR(MAX),
- created_at DATETIME2 DEFAULT GETDATE()
-);
-GO
-
--- Create spatial indexes with various configurations
-CREATE SPATIAL INDEX idx_location_point ON spatial_schema.locations(location_point)
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 32,
- PAD_INDEX = ON,
- FILLFACTOR = 85,
- SORT_IN_TEMPDB = ON,
- ALLOW_ROW_LOCKS = ON,
- ALLOW_PAGE_LOCKS = ON,
- MAXDOP = 2,
- DATA_COMPRESSION = PAGE
-);
-GO
-
-CREATE SPATIAL INDEX idx_boundary_polygon ON spatial_schema.locations(boundary_polygon)
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 16,
- FILLFACTOR = 80
-);
-GO
-
-CREATE SPATIAL INDEX idx_route_line ON spatial_schema.locations(route_line)
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 64
-);
-GO
-
--- Create regular indexes on the same table
-CREATE INDEX idx_name ON spatial_schema.locations(name);
-CREATE INDEX idx_created_at ON spatial_schema.locations(created_at);
-GO
-`,
- wantMatch: true,
- },
- {
- name: "spatial_indexes_geometry",
- setupSQL: `
-CREATE SCHEMA geom_schema;
-GO
-
-CREATE TABLE geom_schema.shapes (
- shape_id INT IDENTITY(1,1) PRIMARY KEY,
- shape_name NVARCHAR(100) NOT NULL,
- shape_point GEOMETRY NOT NULL,
- shape_polygon GEOMETRY NOT NULL,
- shape_line GEOMETRY,
- area_size AS shape_polygon.STArea() PERSISTED,
- center_x AS shape_point.STX PERSISTED,
- center_y AS shape_point.STY PERSISTED
-);
-GO
-
--- Create GEOMETRY spatial indexes with bounding boxes
-CREATE SPATIAL INDEX idx_shape_point ON geom_schema.shapes(shape_point)
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (0, 0, 100, 100),
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = LOW, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 16,
- PAD_INDEX = ON,
- FILLFACTOR = 90
-);
-GO
-
-CREATE SPATIAL INDEX idx_shape_polygon ON geom_schema.shapes(shape_polygon)
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-180, -90, 180, 90),
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 64
-);
-GO
-
-CREATE SPATIAL INDEX idx_shape_line ON geom_schema.shapes(shape_line)
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-1000, -1000, 1000, 1000),
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = MEDIUM, LEVEL_4 = HIGH),
- CELLS_PER_OBJECT = 8
-);
-GO
-
--- Create unique index on shape_name
-CREATE UNIQUE INDEX idx_shape_name ON geom_schema.shapes(shape_name);
-GO
-`,
- wantMatch: true,
- },
- {
- name: "spatial_indexes_mixed_with_constraints",
- setupSQL: `
-CREATE TABLE dbo.spatial_mixed (
- id INT IDENTITY(1,1) PRIMARY KEY,
- code VARCHAR(50) UNIQUE NOT NULL,
- geo_location GEOGRAPHY NOT NULL,
- geom_shape GEOMETRY NOT NULL,
- status NVARCHAR(20) CHECK (status IN ('active', 'inactive', 'pending')),
- parent_id INT,
- CONSTRAINT FK_spatial_mixed_parent FOREIGN KEY (parent_id) REFERENCES dbo.spatial_mixed(id)
-);
-GO
-
--- Create both GEOGRAPHY and GEOMETRY spatial indexes
-CREATE SPATIAL INDEX idx_geo_location_mixed ON dbo.spatial_mixed(geo_location)
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 16
-);
-GO
-
-CREATE SPATIAL INDEX idx_geom_shape_mixed ON dbo.spatial_mixed(geom_shape)
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-100, -100, 100, 100),
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = LOW, LEVEL_3 = HIGH, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 32
-);
-GO
-
--- Create regular indexes
-CREATE INDEX idx_status ON dbo.spatial_mixed(status);
-CREATE INDEX idx_parent_id ON dbo.spatial_mixed(parent_id);
-GO
-
--- Create a view using spatial functions
-CREATE VIEW dbo.v_spatial_summary AS
-SELECT
- id,
- code,
- geo_location.STAsText() AS geo_location_wkt,
- geom_shape.STAsText() AS geom_shape_wkt,
- geom_shape.STArea() AS shape_area,
- status
-FROM dbo.spatial_mixed
-WHERE status = 'active';
-GO
-`,
- wantMatch: true,
- },
- {
- name: "spatial_indexes_advanced_configurations",
- setupSQL: `
-CREATE SCHEMA advanced_spatial;
-GO
-
--- Table with multiple spatial columns
-CREATE TABLE advanced_spatial.geo_data (
- id BIGINT IDENTITY(1,1) PRIMARY KEY,
- name NVARCHAR(255) NOT NULL,
- -- Geography columns
- current_location GEOGRAPHY NOT NULL,
- delivery_route GEOGRAPHY,
- service_area GEOGRAPHY NOT NULL,
- -- Geometry columns
- building_footprint GEOMETRY,
- floor_plan GEOMETRY,
- -- Regular columns
- category VARCHAR(100),
- is_active BIT DEFAULT 1,
- last_updated DATETIME2 DEFAULT GETDATE()
-);
-GO
-
--- Create spatial indexes with different tessellation schemes
-CREATE SPATIAL INDEX idx_current_location ON advanced_spatial.geo_data(current_location)
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 1,
- PAD_INDEX = OFF,
- FILLFACTOR = 100,
- ALLOW_ROW_LOCKS = OFF,
- ALLOW_PAGE_LOCKS = OFF
-);
-GO
-
-CREATE SPATIAL INDEX idx_delivery_route ON advanced_spatial.geo_data(delivery_route)
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = HIGH, LEVEL_4 = HIGH),
- CELLS_PER_OBJECT = 8192,
- PAD_INDEX = ON,
- FILLFACTOR = 50
-);
-GO
-
-CREATE SPATIAL INDEX idx_service_area ON advanced_spatial.geo_data(service_area)
-USING GEOGRAPHY_GRID
-WITH (
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = LOW, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 256
-);
-GO
-
-CREATE SPATIAL INDEX idx_building_footprint ON advanced_spatial.geo_data(building_footprint)
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (-10000, -10000, 10000, 10000),
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = HIGH),
- CELLS_PER_OBJECT = 128
-);
-GO
-
-CREATE SPATIAL INDEX idx_floor_plan ON advanced_spatial.geo_data(floor_plan)
-USING GEOMETRY_GRID
-WITH (
- BOUNDING_BOX = (0, 0, 1000, 1000),
- GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = MEDIUM, LEVEL_3 = LOW, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 512
-);
-GO
-
--- Create filtered indexes
-CREATE INDEX idx_active_category ON advanced_spatial.geo_data(category)
-WHERE is_active = 1;
-GO
+ t.Run(tc.Description, func(t *testing.T) {
+ var metadata storepb.DatabaseSchemaMetadata
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Metadata), &metadata))
--- Create columnstore index
-CREATE NONCLUSTERED COLUMNSTORE INDEX ncci_geo_data
-ON advanced_spatial.geo_data(id, name, category, is_active, last_updated);
-GO
-`,
- wantMatch: true,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel() // Safe to parallelize - shared container, unique databases per test
- // Use test name for database name - each test case has a unique name
- databaseName := fmt.Sprintf("test_%s_%s", strings.ReplaceAll(tc.name, " ", "_"), strings.ReplaceAll(uuid.New().String(), "-", "_"))
-
- // Create test database using container's master connection
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE [%s]", databaseName))
- require.NoError(t, err)
-
- // Connect to test database
- testDriver, err := createMSSQLDriver(ctx, container.GetHost(), container.GetPort(), databaseName)
- require.NoError(t, err)
- defer testDriver.Close(ctx)
-
- // Step 1: Initialize database schema and get metadata A
- err = executeSQL(ctx, testDriver, tc.setupSQL)
- require.NoError(t, err)
-
- metadataA, err := testDriver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Step 2: Call GetDatabaseDefinition to generate database definition X
- definitionX, err := GetDatabaseDefinition(schema.GetDefinitionContext{}, metadataA)
- require.NoError(t, err)
- require.NotEmpty(t, definitionX)
-
- // Step 3: Create a new database and run the definition X
- newDatabaseName := fmt.Sprintf("copy_%s", databaseName)
-
- // Create new database using container's master connection
- _, err = container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE [%s]", newDatabaseName))
- require.NoError(t, err)
-
- // Connect to the new database
- newDriver, err := createMSSQLDriver(ctx, container.GetHost(), container.GetPort(), newDatabaseName)
- require.NoError(t, err)
- defer newDriver.Close(ctx)
-
- // Execute the generated definition
- err = executeSQL(ctx, newDriver, definitionX)
- require.NoError(t, err)
-
- // Get metadata B
- metadataB, err := newDriver.SyncDBSchema(ctx)
+ definition, err := GetDatabaseDefinition(schema.GetDefinitionContext{}, &metadata)
require.NoError(t, err)
- // Step 4: Compare metadata A and B
- if tc.wantMatch {
- // Note: Direct comparison might fail due to:
- // 1. System-generated names for constraints
- // 2. Minor differences in index/constraint definitions
-
- require.Equal(t, len(metadataA.Schemas), len(metadataB.Schemas), "Number of schemas should match")
-
- for i, schemaA := range metadataA.Schemas {
- schemaB := metadataB.Schemas[i]
- require.Equal(t, schemaA.Name, schemaB.Name, "Schema names should match")
- require.Equal(t, len(schemaA.Tables), len(schemaB.Tables), "Number of tables in schema %s should match", schemaA.Name)
- require.Equal(t, len(schemaA.Views), len(schemaB.Views), "Number of views in schema %s should match", schemaA.Name)
- require.Equal(t, len(schemaA.Functions), len(schemaB.Functions), "Number of functions in schema %s should match", schemaA.Name)
- require.Equal(t, len(schemaA.Procedures), len(schemaB.Procedures), "Number of procedures in schema %s should match", schemaA.Name)
-
- // Compare tables in detail
- for j, tableA := range schemaA.Tables {
- tableB := schemaB.Tables[j]
- require.Equal(t, tableA.Name, tableB.Name, "Table names should match")
- require.Equal(t, len(tableA.Columns), len(tableB.Columns), "Number of columns in table %s.%s should match", schemaA.Name, tableA.Name)
- require.Equal(t, len(tableA.Indexes), len(tableB.Indexes), "Number of indexes in table %s.%s should match", schemaA.Name, tableA.Name)
-
- // Compare spatial indexes specifically
- spatialIndexesA := make(map[string]*storepb.IndexMetadata)
- spatialIndexesB := make(map[string]*storepb.IndexMetadata)
-
- for _, idx := range tableA.Indexes {
- if idx.Type == "SPATIAL" {
- spatialIndexesA[idx.Name] = idx
- }
- }
-
- for _, idx := range tableB.Indexes {
- if idx.Type == "SPATIAL" {
- spatialIndexesB[idx.Name] = idx
- }
- }
-
- require.Equal(t, len(spatialIndexesA), len(spatialIndexesB), "Number of spatial indexes in table %s.%s should match", schemaA.Name, tableA.Name)
-
- // Compare each spatial index in detail
- for name, idxA := range spatialIndexesA {
- idxB, exists := spatialIndexesB[name]
- require.True(t, exists, "Spatial index %s should exist in both schemas", name)
-
- // Compare spatial index properties
- require.Equal(t, idxA.Type, idxB.Type, "Index type should match for %s", name)
- require.Equal(t, idxA.Unique, idxB.Unique, "Unique property should match for %s", name)
- require.Equal(t, idxA.Primary, idxB.Primary, "Primary property should match for %s", name)
- require.Equal(t, idxA.Expressions, idxB.Expressions, "Expressions should match for %s", name)
-
- // Compare spatial configuration
- if idxA.SpatialConfig != nil {
- require.NotNil(t, idxB.SpatialConfig, "Spatial config should exist for %s in schema B", name)
-
- // Compare method
- require.Equal(t, idxA.SpatialConfig.Method, idxB.SpatialConfig.Method, "Spatial method should match for %s", name)
-
- // Compare tessellation
- if idxA.SpatialConfig.Tessellation != nil {
- require.NotNil(t, idxB.SpatialConfig.Tessellation, "Tessellation config should exist for %s in schema B", name)
- require.Equal(t, idxA.SpatialConfig.Tessellation.Scheme, idxB.SpatialConfig.Tessellation.Scheme, "Tessellation scheme should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Tessellation.CellsPerObject, idxB.SpatialConfig.Tessellation.CellsPerObject, "CellsPerObject should match for %s", name)
-
- // Compare grid levels
- require.Equal(t, len(idxA.SpatialConfig.Tessellation.GridLevels), len(idxB.SpatialConfig.Tessellation.GridLevels), "Number of grid levels should match for %s", name)
- for k, levelA := range idxA.SpatialConfig.Tessellation.GridLevels {
- levelB := idxB.SpatialConfig.Tessellation.GridLevels[k]
- require.Equal(t, levelA.Level, levelB.Level, "Grid level should match for %s", name)
- require.Equal(t, levelA.Density, levelB.Density, "Grid density should match for %s at level %d", name, levelA.Level)
- }
-
- // Compare bounding box for GEOMETRY indexes
- if idxA.SpatialConfig.Tessellation.BoundingBox != nil {
- require.NotNil(t, idxB.SpatialConfig.Tessellation.BoundingBox, "Bounding box should exist for %s in schema B", name)
- require.Equal(t, idxA.SpatialConfig.Tessellation.BoundingBox.Xmin, idxB.SpatialConfig.Tessellation.BoundingBox.Xmin, "Xmin should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Tessellation.BoundingBox.Ymin, idxB.SpatialConfig.Tessellation.BoundingBox.Ymin, "Ymin should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Tessellation.BoundingBox.Xmax, idxB.SpatialConfig.Tessellation.BoundingBox.Xmax, "Xmax should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Tessellation.BoundingBox.Ymax, idxB.SpatialConfig.Tessellation.BoundingBox.Ymax, "Ymax should match for %s", name)
- }
- }
-
- // Compare storage configuration
- if idxA.SpatialConfig.Storage != nil {
- require.NotNil(t, idxB.SpatialConfig.Storage, "Storage config should exist for %s in schema B", name)
- require.Equal(t, idxA.SpatialConfig.Storage.Fillfactor, idxB.SpatialConfig.Storage.Fillfactor, "Fillfactor should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Storage.PadIndex, idxB.SpatialConfig.Storage.PadIndex, "PadIndex should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Storage.AllowRowLocks, idxB.SpatialConfig.Storage.AllowRowLocks, "AllowRowLocks should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Storage.AllowPageLocks, idxB.SpatialConfig.Storage.AllowPageLocks, "AllowPageLocks should match for %s", name)
- }
-
- // Compare dimensional configuration
- if idxA.SpatialConfig.Dimensional != nil {
- require.NotNil(t, idxB.SpatialConfig.Dimensional, "Dimensional config should exist for %s in schema B", name)
- require.Equal(t, idxA.SpatialConfig.Dimensional.DataType, idxB.SpatialConfig.Dimensional.DataType, "Spatial data type should match for %s", name)
- require.Equal(t, idxA.SpatialConfig.Dimensional.Dimensions, idxB.SpatialConfig.Dimensional.Dimensions, "Dimensions should match for %s", name)
- }
- }
- }
- }
- }
+ if record {
+ tests[i].Expected = definition
+ return
}
+ require.Equal(t, tc.Expected, definition)
})
}
+
+ if record {
+ yamltest.Record(t, filepath, tests)
+ }
}
diff --git a/backend/plugin/schema/mssql/get_database_metadata_test.go b/backend/plugin/schema/mssql/get_database_metadata_test.go
index 29159d8b14..5efe94da33 100644
--- a/backend/plugin/schema/mssql/get_database_metadata_test.go
+++ b/backend/plugin/schema/mssql/get_database_metadata_test.go
@@ -2,7 +2,6 @@ package mssql
import (
"encoding/json"
- "io"
"os"
"testing"
@@ -63,42 +62,43 @@ CREATE TABLE sales.orders (
}
type getDatabaseMetadataCase struct {
- Input string
- Result string
+ Description string `yaml:"description"`
+ Schema string `yaml:"schema"`
+ Metadata string `yaml:"metadata"`
}
+// TestGetDatabaseMetadata pins what the parser extracts from each schema text.
+// The goldens describe this package's own output, not SQL Server's catalog:
+// whether the parser agrees with a live server is engine conformance and belongs
+// in omni.
func TestGetDatabaseMetadata(t *testing.T) {
- tests := []getDatabaseMetadataCase{}
const (
- record = false
+ record = false
+ filepath = "testdata/get_database_metadata.yaml"
)
- var (
- filepath = "test-data/test_get_database_metadata.yaml"
- )
-
- a := require.New(t)
- yamlFile, err := os.Open(filepath)
- a.NoError(err)
- defer yamlFile.Close()
- byteValue, err := io.ReadAll(yamlFile)
- a.NoError(err)
- a.NoError(yaml.Unmarshal(byteValue, &tests))
+ var tests []getDatabaseMetadataCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
- for i, t := range tests {
- meta, err := GetDatabaseMetadata(t.Input)
- a.NoError(err)
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ metadata, err := GetDatabaseMetadata(tc.Schema)
+ require.NoError(t, err)
- jsonBytes, err := json.MarshalIndent(meta, "", " ")
- a.NoError(err)
- result := string(jsonBytes)
+ encoded, err := json.MarshalIndent(metadata, "", " ")
+ require.NoError(t, err)
+ result := string(encoded) + "\n"
- if record {
- tests[i].Result = result
- } else {
- a.Equal(t.Result, result, t.Input)
- }
+ if record {
+ tests[i].Metadata = result
+ return
+ }
+ require.Equal(t, tc.Metadata, result)
+ })
}
+
if record {
yamltest.Record(t, filepath, tests)
}
diff --git a/backend/plugin/schema/mssql/main_test.go b/backend/plugin/schema/mssql/main_test.go
deleted file mode 100644
index aae886b962..0000000000
--- a/backend/plugin/schema/mssql/main_test.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package mssql
-
-import (
- "testing"
-
- "github.com/bytebase/bytebase/backend/common/testcontainer"
-)
-
-func TestMain(m *testing.M) { testcontainer.Main(m) }
diff --git a/backend/plugin/schema/mssql/test-data/test_get_database_definition.yaml b/backend/plugin/schema/mssql/test-data/test_get_database_definition.yaml
deleted file mode 100644
index d798f6987d..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_get_database_definition.yaml
+++ /dev/null
@@ -1,826 +0,0 @@
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "tables": [
- {
- "name": "users",
- "columns": [
- {
- "name": "id",
- "position": 1,
- "type": "INT",
- "isIdentity": true,
- "identitySeed": "1",
- "identityIncrement": "1"
- },
- {
- "name": "name",
- "position": 2,
- "type": "NVARCHAR(100)",
- "nullable": false
- },
- {
- "name": "email",
- "position": 3,
- "type": "NVARCHAR(255)",
- "nullable": true,
- "default": "''"
- },
- {
- "name": "created_at",
- "position": 4,
- "type": "DATETIME2",
- "nullable": false,
- "default": "GETDATE()"
- }
- ],
- "indexes": [
- {
- "name": "PK_users",
- "expressions": ["id"],
- "descending": [false],
- "primary": true,
- "isConstraint": true,
- "type": "CLUSTERED"
- },
- {
- "name": "IX_users_email",
- "expressions": ["email"],
- "descending": [false],
- "unique": true
- }
- ]
- }
- ]
- }
- ]
- }
- output: |+
- CREATE TABLE [dbo].[users] (
- [id] INT IDENTITY(1,1) NOT NULL,
- [name] NVARCHAR(100) NOT NULL,
- [email] NVARCHAR(255) DEFAULT '',
- [created_at] DATETIME2 DEFAULT GETDATE() NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id] ASC)
- );
-
- CREATE UNIQUE INDEX [IX_users_email] ON
- [dbo].[users] (
- [email] ASC
- );
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "tables": [
- {
- "name": "orders",
- "columns": [
- {
- "name": "order_id",
- "position": 1,
- "type": "INT",
- "isIdentity": true,
- "identitySeed": "1",
- "identityIncrement": "1"
- },
- {
- "name": "user_id",
- "position": 2,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "amount",
- "position": 3,
- "type": "DECIMAL(10,2)",
- "nullable": false
- },
- {
- "name": "status",
- "position": 4,
- "type": "NVARCHAR(20)",
- "nullable": false,
- "default": "'pending'"
- }
- ],
- "indexes": [
- {
- "name": "PK_orders",
- "expressions": ["order_id"],
- "descending": [false],
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_orders_users",
- "columns": ["user_id"],
- "referencedSchema": "dbo",
- "referencedTable": "users",
- "referencedColumns": ["id"],
- "onDelete": "CASCADE",
- "onUpdate": "NO ACTION"
- }
- ],
- "checkConstraints": [
- {
- "name": "CK_orders_amount",
- "expression": "([amount] > 0)"
- },
- {
- "name": "CK_orders_status",
- "expression": "([status] IN ('pending', 'completed', 'cancelled'))"
- }
- ]
- }
- ]
- }
- ]
- }
- output: |+
- CREATE TABLE [dbo].[orders] (
- [order_id] INT IDENTITY(1,1) NOT NULL,
- [user_id] INT NOT NULL,
- [amount] DECIMAL(10,2) NOT NULL,
- [status] NVARCHAR(20) DEFAULT 'pending' NOT NULL,
- CONSTRAINT [PK_orders] PRIMARY KEY ([order_id] ASC),
- CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION,
- CONSTRAINT [CK_orders_amount] CHECK ([amount] > 0),
- CONSTRAINT [CK_orders_status] CHECK ([status] IN ('pending', 'completed', 'cancelled'))
- );
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "views": [
- {
- "name": "v_active_users",
- "definition": "CREATE VIEW [dbo].[v_active_users] AS SELECT u.id, u.name, u.email, COUNT(o.order_id) as order_count\nFROM dbo.users u\nLEFT JOIN dbo.orders o ON u.id = o.user_id\nWHERE u.created_at >= DATEADD(month, -6, GETDATE())\nGROUP BY u.id, u.name, u.email"
- }
- ]
- }
- ]
- }
- output: |+
- CREATE VIEW [dbo].[v_active_users] AS SELECT u.id, u.name, u.email, COUNT(o.order_id) as order_count
- FROM dbo.users u
- LEFT JOIN dbo.orders o ON u.id = o.user_id
- WHERE u.created_at >= DATEADD(month, -6, GETDATE())
- GROUP BY u.id, u.name, u.email;
-
- GO
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "functions": [
- {
- "name": "fn_GetUserOrderTotal",
- "definition": "CREATE FUNCTION [dbo].[fn_GetUserOrderTotal]\n(\n @UserId INT\n)\nRETURNS DECIMAL(10,2)\nAS\nBEGIN\n DECLARE @Total DECIMAL(10,2)\n\n SELECT @Total = SUM(amount)\n FROM dbo.orders\n WHERE user_id = @UserId\n AND status = 'completed'\n\n RETURN ISNULL(@Total, 0)\nEND"
- }
- ]
- }
- ]
- }
- output: |+
- CREATE FUNCTION [dbo].[fn_GetUserOrderTotal]
- (
- @UserId INT
- )
- RETURNS DECIMAL(10,2)
- AS
- BEGIN
- DECLARE @Total DECIMAL(10,2)
-
- SELECT @Total = SUM(amount)
- FROM dbo.orders
- WHERE user_id = @UserId
- AND status = 'completed'
-
- RETURN ISNULL(@Total, 0)
- END
-
- GO
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "procedures": [
- {
- "name": "sp_UpdateOrderStatus",
- "definition": "CREATE PROCEDURE [dbo].[sp_UpdateOrderStatus]\n @OrderId INT,\n @NewStatus NVARCHAR(20)\nAS\nBEGIN\n SET NOCOUNT ON;\n\n UPDATE dbo.orders\n SET status = @NewStatus\n WHERE order_id = @OrderId;\n\n SELECT @@ROWCOUNT AS RowsAffected;\nEND"
- }
- ]
- }
- ]
- }
- output: |+
- CREATE PROCEDURE [dbo].[sp_UpdateOrderStatus]
- @OrderId INT,
- @NewStatus NVARCHAR(20)
- AS
- BEGIN
- SET NOCOUNT ON;
-
- UPDATE dbo.orders
- SET status = @NewStatus
- WHERE order_id = @OrderId;
-
- SELECT @@ROWCOUNT AS RowsAffected;
- END
-
- GO
-
-- input: |
- {
- "schemas": [
- {
- "name": "sales",
- "tables": [
- {
- "name": "products",
- "columns": [
- {
- "name": "product_id",
- "position": 1,
- "type": "INT",
- "isIdentity": true,
- "identitySeed": "1",
- "identityIncrement": "1"
- },
- {
- "name": "name",
- "position": 2,
- "type": "NVARCHAR(200)",
- "nullable": false
- }
- ],
- "indexes": [
- {
- "name": "PK_products",
- "expressions": ["product_id"],
- "descending": [false],
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ]
- }
- output: |+
- CREATE SCHEMA [sales];
- GO
-
- CREATE TABLE [sales].[products] (
- [product_id] INT IDENTITY(1,1) NOT NULL,
- [name] NVARCHAR(200) NOT NULL,
- CONSTRAINT [PK_products] PRIMARY KEY ([product_id] ASC)
- );
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "tables": [
- {
- "name": "employees",
- "columns": [
- {
- "name": "employee_id",
- "position": 1,
- "type": "INT",
- "isIdentity": true,
- "identitySeed": "1",
- "identityIncrement": "1"
- },
- {
- "name": "name",
- "position": 2,
- "type": "NVARCHAR(100)",
- "nullable": false
- }
- ],
- "indexes": [
- {
- "name": "PK_employees",
- "expressions": ["employee_id"],
- "descending": [false],
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "views": [
- {
- "name": "v_employee_list",
- "definition": "CREATE VIEW [dbo].[v_employee_list] AS SELECT employee_id, name FROM dbo.employees WHERE employee_id > 0"
- }
- ],
- "functions": [
- {
- "name": "fn_GetEmployeeName",
- "definition": "CREATE FUNCTION [dbo].[fn_GetEmployeeName](@EmpId INT) RETURNS NVARCHAR(100) AS BEGIN DECLARE @Name NVARCHAR(100); SELECT @Name = name FROM dbo.employees WHERE employee_id = @EmpId; RETURN @Name; END"
- }
- ],
- "procedures": [
- {
- "name": "sp_GetEmployee",
- "definition": "CREATE PROCEDURE [dbo].[sp_GetEmployee] @EmpId INT AS BEGIN SELECT * FROM dbo.employees WHERE employee_id = @EmpId; END"
- }
- ]
- }
- ]
- }
- output: |+
- CREATE TABLE [dbo].[employees] (
- [employee_id] INT IDENTITY(1,1) NOT NULL,
- [name] NVARCHAR(100) NOT NULL,
- CONSTRAINT [PK_employees] PRIMARY KEY ([employee_id] ASC)
- );
-
- GO
-
- CREATE VIEW [dbo].[v_employee_list] AS SELECT employee_id, name FROM dbo.employees WHERE employee_id > 0;
-
- GO
-
- CREATE FUNCTION [dbo].[fn_GetEmployeeName](@EmpId INT) RETURNS NVARCHAR(100) AS BEGIN DECLARE @Name NVARCHAR(100); SELECT @Name = name FROM dbo.employees WHERE employee_id = @EmpId; RETURN @Name; END
-
- GO
-
- CREATE PROCEDURE [dbo].[sp_GetEmployee] @EmpId INT AS BEGIN SELECT * FROM dbo.employees WHERE employee_id = @EmpId; END
-
- GO
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "tables": [
- {
- "name": "international_data",
- "columns": [
- {
- "name": "id",
- "position": 1,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "text_data",
- "position": 2,
- "type": "NVARCHAR(MAX)",
- "nullable": true,
- "collation": "Latin1_General_CI_AS"
- }
- ]
- }
- ]
- }
- ]
- }
- output: |+
- CREATE TABLE [dbo].[international_data] (
- [id] INT NOT NULL,
- [text_data] NVARCHAR(MAX) COLLATE Latin1_General_CI_AS
- );
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "tables": [
- {
- "name": "fact_sales",
- "columns": [
- {
- "name": "sale_id",
- "position": 1,
- "type": "BIGINT",
- "nullable": false
- },
- {
- "name": "product_id",
- "position": 2,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "quantity",
- "position": 3,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "amount",
- "position": 4,
- "type": "DECIMAL(10,2)",
- "nullable": false
- }
- ],
- "indexes": [
- {
- "name": "CCI_fact_sales",
- "type": "CLUSTERED COLUMNSTORE"
- },
- {
- "name": "NCCI_fact_sales_product",
- "type": "NONCLUSTERED COLUMNSTORE",
- "expressions": ["product_id", "quantity"]
- }
- ]
- }
- ]
- }
- ]
- }
- output: |+
- CREATE TABLE [dbo].[fact_sales] (
- [sale_id] BIGINT NOT NULL,
- [product_id] INT NOT NULL,
- [quantity] INT NOT NULL,
- [amount] DECIMAL(10,2) NOT NULL
- );
-
- CREATE CLUSTERED COLUMNSTORE INDEX [CCI_fact_sales] ON [dbo].[fact_sales];
-
- CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_fact_sales_product] ON [dbo].[fact_sales] (
- [product_id],
- [quantity]
- );
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "tables": [
- {
- "name": "customers",
- "columns": [
- {
- "name": "customer_id",
- "position": 1,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "name",
- "position": 2,
- "type": "NVARCHAR(100)",
- "nullable": false
- }
- ]
- },
- {
- "name": "orders",
- "columns": [
- {
- "name": "order_id",
- "position": 1,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "customer_id",
- "position": 2,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "total",
- "position": 3,
- "type": "DECIMAL(10,2)",
- "nullable": false
- }
- ]
- }
- ],
- "views": [
- {
- "name": "v_customer_orders",
- "definition": "CREATE VIEW [dbo].[v_customer_orders] AS SELECT c.customer_id, c.name, o.order_id, o.total FROM dbo.customers c JOIN dbo.orders o ON c.customer_id = o.customer_id"
- },
- {
- "name": "v_customer_summary",
- "definition": "CREATE VIEW [dbo].[v_customer_summary] AS SELECT customer_id, name, COUNT(order_id) as order_count, SUM(total) as total_amount FROM dbo.v_customer_orders GROUP BY customer_id, name"
- },
- {
- "name": "v_top_customers",
- "definition": "CREATE VIEW [dbo].[v_top_customers] AS SELECT TOP 10 * FROM dbo.v_customer_summary ORDER BY total_amount DESC"
- }
- ]
- }
- ]
- }
- output: |+
- CREATE TABLE [dbo].[customers] (
- [customer_id] INT NOT NULL,
- [name] NVARCHAR(100) NOT NULL
- );
-
- CREATE TABLE [dbo].[orders] (
- [order_id] INT NOT NULL,
- [customer_id] INT NOT NULL,
- [total] DECIMAL(10,2) NOT NULL
- );
-
- GO
-
- CREATE VIEW [dbo].[v_customer_orders] AS SELECT c.customer_id, c.name, o.order_id, o.total FROM dbo.customers c JOIN dbo.orders o ON c.customer_id = o.customer_id;
-
- GO
-
- CREATE VIEW [dbo].[v_customer_summary] AS SELECT customer_id, name, COUNT(order_id) as order_count, SUM(total) as total_amount FROM dbo.v_customer_orders GROUP BY customer_id, name;
-
- GO
-
- CREATE VIEW [dbo].[v_top_customers] AS SELECT TOP 10 * FROM dbo.v_customer_summary ORDER BY total_amount DESC;
-
- GO
-
-- input: |
- {
- "schemas": [
- {
- "name": "sales",
- "tables": [
- {
- "name": "products",
- "columns": [
- {
- "name": "product_id",
- "position": 1,
- "type": "INT",
- "nullable": false
- },
- {
- "name": "name",
- "position": 2,
- "type": "NVARCHAR(100)",
- "nullable": false
- }
- ]
- }
- ],
- "views": [
- {
- "name": "v_product_list",
- "definition": "CREATE VIEW [sales].[v_product_list] AS SELECT product_id, name FROM sales.products"
- }
- ]
- },
- {
- "name": "reporting",
- "views": [
- {
- "name": "v_all_products",
- "definition": "CREATE VIEW [reporting].[v_all_products] AS SELECT * FROM sales.v_product_list"
- }
- ]
- }
- ]
- }
- output: |+
- CREATE SCHEMA [sales];
- GO
-
- CREATE SCHEMA [reporting];
- GO
-
- CREATE TABLE [sales].[products] (
- [product_id] INT NOT NULL,
- [name] NVARCHAR(100) NOT NULL
- );
-
- GO
-
- CREATE VIEW [sales].[v_product_list] AS SELECT product_id, name FROM sales.products;
-
- GO
-
- CREATE VIEW [reporting].[v_all_products] AS SELECT * FROM sales.v_product_list;
-
- GO
-
-- input: |
- {
- "schemas": [
- {
- "name": "dbo",
- "tables": [
- {
- "name": "spatial_features",
- "columns": [
- {
- "name": "id",
- "position": 1,
- "type": "INT",
- "isIdentity": true,
- "identitySeed": "1",
- "identityIncrement": "1"
- },
- {
- "name": "feature_name",
- "position": 2,
- "type": "NVARCHAR(200)",
- "nullable": false
- },
- {
- "name": "location_point",
- "position": 3,
- "type": "GEOMETRY",
- "nullable": false
- },
- {
- "name": "boundary_polygon",
- "position": 4,
- "type": "GEOMETRY",
- "nullable": false
- },
- {
- "name": "geo_location",
- "position": 5,
- "type": "GEOGRAPHY",
- "nullable": false
- }
- ],
- "indexes": [
- {
- "name": "PK_spatial_features",
- "expressions": ["id"],
- "descending": [false],
- "primary": true,
- "isConstraint": true,
- "type": "CLUSTERED"
- },
- {
- "name": "idx_location_point",
- "expressions": ["location_point"],
- "descending": [false],
- "type": "SPATIAL",
- "spatialConfig": {
- "method": "SPATIAL",
- "tessellation": {
- "scheme": "GEOMETRY_GRID",
- "boundingBox": {
- "xmin": -180,
- "ymin": -90,
- "xmax": 180,
- "ymax": 90
- },
- "gridLevels": [
- {
- "level": 1,
- "density": "MEDIUM"
- },
- {
- "level": 2,
- "density": "HIGH"
- },
- {
- "level": 3,
- "density": "MEDIUM"
- },
- {
- "level": 4,
- "density": "LOW"
- }
- ],
- "cellsPerObject": 32
- },
- "storage": {
- "padIndex": true,
- "fillfactor": 85,
- "sortInTempdb": "ON",
- "allowRowLocks": true,
- "allowPageLocks": true,
- "maxdop": 2,
- "dataCompression": "PAGE"
- },
- "dimensional": {
- "dimensions": 2,
- "dataType": "GEOMETRY"
- }
- }
- },
- {
- "name": "idx_boundary_polygon",
- "expressions": ["boundary_polygon"],
- "descending": [false],
- "type": "SPATIAL",
- "spatialConfig": {
- "method": "SPATIAL",
- "tessellation": {
- "scheme": "GEOMETRY_AUTO_GRID",
- "cellsPerObject": 16
- },
- "dimensional": {
- "dimensions": 2,
- "dataType": "GEOMETRY"
- }
- }
- },
- {
- "name": "idx_geo_location",
- "expressions": ["geo_location"],
- "descending": [false],
- "type": "SPATIAL",
- "spatialConfig": {
- "method": "SPATIAL",
- "tessellation": {
- "scheme": "GEOGRAPHY_GRID",
- "gridLevels": [
- {
- "level": 1,
- "density": "LOW"
- },
- {
- "level": 2,
- "density": "MEDIUM"
- },
- {
- "level": 3,
- "density": "HIGH"
- },
- {
- "level": 4,
- "density": "MEDIUM"
- }
- ],
- "cellsPerObject": 8
- },
- "storage": {
- "fillfactor": 80,
- "online": true
- },
- "dimensional": {
- "dimensions": 2,
- "dataType": "GEOGRAPHY"
- }
- }
- }
- ]
- }
- ]
- }
- ]
- }
- output: |+
- CREATE TABLE [dbo].[spatial_features] (
- [id] INT IDENTITY(1,1) NOT NULL,
- [feature_name] NVARCHAR(200) NOT NULL,
- [location_point] GEOMETRY NOT NULL,
- [boundary_polygon] GEOMETRY NOT NULL,
- [geo_location] GEOGRAPHY NOT NULL,
- CONSTRAINT [PK_spatial_features] PRIMARY KEY CLUSTERED ([id] ASC)
- );
-
- CREATE SPATIAL INDEX [idx_location_point] ON [dbo].[spatial_features] ([location_point])
- USING GEOMETRY_GRID
- WITH (
- BOUNDING_BOX = (-180, -90, 180, 90),
- GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
- CELLS_PER_OBJECT = 32,
- PAD_INDEX = ON,
- FILLFACTOR = 85,
- SORT_IN_TEMPDB = ON,
- MAXDOP = 2,
- DATA_COMPRESSION = PAGE
- );
-
- CREATE SPATIAL INDEX [idx_boundary_polygon] ON [dbo].[spatial_features] ([boundary_polygon])
- USING GEOMETRY_AUTO_GRID
- WITH (
- CELLS_PER_OBJECT = 16
- );
-
- CREATE SPATIAL INDEX [idx_geo_location] ON [dbo].[spatial_features] ([geo_location])
- USING GEOGRAPHY_GRID
- WITH (
- GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
- CELLS_PER_OBJECT = 8,
- FILLFACTOR = 80,
- ONLINE = ON,
- ALLOW_ROW_LOCKS = OFF,
- ALLOW_PAGE_LOCKS = OFF
- );
-
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_constraints.yaml b/backend/plugin/schema/mssql/test-data/test_migration_constraints.yaml
deleted file mode 100644
index 1ad9ac71f2..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_migration_constraints.yaml
+++ /dev/null
@@ -1,123 +0,0 @@
-- description: Add foreign key constraint
- oldSchema: |
- CREATE TABLE [dbo].[departments] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE TABLE [dbo].[employees] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [department_id] int NOT NULL,
- CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[departments] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE TABLE [dbo].[employees] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [department_id] int NOT NULL,
- CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id]),
- CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[employees] ADD CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
-
-- description: Drop foreign key constraint
- oldSchema: |
- CREATE TABLE [dbo].[departments] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE TABLE [dbo].[employees] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [department_id] int NOT NULL,
- CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id]),
- CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[departments] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE TABLE [dbo].[employees] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [department_id] int NOT NULL,
- CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[employees] DROP CONSTRAINT [FK_employees_departments];
- GO
-
-- description: Add check constraint
- oldSchema: |
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [price] decimal(10,2) NOT NULL,
- CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [price] decimal(10,2) NOT NULL,
- CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
- CONSTRAINT [CK_products_price] CHECK ([price] > 0)
- );
- expected: |+
- ALTER TABLE [dbo].[products] ADD CONSTRAINT [CK_products_price] CHECK ([price] > 0);
-
-- description: Drop check constraint
- oldSchema: |
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [price] decimal(10,2) NOT NULL,
- CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
- CONSTRAINT [CK_products_price] CHECK ([price] > 0)
- );
- newSchema: |
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [price] decimal(10,2) NOT NULL,
- CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[products] DROP CONSTRAINT [CK_products_price];
-
-- description: Add primary key to existing table
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[users] ADD CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id]);
-
-- description: Drop primary key constraint
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL
- );
- expected: |+
- ALTER TABLE [dbo].[users] DROP CONSTRAINT [PK_users];
-
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_functions.yaml b/backend/plugin/schema/mssql/test-data/test_migration_functions.yaml
deleted file mode 100644
index 3906bd0ef5..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_migration_functions.yaml
+++ /dev/null
@@ -1,105 +0,0 @@
-- description: Create scalar function
- oldSchema: ""
- newSchema: |
- CREATE FUNCTION [dbo].[GetFullName]
- (
- @FirstName nvarchar(50),
- @LastName nvarchar(50)
- )
- RETURNS nvarchar(101)
- AS
- BEGIN
- RETURN @FirstName + ' ' + @LastName
- END
- expected: |
- CREATE FUNCTION [dbo].[GetFullName]
- (
- @FirstName nvarchar(50),
- @LastName nvarchar(50)
- )
- RETURNS nvarchar(101)
- AS
- BEGIN
- RETURN @FirstName + ' ' + @LastName
- END;
- GO
-- description: Drop function
- oldSchema: |
- CREATE FUNCTION [dbo].[GetFullName]
- (
- @FirstName nvarchar(50),
- @LastName nvarchar(50)
- )
- RETURNS nvarchar(101)
- AS
- BEGIN
- RETURN @FirstName + ' ' + @LastName
- END
- newSchema: ""
- expected: |
- DROP FUNCTION [dbo].[GetFullName];
- GO
-- description: Create table-valued function
- oldSchema: ""
- newSchema: |
- CREATE FUNCTION [dbo].[GetEmployeesByDepartment]
- (
- @DepartmentId int
- )
- RETURNS TABLE
- AS
- RETURN
- (
- SELECT Id, Name, Email
- FROM Employees
- WHERE DepartmentId = @DepartmentId
- )
- expected: |
- CREATE FUNCTION [dbo].[GetEmployeesByDepartment]
- (
- @DepartmentId int
- )
- RETURNS TABLE
- AS
- RETURN
- (
- SELECT Id, Name, Email
- FROM Employees
- WHERE DepartmentId = @DepartmentId
- );
- GO
-- description: Create inline table-valued function
- oldSchema: ""
- newSchema: |
- CREATE FUNCTION [dbo].[GetActiveUsers]()
- RETURNS @Users TABLE
- (
- UserId int,
- UserName nvarchar(100),
- LastLogin datetime
- )
- AS
- BEGIN
- INSERT INTO @Users
- SELECT Id, Name, LastLogin
- FROM Users
- WHERE IsActive = 1
- RETURN
- END
- expected: |
- CREATE FUNCTION [dbo].[GetActiveUsers]()
- RETURNS @Users TABLE
- (
- UserId int,
- UserName nvarchar(100),
- LastLogin datetime
- )
- AS
- BEGIN
- INSERT INTO @Users
- SELECT Id, Name, LastLogin
- FROM Users
- WHERE IsActive = 1
- RETURN
- END;
- GO
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_indexes.yaml b/backend/plugin/schema/mssql/test-data/test_migration_indexes.yaml
deleted file mode 100644
index 8dffc2bb1e..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_migration_indexes.yaml
+++ /dev/null
@@ -1,129 +0,0 @@
-- description: Create regular index
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
- expected: |+
- CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
-
-- description: Drop index
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- DROP INDEX [IX_users_email] ON [dbo].[users];
-
-- description: Create unique index
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE UNIQUE NONCLUSTERED INDEX [UX_users_email] ON [dbo].[users] ([email]);
- expected: |+
- CREATE UNIQUE NONCLUSTERED INDEX [UX_users_email] ON [dbo].[users] ([email]);
-
-- description: Create unique constraint
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id]),
- CONSTRAINT [UQ_users_email] UNIQUE NONCLUSTERED ([email])
- );
- expected: |+
- ALTER TABLE [dbo].[users] ADD CONSTRAINT [UQ_users_email] UNIQUE NONCLUSTERED ([email]);
-
-- description: Create clustered columnstore index
- oldSchema: |
- CREATE TABLE [dbo].[sales_data] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [sale_date] datetime NOT NULL,
- [amount] decimal(10,2) NOT NULL
- );
- newSchema: |
- CREATE TABLE [dbo].[sales_data] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [sale_date] datetime NOT NULL,
- [amount] decimal(10,2) NOT NULL
- );
- CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
- expected: |+
- CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
-
-- description: Create nonclustered columnstore index with columns
- oldSchema: |
- CREATE TABLE [dbo].[analytics_data] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [sale_date] datetime NOT NULL,
- [amount] decimal(10,2) NOT NULL,
- [region] nvarchar(50) NOT NULL,
- CONSTRAINT [PK_analytics_data] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[analytics_data] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [sale_date] datetime NOT NULL,
- [amount] decimal(10,2) NOT NULL,
- [region] nvarchar(50) NOT NULL,
- CONSTRAINT [PK_analytics_data] PRIMARY KEY CLUSTERED ([id])
- );
- CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_analytics_data] ON [dbo].[analytics_data] ([product_id], [sale_date], [amount]);
- expected: |+
- CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_analytics_data] ON [dbo].[analytics_data] ([product_id], [sale_date], [amount]);
-
-- description: Drop columnstore index
- oldSchema: |
- CREATE TABLE [dbo].[sales_data] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [sale_date] datetime NOT NULL,
- [amount] decimal(10,2) NOT NULL
- );
- CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
- newSchema: |
- CREATE TABLE [dbo].[sales_data] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [sale_date] datetime NOT NULL,
- [amount] decimal(10,2) NOT NULL
- );
- expected: |+
- DROP INDEX [CCI_sales_data] ON [dbo].[sales_data];
-
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_procedures.yaml b/backend/plugin/schema/mssql/test-data/test_migration_procedures.yaml
deleted file mode 100644
index 6d7b3d3ad6..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_migration_procedures.yaml
+++ /dev/null
@@ -1,125 +0,0 @@
-- description: Create simple procedure
- oldSchema: ""
- newSchema: |
- CREATE PROCEDURE [dbo].[GetUserById]
- @UserId int
- AS
- BEGIN
- SELECT * FROM Users WHERE Id = @UserId
- END
- expected: |
- CREATE PROCEDURE [dbo].[GetUserById]
- @UserId int
- AS
- BEGIN
- SELECT * FROM Users WHERE Id = @UserId
- END;
- GO
-- description: Drop procedure
- oldSchema: |
- CREATE PROCEDURE [dbo].[GetUserById]
- @UserId int
- AS
- BEGIN
- SELECT * FROM Users WHERE Id = @UserId
- END
- newSchema: ""
- expected: |
- DROP PROCEDURE [dbo].[GetUserById];
- GO
-- description: Create procedure with output parameters
- oldSchema: ""
- newSchema: |
- CREATE PROCEDURE [dbo].[GetUserCount]
- @DepartmentId int,
- @UserCount int OUTPUT
- AS
- BEGIN
- SELECT @UserCount = COUNT(*)
- FROM Users
- WHERE DepartmentId = @DepartmentId
- END
- expected: |
- CREATE PROCEDURE [dbo].[GetUserCount]
- @DepartmentId int,
- @UserCount int OUTPUT
- AS
- BEGIN
- SELECT @UserCount = COUNT(*)
- FROM Users
- WHERE DepartmentId = @DepartmentId
- END;
- GO
-- description: Alter procedure
- oldSchema: |
- CREATE PROCEDURE [dbo].[UpdateUser]
- @UserId int,
- @Name nvarchar(100)
- AS
- BEGIN
- UPDATE Users SET Name = @Name WHERE Id = @UserId
- END
- newSchema: |
- CREATE PROCEDURE [dbo].[UpdateUser]
- @UserId int,
- @Name nvarchar(100),
- @Email nvarchar(255)
- AS
- BEGIN
- UPDATE Users
- SET Name = @Name, Email = @Email
- WHERE Id = @UserId
- END
- expected: |
- DROP PROCEDURE [dbo].[UpdateUser];
- GO
- CREATE PROCEDURE [dbo].[UpdateUser]
- @UserId int,
- @Name nvarchar(100),
- @Email nvarchar(255)
- AS
- BEGIN
- UPDATE Users
- SET Name = @Name, Email = @Email
- WHERE Id = @UserId
- END;
- GO
-- description: Create procedure with transaction
- oldSchema: ""
- newSchema: |
- CREATE PROCEDURE [dbo].[TransferFunds]
- @FromAccount int,
- @ToAccount int,
- @Amount decimal(10,2)
- AS
- BEGIN
- BEGIN TRANSACTION
- BEGIN TRY
- UPDATE Accounts SET Balance = Balance - @Amount WHERE Id = @FromAccount
- UPDATE Accounts SET Balance = Balance + @Amount WHERE Id = @ToAccount
- COMMIT TRANSACTION
- END TRY
- BEGIN CATCH
- ROLLBACK TRANSACTION
- THROW
- END CATCH
- END
- expected: |
- CREATE PROCEDURE [dbo].[TransferFunds]
- @FromAccount int,
- @ToAccount int,
- @Amount decimal(10,2)
- AS
- BEGIN
- BEGIN TRANSACTION
- BEGIN TRY
- UPDATE Accounts SET Balance = Balance - @Amount WHERE Id = @FromAccount
- UPDATE Accounts SET Balance = Balance + @Amount WHERE Id = @ToAccount
- COMMIT TRANSACTION
- END TRY
- BEGIN CATCH
- ROLLBACK TRANSACTION
- THROW
- END CATCH
- END;
- GO
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml b/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml
deleted file mode 100644
index b30cfc827e..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml
+++ /dev/null
@@ -1,230 +0,0 @@
-- description: Safe order - drop dependent objects before tables
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL PRIMARY KEY,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE TABLE [dbo].[orders] (
- [id] int NOT NULL PRIMARY KEY,
- [user_id] int NOT NULL,
- CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users]([id])
- );
- GO
- CREATE INDEX [IX_orders_user_id] ON [dbo].[orders]([user_id]);
- GO
- CREATE VIEW [dbo].[v_user_orders] AS
- SELECT u.id, u.name, COUNT(o.id) as order_count
- FROM [dbo].[users] u
- LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
- GROUP BY u.id, u.name;
- GO
- CREATE PROCEDURE [dbo].[sp_get_user_orders]
- @user_id int
- AS
- BEGIN
- SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
- END;
- GO
- newSchema: ""
- expected: |
- ALTER TABLE [dbo].[orders] DROP CONSTRAINT [FK_orders_users];
- DROP PROCEDURE [dbo].[sp_get_user_orders];
- GO
- DROP VIEW [dbo].[v_user_orders];
- GO
- DROP TABLE [dbo].[orders];
- DROP TABLE [dbo].[users];
-- description: Safe order - create tables before dependent objects
- oldSchema: ""
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL PRIMARY KEY,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE TABLE [dbo].[orders] (
- [id] int NOT NULL PRIMARY KEY,
- [user_id] int NOT NULL,
- CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users]([id])
- );
- GO
- CREATE INDEX [IX_orders_user_id] ON [dbo].[orders]([user_id]);
- GO
- CREATE VIEW [dbo].[v_user_orders] AS
- SELECT u.id, u.name, COUNT(o.id) as order_count
- FROM [dbo].[users] u
- LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
- GROUP BY u.id, u.name;
- GO
- CREATE PROCEDURE [dbo].[sp_get_user_orders]
- @user_id int
- AS
- BEGIN
- SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
- END;
- GO
- expected: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL,
- CONSTRAINT [PK_users_1] PRIMARY KEY ([id])
- );
- CREATE TABLE [dbo].[orders] (
- [id] int NOT NULL,
- [user_id] int NOT NULL,
- CONSTRAINT [PK_orders_2] PRIMARY KEY ([id])
- );
- CREATE INDEX [IX_orders_user_id] ON [dbo].[orders] ([user_id]);
- ALTER TABLE [dbo].[orders] ADD CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
-
- GO
- CREATE VIEW [dbo].[v_user_orders] AS
- SELECT u.id, u.name, COUNT(o.id) as order_count
- FROM [dbo].[users] u
- LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
- GROUP BY u.id, u.name;
- GO
- CREATE PROCEDURE [dbo].[sp_get_user_orders]
- @user_id int
- AS
- BEGIN
- SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
- END;
- GO
-- description: Safe order - complex view dependencies with drops and creates
- oldSchema: |
- CREATE TABLE [dbo].[departments] (
- [id] int NOT NULL PRIMARY KEY,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE TABLE [dbo].[employees] (
- [id] int NOT NULL PRIMARY KEY,
- [name] nvarchar(100) NULL,
- [dept_id] int NULL
- );
- GO
- CREATE VIEW [dbo].[v_departments] AS
- SELECT id, name FROM [dbo].[departments];
- GO
- CREATE VIEW [dbo].[v_employees] AS
- SELECT e.id, e.name, e.dept_id, d.name as dept_name
- FROM [dbo].[employees] e
- LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
- GO
- CREATE VIEW [dbo].[v_employee_dept] AS
- SELECT id, name, dept_name
- FROM [dbo].[v_employees];
- GO
- newSchema: |
- CREATE TABLE [dbo].[departments] (
- [id] int NOT NULL PRIMARY KEY,
- [name] nvarchar(100) NULL,
- [location] nvarchar(200) NULL
- );
- GO
- CREATE TABLE [dbo].[employees] (
- [id] int NOT NULL PRIMARY KEY,
- [name] nvarchar(100) NULL,
- [dept_id] int NULL,
- [salary] decimal(10,2) NULL
- );
- GO
- CREATE VIEW [dbo].[v_departments] AS
- SELECT id, name, location FROM [dbo].[departments];
- GO
- CREATE VIEW [dbo].[v_employees] AS
- SELECT e.id, e.name, e.dept_id, e.salary, d.name as dept_name, d.location
- FROM [dbo].[employees] e
- LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
- GO
- CREATE VIEW [dbo].[v_employee_dept] AS
- SELECT id, name, salary, dept_name, location
- FROM [dbo].[v_employees];
- GO
- CREATE VIEW [dbo].[v_dept_summary] AS
- SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
- FROM [dbo].[v_employee_dept]
- GROUP BY dept_name, location;
- GO
- expected: |
- DROP VIEW [dbo].[v_employee_dept];
- GO
- DROP VIEW [dbo].[v_employees];
- GO
- DROP VIEW [dbo].[v_departments];
- GO
-
- ALTER TABLE [dbo].[departments] ADD [location] nvarchar(200) NULL;
-
- ALTER TABLE [dbo].[employees] ADD [salary] decimal(10,2) NULL;
-
-
- GO
- CREATE VIEW [dbo].[v_departments] AS
- SELECT id, name, location FROM [dbo].[departments];
- GO
- CREATE VIEW [dbo].[v_employees] AS
- SELECT e.id, e.name, e.dept_id, e.salary, d.name as dept_name, d.location
- FROM [dbo].[employees] e
- LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
- GO
- CREATE VIEW [dbo].[v_employee_dept] AS
- SELECT id, name, salary, dept_name, location
- FROM [dbo].[v_employees];
- GO
- CREATE VIEW [dbo].[v_dept_summary] AS
- SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
- FROM [dbo].[v_employee_dept]
- GROUP BY dept_name, location;
- GO
-- description: Safe order - circular view dependency fallback
- oldSchema: ""
- newSchema: |
- CREATE TABLE [dbo].[table1] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE TABLE [dbo].[table2] (
- [id] int NOT NULL,
- [value] nvarchar(100) NULL
- );
- GO
- -- Note: These views create a circular dependency which should fall back to original order
- CREATE VIEW [dbo].[v_circular1] AS
- SELECT t1.id, t1.name, t2.value
- FROM [dbo].[table1] t1
- JOIN [dbo].[table2] t2 ON t1.id = t2.id
- WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular2] v WHERE v.id = t1.id);
- GO
- CREATE VIEW [dbo].[v_circular2] AS
- SELECT t2.id, t2.value, t1.name
- FROM [dbo].[table2] t2
- JOIN [dbo].[table1] t1 ON t2.id = t1.id
- WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular1] v WHERE v.id = t2.id);
- GO
- expected: |
- CREATE TABLE [dbo].[table1] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- CREATE TABLE [dbo].[table2] (
- [id] int NOT NULL,
- [value] nvarchar(100) NULL
- );
-
- GO
- CREATE VIEW [dbo].[v_circular1] AS
- SELECT t1.id, t1.name, t2.value
- FROM [dbo].[table1] t1
- JOIN [dbo].[table2] t2 ON t1.id = t2.id
- WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular2] v WHERE v.id = t1.id);
- GO
- CREATE VIEW [dbo].[v_circular2] AS
- SELECT t2.id, t2.value, t1.name
- FROM [dbo].[table2] t2
- JOIN [dbo].[table1] t1 ON t2.id = t1.id
- WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular1] v WHERE v.id = t2.id);
- GO
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_tables.yaml b/backend/plugin/schema/mssql/test-data/test_migration_tables.yaml
deleted file mode 100644
index 51b53e2c59..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_migration_tables.yaml
+++ /dev/null
@@ -1,159 +0,0 @@
-- description: Create new table
- oldSchema: ""
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [email] nvarchar(255) NOT NULL,
- [created_at] datetime NOT NULL DEFAULT GETDATE(),
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [email] nvarchar(255) NOT NULL,
- [created_at] datetime NOT NULL DEFAULT GETDATE(),
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
-- description: Drop table
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: ""
- expected: |
- DROP TABLE [dbo].[users];
-- description: Add column to existing table
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [email] nvarchar(255) NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[users] ADD [email] nvarchar(255) NULL;
-
-- description: Drop column from table
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [email] nvarchar(255) NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[users] DROP COLUMN [email];
-
-- description: Alter column type
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(50) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[users] ALTER COLUMN [name] nvarchar(100) NOT NULL;
-
-- description: Change column nullability
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [email] nvarchar(255) NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NOT NULL,
- [email] nvarchar(255) NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[users] ALTER COLUMN [email] nvarchar(255) NULL;
-
-- description: Add default constraint
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [status] int NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [status] int NOT NULL DEFAULT 1,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_status] DEFAULT 1 FOR [status];
-
-- description: Create table with check constraint
- oldSchema: ""
- newSchema: |
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [price] decimal(10,2) NOT NULL,
- CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
- CONSTRAINT [CK_products_price] CHECK ([price] > 0)
- );
- expected: |
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [price] decimal(10,2) NOT NULL,
- CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
- CONSTRAINT [CK_products_price] CHECK ([price] > 0)
- );
-- description: Remove default constraint
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [status] int NOT NULL DEFAULT 1,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [status] int NOT NULL,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: ""
-
-- description: Change default constraint value
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [status] int NOT NULL DEFAULT 1,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [status] int NOT NULL DEFAULT 2,
- CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
- );
- expected: |+
- ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_status] DEFAULT 2 FOR [status];
-
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_views.yaml b/backend/plugin/schema/mssql/test-data/test_migration_views.yaml
deleted file mode 100644
index ec586afbd4..0000000000
--- a/backend/plugin/schema/mssql/test-data/test_migration_views.yaml
+++ /dev/null
@@ -1,283 +0,0 @@
-- description: Create single view
- oldSchema: ""
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- expected: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
-
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
-- description: Create views with dependencies - deterministic order
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE TABLE [dbo].[orders] (
- [id] int NOT NULL,
- [user_id] int NOT NULL,
- [amount] decimal(10,2) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- CREATE VIEW [dbo].[v_orders_with_users] AS
- SELECT o.id, o.user_id, o.amount, v.name
- FROM [dbo].[orders] o
- JOIN [dbo].[v_users] v ON o.user_id = v.id;
- GO
- CREATE VIEW [dbo].[v_user_order_summary] AS
- SELECT u.id, u.name, COUNT(o.id) as order_count
- FROM [dbo].[v_users] u
- LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
- GROUP BY u.id, u.name;
- GO
- expected: |
- CREATE TABLE [dbo].[orders] (
- [id] int NOT NULL,
- [user_id] int NOT NULL,
- [amount] decimal(10,2) NULL
- );
-
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- CREATE VIEW [dbo].[v_orders_with_users] AS
- SELECT o.id, o.user_id, o.amount, v.name
- FROM [dbo].[orders] o
- JOIN [dbo].[v_users] v ON o.user_id = v.id;
- GO
- CREATE VIEW [dbo].[v_user_order_summary] AS
- SELECT u.id, u.name, COUNT(o.id) as order_count
- FROM [dbo].[v_users] u
- LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
- GROUP BY u.id, u.name;
- GO
-- description: Drop views with dependencies - deterministic order
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE TABLE [dbo].[orders] (
- [id] int NOT NULL,
- [user_id] int NOT NULL,
- [amount] decimal(10,2) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- CREATE VIEW [dbo].[v_orders_with_users] AS
- SELECT o.id, o.user_id, o.amount, v.name
- FROM [dbo].[orders] o
- JOIN [dbo].[v_users] v ON o.user_id = v.id;
- GO
- CREATE VIEW [dbo].[v_user_order_summary] AS
- SELECT u.id, u.name, COUNT(o.id) as order_count
- FROM [dbo].[v_users] u
- LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
- GROUP BY u.id, u.name;
- GO
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE TABLE [dbo].[orders] (
- [id] int NOT NULL,
- [user_id] int NOT NULL,
- [amount] decimal(10,2) NULL
- );
- GO
- expected: |
- DROP VIEW [dbo].[v_user_order_summary];
- GO
- DROP VIEW [dbo].[v_orders_with_users];
- GO
- DROP VIEW [dbo].[v_users];
- GO
-- description: Alter view - drop and recreate
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL,
- [email] nvarchar(200) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name, email FROM [dbo].[users];
- GO
- expected: |
- DROP VIEW [dbo].[v_users];
- GO
-
- ALTER TABLE [dbo].[users] ADD [email] nvarchar(200) NULL;
-
-
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name, email FROM [dbo].[users];
- GO
-- description: Alter multiple views with dependencies
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- CREATE VIEW [dbo].[v_active_users] AS
- SELECT * FROM [dbo].[v_users] WHERE id > 0;
- GO
- newSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL,
- [status] nvarchar(50) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name, status FROM [dbo].[users];
- GO
- CREATE VIEW [dbo].[v_active_users] AS
- SELECT * FROM [dbo].[v_users] WHERE status = 'active';
- GO
- expected: |
- DROP VIEW [dbo].[v_active_users];
- GO
- DROP VIEW [dbo].[v_users];
- GO
-
- ALTER TABLE [dbo].[users] ADD [status] nvarchar(50) NULL;
-
-
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name, status FROM [dbo].[users];
- GO
- CREATE VIEW [dbo].[v_active_users] AS
- SELECT * FROM [dbo].[v_users] WHERE status = 'active';
- GO
-- description: Create views in different schemas
- oldSchema: |
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- newSchema: |
- CREATE SCHEMA [reporting];
- GO
- CREATE TABLE [dbo].[users] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL
- );
- GO
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- CREATE VIEW [reporting].[v_user_report] AS
- SELECT * FROM [dbo].[v_users];
- GO
- expected: |
- CREATE SCHEMA [reporting];
- GO
-
- CREATE VIEW [dbo].[v_users] AS
- SELECT id, name FROM [dbo].[users];
- GO
- CREATE VIEW [reporting].[v_user_report] AS
- SELECT * FROM [dbo].[v_users];
- GO
-- description: Complex view dependencies across schemas
- oldSchema: ""
- newSchema: |
- CREATE SCHEMA [sales];
- GO
- CREATE SCHEMA [reporting];
- GO
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL,
- [price] decimal(10,2) NULL
- );
- GO
- CREATE TABLE [sales].[orders] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [quantity] int NOT NULL
- );
- GO
- CREATE VIEW [sales].[v_order_details] AS
- SELECT o.id, o.product_id, o.quantity, p.name, p.price
- FROM [sales].[orders] o
- JOIN [dbo].[products] p ON o.product_id = p.id;
- GO
- CREATE VIEW [reporting].[v_sales_summary] AS
- SELECT product_id, SUM(quantity) as total_quantity, SUM(quantity * price) as total_revenue
- FROM [sales].[v_order_details]
- GROUP BY product_id;
- GO
- expected: |
- CREATE SCHEMA [reporting];
- GO
- CREATE SCHEMA [sales];
- GO
-
- CREATE TABLE [dbo].[products] (
- [id] int NOT NULL,
- [name] nvarchar(100) NULL,
- [price] decimal(10,2) NULL
- );
- CREATE TABLE [sales].[orders] (
- [id] int NOT NULL,
- [product_id] int NOT NULL,
- [quantity] int NOT NULL
- );
-
- GO
- CREATE VIEW [sales].[v_order_details] AS
- SELECT o.id, o.product_id, o.quantity, p.name, p.price
- FROM [sales].[orders] o
- JOIN [dbo].[products] p ON o.product_id = p.id;
- GO
- CREATE VIEW [reporting].[v_sales_summary] AS
- SELECT product_id, SUM(quantity) as total_quantity, SUM(quantity * price) as total_revenue
- FROM [sales].[v_order_details]
- GROUP BY product_id;
- GO
diff --git a/backend/plugin/schema/mssql/testdata/generate_migration.yaml b/backend/plugin/schema/mssql/testdata/generate_migration.yaml
new file mode 100644
index 0000000000..7ddba7ad37
--- /dev/null
+++ b/backend/plugin/schema/mssql/testdata/generate_migration.yaml
@@ -0,0 +1,3859 @@
+- description: Create new table
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ [created_at] datetime NOT NULL DEFAULT GETDATE(),
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ [created_at] datetime NOT NULL DEFAULT GETDATE(),
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+- description: Drop table
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: ""
+ expected: |
+ DROP TABLE [dbo].[users];
+- description: Add column to existing table
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [email] nvarchar(255) NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] ADD [email] nvarchar(255) NULL;
+
+- description: Drop column from table
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [email] nvarchar(255) NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] DROP COLUMN [email];
+
+- description: Alter column type
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(50) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] ALTER COLUMN [name] nvarchar(100) NOT NULL;
+
+- description: Change column nullability
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [email] nvarchar(255) NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] ALTER COLUMN [email] nvarchar(255) NULL;
+
+- description: Add default constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [status] int NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [status] int NOT NULL DEFAULT 1,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_status] DEFAULT 1 FOR [status];
+
+- description: Create table with check constraint
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [price] decimal(10,2) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
+ CONSTRAINT [CK_products_price] CHECK ([price] > 0)
+ );
+ expected: |
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [price] decimal(10,2) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
+ CONSTRAINT [CK_products_price] CHECK ([price] > 0)
+ );
+- description: Remove default constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [status] int NOT NULL DEFAULT 1,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [status] int NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: ""
+- description: Change default constraint value
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [status] int NOT NULL DEFAULT 1,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [status] int NOT NULL DEFAULT 2,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_status] DEFAULT 2 FOR [status];
+
+- description: Create regular index
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
+ expected: |+
+ CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
+
+- description: Drop index
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ DROP INDEX [IX_users_email] ON [dbo].[users];
+
+- description: Create unique index
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE UNIQUE NONCLUSTERED INDEX [UX_users_email] ON [dbo].[users] ([email]);
+ expected: |+
+ CREATE UNIQUE NONCLUSTERED INDEX [UX_users_email] ON [dbo].[users] ([email]);
+
+- description: Create unique constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [email] nvarchar(255) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id]),
+ CONSTRAINT [UQ_users_email] UNIQUE NONCLUSTERED ([email])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] ADD CONSTRAINT [UQ_users_email] UNIQUE NONCLUSTERED ([email]);
+
+- description: Create clustered columnstore index
+ oldSchema: |
+ CREATE TABLE [dbo].[sales_data] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [sale_date] datetime NOT NULL,
+ [amount] decimal(10,2) NOT NULL
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[sales_data] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [sale_date] datetime NOT NULL,
+ [amount] decimal(10,2) NOT NULL
+ );
+ CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
+ expected: |+
+ CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
+
+- description: Create nonclustered columnstore index with columns
+ oldSchema: |
+ CREATE TABLE [dbo].[analytics_data] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [sale_date] datetime NOT NULL,
+ [amount] decimal(10,2) NOT NULL,
+ [region] nvarchar(50) NOT NULL,
+ CONSTRAINT [PK_analytics_data] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[analytics_data] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [sale_date] datetime NOT NULL,
+ [amount] decimal(10,2) NOT NULL,
+ [region] nvarchar(50) NOT NULL,
+ CONSTRAINT [PK_analytics_data] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_analytics_data] ON [dbo].[analytics_data] ([product_id], [sale_date], [amount]);
+ expected: |+
+ CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_analytics_data] ON [dbo].[analytics_data] ([product_id], [sale_date], [amount]);
+
+- description: Drop columnstore index
+ oldSchema: |
+ CREATE TABLE [dbo].[sales_data] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [sale_date] datetime NOT NULL,
+ [amount] decimal(10,2) NOT NULL
+ );
+ CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
+ newSchema: |
+ CREATE TABLE [dbo].[sales_data] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [sale_date] datetime NOT NULL,
+ [amount] decimal(10,2) NOT NULL
+ );
+ expected: |+
+ DROP INDEX [CCI_sales_data] ON [dbo].[sales_data];
+
+- description: Add foreign key constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [department_id] int NOT NULL,
+ CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [department_id] int NOT NULL,
+ CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id]),
+ CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[employees] ADD CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+
+- description: Drop foreign key constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [department_id] int NOT NULL,
+ CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id]),
+ CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([id])
+ );
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ [department_id] int NOT NULL,
+ CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[employees] DROP CONSTRAINT [FK_employees_departments];
+ GO
+
+- description: Add check constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [price] decimal(10,2) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [price] decimal(10,2) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
+ CONSTRAINT [CK_products_price] CHECK ([price] > 0)
+ );
+ expected: |+
+ ALTER TABLE [dbo].[products] ADD CONSTRAINT [CK_products_price] CHECK ([price] > 0);
+
+- description: Drop check constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [price] decimal(10,2) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
+ CONSTRAINT [CK_products_price] CHECK ([price] > 0)
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [price] decimal(10,2) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[products] DROP CONSTRAINT [CK_products_price];
+
+- description: Add primary key to existing table
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] ADD CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id]);
+
+- description: Drop primary key constraint
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
+ );
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NOT NULL
+ );
+ expected: |+
+ ALTER TABLE [dbo].[users] DROP CONSTRAINT [PK_users];
+
+- description: Create scalar function
+ oldSchema: ""
+ newSchema: |
+ CREATE FUNCTION [dbo].[GetFullName]
+ (
+ @FirstName nvarchar(50),
+ @LastName nvarchar(50)
+ )
+ RETURNS nvarchar(101)
+ AS
+ BEGIN
+ RETURN @FirstName + ' ' + @LastName
+ END
+ expected: |
+ CREATE FUNCTION [dbo].[GetFullName]
+ (
+ @FirstName nvarchar(50),
+ @LastName nvarchar(50)
+ )
+ RETURNS nvarchar(101)
+ AS
+ BEGIN
+ RETURN @FirstName + ' ' + @LastName
+ END;
+ GO
+- description: Drop function
+ oldSchema: |
+ CREATE FUNCTION [dbo].[GetFullName]
+ (
+ @FirstName nvarchar(50),
+ @LastName nvarchar(50)
+ )
+ RETURNS nvarchar(101)
+ AS
+ BEGIN
+ RETURN @FirstName + ' ' + @LastName
+ END
+ newSchema: ""
+ expected: |
+ DROP FUNCTION [dbo].[GetFullName];
+ GO
+- description: Create table-valued function
+ oldSchema: ""
+ newSchema: |
+ CREATE FUNCTION [dbo].[GetEmployeesByDepartment]
+ (
+ @DepartmentId int
+ )
+ RETURNS TABLE
+ AS
+ RETURN
+ (
+ SELECT Id, Name, Email
+ FROM Employees
+ WHERE DepartmentId = @DepartmentId
+ )
+ expected: |
+ CREATE FUNCTION [dbo].[GetEmployeesByDepartment]
+ (
+ @DepartmentId int
+ )
+ RETURNS TABLE
+ AS
+ RETURN
+ (
+ SELECT Id, Name, Email
+ FROM Employees
+ WHERE DepartmentId = @DepartmentId
+ );
+ GO
+- description: Create inline table-valued function
+ oldSchema: ""
+ newSchema: |
+ CREATE FUNCTION [dbo].[GetActiveUsers]()
+ RETURNS @Users TABLE
+ (
+ UserId int,
+ UserName nvarchar(100),
+ LastLogin datetime
+ )
+ AS
+ BEGIN
+ INSERT INTO @Users
+ SELECT Id, Name, LastLogin
+ FROM Users
+ WHERE IsActive = 1
+ RETURN
+ END
+ expected: |
+ CREATE FUNCTION [dbo].[GetActiveUsers]()
+ RETURNS @Users TABLE
+ (
+ UserId int,
+ UserName nvarchar(100),
+ LastLogin datetime
+ )
+ AS
+ BEGIN
+ INSERT INTO @Users
+ SELECT Id, Name, LastLogin
+ FROM Users
+ WHERE IsActive = 1
+ RETURN
+ END;
+ GO
+- description: Create simple procedure
+ oldSchema: ""
+ newSchema: |
+ CREATE PROCEDURE [dbo].[GetUserById]
+ @UserId int
+ AS
+ BEGIN
+ SELECT * FROM Users WHERE Id = @UserId
+ END
+ expected: |
+ CREATE PROCEDURE [dbo].[GetUserById]
+ @UserId int
+ AS
+ BEGIN
+ SELECT * FROM Users WHERE Id = @UserId
+ END;
+ GO
+- description: Drop procedure
+ oldSchema: |
+ CREATE PROCEDURE [dbo].[GetUserById]
+ @UserId int
+ AS
+ BEGIN
+ SELECT * FROM Users WHERE Id = @UserId
+ END
+ newSchema: ""
+ expected: |
+ DROP PROCEDURE [dbo].[GetUserById];
+ GO
+- description: Create procedure with output parameters
+ oldSchema: ""
+ newSchema: |
+ CREATE PROCEDURE [dbo].[GetUserCount]
+ @DepartmentId int,
+ @UserCount int OUTPUT
+ AS
+ BEGIN
+ SELECT @UserCount = COUNT(*)
+ FROM Users
+ WHERE DepartmentId = @DepartmentId
+ END
+ expected: |
+ CREATE PROCEDURE [dbo].[GetUserCount]
+ @DepartmentId int,
+ @UserCount int OUTPUT
+ AS
+ BEGIN
+ SELECT @UserCount = COUNT(*)
+ FROM Users
+ WHERE DepartmentId = @DepartmentId
+ END;
+ GO
+- description: Alter procedure
+ oldSchema: |
+ CREATE PROCEDURE [dbo].[UpdateUser]
+ @UserId int,
+ @Name nvarchar(100)
+ AS
+ BEGIN
+ UPDATE Users SET Name = @Name WHERE Id = @UserId
+ END
+ newSchema: |
+ CREATE PROCEDURE [dbo].[UpdateUser]
+ @UserId int,
+ @Name nvarchar(100),
+ @Email nvarchar(255)
+ AS
+ BEGIN
+ UPDATE Users
+ SET Name = @Name, Email = @Email
+ WHERE Id = @UserId
+ END
+ expected: |
+ DROP PROCEDURE [dbo].[UpdateUser];
+ GO
+ CREATE PROCEDURE [dbo].[UpdateUser]
+ @UserId int,
+ @Name nvarchar(100),
+ @Email nvarchar(255)
+ AS
+ BEGIN
+ UPDATE Users
+ SET Name = @Name, Email = @Email
+ WHERE Id = @UserId
+ END;
+ GO
+- description: Create procedure with transaction
+ oldSchema: ""
+ newSchema: |
+ CREATE PROCEDURE [dbo].[TransferFunds]
+ @FromAccount int,
+ @ToAccount int,
+ @Amount decimal(10,2)
+ AS
+ BEGIN
+ BEGIN TRANSACTION
+ BEGIN TRY
+ UPDATE Accounts SET Balance = Balance - @Amount WHERE Id = @FromAccount
+ UPDATE Accounts SET Balance = Balance + @Amount WHERE Id = @ToAccount
+ COMMIT TRANSACTION
+ END TRY
+ BEGIN CATCH
+ ROLLBACK TRANSACTION
+ THROW
+ END CATCH
+ END
+ expected: |
+ CREATE PROCEDURE [dbo].[TransferFunds]
+ @FromAccount int,
+ @ToAccount int,
+ @Amount decimal(10,2)
+ AS
+ BEGIN
+ BEGIN TRANSACTION
+ BEGIN TRY
+ UPDATE Accounts SET Balance = Balance - @Amount WHERE Id = @FromAccount
+ UPDATE Accounts SET Balance = Balance + @Amount WHERE Id = @ToAccount
+ COMMIT TRANSACTION
+ END TRY
+ BEGIN CATCH
+ ROLLBACK TRANSACTION
+ THROW
+ END CATCH
+ END;
+ GO
+- description: Create single view
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ expected: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+- description: Create views with dependencies - deterministic order
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_orders_with_users] AS
+ SELECT o.id, o.user_id, o.amount, v.name
+ FROM [dbo].[orders] o
+ JOIN [dbo].[v_users] v ON o.user_id = v.id;
+ GO
+ CREATE VIEW [dbo].[v_user_order_summary] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[v_users] u
+ LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ expected: |
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_orders_with_users] AS
+ SELECT o.id, o.user_id, o.amount, v.name
+ FROM [dbo].[orders] o
+ JOIN [dbo].[v_users] v ON o.user_id = v.id;
+ GO
+ CREATE VIEW [dbo].[v_user_order_summary] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[v_users] u
+ LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+- description: Drop views with dependencies - deterministic order
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_orders_with_users] AS
+ SELECT o.id, o.user_id, o.amount, v.name
+ FROM [dbo].[orders] o
+ JOIN [dbo].[v_users] v ON o.user_id = v.id;
+ GO
+ CREATE VIEW [dbo].[v_user_order_summary] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[v_users] u
+ LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_user_order_summary];
+ GO
+ DROP VIEW [dbo].[v_orders_with_users];
+ GO
+ DROP VIEW [dbo].[v_users];
+ GO
+- description: Alter view - drop and recreate
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [email] nvarchar(200) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, email FROM [dbo].[users];
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_users];
+ GO
+
+ ALTER TABLE [dbo].[users] ADD [email] nvarchar(200) NULL;
+
+
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, email FROM [dbo].[users];
+ GO
+- description: Alter multiple views with dependencies
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_active_users] AS
+ SELECT * FROM [dbo].[v_users] WHERE id > 0;
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [status] nvarchar(50) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, status FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_active_users] AS
+ SELECT * FROM [dbo].[v_users] WHERE status = 'active';
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_active_users];
+ GO
+ DROP VIEW [dbo].[v_users];
+ GO
+
+ ALTER TABLE [dbo].[users] ADD [status] nvarchar(50) NULL;
+
+
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, status FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_active_users] AS
+ SELECT * FROM [dbo].[v_users] WHERE status = 'active';
+ GO
+- description: Create views in different schemas
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ newSchema: |
+ CREATE SCHEMA [reporting];
+ GO
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [reporting].[v_user_report] AS
+ SELECT * FROM [dbo].[v_users];
+ GO
+ expected: |
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [reporting].[v_user_report] AS
+ SELECT * FROM [dbo].[v_users];
+ GO
+- description: Complex view dependencies across schemas
+ oldSchema: ""
+ newSchema: |
+ CREATE SCHEMA [sales];
+ GO
+ CREATE SCHEMA [reporting];
+ GO
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [price] decimal(10,2) NULL
+ );
+ GO
+ CREATE TABLE [sales].[orders] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [quantity] int NOT NULL
+ );
+ GO
+ CREATE VIEW [sales].[v_order_details] AS
+ SELECT o.id, o.product_id, o.quantity, p.name, p.price
+ FROM [sales].[orders] o
+ JOIN [dbo].[products] p ON o.product_id = p.id;
+ GO
+ CREATE VIEW [reporting].[v_sales_summary] AS
+ SELECT product_id, SUM(quantity) as total_quantity, SUM(quantity * price) as total_revenue
+ FROM [sales].[v_order_details]
+ GROUP BY product_id;
+ GO
+ expected: |
+ CREATE SCHEMA [reporting];
+ GO
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [price] decimal(10,2) NULL
+ );
+ CREATE TABLE [sales].[orders] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [quantity] int NOT NULL
+ );
+
+ GO
+ CREATE VIEW [sales].[v_order_details] AS
+ SELECT o.id, o.product_id, o.quantity, p.name, p.price
+ FROM [sales].[orders] o
+ JOIN [dbo].[products] p ON o.product_id = p.id;
+ GO
+ CREATE VIEW [reporting].[v_sales_summary] AS
+ SELECT product_id, SUM(quantity) as total_quantity, SUM(quantity * price) as total_revenue
+ FROM [sales].[v_order_details]
+ GROUP BY product_id;
+ GO
+- description: Safe order - drop dependent objects before tables
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL PRIMARY KEY,
+ [user_id] int NOT NULL,
+ CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users]([id])
+ );
+ GO
+ CREATE INDEX [IX_orders_user_id] ON [dbo].[orders]([user_id]);
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[users] u
+ LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ CREATE PROCEDURE [dbo].[sp_get_user_orders]
+ @user_id int
+ AS
+ BEGIN
+ SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
+ END;
+ GO
+ newSchema: ""
+ expected: |
+ ALTER TABLE [dbo].[orders] DROP CONSTRAINT [FK_orders_users];
+ DROP PROCEDURE [dbo].[sp_get_user_orders];
+ GO
+ DROP VIEW [dbo].[v_user_orders];
+ GO
+ DROP TABLE [dbo].[orders];
+ DROP TABLE [dbo].[users];
+- description: Safe order - create tables before dependent objects
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL PRIMARY KEY,
+ [user_id] int NOT NULL,
+ CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users]([id])
+ );
+ GO
+ CREATE INDEX [IX_orders_user_id] ON [dbo].[orders]([user_id]);
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[users] u
+ LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ CREATE PROCEDURE [dbo].[sp_get_user_orders]
+ @user_id int
+ AS
+ BEGIN
+ SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
+ END;
+ GO
+ expected: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ CONSTRAINT [PK_users_1] PRIMARY KEY ([id])
+ );
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ CONSTRAINT [PK_orders_2] PRIMARY KEY ([id])
+ );
+ CREATE INDEX [IX_orders_user_id] ON [dbo].[orders] ([user_id]);
+ ALTER TABLE [dbo].[orders] ADD CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[users] u
+ LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ CREATE PROCEDURE [dbo].[sp_get_user_orders]
+ @user_id int
+ AS
+ BEGIN
+ SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
+ END;
+ GO
+- description: Safe order - complex view dependencies with drops and creates
+ oldSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL,
+ [dept_id] int NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_departments] AS
+ SELECT id, name FROM [dbo].[departments];
+ GO
+ CREATE VIEW [dbo].[v_employees] AS
+ SELECT e.id, e.name, e.dept_id, d.name as dept_name
+ FROM [dbo].[employees] e
+ LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
+ GO
+ CREATE VIEW [dbo].[v_employee_dept] AS
+ SELECT id, name, dept_name
+ FROM [dbo].[v_employees];
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL,
+ [location] nvarchar(200) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL,
+ [dept_id] int NULL,
+ [salary] decimal(10,2) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_departments] AS
+ SELECT id, name, location FROM [dbo].[departments];
+ GO
+ CREATE VIEW [dbo].[v_employees] AS
+ SELECT e.id, e.name, e.dept_id, e.salary, d.name as dept_name, d.location
+ FROM [dbo].[employees] e
+ LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
+ GO
+ CREATE VIEW [dbo].[v_employee_dept] AS
+ SELECT id, name, salary, dept_name, location
+ FROM [dbo].[v_employees];
+ GO
+ CREATE VIEW [dbo].[v_dept_summary] AS
+ SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
+ FROM [dbo].[v_employee_dept]
+ GROUP BY dept_name, location;
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_employee_dept];
+ GO
+ DROP VIEW [dbo].[v_employees];
+ GO
+ DROP VIEW [dbo].[v_departments];
+ GO
+
+ ALTER TABLE [dbo].[departments] ADD [location] nvarchar(200) NULL;
+
+ ALTER TABLE [dbo].[employees] ADD [salary] decimal(10,2) NULL;
+
+
+ GO
+ CREATE VIEW [dbo].[v_departments] AS
+ SELECT id, name, location FROM [dbo].[departments];
+ GO
+ CREATE VIEW [dbo].[v_employees] AS
+ SELECT e.id, e.name, e.dept_id, e.salary, d.name as dept_name, d.location
+ FROM [dbo].[employees] e
+ LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
+ GO
+ CREATE VIEW [dbo].[v_employee_dept] AS
+ SELECT id, name, salary, dept_name, location
+ FROM [dbo].[v_employees];
+ GO
+ CREATE VIEW [dbo].[v_dept_summary] AS
+ SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
+ FROM [dbo].[v_employee_dept]
+ GROUP BY dept_name, location;
+ GO
+- description: Safe order - circular view dependency fallback
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[table1] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[table2] (
+ [id] int NOT NULL,
+ [value] nvarchar(100) NULL
+ );
+ GO
+ -- Note: These views create a circular dependency which should fall back to original order
+ CREATE VIEW [dbo].[v_circular1] AS
+ SELECT t1.id, t1.name, t2.value
+ FROM [dbo].[table1] t1
+ JOIN [dbo].[table2] t2 ON t1.id = t2.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular2] v WHERE v.id = t1.id);
+ GO
+ CREATE VIEW [dbo].[v_circular2] AS
+ SELECT t2.id, t2.value, t1.name
+ FROM [dbo].[table2] t2
+ JOIN [dbo].[table1] t1 ON t2.id = t1.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular1] v WHERE v.id = t2.id);
+ GO
+ expected: |
+ CREATE TABLE [dbo].[table1] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ CREATE TABLE [dbo].[table2] (
+ [id] int NOT NULL,
+ [value] nvarchar(100) NULL
+ );
+
+ GO
+ CREATE VIEW [dbo].[v_circular1] AS
+ SELECT t1.id, t1.name, t2.value
+ FROM [dbo].[table1] t1
+ JOIN [dbo].[table2] t2 ON t1.id = t2.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular2] v WHERE v.id = t1.id);
+ GO
+ CREATE VIEW [dbo].[v_circular2] AS
+ SELECT t2.id, t2.value, t1.name
+ FROM [dbo].[table2] t2
+ JOIN [dbo].[table1] t1 ON t2.id = t1.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular1] v WHERE v.id = t2.id);
+ GO
+- description: Basic table operations with foreign keys, indexes, and constraints
+ oldSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ [status] NVARCHAR(20),
+ CONSTRAINT [uk_users_email] UNIQUE ([email]),
+ CONSTRAINT [ck_users_status] CHECK ([status] IN ('active', 'inactive', 'suspended'))
+ );
+
+ CREATE INDEX [idx_users_username] ON [app].[users] ([username]);
+
+ CREATE TABLE [app].[posts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NTEXT,
+ [published_at] DATETIME2,
+ CONSTRAINT [fk_posts_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]) ON DELETE CASCADE
+ );
+
+ CREATE INDEX [idx_posts_user_id] ON [app].[posts] ([user_id]);
+
+ CREATE TABLE [app].[comments] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [post_id] INT NOT NULL,
+ [user_id] INT NOT NULL,
+ [content] NTEXT NOT NULL,
+ [created_at] DATETIME2,
+ CONSTRAINT [fk_comments_post] FOREIGN KEY ([post_id]) REFERENCES [app].[posts]([id]) ON DELETE CASCADE,
+ CONSTRAINT [fk_comments_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id])
+ );
+
+ CREATE INDEX [idx_comments_post_id] ON [app].[comments] ([post_id]);
+ newSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ CONSTRAINT [uk_users_email] UNIQUE ([email])
+ );
+
+ CREATE INDEX [idx_users_username] ON [app].[users] ([username]);
+
+ CREATE TABLE [app].[posts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NTEXT,
+ [published_at] DATETIME2,
+ CONSTRAINT [fk_posts_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]) ON DELETE CASCADE
+ );
+
+ CREATE INDEX [idx_posts_user_id] ON [app].[posts] ([user_id]);
+ expected: |+
+ ALTER TABLE [app].[comments] DROP CONSTRAINT [fk_comments_post];
+ ALTER TABLE [app].[comments] DROP CONSTRAINT [fk_comments_user];
+ ALTER TABLE [app].[users] DROP CONSTRAINT [ck_users_status];
+ ALTER TABLE [app].[users] DROP COLUMN [status];
+ GO
+ DROP TABLE [app].[comments];
+
+- description: Cross-schema operations with new schema creation
+ oldSchema: |
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE SCHEMA [inventory];
+ GO
+
+ CREATE TABLE [sales].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100)
+ );
+
+ CREATE TABLE [sales].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [customer_id] INT NOT NULL,
+ [order_date] DATE,
+ [total] DECIMAL(10,2),
+ [product_id] INT,
+ CONSTRAINT [fk_orders_customer] FOREIGN KEY ([customer_id]) REFERENCES [sales].[customers]([id])
+ );
+
+ CREATE TABLE [inventory].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [category_id] INT,
+ CONSTRAINT [ck_products_price] CHECK ([price] > 0)
+ );
+
+ ALTER TABLE [sales].[orders] ADD CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [inventory].[products]([id]);
+ newSchema: |
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE TABLE [sales].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100)
+ );
+
+ CREATE TABLE [sales].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [customer_id] INT NOT NULL,
+ [order_date] DATE,
+ [total] DECIMAL(10,2),
+ CONSTRAINT [fk_orders_customer] FOREIGN KEY ([customer_id]) REFERENCES [sales].[customers]([id])
+ );
+ expected: |+
+ ALTER TABLE [sales].[orders] DROP COLUMN [product_id];
+ DROP TABLE [inventory].[products];
+ DROP SCHEMA [inventory];
+ GO
+
+- description: View creation with dependencies
+ oldSchema: |
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE TABLE [reporting].[sales_data] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [product_name] NVARCHAR(100) NOT NULL,
+ [quantity] INT NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [sale_date] DATE
+ );
+
+ CREATE TABLE [reporting].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [region] NVARCHAR(50)
+ );
+ GO
+
+ CREATE VIEW [reporting].[product_summary] AS
+ SELECT
+ [product_name],
+ COUNT(*) as [sale_count],
+ SUM([quantity]) as [total_quantity],
+ AVG([price]) as [avg_price]
+ FROM [reporting].[sales_data]
+ GROUP BY [product_name];
+ GO
+
+ CREATE VIEW [reporting].[top_products] AS
+ SELECT TOP 10
+ [product_name],
+ [total_quantity]
+ FROM [reporting].[product_summary]
+ WHERE [total_quantity] > 100
+ ORDER BY [total_quantity] DESC;
+ GO
+ newSchema: |
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE TABLE [reporting].[sales_data] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [product_name] NVARCHAR(100) NOT NULL,
+ [quantity] INT NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [sale_date] DATE
+ );
+
+ CREATE TABLE [reporting].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [region] NVARCHAR(50)
+ );
+ expected: |
+ DROP VIEW [reporting].[top_products];
+ GO
+ DROP VIEW [reporting].[product_summary];
+ GO
+- description: Functions and procedures creation
+ oldSchema: |
+ CREATE SCHEMA [calc];
+ GO
+
+ CREATE TABLE [calc].[numbers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [value] INT NOT NULL,
+ [category] NVARCHAR(20)
+ );
+ GO
+
+ CREATE FUNCTION [calc].[square](@input INT)
+ RETURNS INT
+ AS
+ BEGIN
+ RETURN @input * @input;
+ END;
+ GO
+
+ CREATE FUNCTION [calc].[get_numbers_by_category](@category NVARCHAR(20))
+ RETURNS TABLE
+ AS
+ RETURN (
+ SELECT [id], [value], [category]
+ FROM [calc].[numbers]
+ WHERE [category] = @category
+ );
+ GO
+
+ CREATE PROCEDURE [calc].[add_number]
+ @value INT,
+ @category NVARCHAR(20)
+ AS
+ BEGIN
+ INSERT INTO [calc].[numbers] ([value], [category])
+ VALUES (@value, @category);
+ END;
+ GO
+ newSchema: |
+ CREATE SCHEMA [calc];
+ GO
+
+ CREATE TABLE [calc].[numbers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [value] INT NOT NULL,
+ [category] NVARCHAR(20)
+ );
+ expected: |
+ DROP PROCEDURE [calc].[add_number];
+ GO
+ DROP FUNCTION [calc].[get_numbers_by_category];
+ GO
+ DROP FUNCTION [calc].[square];
+ GO
+- description: Various index types including filtered and computed column indexes
+ oldSchema: |
+ CREATE SCHEMA [perf];
+ GO
+
+ CREATE TABLE [perf].[events] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_name] NVARCHAR(100) NOT NULL,
+ [event_data] NVARCHAR(MAX),
+ [timestamp] DATETIME2,
+ [user_id] INT,
+ [category] NVARCHAR(50),
+ [event_month] AS DATEPART(MONTH, [timestamp])
+ );
+
+ CREATE INDEX [idx_events_timestamp] ON [perf].[events] ([timestamp]);
+ CREATE INDEX [idx_events_user_category] ON [perf].[events] ([user_id], [category]);
+ CREATE UNIQUE INDEX [idx_events_name_timestamp] ON [perf].[events] ([event_name], [timestamp]);
+
+ CREATE INDEX [idx_events_recent] ON [perf].[events] ([event_name])
+ WHERE [timestamp] >= '2023-01-01';
+
+ CREATE INDEX [idx_events_month] ON [perf].[events] ([event_month]);
+ newSchema: |
+ CREATE SCHEMA [perf];
+ GO
+
+ CREATE TABLE [perf].[events] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_name] NVARCHAR(100) NOT NULL,
+ [event_data] NVARCHAR(MAX),
+ [timestamp] DATETIME2,
+ [user_id] INT,
+ [category] NVARCHAR(50)
+ );
+ expected: |+
+ DROP INDEX [idx_events_month] ON [perf].[events];
+ DROP INDEX [idx_events_name_timestamp] ON [perf].[events];
+ DROP INDEX [idx_events_recent] ON [perf].[events];
+ DROP INDEX [idx_events_timestamp] ON [perf].[events];
+ DROP INDEX [idx_events_user_category] ON [perf].[events];
+ GO
+ ALTER TABLE [perf].[events] DROP COLUMN [event_month];
+
+- description: Complex constraints with multiple check constraints and foreign keys
+ oldSchema: |
+ CREATE SCHEMA [finance];
+ GO
+
+ CREATE TABLE [finance].[accounts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [account_number] NVARCHAR(20) NOT NULL,
+ [balance] DECIMAL(15,2),
+ [account_type] NVARCHAR(20) NOT NULL,
+ [created_at] DATETIME2 DEFAULT GETDATE(),
+ CONSTRAINT [ck_accounts_balance] CHECK ([balance] >= 0),
+ CONSTRAINT [ck_accounts_type] CHECK ([account_type] IN ('CHECKING', 'SAVINGS', 'CREDIT')),
+ CONSTRAINT [uk_accounts_number] UNIQUE ([account_number])
+ );
+
+ CREATE TABLE [finance].[transactions] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [account_id] INT NOT NULL,
+ [amount] DECIMAL(15,2) NOT NULL,
+ [transaction_type] NVARCHAR(20) NOT NULL,
+ [transaction_date] DATETIME2,
+ CONSTRAINT [fk_transactions_account] FOREIGN KEY ([account_id]) REFERENCES [finance].[accounts]([id]),
+ CONSTRAINT [ck_transactions_amount] CHECK ([amount] != 0),
+ CONSTRAINT [ck_transactions_type] CHECK ([transaction_type] IN ('DEBIT', 'CREDIT'))
+ );
+ newSchema: |
+ CREATE SCHEMA [finance];
+ GO
+
+ CREATE TABLE [finance].[accounts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [account_number] NVARCHAR(20) NOT NULL,
+ [balance] DECIMAL(15,2),
+ [account_type] NVARCHAR(20) NOT NULL,
+ [created_at] DATETIME2 DEFAULT GETDATE()
+ );
+ expected: |+
+ ALTER TABLE [finance].[transactions] DROP CONSTRAINT [fk_transactions_account];
+ ALTER TABLE [finance].[accounts] DROP CONSTRAINT [ck_accounts_balance];
+ ALTER TABLE [finance].[accounts] DROP CONSTRAINT [ck_accounts_type];
+ ALTER TABLE [finance].[accounts] DROP CONSTRAINT [uk_accounts_number];
+ DROP TABLE [finance].[transactions];
+
+- description: Column additions and self-referencing foreign keys
+ oldSchema: |
+ CREATE SCHEMA [hr];
+ GO
+
+ CREATE TABLE [hr].[departments] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [budget] DECIMAL(15,2)
+ );
+
+ CREATE TABLE [hr].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [first_name] NVARCHAR(50),
+ [last_name] NVARCHAR(50),
+ [email] NVARCHAR(100),
+ [phone] VARCHAR(20),
+ [hire_date] DATE,
+ [salary] DECIMAL(10,2),
+ [department_id] INT,
+ [manager_id] INT,
+ [status] NVARCHAR(20),
+ CONSTRAINT [fk_employees_department] FOREIGN KEY ([department_id]) REFERENCES [hr].[departments]([id]),
+ CONSTRAINT [fk_employees_manager] FOREIGN KEY ([manager_id]) REFERENCES [hr].[employees]([id]),
+ CONSTRAINT [ck_employees_salary] CHECK ([salary] > 0),
+ CONSTRAINT [ck_employees_status] CHECK ([status] IN ('ACTIVE', 'INACTIVE', 'TERMINATED'))
+ );
+ newSchema: |
+ CREATE SCHEMA [hr];
+ GO
+
+ CREATE TABLE [hr].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [first_name] NVARCHAR(50),
+ [last_name] NVARCHAR(50),
+ [email] NVARCHAR(100),
+ [phone] VARCHAR(20),
+ [hire_date] DATE,
+ [salary] DECIMAL(10,2)
+ );
+ expected: |+
+ ALTER TABLE [hr].[employees] DROP CONSTRAINT [fk_employees_department];
+ GO
+ ALTER TABLE [hr].[employees] DROP CONSTRAINT [fk_employees_manager];
+ GO
+ ALTER TABLE [hr].[employees] DROP CONSTRAINT [ck_employees_salary];
+ ALTER TABLE [hr].[employees] DROP CONSTRAINT [ck_employees_status];
+ ALTER TABLE [hr].[employees] DROP CONSTRAINT [PK_employees_2];
+ GO
+ ALTER TABLE [hr].[employees] DROP COLUMN [department_id];
+ ALTER TABLE [hr].[employees] DROP COLUMN [manager_id];
+ ALTER TABLE [hr].[employees] DROP COLUMN [status];
+ GO
+ DROP TABLE [hr].[departments];
+
+ ALTER TABLE [hr].[employees] ADD CONSTRAINT [PK_employees_1] PRIMARY KEY ([id]);
+
+- description: Multiple schema dependencies with cross-schema foreign keys
+ oldSchema: |
+ CREATE SCHEMA [core];
+ GO
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [core].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE [core].[roles] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(50) NOT NULL
+ );
+
+ CREATE TABLE [core].[user_roles] (
+ [user_id] INT NOT NULL,
+ [role_id] INT NOT NULL,
+ [assigned_at] DATETIME2,
+ CONSTRAINT [pk_user_roles] PRIMARY KEY ([user_id], [role_id]),
+ CONSTRAINT [fk_user_roles_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE,
+ CONSTRAINT [fk_user_roles_role] FOREIGN KEY ([role_id]) REFERENCES [core].[roles]([id]) ON DELETE CASCADE
+ );
+
+ CREATE TABLE [app].[sessions] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [token] NVARCHAR(255) NOT NULL,
+ [expires_at] DATETIME2 NOT NULL,
+ CONSTRAINT [fk_sessions_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE
+ );
+
+ CREATE TABLE [app].[audit_log] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT,
+ [action] NVARCHAR(100) NOT NULL,
+ [timestamp] DATETIME2,
+ [details] NVARCHAR(MAX),
+ CONSTRAINT [fk_audit_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id])
+ );
+ newSchema: |
+ CREATE SCHEMA [core];
+ GO
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [core].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE [core].[roles] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(50) NOT NULL
+ );
+ expected: |
+ ALTER TABLE [app].[audit_log] DROP CONSTRAINT [fk_audit_user];
+ ALTER TABLE [app].[sessions] DROP CONSTRAINT [fk_sessions_user];
+ ALTER TABLE [core].[user_roles] DROP CONSTRAINT [fk_user_roles_user];
+ ALTER TABLE [core].[user_roles] DROP CONSTRAINT [fk_user_roles_role];
+ DROP TABLE [app].[audit_log];
+ DROP TABLE [app].[sessions];
+ DROP TABLE [core].[user_roles];
+- description: Computed columns with indexes
+ oldSchema: |
+ CREATE SCHEMA [ecommerce];
+ GO
+
+ CREATE TABLE [ecommerce].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [tax_rate] DECIMAL(5,4),
+ [price_with_tax] AS ([price] * (1 + [tax_rate])),
+ [price_category] AS (
+ CASE
+ WHEN [price] < 10 THEN 'Budget'
+ WHEN [price] < 100 THEN 'Standard'
+ ELSE 'Premium'
+ END
+ )
+ );
+ GO
+
+ CREATE INDEX [idx_products_price_category] ON [ecommerce].[products] ([price_category]);
+ CREATE INDEX [idx_products_price_with_tax] ON [ecommerce].[products] ([price_with_tax]);
+
+ CREATE TABLE [ecommerce].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [unit_price] DECIMAL(10,2) NOT NULL,
+ [total] DECIMAL(15,2),
+ [order_date] DATETIME2,
+ [computed_total] AS ([quantity] * [unit_price]),
+ CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [ecommerce].[products]([id])
+ );
+ GO
+ newSchema: |
+ CREATE SCHEMA [ecommerce];
+ GO
+
+ CREATE TABLE [ecommerce].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [tax_rate] DECIMAL(5,4)
+ );
+ expected: |+
+ ALTER TABLE [ecommerce].[orders] DROP CONSTRAINT [fk_orders_product];
+ DROP INDEX [idx_products_price_category] ON [ecommerce].[products];
+ DROP INDEX [idx_products_price_with_tax] ON [ecommerce].[products];
+ GO
+ ALTER TABLE [ecommerce].[products] DROP COLUMN [price_with_tax];
+ ALTER TABLE [ecommerce].[products] DROP COLUMN [price_category];
+ GO
+ DROP TABLE [ecommerce].[orders];
+
+- description: Create tables with foreign key constraints
+ oldSchema: ""
+ newSchema: |
+ CREATE SCHEMA [test];
+ GO
+
+ CREATE TABLE [test].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ CONSTRAINT [uk_email] UNIQUE ([email])
+ );
+
+ CREATE INDEX [idx_username] ON [test].[users] ([username]);
+
+ CREATE TABLE [test].[posts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [published_at] DATETIME2,
+ CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE CASCADE
+ );
+
+ CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);
+ expected: |
+ CREATE SCHEMA [test];
+ GO
+
+ CREATE TABLE [test].[users] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2 NULL,
+ CONSTRAINT [PK_users_1] PRIMARY KEY ([id]),
+ CONSTRAINT [uk_email] UNIQUE ([email])
+ );
+ CREATE INDEX [idx_username] ON [test].[users] ([username]);
+ CREATE TABLE [test].[posts] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX) NULL,
+ [published_at] DATETIME2 NULL,
+ CONSTRAINT [PK_posts_2] PRIMARY KEY ([id])
+ );
+ CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);
+ ALTER TABLE [test].[posts] ADD CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION;
+- description: Tables with multiple foreign key constraints
+ oldSchema: |
+ CREATE SCHEMA [test];
+ GO
+
+ CREATE TABLE [test].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ [is_active] BIT,
+ CONSTRAINT [uk_email] UNIQUE ([email])
+ );
+ GO
+
+ CREATE INDEX [idx_username] ON [test].[users] ([username]);
+ GO
+
+ CREATE INDEX [idx_email_active] ON [test].[users] ([email], [is_active]);
+ GO
+
+ CREATE TABLE [test].[posts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [published_at] DATETIME2,
+ CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE CASCADE,
+ CONSTRAINT [chk_title_length] CHECK (LEN([title]) > 0)
+ );
+ GO
+
+ CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);
+ GO
+
+ CREATE TABLE [test].[comments] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [post_id] INT NOT NULL,
+ [user_id] INT NOT NULL,
+ [content] NVARCHAR(MAX) NOT NULL,
+ [created_at] DATETIME2,
+ CONSTRAINT [fk_comment_post] FOREIGN KEY ([post_id]) REFERENCES [test].[posts]([id]) ON DELETE CASCADE,
+ CONSTRAINT [fk_comment_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE NO ACTION
+ );
+ GO
+
+ CREATE INDEX [idx_post_user] ON [test].[comments] ([post_id], [user_id]);
+ GO
+ newSchema: |
+ CREATE SCHEMA [test];
+ GO
+
+ CREATE TABLE [test].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ CONSTRAINT [uk_email] UNIQUE ([email])
+ );
+ GO
+
+ CREATE INDEX [idx_username] ON [test].[users] ([username]);
+ GO
+
+ CREATE TABLE [test].[posts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [published_at] DATETIME2,
+ CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE CASCADE
+ );
+ GO
+
+ CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);
+ GO
+ expected: |+
+ ALTER TABLE [test].[comments] DROP CONSTRAINT [fk_comment_post];
+ ALTER TABLE [test].[comments] DROP CONSTRAINT [fk_comment_user];
+ ALTER TABLE [test].[posts] DROP CONSTRAINT [chk_title_length];
+ DROP INDEX [idx_email_active] ON [test].[users];
+ GO
+ ALTER TABLE [test].[users] DROP COLUMN [is_active];
+ GO
+ DROP TABLE [test].[comments];
+
+- description: Drop and recreate foreign key constraints with different options
+ oldSchema: |
+ CREATE SCHEMA [library];
+ GO
+
+ CREATE TABLE [library].[authors] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100),
+ CONSTRAINT [uk_email] UNIQUE ([email])
+ );
+
+ CREATE TABLE [library].[books] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [author_id] INT NOT NULL,
+ [isbn] NVARCHAR(20),
+ [published_year] INT,
+ [price] DECIMAL(8, 2),
+ CONSTRAINT [fk_author_new] FOREIGN KEY ([author_id]) REFERENCES [library].[authors]([id]) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT [chk_year_extended] CHECK ([published_year] >= 1000 AND [published_year] <= 2030),
+ CONSTRAINT [chk_price_positive] CHECK ([price] > 0),
+ CONSTRAINT [chk_title_length] CHECK (LEN([title]) >= 3),
+ CONSTRAINT [uk_isbn] UNIQUE ([isbn])
+ );
+
+ CREATE INDEX [idx_author] ON [library].[books] ([author_id]);
+ CREATE INDEX [idx_year] ON [library].[books] ([published_year]);
+ newSchema: |
+ CREATE SCHEMA [library];
+ GO
+
+ CREATE TABLE [library].[authors] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100),
+ CONSTRAINT [uk_email] UNIQUE ([email])
+ );
+
+ CREATE TABLE [library].[books] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [author_id] INT NOT NULL,
+ [isbn] NVARCHAR(20),
+ [published_year] INT,
+ [price] DECIMAL(8, 2),
+ CONSTRAINT [fk_author] FOREIGN KEY ([author_id]) REFERENCES [library].[authors]([id]),
+ CONSTRAINT [chk_year_valid] CHECK ([published_year] >= 1000 AND [published_year] <= 2100),
+ CONSTRAINT [chk_price_positive] CHECK ([price] > 0),
+ CONSTRAINT [uk_isbn] UNIQUE ([isbn])
+ );
+
+ CREATE INDEX [idx_author] ON [library].[books] ([author_id]);
+ CREATE INDEX [idx_year] ON [library].[books] ([published_year]);
+ expected: |+
+ ALTER TABLE [library].[books] DROP CONSTRAINT [fk_author_new];
+ GO
+ ALTER TABLE [library].[books] DROP CONSTRAINT [chk_title_length];
+ ALTER TABLE [library].[books] DROP CONSTRAINT [chk_year_extended];
+
+ ALTER TABLE [library].[books] ADD CONSTRAINT [chk_year_valid] CHECK ([published_year] >= 1000 AND [published_year] <= 2100);
+ ALTER TABLE [library].[books] ADD CONSTRAINT [fk_author] FOREIGN KEY ([author_id]) REFERENCES [library].[authors] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+
+- description: Self-referencing foreign keys and complex view dependencies
+ oldSchema: |
+ CREATE SCHEMA [company];
+ GO
+
+ CREATE TABLE [company].[departments] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [manager_id] INT
+ );
+
+ CREATE TABLE [company].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [department_id] INT,
+ [salary] DECIMAL(10, 2),
+ [hire_date] DATE,
+ CONSTRAINT [fk_dept] FOREIGN KEY ([department_id]) REFERENCES [company].[departments]([id])
+ );
+
+ CREATE INDEX [idx_dept] ON [company].[employees] ([department_id]);
+
+ -- Add self-referencing foreign key
+ ALTER TABLE [company].[departments] ADD CONSTRAINT [fk_manager] FOREIGN KEY ([manager_id]) REFERENCES [company].[employees]([id]);
+
+ -- Create base view
+ CREATE VIEW [company].[dept_employee_count] AS
+ SELECT d.[id] AS dept_id, d.[name] AS dept_name, COUNT(e.[id]) AS emp_count
+ FROM [company].[departments] d
+ LEFT JOIN [company].[employees] e ON d.[id] = e.[department_id]
+ GROUP BY d.[id], d.[name];
+ GO
+
+ -- Create dependent view
+ CREATE VIEW [company].[dept_summary] AS
+ SELECT
+ dept_id,
+ dept_name,
+ emp_count,
+ 0 AS avg_salary,
+ 0 AS max_salary,
+ 0 AS min_salary
+ FROM [company].[dept_employee_count];
+ GO
+
+ -- Create highly dependent view
+ CREATE VIEW [company].[dept_manager_summary] AS
+ SELECT
+ ds.dept_id,
+ ds.dept_name,
+ ds.emp_count,
+ ds.avg_salary,
+ m.[name] AS manager_name
+ FROM [company].[dept_summary] ds
+ JOIN [company].[departments] d ON ds.dept_id = d.[id]
+ LEFT JOIN [company].[employees] m ON d.[manager_id] = m.[id];
+ GO
+
+ -- Create stored procedure using views
+ CREATE PROCEDURE [company].[GetDepartmentReport]
+ @dept_name_pattern NVARCHAR(100)
+ AS
+ BEGIN
+ SELECT * FROM [company].[dept_manager_summary]
+ WHERE dept_name LIKE '%' + @dept_name_pattern + '%';
+ END;
+ newSchema: |
+ CREATE SCHEMA [company];
+ GO
+
+ CREATE TABLE [company].[departments] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [manager_id] INT
+ );
+
+ CREATE TABLE [company].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [department_id] INT,
+ [salary] DECIMAL(10, 2),
+ [hire_date] DATE,
+ CONSTRAINT [fk_dept] FOREIGN KEY ([department_id]) REFERENCES [company].[departments]([id])
+ );
+
+ CREATE INDEX [idx_dept] ON [company].[employees] ([department_id]);
+
+ -- Add self-referencing foreign key
+ ALTER TABLE [company].[departments] ADD CONSTRAINT [fk_manager] FOREIGN KEY ([manager_id]) REFERENCES [company].[employees]([id]);
+ expected: |
+ DROP PROCEDURE [company].[GetDepartmentReport];
+ GO
+ DROP VIEW [company].[dept_manager_summary];
+ GO
+ DROP VIEW [company].[dept_summary];
+ GO
+ DROP VIEW [company].[dept_employee_count];
+ GO
+- description: Adding comments to tables and columns using SQL Server extended properties
+ oldSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ [status] NVARCHAR(20)
+ );
+
+ CREATE TABLE [app].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [category] NVARCHAR(50)
+ );
+
+ CREATE INDEX [idx_users_email] ON [app].[users] ([email]);
+ CREATE INDEX [idx_products_category] ON [app].[products] ([category]);
+
+ CREATE TABLE [app].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [order_date] DATETIME2,
+ CONSTRAINT [fk_orders_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]),
+ CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [app].[products]([id])
+ );
+ GO
+
+ -- Add table comments using extended properties
+ EXEC sp_addextendedproperty 'MS_Description', 'User accounts and profile information', 'SCHEMA', 'app', 'TABLE', 'users';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product catalog with pricing information', 'SCHEMA', 'app', 'TABLE', 'products';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer orders tracking system', 'SCHEMA', 'app', 'TABLE', 'orders';
+ GO
+
+ -- Add column comments for users table
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique identifier for each user', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique username for login authentication', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';
+ EXEC sp_addextendedproperty 'MS_Description', 'User email address for notifications', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';
+ EXEC sp_addextendedproperty 'MS_Description', 'Timestamp when the user account was created', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';
+ EXEC sp_addextendedproperty 'MS_Description', 'Current status: active, inactive, or suspended', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';
+ GO
+
+ -- Add column comments for products table
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique product identifier', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product display name', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product price in USD', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product category classification', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';
+ GO
+
+ -- Add comments to orders table
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique order identifier', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Reference to the user who placed the order', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Reference to the ordered product', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Number of items ordered', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';
+ EXEC sp_addextendedproperty 'MS_Description', 'When the order was placed', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';
+ newSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ [status] NVARCHAR(20)
+ );
+
+ CREATE TABLE [app].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [category] NVARCHAR(50)
+ );
+
+ CREATE INDEX [idx_users_email] ON [app].[users] ([email]);
+ CREATE INDEX [idx_products_category] ON [app].[products] ([category]);
+ expected: |
+ ALTER TABLE [app].[orders] DROP CONSTRAINT [fk_orders_user];
+ ALTER TABLE [app].[orders] DROP CONSTRAINT [fk_orders_product];
+ DROP TABLE [app].[orders];
+
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';
+ GO
+- description: Modifying existing comments and removing comments using extended properties
+ oldSchema: |
+ CREATE SCHEMA [test];
+ GO
+
+ CREATE TABLE [test].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100),
+ [phone] NVARCHAR(20),
+ [created_at] DATETIME2 DEFAULT GETDATE()
+ );
+ GO
+
+ EXEC sp_addextendedproperty 'MS_Description', 'Complete customer database with contact details and preferences', 'SCHEMA', 'test', 'TABLE', 'customers';
+ EXEC sp_addextendedproperty 'MS_Description', 'Primary key - auto-generated customer identifier', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer business or personal name', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'name';
+ EXEC sp_addextendedproperty 'MS_Description', 'Primary email address for communications and billing', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'email';
+ EXEC sp_addextendedproperty 'MS_Description', 'Account creation timestamp for auditing', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'created_at';
+ GO
+
+ CREATE TABLE [test].[invoices] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [customer_id] INT NOT NULL,
+ [amount] DECIMAL(10,2) NOT NULL,
+ [invoice_date] DATE,
+ [payment_status] NVARCHAR(20),
+ CONSTRAINT [fk_invoices_customer] FOREIGN KEY ([customer_id]) REFERENCES [test].[customers]([id])
+ );
+ GO
+
+ EXEC sp_addextendedproperty 'MS_Description', 'Financial invoice tracking and billing system', 'SCHEMA', 'test', 'TABLE', 'invoices';
+ EXEC sp_addextendedproperty 'MS_Description', 'Current payment status: pending, paid, overdue, cancelled', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'payment_status';
+ newSchema: |
+ CREATE SCHEMA [test];
+ GO
+
+ CREATE TABLE [test].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100),
+ [phone] NVARCHAR(20),
+ [created_at] DATETIME2 DEFAULT GETDATE()
+ );
+ GO
+
+ -- Add initial comments
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer information database', 'SCHEMA', 'test', 'TABLE', 'customers';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer unique ID', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer full name', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'name';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer email for marketing', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'email';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer contact number', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'phone';
+ GO
+
+ CREATE TABLE [test].[invoices] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [customer_id] INT NOT NULL,
+ [amount] DECIMAL(10,2) NOT NULL,
+ [invoice_date] DATE,
+ CONSTRAINT [fk_invoices_customer] FOREIGN KEY ([customer_id]) REFERENCES [test].[customers]([id])
+ );
+ GO
+
+ -- Add comments to invoices table
+ EXEC sp_addextendedproperty 'MS_Description', 'Invoice records for billing', 'SCHEMA', 'test', 'TABLE', 'invoices';
+ EXEC sp_addextendedproperty 'MS_Description', 'Invoice number', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Link to customer', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'customer_id';
+ expected: |
+ ALTER TABLE [test].[invoices] DROP COLUMN [payment_status];
+
+ EXEC sp_updateextendedproperty 'MS_Description', 'Customer information database', 'SCHEMA', 'test', 'TABLE', 'customers';
+ EXEC sp_updateextendedproperty 'MS_Description', 'Customer unique ID', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'id';
+ EXEC sp_updateextendedproperty 'MS_Description', 'Customer full name', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'name';
+ EXEC sp_updateextendedproperty 'MS_Description', 'Customer email for marketing', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'email';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer contact number', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'phone';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'test', 'TABLE', 'customers', 'COLUMN', 'created_at';
+ EXEC sp_updateextendedproperty 'MS_Description', 'Invoice records for billing', 'SCHEMA', 'test', 'TABLE', 'invoices';
+ EXEC sp_addextendedproperty 'MS_Description', 'Invoice number', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Link to customer', 'SCHEMA', 'test', 'TABLE', 'invoices', 'COLUMN', 'customer_id';
+ GO
+- description: Comments with special characters, quotes, multiline text, and Unicode
+ oldSchema: |
+ CREATE SCHEMA [special];
+ GO
+
+ CREATE TABLE [special].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [author] NVARCHAR(100),
+ [created_date] DATETIME2,
+ [metadata] NVARCHAR(500)
+ );
+
+ CREATE TABLE [special].[translations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [document_id] INT NOT NULL,
+ [lang_code] NVARCHAR(10) NOT NULL,
+ [translated_title] NVARCHAR(200),
+ [translated_content] NVARCHAR(MAX),
+ CONSTRAINT [fk_translations_doc] FOREIGN KEY ([document_id]) REFERENCES [special].[documents]([id])
+ );
+
+ CREATE TABLE [special].[test_extreme] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [data] NVARCHAR(MAX)
+ );
+ GO
+
+ -- Add table comments with special characters and quotes
+ EXEC sp_addextendedproperty 'MS_Description', 'Document storage system - handles files, "metadata", & special chars: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'documents';
+ GO
+
+ -- Add multiline comment with special formatting
+ EXEC sp_addextendedproperty 'MS_Description',
+ 'Translation table for international support:
+ - Supports Unicode characters: αβγδε, 中文, العربية, русский
+ - Handles quotes: "double quotes" and ''single quotes''
+ - Special symbols: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'translations';
+ GO
+
+ -- Column comments with various special cases
+ EXEC sp_addextendedproperty 'MS_Description', 'Primary key (auto-increment) - unique ID for each document', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Document title - may contain "quotes", ''apostrophes'', and symbols: @#$%', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';
+ GO
+
+ -- Multiline comment with technical details
+ EXEC sp_addextendedproperty 'MS_Description',
+ 'Document content field:
+ • Supports rich text formatting
+ • HTML tags like <p>, <div>, <span>
+ • Special characters: © ® ™ § ¶ † ‡ • ‰ ′ ″
+ • Mathematical: ± × ÷ ≠ ≤ ≥ ∞ ∑ ∏ ∫
+ • Currency: $ € £ ¥ ₹ ₽
+ • Arrows: ← → ↑ ↓ ↔ ⇐ ⇒ ⇔', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';
+ GO
+
+ -- Comment with SQL injection attempt (should be safely handled)
+ EXEC sp_addextendedproperty 'MS_Description', 'Author name field - prevents SQL injection like ''; DROP TABLE users; --', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';
+ GO
+
+ -- Comment with JSON-like structure
+ EXEC sp_addextendedproperty 'MS_Description', 'Metadata JSON: {"version": "1.0", "tags": ["important", "draft"], "settings": {"public": false}}', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';
+ GO
+
+ -- Unicode characters in comments
+ EXEC sp_addextendedproperty 'MS_Description', 'Language code: en-US, fr-FR, de-DE, ja-JP, zh-CN, ar-SA, ru-RU, hi-IN, 한국어, ไทย', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';
+ GO
+
+ -- Comment with URLs and file paths
+ EXEC sp_addextendedproperty 'MS_Description', 'Translated content - may reference URLs like https://example.com/path?param=value&other=123 or file paths C:\Users\Name\Documents\file.txt', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';
+ GO
+
+ -- Extremely long comment to test limits
+ EXEC sp_addextendedproperty 'MS_Description',
+ 'This is an extremely long comment designed to test the limits of extended property storage in SQL Server. It contains multiple lines of text with various formatting, special characters, and technical information. The purpose is to verify that the migration system can properly handle, store, and retrieve complex comment data without truncation or corruption. This comment includes: numbers (123456789), symbols (!@#$%^&*()_+-={}[]|\:";''<>?,./ ), Unicode characters (αβγδε中文العربيةрусский한국어), and structured data like JSON {"key": "value", "array": [1, 2, 3], "nested": {"deep": true}}. Additionally, it tests SQL-like syntax: SELECT * FROM table WHERE column = ''value'' AND other_column IN (1, 2, 3); as well as HTML markup: <html><body><p class="test">Content</p></body></html> and XML: <?xml version="1.0"?><root><item id="1">Test</item></root>. The comment system should preserve all these characters and structures exactly as written, demonstrating robust handling of complex metadata in database schema documentation.', 'SCHEMA', 'special', 'TABLE', 'test_extreme';
+ newSchema: |
+ CREATE SCHEMA [special];
+ GO
+
+ CREATE TABLE [special].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [author] NVARCHAR(100),
+ [created_date] DATETIME2,
+ [metadata] NVARCHAR(500)
+ );
+
+ CREATE TABLE [special].[translations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [document_id] INT NOT NULL,
+ [lang_code] NVARCHAR(10) NOT NULL,
+ [translated_title] NVARCHAR(200),
+ [translated_content] NVARCHAR(MAX),
+ CONSTRAINT [fk_translations_doc] FOREIGN KEY ([document_id]) REFERENCES [special].[documents]([id])
+ );
+ expected: |
+ DROP TABLE [special].[test_extreme];
+
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';
+ EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';
+ GO
+- description: Default constraint operations including add, remove, modify with various data types and expressions
+ oldSchema: |
+ CREATE SCHEMA [defaults];
+ GO
+
+ CREATE TABLE [defaults].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [hire_date] DATE NOT NULL DEFAULT GETDATE(),
+ [status] NVARCHAR(20) NOT NULL CONSTRAINT [DF_employees_status_new] DEFAULT 'pending',
+ [is_active] BIT NOT NULL DEFAULT 1,
+ [salary] DECIMAL(10,2) DEFAULT 50000.00,
+ [department_id] INT DEFAULT 1,
+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),
+ [updated_at] DATETIME2,
+ [vacation_days] INT NOT NULL DEFAULT 15,
+ [bonus_percentage] DECIMAL(5,2) DEFAULT (CASE WHEN MONTH(GETDATE()) = 12 THEN 10.0 ELSE 5.0 END)
+ );
+
+ CREATE TABLE [defaults].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00,
+ [stock] INT NOT NULL DEFAULT 0,
+ [is_available] BIT DEFAULT 1,
+ [cost] DECIMAL(10,2) NOT NULL
+ );
+
+ CREATE TABLE [defaults].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [order_number] NVARCHAR(50) NOT NULL DEFAULT CONCAT('ORD-', YEAR(GETDATE()), '-', FORMAT(GETDATE(), 'MMdd')),
+ [order_date] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
+ [status] NVARCHAR(20) NOT NULL DEFAULT 'pending',
+ [total] DECIMAL(10,2) NOT NULL DEFAULT 0,
+ [discount] DECIMAL(5,2) DEFAULT NULL,
+ [is_paid] BIT NOT NULL DEFAULT 0,
+ [notes] NVARCHAR(MAX) DEFAULT 'No notes'
+ );
+ newSchema: |
+ CREATE SCHEMA [defaults];
+ GO
+
+ CREATE TABLE [defaults].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [hire_date] DATE NOT NULL DEFAULT GETDATE(),
+ [status] NVARCHAR(20) NOT NULL DEFAULT 'active',
+ [is_active] BIT NOT NULL DEFAULT 1,
+ [salary] DECIMAL(10,2) DEFAULT 50000.00,
+ [department_id] INT DEFAULT 1,
+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),
+ [updated_at] DATETIME2
+ );
+
+ CREATE TABLE [defaults].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00,
+ [stock] INT NOT NULL DEFAULT 0,
+ [is_available] BIT DEFAULT 1
+ );
+ expected: |+
+ ALTER TABLE [defaults].[employees] DROP COLUMN [vacation_days];
+ ALTER TABLE [defaults].[employees] DROP COLUMN [bonus_percentage];
+ ALTER TABLE [defaults].[products] DROP COLUMN [cost];
+ GO
+ DROP TABLE [defaults].[orders];
+
+ ALTER TABLE [defaults].[employees] ADD CONSTRAINT [DF_employees_status] DEFAULT 'active' FOR [status];
+
+- description: Complex default expressions using system functions, variables, and conditional logic
+ oldSchema: |
+ CREATE SCHEMA [complex];
+ GO
+
+ CREATE TABLE [complex].[audit_log] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_type] NVARCHAR(50) NOT NULL,
+ [user_name] NVARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,
+ [event_time] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
+ [ip_address] NVARCHAR(45),
+ [session_id] UNIQUEIDENTIFIER DEFAULT NEWID(),
+ [server_name] NVARCHAR(100) DEFAULT @@SERVERNAME,
+ [database_name] NVARCHAR(100) DEFAULT DB_NAME(),
+ [schema_name] NVARCHAR(100) DEFAULT SCHEMA_NAME()
+ );
+
+ CREATE TABLE [complex].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [version] INT NOT NULL DEFAULT 1,
+ [created_date] DATE DEFAULT CAST(GETDATE() AS DATE),
+ [expiry_date] DATE DEFAULT DATEADD(YEAR, 1, CAST(GETDATE() AS DATE)),
+ [document_code] NVARCHAR(50) DEFAULT CONCAT('DOC-', FORMAT(GETDATE(), 'yyyyMMdd'), '-', NEWID()),
+ [priority] INT DEFAULT
+ CASE
+ WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 1
+ WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 2
+ ELSE 3
+ END
+ );
+
+ CREATE TABLE [complex].[calculations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [value1] DECIMAL(10,2) NOT NULL,
+ [value2] DECIMAL(10,2) NOT NULL,
+ [pi_value] DECIMAL(10,8) DEFAULT PI(),
+ [random_value] FLOAT DEFAULT RAND(),
+ [checksum_value] INT DEFAULT CHECKSUM(NEWID()),
+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),
+ [created_offset] DATETIMEOFFSET DEFAULT SYSDATETIMEOFFSET()
+ );
+ newSchema: |
+ CREATE SCHEMA [complex];
+ GO
+
+ CREATE TABLE [complex].[audit_log] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_type] NVARCHAR(50) NOT NULL,
+ [user_name] NVARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,
+ [event_time] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
+ [ip_address] NVARCHAR(45),
+ [session_id] UNIQUEIDENTIFIER DEFAULT NEWID()
+ );
+
+ CREATE TABLE [complex].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [version] INT NOT NULL DEFAULT 1,
+ [created_date] DATE DEFAULT CAST(GETDATE() AS DATE),
+ [expiry_date] DATE DEFAULT DATEADD(YEAR, 1, CAST(GETDATE() AS DATE))
+ );
+ expected: |+
+ ALTER TABLE [complex].[audit_log] DROP COLUMN [server_name];
+ ALTER TABLE [complex].[audit_log] DROP COLUMN [database_name];
+ ALTER TABLE [complex].[audit_log] DROP COLUMN [schema_name];
+ ALTER TABLE [complex].[documents] DROP COLUMN [document_code];
+ ALTER TABLE [complex].[documents] DROP COLUMN [priority];
+ GO
+ DROP TABLE [complex].[calculations];
+
+- description: Edge cases for default constraints including special characters, unicode, extreme values
+ oldSchema: "CREATE SCHEMA [edge];\nGO\n\nCREATE TABLE [edge].[test_defaults] (\n [id] INT IDENTITY(1,1) PRIMARY KEY,\n [nullable_with_default] INT CONSTRAINT [DF_test_defaults_nullable_new] DEFAULT 84,\n [string_default] NVARCHAR(50) DEFAULT N'Default''s value',\n [empty_string] NVARCHAR(50) DEFAULT '',\n [zero_default] INT DEFAULT 0,\n [negative_default] INT DEFAULT -1,\n [decimal_precision] DECIMAL(18,6) DEFAULT 123.456789,\n [special_chars] NVARCHAR(100) DEFAULT N'Line1' + CHAR(13) + CHAR(10) + N'Line2',\n [unicode_default] NVARCHAR(100) DEFAULT N'你好世界 \U0001F30D',\n [max_int] BIGINT DEFAULT 9223372036854775807,\n [min_int] BIGINT DEFAULT -9223372036854775808,\n [json_config] NVARCHAR(MAX) DEFAULT N'{\"enabled\": true, \"count\": 0}'\n);\n\nCREATE TABLE [edge].[flags] (\n [id] INT IDENTITY(1,1) PRIMARY KEY,\n [is_enabled] BIT NOT NULL DEFAULT 1,\n [is_deleted] BIT NOT NULL DEFAULT 0,\n [is_visible] BIT DEFAULT 1,\n [is_archived] BIT DEFAULT 0\n);\n"
+ newSchema: |
+ CREATE SCHEMA [edge];
+ GO
+
+ CREATE TABLE [edge].[test_defaults] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [nullable_with_default] INT DEFAULT 42,
+ [string_default] NVARCHAR(50) DEFAULT N'Default''s value',
+ [empty_string] NVARCHAR(50) DEFAULT '',
+ [zero_default] INT DEFAULT 0,
+ [negative_default] INT DEFAULT -1,
+ [decimal_precision] DECIMAL(18,6) DEFAULT 123.456789
+ );
+ expected: |+
+ ALTER TABLE [edge].[test_defaults] DROP COLUMN [special_chars];
+ ALTER TABLE [edge].[test_defaults] DROP COLUMN [unicode_default];
+ ALTER TABLE [edge].[test_defaults] DROP COLUMN [max_int];
+ ALTER TABLE [edge].[test_defaults] DROP COLUMN [min_int];
+ ALTER TABLE [edge].[test_defaults] DROP COLUMN [json_config];
+ GO
+ DROP TABLE [edge].[flags];
+
+ ALTER TABLE [edge].[test_defaults] ADD CONSTRAINT [DF_test_defaults_nullable_with_default] DEFAULT 42 FOR [nullable_with_default];
+
+- description: Reverse of basic table operations - dropping column, table, index, and constraint
+ oldSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ CONSTRAINT [uk_users_email] UNIQUE ([email])
+ );
+
+ CREATE INDEX [idx_users_username] ON [app].[users] ([username]);
+
+ CREATE TABLE [app].[posts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NTEXT,
+ [published_at] DATETIME2,
+ CONSTRAINT [fk_posts_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]) ON DELETE CASCADE
+ );
+
+ CREATE INDEX [idx_posts_user_id] ON [app].[posts] ([user_id]);
+ newSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ [status] NVARCHAR(20),
+ CONSTRAINT [uk_users_email] UNIQUE ([email]),
+ CONSTRAINT [ck_users_status] CHECK ([status] IN ('active', 'inactive', 'suspended'))
+ );
+
+ CREATE INDEX [idx_users_username] ON [app].[users] ([username]);
+
+ CREATE TABLE [app].[posts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NTEXT,
+ [published_at] DATETIME2,
+ CONSTRAINT [fk_posts_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]) ON DELETE CASCADE
+ );
+
+ CREATE INDEX [idx_posts_user_id] ON [app].[posts] ([user_id]);
+
+ CREATE TABLE [app].[comments] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [post_id] INT NOT NULL,
+ [user_id] INT NOT NULL,
+ [content] NTEXT NOT NULL,
+ [created_at] DATETIME2,
+ CONSTRAINT [fk_comments_post] FOREIGN KEY ([post_id]) REFERENCES [app].[posts]([id]) ON DELETE CASCADE,
+ CONSTRAINT [fk_comments_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id])
+ );
+
+ CREATE INDEX [idx_comments_post_id] ON [app].[comments] ([post_id]);
+ expected: |
+ CREATE TABLE [app].[comments] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [post_id] INT NOT NULL,
+ [user_id] INT NOT NULL,
+ [content] NTEXT NOT NULL,
+ [created_at] DATETIME2 NULL,
+ CONSTRAINT [PK_comments_3] PRIMARY KEY ([id])
+ );
+ CREATE INDEX [idx_comments_post_id] ON [app].[comments] ([post_id]);
+ ALTER TABLE [app].[users] ADD [status] NVARCHAR(20) NULL;
+ ALTER TABLE [app].[users] ADD CONSTRAINT [ck_users_status] CHECK ([status] IN ('active', 'inactive', 'suspended'));
+
+ ALTER TABLE [app].[comments] ADD CONSTRAINT [fk_comments_post] FOREIGN KEY ([post_id]) REFERENCES [app].[posts] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION;
+ ALTER TABLE [app].[comments] ADD CONSTRAINT [fk_comments_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+- description: Reverse of schema operations - dropping cross-schema foreign key, table, and schema
+ oldSchema: |
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE TABLE [sales].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100)
+ );
+
+ CREATE TABLE [sales].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [customer_id] INT NOT NULL,
+ [order_date] DATE,
+ [total] DECIMAL(10,2),
+ CONSTRAINT [fk_orders_customer] FOREIGN KEY ([customer_id]) REFERENCES [sales].[customers]([id])
+ );
+ newSchema: |
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE SCHEMA [inventory];
+ GO
+
+ CREATE TABLE [sales].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100)
+ );
+
+ CREATE TABLE [sales].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [customer_id] INT NOT NULL,
+ [order_date] DATE,
+ [total] DECIMAL(10,2),
+ [product_id] INT,
+ CONSTRAINT [fk_orders_customer] FOREIGN KEY ([customer_id]) REFERENCES [sales].[customers]([id])
+ );
+
+ CREATE TABLE [inventory].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [category_id] INT,
+ CONSTRAINT [ck_products_price] CHECK ([price] > 0)
+ );
+
+ ALTER TABLE [sales].[orders] ADD CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [inventory].[products]([id]);
+ expected: |+
+ CREATE SCHEMA [inventory];
+ GO
+
+ CREATE TABLE [inventory].[products] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [category_id] INT NULL,
+ CONSTRAINT [PK_products_3] PRIMARY KEY ([id]),
+ CONSTRAINT [ck_products_price] CHECK ([price] > 0)
+ );
+ ALTER TABLE [sales].[orders] ADD [product_id] INT NULL;
+
+- description: Reverse of view operations - dropping views in correct dependency order
+ oldSchema: |
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE TABLE [reporting].[sales_data] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [product_name] NVARCHAR(100) NOT NULL,
+ [quantity] INT NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [sale_date] DATE
+ );
+
+ CREATE TABLE [reporting].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [region] NVARCHAR(50)
+ );
+ newSchema: |
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE TABLE [reporting].[sales_data] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [product_name] NVARCHAR(100) NOT NULL,
+ [quantity] INT NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [sale_date] DATE
+ );
+
+ CREATE TABLE [reporting].[customers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [region] NVARCHAR(50)
+ );
+ GO
+
+ CREATE VIEW [reporting].[product_summary] AS
+ SELECT
+ [product_name],
+ COUNT(*) as [sale_count],
+ SUM([quantity]) as [total_quantity],
+ AVG([price]) as [avg_price]
+ FROM [reporting].[sales_data]
+ GROUP BY [product_name];
+ GO
+
+ CREATE VIEW [reporting].[top_products] AS
+ SELECT TOP 10
+ [product_name],
+ [total_quantity]
+ FROM [reporting].[product_summary]
+ WHERE [total_quantity] > 100
+ ORDER BY [total_quantity] DESC;
+ GO
+ expected: |
+ CREATE VIEW [reporting].[product_summary] AS
+ SELECT
+ [product_name],
+ COUNT(*) as [sale_count],
+ SUM([quantity]) as [total_quantity],
+ AVG([price]) as [avg_price]
+ FROM [reporting].[sales_data]
+ GROUP BY [product_name];
+ GO
+ CREATE VIEW [reporting].[top_products] AS
+ SELECT TOP 10
+ [product_name],
+ [total_quantity]
+ FROM [reporting].[product_summary]
+ WHERE [total_quantity] > 100
+ ORDER BY [total_quantity] DESC;
+ GO
+- description: Reverse of function and procedure operations - dropping procedures and functions
+ oldSchema: |
+ CREATE SCHEMA [calc];
+ GO
+
+ CREATE TABLE [calc].[numbers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [value] INT NOT NULL,
+ [category] NVARCHAR(20)
+ );
+ newSchema: |
+ CREATE SCHEMA [calc];
+ GO
+
+ CREATE TABLE [calc].[numbers] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [value] INT NOT NULL,
+ [category] NVARCHAR(20)
+ );
+ GO
+
+ CREATE FUNCTION [calc].[square](@input INT)
+ RETURNS INT
+ AS
+ BEGIN
+ RETURN @input * @input;
+ END;
+ GO
+
+ CREATE FUNCTION [calc].[get_numbers_by_category](@category NVARCHAR(20))
+ RETURNS TABLE
+ AS
+ RETURN (
+ SELECT [id], [value], [category]
+ FROM [calc].[numbers]
+ WHERE [category] = @category
+ );
+ GO
+
+ CREATE PROCEDURE [calc].[add_number]
+ @value INT,
+ @category NVARCHAR(20)
+ AS
+ BEGIN
+ INSERT INTO [calc].[numbers] ([value], [category])
+ VALUES (@value, @category);
+ END;
+ GO
+ expected: |
+ CREATE FUNCTION [calc].[get_numbers_by_category](@category NVARCHAR(20))
+ RETURNS TABLE
+ AS
+ RETURN (
+ SELECT [id], [value], [category]
+ FROM [calc].[numbers]
+ WHERE [category] = @category
+ );
+ GO
+ CREATE FUNCTION [calc].[square](@input INT)
+ RETURNS INT
+ AS
+ BEGIN
+ RETURN @input * @input;
+ END;
+ GO
+ CREATE PROCEDURE [calc].[add_number]
+ @value INT,
+ @category NVARCHAR(20)
+ AS
+ BEGIN
+ INSERT INTO [calc].[numbers] ([value], [category])
+ VALUES (@value, @category);
+ END;
+ GO
+- description: Reverse of index operations - dropping various index types including filtered and computed column indexes
+ oldSchema: |
+ CREATE SCHEMA [perf];
+ GO
+
+ CREATE TABLE [perf].[events] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_name] NVARCHAR(100) NOT NULL,
+ [event_data] NVARCHAR(MAX),
+ [timestamp] DATETIME2,
+ [user_id] INT,
+ [category] NVARCHAR(50)
+ );
+ newSchema: |
+ CREATE SCHEMA [perf];
+ GO
+
+ CREATE TABLE [perf].[events] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_name] NVARCHAR(100) NOT NULL,
+ [event_data] NVARCHAR(MAX),
+ [timestamp] DATETIME2,
+ [user_id] INT,
+ [category] NVARCHAR(50),
+ [event_month] AS DATEPART(MONTH, [timestamp])
+ );
+
+ CREATE INDEX [idx_events_timestamp] ON [perf].[events] ([timestamp]);
+ CREATE INDEX [idx_events_user_category] ON [perf].[events] ([user_id], [category]);
+ CREATE UNIQUE INDEX [idx_events_name_timestamp] ON [perf].[events] ([event_name], [timestamp]);
+
+ CREATE INDEX [idx_events_recent] ON [perf].[events] ([event_name])
+ WHERE [timestamp] >= '2023-01-01';
+
+ CREATE INDEX [idx_events_month] ON [perf].[events] ([event_month]);
+ expected: |+
+ ALTER TABLE [perf].[events] ADD [event_month] NULL;
+ CREATE INDEX [idx_events_month] ON [perf].[events] ([event_month]);
+ CREATE UNIQUE INDEX [idx_events_name_timestamp] ON [perf].[events] ([event_name], [timestamp]);
+ CREATE INDEX [idx_events_recent] ON [perf].[events] ([event_name]);
+ CREATE INDEX [idx_events_timestamp] ON [perf].[events] ([timestamp]);
+ CREATE INDEX [idx_events_user_category] ON [perf].[events] ([user_id], [category]);
+
+- description: Reverse of complex constraints - dropping tables with foreign keys and removing constraints
+ oldSchema: |
+ CREATE SCHEMA [finance];
+ GO
+
+ CREATE TABLE [finance].[accounts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [account_number] NVARCHAR(20) NOT NULL,
+ [balance] DECIMAL(15,2),
+ [account_type] NVARCHAR(20) NOT NULL,
+ [created_at] DATETIME2 DEFAULT GETDATE()
+ );
+ newSchema: |
+ CREATE SCHEMA [finance];
+ GO
+
+ CREATE TABLE [finance].[accounts] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [account_number] NVARCHAR(20) NOT NULL,
+ [balance] DECIMAL(15,2),
+ [account_type] NVARCHAR(20) NOT NULL,
+ [created_at] DATETIME2 DEFAULT GETDATE(),
+ CONSTRAINT [ck_accounts_balance] CHECK ([balance] >= 0),
+ CONSTRAINT [ck_accounts_type] CHECK ([account_type] IN ('CHECKING', 'SAVINGS', 'CREDIT')),
+ CONSTRAINT [uk_accounts_number] UNIQUE ([account_number])
+ );
+
+ CREATE TABLE [finance].[transactions] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [account_id] INT NOT NULL,
+ [amount] DECIMAL(15,2) NOT NULL,
+ [transaction_type] NVARCHAR(20) NOT NULL,
+ [transaction_date] DATETIME2,
+ CONSTRAINT [fk_transactions_account] FOREIGN KEY ([account_id]) REFERENCES [finance].[accounts]([id]),
+ CONSTRAINT [ck_transactions_amount] CHECK ([amount] != 0),
+ CONSTRAINT [ck_transactions_type] CHECK ([transaction_type] IN ('DEBIT', 'CREDIT'))
+ );
+ expected: |
+ CREATE TABLE [finance].[transactions] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [account_id] INT NOT NULL,
+ [amount] DECIMAL(15,2) NOT NULL,
+ [transaction_type] NVARCHAR(20) NOT NULL,
+ [transaction_date] DATETIME2 NULL,
+ CONSTRAINT [PK_transactions_2] PRIMARY KEY ([id]),
+ CONSTRAINT [ck_transactions_amount] CHECK ([amount] != 0),
+ CONSTRAINT [ck_transactions_type] CHECK ([transaction_type] IN ('DEBIT', 'CREDIT'))
+ );
+ ALTER TABLE [finance].[accounts] ADD CONSTRAINT [uk_accounts_number] UNIQUE ([account_number]);
+ ALTER TABLE [finance].[accounts] ADD CONSTRAINT [ck_accounts_balance] CHECK ([balance] >= 0);
+ ALTER TABLE [finance].[accounts] ADD CONSTRAINT [ck_accounts_type] CHECK ([account_type] IN ('CHECKING', 'SAVINGS', 'CREDIT'));
+
+ ALTER TABLE [finance].[transactions] ADD CONSTRAINT [fk_transactions_account] FOREIGN KEY ([account_id]) REFERENCES [finance].[accounts] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+- description: Reverse of column modifications - dropping columns, constraints, and related tables
+ oldSchema: |
+ CREATE SCHEMA [hr];
+ GO
+
+ CREATE TABLE [hr].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [first_name] NVARCHAR(50),
+ [last_name] NVARCHAR(50),
+ [email] NVARCHAR(100),
+ [phone] VARCHAR(20),
+ [hire_date] DATE,
+ [salary] DECIMAL(10,2)
+ );
+ newSchema: |
+ CREATE SCHEMA [hr];
+ GO
+
+ CREATE TABLE [hr].[departments] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [budget] DECIMAL(15,2)
+ );
+
+ CREATE TABLE [hr].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [first_name] NVARCHAR(50),
+ [last_name] NVARCHAR(50),
+ [email] NVARCHAR(100),
+ [phone] VARCHAR(20),
+ [hire_date] DATE,
+ [salary] DECIMAL(10,2),
+ [department_id] INT,
+ [manager_id] INT,
+ [status] NVARCHAR(20),
+ CONSTRAINT [fk_employees_department] FOREIGN KEY ([department_id]) REFERENCES [hr].[departments]([id]),
+ CONSTRAINT [fk_employees_manager] FOREIGN KEY ([manager_id]) REFERENCES [hr].[employees]([id]),
+ CONSTRAINT [ck_employees_salary] CHECK ([salary] > 0),
+ CONSTRAINT [ck_employees_status] CHECK ([status] IN ('ACTIVE', 'INACTIVE', 'TERMINATED'))
+ );
+ expected: |+
+ ALTER TABLE [hr].[employees] DROP CONSTRAINT [PK_employees_1];
+
+ CREATE TABLE [hr].[departments] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ [budget] DECIMAL(15,2) NULL,
+ CONSTRAINT [PK_departments_1] PRIMARY KEY ([id])
+ );
+ ALTER TABLE [hr].[employees] ADD [department_id] INT NULL;
+ ALTER TABLE [hr].[employees] ADD [manager_id] INT NULL;
+ ALTER TABLE [hr].[employees] ADD [status] NVARCHAR(20) NULL;
+ ALTER TABLE [hr].[employees] ADD CONSTRAINT [PK_employees_2] PRIMARY KEY ([id]);
+ ALTER TABLE [hr].[employees] ADD CONSTRAINT [ck_employees_salary] CHECK ([salary] > 0);
+ ALTER TABLE [hr].[employees] ADD CONSTRAINT [ck_employees_status] CHECK ([status] IN ('ACTIVE', 'INACTIVE', 'TERMINATED'));
+ ALTER TABLE [hr].[employees] ADD CONSTRAINT [fk_employees_department] FOREIGN KEY ([department_id]) REFERENCES [hr].[departments] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+ ALTER TABLE [hr].[employees] ADD CONSTRAINT [fk_employees_manager] FOREIGN KEY ([manager_id]) REFERENCES [hr].[employees] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+
+- description: Reverse of multiple schema dependencies - dropping cross-schema references
+ oldSchema: |
+ CREATE SCHEMA [core];
+ GO
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [core].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE [core].[roles] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(50) NOT NULL
+ );
+ newSchema: |
+ CREATE SCHEMA [core];
+ GO
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [core].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE [core].[roles] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(50) NOT NULL
+ );
+
+ CREATE TABLE [core].[user_roles] (
+ [user_id] INT NOT NULL,
+ [role_id] INT NOT NULL,
+ [assigned_at] DATETIME2,
+ CONSTRAINT [pk_user_roles] PRIMARY KEY ([user_id], [role_id]),
+ CONSTRAINT [fk_user_roles_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE,
+ CONSTRAINT [fk_user_roles_role] FOREIGN KEY ([role_id]) REFERENCES [core].[roles]([id]) ON DELETE CASCADE
+ );
+
+ CREATE TABLE [app].[sessions] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [token] NVARCHAR(255) NOT NULL,
+ [expires_at] DATETIME2 NOT NULL,
+ CONSTRAINT [fk_sessions_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE
+ );
+
+ CREATE TABLE [app].[audit_log] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT,
+ [action] NVARCHAR(100) NOT NULL,
+ [timestamp] DATETIME2,
+ [details] NVARCHAR(MAX),
+ CONSTRAINT [fk_audit_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id])
+ );
+ expected: |
+ CREATE TABLE [app].[audit_log] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [user_id] INT NULL,
+ [action] NVARCHAR(100) NOT NULL,
+ [timestamp] DATETIME2 NULL,
+ [details] NVARCHAR(MAX) NULL,
+ CONSTRAINT [PK_audit_log_4] PRIMARY KEY ([id])
+ );
+ CREATE TABLE [app].[sessions] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [user_id] INT NOT NULL,
+ [token] NVARCHAR(255) NOT NULL,
+ [expires_at] DATETIME2 NOT NULL,
+ CONSTRAINT [PK_sessions_3] PRIMARY KEY ([id])
+ );
+ CREATE TABLE [core].[user_roles] (
+ [user_id] INT NOT NULL,
+ [role_id] INT NOT NULL,
+ [assigned_at] DATETIME2 NULL,
+ CONSTRAINT [pk_user_roles] PRIMARY KEY ([user_id], [role_id])
+ );
+ ALTER TABLE [app].[audit_log] ADD CONSTRAINT [fk_audit_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+ ALTER TABLE [app].[sessions] ADD CONSTRAINT [fk_sessions_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION;
+ ALTER TABLE [core].[user_roles] ADD CONSTRAINT [fk_user_roles_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION;
+ ALTER TABLE [core].[user_roles] ADD CONSTRAINT [fk_user_roles_role] FOREIGN KEY ([role_id]) REFERENCES [core].[roles] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION;
+- description: Reverse of computed columns - dropping indexes and computed columns
+ oldSchema: |
+ CREATE SCHEMA [ecommerce];
+ GO
+
+ CREATE TABLE [ecommerce].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [tax_rate] DECIMAL(5,4)
+ );
+ newSchema: |
+ CREATE SCHEMA [ecommerce];
+ GO
+
+ CREATE TABLE [ecommerce].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [tax_rate] DECIMAL(5,4),
+ [price_with_tax] AS ([price] * (1 + [tax_rate])),
+ [price_category] AS (
+ CASE
+ WHEN [price] < 10 THEN 'Budget'
+ WHEN [price] < 100 THEN 'Standard'
+ ELSE 'Premium'
+ END
+ )
+ );
+ GO
+
+ CREATE INDEX [idx_products_price_category] ON [ecommerce].[products] ([price_category]);
+ CREATE INDEX [idx_products_price_with_tax] ON [ecommerce].[products] ([price_with_tax]);
+
+ CREATE TABLE [ecommerce].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [unit_price] DECIMAL(10,2) NOT NULL,
+ [total] DECIMAL(15,2),
+ [order_date] DATETIME2,
+ [computed_total] AS ([quantity] * [unit_price]),
+ CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [ecommerce].[products]([id])
+ );
+ GO
+ expected: |
+ CREATE TABLE [ecommerce].[orders] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [unit_price] DECIMAL(10,2) NOT NULL,
+ [total] DECIMAL(15,2) NULL,
+ [order_date] DATETIME2 NULL,
+ [computed_total] NULL,
+ CONSTRAINT [PK_orders_2] PRIMARY KEY ([id])
+ );
+ ALTER TABLE [ecommerce].[products] ADD [price_with_tax] NULL;
+ ALTER TABLE [ecommerce].[products] ADD [price_category] NULL;
+ CREATE INDEX [idx_products_price_category] ON [ecommerce].[products] ([price_category]);
+ CREATE INDEX [idx_products_price_with_tax] ON [ecommerce].[products] ([price_with_tax]);
+
+ ALTER TABLE [ecommerce].[orders] ADD CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [ecommerce].[products] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+- description: Reverse of temporal tables - disabling system versioning and dropping history
+ oldSchema: |
+ CREATE SCHEMA [tracking];
+ GO
+
+ CREATE TABLE [tracking].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [last_modified] DATETIME2
+ );
+ newSchema: |
+ CREATE SCHEMA [tracking];
+ GO
+
+ CREATE TABLE [tracking].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [last_modified] DATETIME2,
+ [valid_from] DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
+ [valid_to] DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
+ PERIOD FOR SYSTEM_TIME ([valid_from], [valid_to])
+ );
+
+ CREATE TABLE [tracking].[products_history] (
+ [id] INT NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [last_modified] DATETIME2,
+ [valid_from] DATETIME2 NOT NULL,
+ [valid_to] DATETIME2 NOT NULL
+ );
+
+ CREATE CLUSTERED INDEX [idx_products_history_period] ON [tracking].[products_history] ([valid_to], [valid_from]);
+
+ ALTER TABLE [tracking].[products] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [tracking].[products_history]));
+ expected: |+
+ CREATE TABLE [tracking].[products_history] (
+ [id] INT NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [last_modified] DATETIME2 NULL,
+ [valid_from] DATETIME2 NOT NULL,
+ [valid_to] DATETIME2 NOT NULL
+ );
+ CREATE CLUSTERED INDEX [idx_products_history_period] ON [tracking].[products_history] ([valid_to], [valid_from]);
+ ALTER TABLE [tracking].[products] ADD [valid_from] DATETIME2 NOT NULL;
+ ALTER TABLE [tracking].[products] ADD [valid_to] DATETIME2 NOT NULL;
+
+- description: Reverse of table and column comments - dropping extended properties
+ oldSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ [status] NVARCHAR(20)
+ );
+
+ CREATE TABLE [app].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [category] NVARCHAR(50)
+ );
+
+ CREATE INDEX [idx_users_email] ON [app].[users] ([email]);
+ CREATE INDEX [idx_products_category] ON [app].[products] ([category]);
+ newSchema: |
+ CREATE SCHEMA [app];
+ GO
+
+ CREATE TABLE [app].[users] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [username] NVARCHAR(50) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [created_at] DATETIME2,
+ [status] NVARCHAR(20)
+ );
+
+ CREATE TABLE [app].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL,
+ [category] NVARCHAR(50)
+ );
+
+ CREATE INDEX [idx_users_email] ON [app].[users] ([email]);
+ CREATE INDEX [idx_products_category] ON [app].[products] ([category]);
+
+ CREATE TABLE [app].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [user_id] INT NOT NULL,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [order_date] DATETIME2,
+ CONSTRAINT [fk_orders_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]),
+ CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [app].[products]([id])
+ );
+ GO
+
+ -- Add table comments using extended properties
+ EXEC sp_addextendedproperty 'MS_Description', 'User accounts and profile information', 'SCHEMA', 'app', 'TABLE', 'users';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product catalog with pricing information', 'SCHEMA', 'app', 'TABLE', 'products';
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer orders tracking system', 'SCHEMA', 'app', 'TABLE', 'orders';
+ GO
+
+ -- Add column comments for users table
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique identifier for each user', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique username for login authentication', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';
+ EXEC sp_addextendedproperty 'MS_Description', 'User email address for notifications', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';
+ EXEC sp_addextendedproperty 'MS_Description', 'Timestamp when the user account was created', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';
+ EXEC sp_addextendedproperty 'MS_Description', 'Current status: active, inactive, or suspended', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';
+ GO
+
+ -- Add column comments for products table
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique product identifier', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product display name', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product price in USD', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product category classification', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';
+ GO
+
+ -- Add comments to orders table
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique order identifier', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Reference to the user who placed the order', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Reference to the ordered product', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Number of items ordered', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';
+ EXEC sp_addextendedproperty 'MS_Description', 'When the order was placed', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';
+ expected: |
+ CREATE TABLE [app].[orders] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [user_id] INT NOT NULL,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [order_date] DATETIME2 NULL,
+ CONSTRAINT [PK_orders_3] PRIMARY KEY ([id])
+ );
+ ALTER TABLE [app].[orders] ADD CONSTRAINT [fk_orders_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+ ALTER TABLE [app].[orders] ADD CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [app].[products] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+ EXEC sp_addextendedproperty 'MS_Description', 'Customer orders tracking system', 'SCHEMA', 'app', 'TABLE', 'orders';
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique order identifier', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Reference to the user who placed the order', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Reference to the ordered product', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Number of items ordered', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';
+ EXEC sp_addextendedproperty 'MS_Description', 'When the order was placed', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product catalog with pricing information', 'SCHEMA', 'app', 'TABLE', 'products';
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique product identifier', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product display name', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product price in USD', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';
+ EXEC sp_addextendedproperty 'MS_Description', 'Product category classification', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';
+ EXEC sp_addextendedproperty 'MS_Description', 'User accounts and profile information', 'SCHEMA', 'app', 'TABLE', 'users';
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique identifier for each user', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Unique username for login authentication', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';
+ EXEC sp_addextendedproperty 'MS_Description', 'User email address for notifications', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';
+ EXEC sp_addextendedproperty 'MS_Description', 'Timestamp when the user account was created', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';
+ EXEC sp_addextendedproperty 'MS_Description', 'Current status: active, inactive, or suspended', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';
+ GO
+- description: Reverse of default constraint operations - dropping tables, columns with defaults, and default constraints
+ oldSchema: |
+ CREATE SCHEMA [defaults];
+ GO
+
+ CREATE TABLE [defaults].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [hire_date] DATE NOT NULL DEFAULT GETDATE(),
+ [status] NVARCHAR(20) NOT NULL DEFAULT 'active',
+ [is_active] BIT NOT NULL DEFAULT 1,
+ [salary] DECIMAL(10,2) DEFAULT 50000.00,
+ [department_id] INT DEFAULT 1,
+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),
+ [updated_at] DATETIME2
+ );
+
+ CREATE TABLE [defaults].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00,
+ [stock] INT NOT NULL DEFAULT 0,
+ [is_available] BIT DEFAULT 1
+ );
+ newSchema: |
+ CREATE SCHEMA [defaults];
+ GO
+
+ CREATE TABLE [defaults].[employees] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(100) NOT NULL,
+ [hire_date] DATE NOT NULL DEFAULT GETDATE(),
+ [status] NVARCHAR(20) NOT NULL CONSTRAINT [DF_employees_status_new] DEFAULT 'pending',
+ [is_active] BIT NOT NULL DEFAULT 1,
+ [salary] DECIMAL(10,2) DEFAULT 50000.00,
+ [department_id] INT DEFAULT 1,
+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),
+ [updated_at] DATETIME2,
+ [vacation_days] INT NOT NULL DEFAULT 15,
+ [bonus_percentage] DECIMAL(5,2) DEFAULT (CASE WHEN MONTH(GETDATE()) = 12 THEN 10.0 ELSE 5.0 END)
+ );
+
+ CREATE TABLE [defaults].[products] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00,
+ [stock] INT NOT NULL DEFAULT 0,
+ [is_available] BIT DEFAULT 1,
+ [cost] DECIMAL(10,2) NOT NULL
+ );
+
+ CREATE TABLE [defaults].[orders] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [order_number] NVARCHAR(50) NOT NULL DEFAULT CONCAT('ORD-', YEAR(GETDATE()), '-', FORMAT(GETDATE(), 'MMdd')),
+ [order_date] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
+ [status] NVARCHAR(20) NOT NULL DEFAULT 'pending',
+ [total] DECIMAL(10,2) NOT NULL DEFAULT 0,
+ [discount] DECIMAL(5,2) DEFAULT NULL,
+ [is_paid] BIT NOT NULL DEFAULT 0,
+ [notes] NVARCHAR(MAX) DEFAULT 'No notes'
+ );
+ expected: |+
+ CREATE TABLE [defaults].[orders] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [order_number] NVARCHAR(50) NOT NULL DEFAULT CONCAT('ORD-', YEAR(GETDATE()), '-', FORMAT(GETDATE(), 'MMdd')),
+ [order_date] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
+ [status] NVARCHAR(20) NOT NULL DEFAULT 'pending',
+ [total] DECIMAL(10,2) NOT NULL DEFAULT 0,
+ [discount] DECIMAL(5,2) NULL DEFAULT NULL,
+ [is_paid] BIT NOT NULL DEFAULT 0,
+ [notes] NVARCHAR(MAX) NULL DEFAULT 'No notes',
+ CONSTRAINT [PK_orders_3] PRIMARY KEY ([id])
+ );
+ ALTER TABLE [defaults].[employees] ADD [vacation_days] INT NOT NULL DEFAULT 15;
+ ALTER TABLE [defaults].[employees] ADD [bonus_percentage] DECIMAL(5,2) NULL DEFAULT (CASE WHEN MONTH(GETDATE()) = 12 THEN 10.0 ELSE 5.0 END);
+ ALTER TABLE [defaults].[employees] ADD CONSTRAINT [DF_employees_status] DEFAULT 'pending' FOR [status];
+
+ ALTER TABLE [defaults].[products] ADD [cost] DECIMAL(10,2) NOT NULL;
+
+- description: Reverse of complex default expressions - dropping columns with system functions and conditional defaults
+ oldSchema: |
+ CREATE SCHEMA [complex];
+ GO
+
+ CREATE TABLE [complex].[audit_log] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_type] NVARCHAR(50) NOT NULL,
+ [user_name] NVARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,
+ [event_time] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
+ [ip_address] NVARCHAR(45),
+ [session_id] UNIQUEIDENTIFIER DEFAULT NEWID()
+ );
+
+ CREATE TABLE [complex].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [version] INT NOT NULL DEFAULT 1,
+ [created_date] DATE DEFAULT CAST(GETDATE() AS DATE),
+ [expiry_date] DATE DEFAULT DATEADD(YEAR, 1, CAST(GETDATE() AS DATE))
+ );
+ newSchema: |
+ CREATE SCHEMA [complex];
+ GO
+
+ CREATE TABLE [complex].[audit_log] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [event_type] NVARCHAR(50) NOT NULL,
+ [user_name] NVARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,
+ [event_time] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
+ [ip_address] NVARCHAR(45),
+ [session_id] UNIQUEIDENTIFIER DEFAULT NEWID(),
+ [server_name] NVARCHAR(100) DEFAULT @@SERVERNAME,
+ [database_name] NVARCHAR(100) DEFAULT DB_NAME(),
+ [schema_name] NVARCHAR(100) DEFAULT SCHEMA_NAME()
+ );
+
+ CREATE TABLE [complex].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [version] INT NOT NULL DEFAULT 1,
+ [created_date] DATE DEFAULT CAST(GETDATE() AS DATE),
+ [expiry_date] DATE DEFAULT DATEADD(YEAR, 1, CAST(GETDATE() AS DATE)),
+ [document_code] NVARCHAR(50) DEFAULT CONCAT('DOC-', FORMAT(GETDATE(), 'yyyyMMdd'), '-', NEWID()),
+ [priority] INT DEFAULT
+ CASE
+ WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 1
+ WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 2
+ ELSE 3
+ END
+ );
+
+ CREATE TABLE [complex].[calculations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [value1] DECIMAL(10,2) NOT NULL,
+ [value2] DECIMAL(10,2) NOT NULL,
+ [pi_value] DECIMAL(10,8) DEFAULT PI(),
+ [random_value] FLOAT DEFAULT RAND(),
+ [checksum_value] INT DEFAULT CHECKSUM(NEWID()),
+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),
+ [created_offset] DATETIMEOFFSET DEFAULT SYSDATETIMEOFFSET()
+ );
+ expected: |+
+ CREATE TABLE [complex].[calculations] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [value1] DECIMAL(10,2) NOT NULL,
+ [value2] DECIMAL(10,2) NOT NULL,
+ [pi_value] DECIMAL(10,8) NULL DEFAULT PI(),
+ [random_value] FLOAT NULL DEFAULT RAND(),
+ [checksum_value] INT NULL DEFAULT CHECKSUM(NEWID()),
+ [created_at] DATETIME2 NULL DEFAULT SYSDATETIME(),
+ [created_offset] DATETIMEOFFSET NULL DEFAULT SYSDATETIMEOFFSET(),
+ CONSTRAINT [PK_calculations_3] PRIMARY KEY ([id])
+ );
+ ALTER TABLE [complex].[audit_log] ADD [server_name] NVARCHAR(100) NULL DEFAULT @@SERVERNAME;
+ ALTER TABLE [complex].[audit_log] ADD [database_name] NVARCHAR(100) NULL DEFAULT DB_NAME();
+ ALTER TABLE [complex].[audit_log] ADD [schema_name] NVARCHAR(100) NULL DEFAULT SCHEMA_NAME();
+
+ ALTER TABLE [complex].[documents] ADD [document_code] NVARCHAR(50) NULL DEFAULT CONCAT('DOC-', FORMAT(GETDATE(), 'yyyyMMdd'), '-', NEWID());
+ ALTER TABLE [complex].[documents] ADD [priority] INT NULL DEFAULT CASE
+ WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 1
+ WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 2
+ ELSE 3
+ END;
+
+- description: Reverse of comments with special characters - dropping comments with quotes, unicode, and special formatting
+ oldSchema: |
+ CREATE SCHEMA [special];
+ GO
+
+ CREATE TABLE [special].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [author] NVARCHAR(100),
+ [created_date] DATETIME2,
+ [metadata] NVARCHAR(500)
+ );
+
+ CREATE TABLE [special].[translations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [document_id] INT NOT NULL,
+ [lang_code] NVARCHAR(10) NOT NULL,
+ [translated_title] NVARCHAR(200),
+ [translated_content] NVARCHAR(MAX),
+ CONSTRAINT [fk_translations_doc] FOREIGN KEY ([document_id]) REFERENCES [special].[documents]([id])
+ );
+ newSchema: |
+ CREATE SCHEMA [special];
+ GO
+
+ CREATE TABLE [special].[documents] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [title] NVARCHAR(200) NOT NULL,
+ [content] NVARCHAR(MAX),
+ [author] NVARCHAR(100),
+ [created_date] DATETIME2,
+ [metadata] NVARCHAR(500)
+ );
+
+ CREATE TABLE [special].[translations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [document_id] INT NOT NULL,
+ [lang_code] NVARCHAR(10) NOT NULL,
+ [translated_title] NVARCHAR(200),
+ [translated_content] NVARCHAR(MAX),
+ CONSTRAINT [fk_translations_doc] FOREIGN KEY ([document_id]) REFERENCES [special].[documents]([id])
+ );
+
+ CREATE TABLE [special].[test_extreme] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [data] NVARCHAR(MAX)
+ );
+ GO
+
+ -- Add table comments with special characters and quotes
+ EXEC sp_addextendedproperty 'MS_Description', 'Document storage system - handles files, "metadata", & special chars: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'documents';
+ GO
+
+ -- Add multiline comment with special formatting
+ EXEC sp_addextendedproperty 'MS_Description',
+ 'Translation table for international support:
+ - Supports Unicode characters: αβγδε, 中文, العربية, русский
+ - Handles quotes: "double quotes" and ''single quotes''
+ - Special symbols: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'translations';
+ GO
+
+ -- Column comments with various special cases
+ EXEC sp_addextendedproperty 'MS_Description', 'Primary key (auto-increment) - unique ID for each document', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Document title - may contain "quotes", ''apostrophes'', and symbols: @#$%', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';
+ GO
+
+ -- Multiline comment with technical details
+ EXEC sp_addextendedproperty 'MS_Description',
+ 'Document content field:
+ • Supports rich text formatting
+ • HTML tags like <p>, <div>, <span>
+ • Special characters: © ® ™ § ¶ † ‡ • ‰ ′ ″
+ • Mathematical: ± × ÷ ≠ ≤ ≥ ∞ ∑ ∏ ∫
+ • Currency: $ € £ ¥ ₹ ₽
+ • Arrows: ← → ↑ ↓ ↔ ⇐ ⇒ ⇔', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';
+ GO
+
+ -- Comment with SQL injection attempt (should be safely handled)
+ EXEC sp_addextendedproperty 'MS_Description', 'Author name field - prevents SQL injection like ''; DROP TABLE users; --', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';
+ GO
+
+ -- Comment with JSON-like structure
+ EXEC sp_addextendedproperty 'MS_Description', 'Metadata JSON: {"version": "1.0", "tags": ["important", "draft"], "settings": {"public": false}}', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';
+ GO
+
+ -- Unicode characters in comments
+ EXEC sp_addextendedproperty 'MS_Description', 'Language code: en-US, fr-FR, de-DE, ja-JP, zh-CN, ar-SA, ru-RU, hi-IN, 한국어, ไทย', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';
+ GO
+
+ -- Comment with URLs and file paths
+ EXEC sp_addextendedproperty 'MS_Description', 'Translated content - may reference URLs like https://example.com/path?param=value&other=123 or file paths C:\Users\Name\Documents\file.txt', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';
+ GO
+
+ -- Extremely long comment to test limits
+ EXEC sp_addextendedproperty 'MS_Description',
+ 'This is an extremely long comment designed to test the limits of extended property storage in SQL Server. It contains multiple lines of text with various formatting, special characters, and technical information. The purpose is to verify that the migration system can properly handle, store, and retrieve complex comment data without truncation or corruption. This comment includes: numbers (123456789), symbols (!@#$%^&*()_+-={}[]|\:";''<>?,./ ), Unicode characters (αβγδε中文العربيةрусский한국어), and structured data like JSON {"key": "value", "array": [1, 2, 3], "nested": {"deep": true}}. Additionally, it tests SQL-like syntax: SELECT * FROM table WHERE column = ''value'' AND other_column IN (1, 2, 3); as well as HTML markup: <html><body><p class="test">Content</p></body></html> and XML: <?xml version="1.0"?><root><item id="1">Test</item></root>. The comment system should preserve all these characters and structures exactly as written, demonstrating robust handling of complex metadata in database schema documentation.', 'SCHEMA', 'special', 'TABLE', 'test_extreme';
+ expected: |
+ CREATE TABLE [special].[test_extreme] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [data] NVARCHAR(MAX) NULL,
+ CONSTRAINT [PK_test_extreme_3] PRIMARY KEY ([id])
+ );
+ EXEC sp_addextendedproperty 'MS_Description', 'Document storage system - handles files, "metadata", & special chars: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'documents';
+ EXEC sp_addextendedproperty 'MS_Description', 'Primary key (auto-increment) - unique ID for each document', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';
+ EXEC sp_addextendedproperty 'MS_Description', 'Document title - may contain "quotes", ''apostrophes'', and symbols: @#$%', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';
+ EXEC sp_addextendedproperty 'MS_Description', 'Document content field:
+ • Supports rich text formatting
+ • HTML tags like <p>, <div>, <span>
+ • Special characters: © ® ™ § ¶ † ‡ • ‰ ′ ″
+ • Mathematical: ± × ÷ ≠ ≤ ≥ ∞ ∑ ∏ ∫
+ • Currency: $ € £ ¥ ₹ ₽
+ • Arrows: ← → ↑ ↓ ↔ ⇐ ⇒ ⇔', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';
+ EXEC sp_addextendedproperty 'MS_Description', 'Author name field - prevents SQL injection like ''; DROP TABLE users; --', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';
+ EXEC sp_addextendedproperty 'MS_Description', 'Metadata JSON: {"version": "1.0", "tags": ["important", "draft"], "settings": {"public": false}}', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';
+ EXEC sp_addextendedproperty 'MS_Description', 'This is an extremely long comment designed to test the limits of extended property storage in SQL Server. It contains multiple lines of text with various formatting, special characters, and technical information. The purpose is to verify that the migration system can properly handle, store, and retrieve complex comment data without truncation or corruption. This comment includes: numbers (123456789), symbols (!@#$%^&*()_+-={}[]|\:";''<>?,./ ), Unicode characters (αβγδε中文العربيةрусский한국어), and structured data like JSON {"key": "value", "array": [1, 2, 3], "nested": {"deep": true}}. Additionally, it tests SQL-like syntax: SELECT * FROM table WHERE column = ''value'' AND other_column IN (1, 2, 3); as well as HTML markup: <html><body><p class="test">Content</p></body></html> and XML: <?xml version="1.0"?><root><item id="1">Test</item></root>. The comment system should preserve all these characters and structures exactly as written, demonstrating robust handling of complex metadata in database schema documentation.', 'SCHEMA', 'special', 'TABLE', 'test_extreme';
+ EXEC sp_addextendedproperty 'MS_Description', 'Translation table for international support:
+ - Supports Unicode characters: αβγδε, 中文, العربية, русский
+ - Handles quotes: "double quotes" and ''single quotes''
+ - Special symbols: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'translations';
+ EXEC sp_addextendedproperty 'MS_Description', 'Language code: en-US, fr-FR, de-DE, ja-JP, zh-CN, ar-SA, ru-RU, hi-IN, 한국어, ไทย', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';
+ EXEC sp_addextendedproperty 'MS_Description', 'Translated content - may reference URLs like https://example.com/path?param=value&other=123 or file paths C:\Users\Name\Documents\file.txt', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';
+ GO
+- description: Reverse of edge case defaults - dropping special default constraints and columns
+ oldSchema: |
+ CREATE SCHEMA [edge];
+ GO
+
+ CREATE TABLE [edge].[test_defaults] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [nullable_with_default] INT DEFAULT 42,
+ [string_default] NVARCHAR(50) DEFAULT N'Default''s value',
+ [empty_string] NVARCHAR(50) DEFAULT '',
+ [zero_default] INT DEFAULT 0,
+ [negative_default] INT DEFAULT -1,
+ [decimal_precision] DECIMAL(18,6) DEFAULT 123.456789
+ );
+ newSchema: "CREATE SCHEMA [edge];\nGO\n\nCREATE TABLE [edge].[test_defaults] (\n [id] INT IDENTITY(1,1) PRIMARY KEY,\n [nullable_with_default] INT CONSTRAINT [DF_test_defaults_nullable_new] DEFAULT 84,\n [string_default] NVARCHAR(50) DEFAULT N'Default''s value',\n [empty_string] NVARCHAR(50) DEFAULT '',\n [zero_default] INT DEFAULT 0,\n [negative_default] INT DEFAULT -1,\n [decimal_precision] DECIMAL(18,6) DEFAULT 123.456789,\n [special_chars] NVARCHAR(100) DEFAULT N'Line1' + CHAR(13) + CHAR(10) + N'Line2',\n [unicode_default] NVARCHAR(100) DEFAULT N'你好世界 \U0001F30D',\n [max_int] BIGINT DEFAULT 9223372036854775807,\n [min_int] BIGINT DEFAULT -9223372036854775808,\n [json_config] NVARCHAR(MAX) DEFAULT N'{\"enabled\": true, \"count\": 0}'\n);\n\nCREATE TABLE [edge].[flags] (\n [id] INT IDENTITY(1,1) PRIMARY KEY,\n [is_enabled] BIT NOT NULL DEFAULT 1,\n [is_deleted] BIT NOT NULL DEFAULT 0,\n [is_visible] BIT DEFAULT 1,\n [is_archived] BIT DEFAULT 0\n);\n"
+ expected: "CREATE TABLE [edge].[flags] (\n [id] INT IDENTITY(1,1) NOT NULL,\n [is_enabled] BIT NOT NULL DEFAULT 1,\n [is_deleted] BIT NOT NULL DEFAULT 0,\n [is_visible] BIT NULL DEFAULT 1,\n [is_archived] BIT NULL DEFAULT 0,\n CONSTRAINT [PK_flags_2] PRIMARY KEY ([id])\n);\nALTER TABLE [edge].[test_defaults] ADD [special_chars] NVARCHAR(100) NULL DEFAULT N'Line1' + CHAR(13) + CHAR(10) + N'Line2';\nALTER TABLE [edge].[test_defaults] ADD [unicode_default] NVARCHAR(100) NULL DEFAULT N'你好世界 \U0001F30D';\nALTER TABLE [edge].[test_defaults] ADD [max_int] BIGINT NULL DEFAULT 9223372036854775807;\nALTER TABLE [edge].[test_defaults] ADD [min_int] BIGINT NULL DEFAULT -9223372036854775808;\nALTER TABLE [edge].[test_defaults] ADD [json_config] NVARCHAR(MAX) NULL DEFAULT N'{\"enabled\": true, \"count\": 0}';\nALTER TABLE [edge].[test_defaults] ADD CONSTRAINT [DF_test_defaults_nullable_with_default] DEFAULT 84 FOR [nullable_with_default];\n\n"
+- description: Spatial index operations with various tessellation schemes and parameters
+ oldSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ -- Enable spatial types
+ CREATE TABLE [geo].[locations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(200) NOT NULL,
+ [geo_point] GEOMETRY NOT NULL,
+ [geo_polygon] GEOMETRY NOT NULL,
+ [geo_location] GEOGRAPHY NOT NULL,
+ [description] NVARCHAR(MAX)
+ );
+
+ -- Add spatial indexes with different configurations
+
+ -- GEOMETRY_GRID index with full parameters
+ CREATE SPATIAL INDEX [idx_geo_point] ON [geo].[locations] ([geo_point])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-180, -90, 180, 90),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 32,
+ PAD_INDEX = ON,
+ FILLFACTOR = 85,
+ SORT_IN_TEMPDB = ON,
+ ALLOW_ROW_LOCKS = ON,
+ ALLOW_PAGE_LOCKS = ON,
+ MAXDOP = 2,
+ DATA_COMPRESSION = PAGE
+ );
+
+ -- GEOMETRY_AUTO_GRID index (requires bounding box)
+ CREATE SPATIAL INDEX [idx_geo_polygon] ON [geo].[locations] ([geo_polygon])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-1000, -1000, 1000, 1000),
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW)
+ );
+
+ -- GEOGRAPHY_GRID index with specific grid levels
+ CREATE SPATIAL INDEX [idx_geo_location] ON [geo].[locations] ([geo_location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 8,
+ FILLFACTOR = 80
+ );
+
+ -- Add another table with spatial columns
+ CREATE TABLE [geo].[boundaries] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [boundary_name] NVARCHAR(100) NOT NULL,
+ [boundary_shape] GEOMETRY NOT NULL,
+ [center_point] GEOMETRY NOT NULL
+ );
+
+ -- Add spatial index on new table
+ CREATE SPATIAL INDEX [idx_boundary_shape] ON [geo].[boundaries] ([boundary_shape])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (0, 0, 1000, 1000),
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = LOW, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 64
+ );
+ newSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ -- Enable spatial types
+ CREATE TABLE [geo].[locations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(200) NOT NULL,
+ [geo_point] GEOMETRY NOT NULL,
+ [geo_polygon] GEOMETRY NOT NULL,
+ [geo_location] GEOGRAPHY NOT NULL,
+ [description] NVARCHAR(MAX)
+ );
+ expected: |+
+ DROP INDEX [idx_geo_location] ON [geo].[locations];
+ DROP INDEX [idx_geo_point] ON [geo].[locations];
+ DROP INDEX [idx_geo_polygon] ON [geo].[locations];
+ DROP TABLE [geo].[boundaries];
+
+- description: Reverse spatial table operations - dropping table with spatial indexes
+ oldSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ CREATE TABLE [geo].[regions] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [region_name] NVARCHAR(100) NOT NULL,
+ [boundary] GEOMETRY NOT NULL,
+ [population] INT,
+ [area_sqkm] FLOAT
+ );
+ GO
+ newSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ -- Create table with spatial columns and indexes
+ CREATE TABLE [geo].[locations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(200) NOT NULL,
+ [location] GEOGRAPHY NOT NULL,
+ [area] GEOGRAPHY NOT NULL
+ );
+ GO
+
+ -- Create spatial indexes that will be dropped with the table
+ -- Using GEOGRAPHY_GRID which doesn't require BOUNDING_BOX
+ CREATE SPATIAL INDEX [idx_location] ON [geo].[locations] ([location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 16
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_area] ON [geo].[locations] ([area])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 8
+ );
+ GO
+
+ CREATE TABLE [geo].[regions] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [region_name] NVARCHAR(100) NOT NULL,
+ [boundary] GEOMETRY NOT NULL
+ );
+ GO
+ expected: |+
+ ALTER TABLE [geo].[regions] DROP CONSTRAINT [PK_regions_1];
+ GO
+ ALTER TABLE [geo].[regions] DROP COLUMN [population];
+ ALTER TABLE [geo].[regions] DROP COLUMN [area_sqkm];
+
+ CREATE TABLE [geo].[locations] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(200) NOT NULL,
+ [location] GEOGRAPHY NOT NULL,
+ [area] GEOGRAPHY NOT NULL,
+ CONSTRAINT [PK_locations_1] PRIMARY KEY ([id])
+ );
+ CREATE SPATIAL INDEX [idx_location] ON [geo].[locations] ([location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 16,
+ ALLOW_ROW_LOCKS = ON,
+ ALLOW_PAGE_LOCKS = ON
+ );
+ CREATE SPATIAL INDEX [idx_area] ON [geo].[locations] ([area])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 8,
+ ALLOW_ROW_LOCKS = ON,
+ ALLOW_PAGE_LOCKS = ON
+ );
+ ALTER TABLE [geo].[regions] ADD CONSTRAINT [PK_regions_2] PRIMARY KEY ([id]);
+
+- description: Reverse spatial index operations - dropping and recreating spatial indexes
+ oldSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ -- Create table with spatial columns and spatial indexes that can be preserved
+ CREATE TABLE [geo].[locations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(200) NOT NULL,
+ [geo_point] GEOMETRY NOT NULL,
+ [geo_polygon] GEOMETRY NOT NULL,
+ [geo_location] GEOGRAPHY NOT NULL,
+ [description] NVARCHAR(MAX)
+ );
+ GO
+
+ -- Create spatial indexes with basic configuration to avoid preservation issues
+ CREATE SPATIAL INDEX [idx_geo_point] ON [geo].[locations] ([geo_point])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-180, -90, 180, 90),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM)
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_geo_location] ON [geo].[locations] ([geo_location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM)
+ );
+ GO
+ newSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ -- Create table with spatial columns and spatial indexes that can be preserved
+ CREATE TABLE [geo].[locations] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(200) NOT NULL,
+ [geo_point] GEOMETRY NOT NULL,
+ [geo_polygon] GEOMETRY NOT NULL,
+ [geo_location] GEOGRAPHY NOT NULL,
+ [description] NVARCHAR(MAX)
+ );
+ GO
+
+ -- Create spatial indexes with basic configuration to avoid preservation issues
+ CREATE SPATIAL INDEX [idx_geo_point] ON [geo].[locations] ([geo_point])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-180, -90, 180, 90),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM)
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_geo_location] ON [geo].[locations] ([geo_location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM)
+ );
+ GO
+ expected: ""
+- description: Spatial index modifications - recreating with different parameters and adding/dropping indexes
+ oldSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ CREATE TABLE [geo].[spatial_data] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [location] GEOMETRY NOT NULL,
+ [region] GEOMETRY,
+ [area] GEOGRAPHY
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_location] ON [geo].[spatial_data] ([location])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-200, -200, 200, 200),
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 64,
+ PAD_INDEX = ON,
+ FILLFACTOR = 90,
+ ALLOW_ROW_LOCKS = ON,
+ ALLOW_PAGE_LOCKS = ON
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_region] ON [geo].[spatial_data] ([region])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-500, -500, 500, 500),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 32
+ );
+ GO
+ newSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ CREATE TABLE [geo].[spatial_data] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(100) NOT NULL,
+ [location] GEOMETRY NOT NULL,
+ [region] GEOMETRY,
+ [area] GEOGRAPHY
+ );
+ GO
+
+ -- Create initial spatial indexes
+ CREATE SPATIAL INDEX [idx_location] ON [geo].[spatial_data] ([location])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-100, -100, 100, 100),
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 16
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_area] ON [geo].[spatial_data] ([area])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 32
+ );
+ GO
+ expected: |+
+ DROP INDEX [idx_location] ON [geo].[spatial_data];
+ DROP INDEX [idx_region] ON [geo].[spatial_data];
+
+ CREATE SPATIAL INDEX [idx_area] ON [geo].[spatial_data] ([area])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 32,
+ ALLOW_ROW_LOCKS = ON,
+ ALLOW_PAGE_LOCKS = ON
+ );
+ CREATE SPATIAL INDEX [idx_location] ON [geo].[spatial_data] ([location])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-100, -100, 100, 100),
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 16,
+ ALLOW_ROW_LOCKS = ON,
+ ALLOW_PAGE_LOCKS = ON
+ );
+
+- description: Spatial table schema changes - adding columns and indexes while preserving existing spatial indexes
+ oldSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ CREATE TABLE [geo].[points] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [name] NVARCHAR(50) NOT NULL,
+ [location] GEOMETRY NOT NULL,
+ [altitude] FLOAT,
+ [boundary] GEOMETRY,
+ [geo_location] GEOGRAPHY,
+ [created_at] DATETIME2 DEFAULT GETDATE()
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_points_location] ON [geo].[points] ([location])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (0, 0, 100, 100),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM)
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_points_boundary] ON [geo].[points] ([boundary])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-50, -50, 150, 150),
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 8
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_points_geo_location] ON [geo].[points] ([geo_location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = HIGH, LEVEL_4 = HIGH),
+ CELLS_PER_OBJECT = 16
+ );
+ GO
+ newSchema: |
+ CREATE SCHEMA [geo];
+ GO
+
+ CREATE TABLE [geo].[points] (
+ [id] INT IDENTITY(1,1) PRIMARY KEY,
+ [point_name] NVARCHAR(50) NOT NULL,
+ [location] GEOMETRY NOT NULL
+ );
+ GO
+
+ CREATE SPATIAL INDEX [idx_points_location] ON [geo].[points] ([location])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (0, 0, 100, 100),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM)
+ );
+ GO
+ expected: |+
+ DROP INDEX [idx_points_boundary] ON [geo].[points];
+ DROP INDEX [idx_points_geo_location] ON [geo].[points];
+ GO
+ ALTER TABLE [geo].[points] DROP COLUMN [name];
+ ALTER TABLE [geo].[points] DROP COLUMN [altitude];
+ ALTER TABLE [geo].[points] DROP COLUMN [boundary];
+ ALTER TABLE [geo].[points] DROP COLUMN [geo_location];
+ ALTER TABLE [geo].[points] DROP COLUMN [created_at];
+
+ ALTER TABLE [geo].[points] ADD [point_name] NVARCHAR(50) NOT NULL;
+
diff --git a/backend/plugin/schema/mssql/testdata/get_database_definition.yaml b/backend/plugin/schema/mssql/testdata/get_database_definition.yaml
new file mode 100644
index 0000000000..e75e944d05
--- /dev/null
+++ b/backend/plugin/schema/mssql/testdata/get_database_definition.yaml
@@ -0,0 +1,2786 @@
+- description: users
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "NVARCHAR(255)",
+ "nullable": true,
+ "default": "''"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "type": "DATETIME2",
+ "nullable": false,
+ "default": "GETDATE()"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_users",
+ "expressions": ["id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true,
+ "type": "CLUSTERED"
+ },
+ {
+ "name": "IX_users_email",
+ "expressions": ["email"],
+ "descending": [false],
+ "unique": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[users] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(255) DEFAULT '',
+ [created_at] DATETIME2 DEFAULT GETDATE() NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id] ASC)
+ );
+
+ CREATE UNIQUE INDEX [IX_users_email] ON
+ [dbo].[users] (
+ [email] ASC
+ );
+
+- description: orders
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "order_id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "amount",
+ "position": 3,
+ "type": "DECIMAL(10,2)",
+ "nullable": false
+ },
+ {
+ "name": "status",
+ "position": 4,
+ "type": "NVARCHAR(20)",
+ "nullable": false,
+ "default": "'pending'"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_orders",
+ "expressions": ["order_id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_orders_users",
+ "columns": ["user_id"],
+ "referencedSchema": "dbo",
+ "referencedTable": "users",
+ "referencedColumns": ["id"],
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION"
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CK_orders_amount",
+ "expression": "([amount] > 0)"
+ },
+ {
+ "name": "CK_orders_status",
+ "expression": "([status] IN ('pending', 'completed', 'cancelled'))"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[orders] (
+ [order_id] INT IDENTITY(1,1) NOT NULL,
+ [user_id] INT NOT NULL,
+ [amount] DECIMAL(10,2) NOT NULL,
+ [status] NVARCHAR(20) DEFAULT 'pending' NOT NULL,
+ CONSTRAINT [PK_orders] PRIMARY KEY ([order_id] ASC),
+ CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION,
+ CONSTRAINT [CK_orders_amount] CHECK ([amount] > 0),
+ CONSTRAINT [CK_orders_status] CHECK ([status] IN ('pending', 'completed', 'cancelled'))
+ );
+
+- description: v_active_users
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "views": [
+ {
+ "name": "v_active_users",
+ "definition": "CREATE VIEW [dbo].[v_active_users] AS SELECT u.id, u.name, u.email, COUNT(o.order_id) as order_count\nFROM dbo.users u\nLEFT JOIN dbo.orders o ON u.id = o.user_id\nWHERE u.created_at >= DATEADD(month, -6, GETDATE())\nGROUP BY u.id, u.name, u.email"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE VIEW [dbo].[v_active_users] AS SELECT u.id, u.name, u.email, COUNT(o.order_id) as order_count
+ FROM dbo.users u
+ LEFT JOIN dbo.orders o ON u.id = o.user_id
+ WHERE u.created_at >= DATEADD(month, -6, GETDATE())
+ GROUP BY u.id, u.name, u.email;
+
+ GO
+
+- description: fn_getuserordertotal
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "functions": [
+ {
+ "name": "fn_GetUserOrderTotal",
+ "definition": "CREATE FUNCTION [dbo].[fn_GetUserOrderTotal]\n(\n @UserId INT\n)\nRETURNS DECIMAL(10,2)\nAS\nBEGIN\n DECLARE @Total DECIMAL(10,2)\n\n SELECT @Total = SUM(amount)\n FROM dbo.orders\n WHERE user_id = @UserId\n AND status = 'completed'\n\n RETURN ISNULL(@Total, 0)\nEND"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE FUNCTION [dbo].[fn_GetUserOrderTotal]
+ (
+ @UserId INT
+ )
+ RETURNS DECIMAL(10,2)
+ AS
+ BEGIN
+ DECLARE @Total DECIMAL(10,2)
+
+ SELECT @Total = SUM(amount)
+ FROM dbo.orders
+ WHERE user_id = @UserId
+ AND status = 'completed'
+
+ RETURN ISNULL(@Total, 0)
+ END
+
+ GO
+
+- description: sp_updateorderstatus
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "procedures": [
+ {
+ "name": "sp_UpdateOrderStatus",
+ "definition": "CREATE PROCEDURE [dbo].[sp_UpdateOrderStatus]\n @OrderId INT,\n @NewStatus NVARCHAR(20)\nAS\nBEGIN\n SET NOCOUNT ON;\n\n UPDATE dbo.orders\n SET status = @NewStatus\n WHERE order_id = @OrderId;\n\n SELECT @@ROWCOUNT AS RowsAffected;\nEND"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE PROCEDURE [dbo].[sp_UpdateOrderStatus]
+ @OrderId INT,
+ @NewStatus NVARCHAR(20)
+ AS
+ BEGIN
+ SET NOCOUNT ON;
+
+ UPDATE dbo.orders
+ SET status = @NewStatus
+ WHERE order_id = @OrderId;
+
+ SELECT @@ROWCOUNT AS RowsAffected;
+ END
+
+ GO
+
+- description: products
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "sales",
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "product_id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(200)",
+ "nullable": false
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_products",
+ "expressions": ["product_id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE TABLE [sales].[products] (
+ [product_id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(200) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY ([product_id] ASC)
+ );
+
+- description: employees_v_employee_list_fn_getemployeename
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "employee_id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_employees",
+ "expressions": ["employee_id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_employee_list",
+ "definition": "CREATE VIEW [dbo].[v_employee_list] AS SELECT employee_id, name FROM dbo.employees WHERE employee_id > 0"
+ }
+ ],
+ "functions": [
+ {
+ "name": "fn_GetEmployeeName",
+ "definition": "CREATE FUNCTION [dbo].[fn_GetEmployeeName](@EmpId INT) RETURNS NVARCHAR(100) AS BEGIN DECLARE @Name NVARCHAR(100); SELECT @Name = name FROM dbo.employees WHERE employee_id = @EmpId; RETURN @Name; END"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "sp_GetEmployee",
+ "definition": "CREATE PROCEDURE [dbo].[sp_GetEmployee] @EmpId INT AS BEGIN SELECT * FROM dbo.employees WHERE employee_id = @EmpId; END"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[employees] (
+ [employee_id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ CONSTRAINT [PK_employees] PRIMARY KEY ([employee_id] ASC)
+ );
+
+ GO
+
+ CREATE VIEW [dbo].[v_employee_list] AS SELECT employee_id, name FROM dbo.employees WHERE employee_id > 0;
+
+ GO
+
+ CREATE FUNCTION [dbo].[fn_GetEmployeeName](@EmpId INT) RETURNS NVARCHAR(100) AS BEGIN DECLARE @Name NVARCHAR(100); SELECT @Name = name FROM dbo.employees WHERE employee_id = @EmpId; RETURN @Name; END
+
+ GO
+
+ CREATE PROCEDURE [dbo].[sp_GetEmployee] @EmpId INT AS BEGIN SELECT * FROM dbo.employees WHERE employee_id = @EmpId; END
+
+ GO
+
+- description: international_data
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "international_data",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "text_data",
+ "position": 2,
+ "type": "NVARCHAR(MAX)",
+ "nullable": true,
+ "collation": "Latin1_General_CI_AS"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[international_data] (
+ [id] INT NOT NULL,
+ [text_data] NVARCHAR(MAX) COLLATE Latin1_General_CI_AS
+ );
+
+- description: fact_sales
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "fact_sales",
+ "columns": [
+ {
+ "name": "sale_id",
+ "position": 1,
+ "type": "BIGINT",
+ "nullable": false
+ },
+ {
+ "name": "product_id",
+ "position": 2,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "quantity",
+ "position": 3,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "amount",
+ "position": 4,
+ "type": "DECIMAL(10,2)",
+ "nullable": false
+ }
+ ],
+ "indexes": [
+ {
+ "name": "CCI_fact_sales",
+ "type": "CLUSTERED COLUMNSTORE"
+ },
+ {
+ "name": "NCCI_fact_sales_product",
+ "type": "NONCLUSTERED COLUMNSTORE",
+ "expressions": ["product_id", "quantity"]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[fact_sales] (
+ [sale_id] BIGINT NOT NULL,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [amount] DECIMAL(10,2) NOT NULL
+ );
+
+ CREATE CLUSTERED COLUMNSTORE INDEX [CCI_fact_sales] ON [dbo].[fact_sales];
+
+ CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_fact_sales_product] ON [dbo].[fact_sales] (
+ [product_id],
+ [quantity]
+ );
+
+- description: customers_orders_v_customer_orders
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "customers",
+ "columns": [
+ {
+ "name": "customer_id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ }
+ ]
+ },
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "order_id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "customer_id",
+ "position": 2,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "total",
+ "position": 3,
+ "type": "DECIMAL(10,2)",
+ "nullable": false
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_customer_orders",
+ "definition": "CREATE VIEW [dbo].[v_customer_orders] AS SELECT c.customer_id, c.name, o.order_id, o.total FROM dbo.customers c JOIN dbo.orders o ON c.customer_id = o.customer_id"
+ },
+ {
+ "name": "v_customer_summary",
+ "definition": "CREATE VIEW [dbo].[v_customer_summary] AS SELECT customer_id, name, COUNT(order_id) as order_count, SUM(total) as total_amount FROM dbo.v_customer_orders GROUP BY customer_id, name"
+ },
+ {
+ "name": "v_top_customers",
+ "definition": "CREATE VIEW [dbo].[v_top_customers] AS SELECT TOP 10 * FROM dbo.v_customer_summary ORDER BY total_amount DESC"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[customers] (
+ [customer_id] INT NOT NULL,
+ [name] NVARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE [dbo].[orders] (
+ [order_id] INT NOT NULL,
+ [customer_id] INT NOT NULL,
+ [total] DECIMAL(10,2) NOT NULL
+ );
+
+ GO
+
+ CREATE VIEW [dbo].[v_customer_orders] AS SELECT c.customer_id, c.name, o.order_id, o.total FROM dbo.customers c JOIN dbo.orders o ON c.customer_id = o.customer_id;
+
+ GO
+
+ CREATE VIEW [dbo].[v_customer_summary] AS SELECT customer_id, name, COUNT(order_id) as order_count, SUM(total) as total_amount FROM dbo.v_customer_orders GROUP BY customer_id, name;
+
+ GO
+
+ CREATE VIEW [dbo].[v_top_customers] AS SELECT TOP 10 * FROM dbo.v_customer_summary ORDER BY total_amount DESC;
+
+ GO
+
+- description: products_v_product_list_v_all_products
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "sales",
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "product_id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_product_list",
+ "definition": "CREATE VIEW [sales].[v_product_list] AS SELECT product_id, name FROM sales.products"
+ }
+ ]
+ },
+ {
+ "name": "reporting",
+ "views": [
+ {
+ "name": "v_all_products",
+ "definition": "CREATE VIEW [reporting].[v_all_products] AS SELECT * FROM sales.v_product_list"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE TABLE [sales].[products] (
+ [product_id] INT NOT NULL,
+ [name] NVARCHAR(100) NOT NULL
+ );
+
+ GO
+
+ CREATE VIEW [sales].[v_product_list] AS SELECT product_id, name FROM sales.products;
+
+ GO
+
+ CREATE VIEW [reporting].[v_all_products] AS SELECT * FROM sales.v_product_list;
+
+ GO
+
+- description: spatial_features
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "spatial_features",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "feature_name",
+ "position": 2,
+ "type": "NVARCHAR(200)",
+ "nullable": false
+ },
+ {
+ "name": "location_point",
+ "position": 3,
+ "type": "GEOMETRY",
+ "nullable": false
+ },
+ {
+ "name": "boundary_polygon",
+ "position": 4,
+ "type": "GEOMETRY",
+ "nullable": false
+ },
+ {
+ "name": "geo_location",
+ "position": 5,
+ "type": "GEOGRAPHY",
+ "nullable": false
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_spatial_features",
+ "expressions": ["id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true,
+ "type": "CLUSTERED"
+ },
+ {
+ "name": "idx_location_point",
+ "expressions": ["location_point"],
+ "descending": [false],
+ "type": "SPATIAL",
+ "spatialConfig": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_GRID",
+ "boundingBox": {
+ "xmin": -180,
+ "ymin": -90,
+ "xmax": 180,
+ "ymax": 90
+ },
+ "gridLevels": [
+ {
+ "level": 1,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 2,
+ "density": "HIGH"
+ },
+ {
+ "level": 3,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 4,
+ "density": "LOW"
+ }
+ ],
+ "cellsPerObject": 32
+ },
+ "storage": {
+ "padIndex": true,
+ "fillfactor": 85,
+ "sortInTempdb": "ON",
+ "allowRowLocks": true,
+ "allowPageLocks": true,
+ "maxdop": 2,
+ "dataCompression": "PAGE"
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "dataType": "GEOMETRY"
+ }
+ }
+ },
+ {
+ "name": "idx_boundary_polygon",
+ "expressions": ["boundary_polygon"],
+ "descending": [false],
+ "type": "SPATIAL",
+ "spatialConfig": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_AUTO_GRID",
+ "cellsPerObject": 16
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "dataType": "GEOMETRY"
+ }
+ }
+ },
+ {
+ "name": "idx_geo_location",
+ "expressions": ["geo_location"],
+ "descending": [false],
+ "type": "SPATIAL",
+ "spatialConfig": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "gridLevels": [
+ {
+ "level": 1,
+ "density": "LOW"
+ },
+ {
+ "level": 2,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 3,
+ "density": "HIGH"
+ },
+ {
+ "level": 4,
+ "density": "MEDIUM"
+ }
+ ],
+ "cellsPerObject": 8
+ },
+ "storage": {
+ "fillfactor": 80,
+ "online": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "dataType": "GEOGRAPHY"
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[spatial_features] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [feature_name] NVARCHAR(200) NOT NULL,
+ [location_point] GEOMETRY NOT NULL,
+ [boundary_polygon] GEOMETRY NOT NULL,
+ [geo_location] GEOGRAPHY NOT NULL,
+ CONSTRAINT [PK_spatial_features] PRIMARY KEY CLUSTERED ([id] ASC)
+ );
+
+ CREATE SPATIAL INDEX [idx_location_point] ON [dbo].[spatial_features] ([location_point])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-180, -90, 180, 90),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 32,
+ PAD_INDEX = ON,
+ FILLFACTOR = 85,
+ SORT_IN_TEMPDB = ON,
+ MAXDOP = 2,
+ DATA_COMPRESSION = PAGE
+ );
+
+ CREATE SPATIAL INDEX [idx_boundary_polygon] ON [dbo].[spatial_features] ([boundary_polygon])
+ USING GEOMETRY_AUTO_GRID
+ WITH (
+ CELLS_PER_OBJECT = 16
+ );
+
+ CREATE SPATIAL INDEX [idx_geo_location] ON [dbo].[spatial_features] ([geo_location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 8,
+ FILLFACTOR = 80,
+ ONLINE = ON,
+ ALLOW_ROW_LOCKS = OFF,
+ ALLOW_PAGE_LOCKS = OFF
+ );
+
+- description: basic_tables_with_constraints
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo"
+ },
+ {
+ "name": "test_schema",
+ "tables": [
+ {
+ "name": "posts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int",
+ "is_identity": true,
+ "identity_seed": 1,
+ "identity_increment": 1
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "title",
+ "position": 3,
+ "type": "nvarchar(200)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "content",
+ "position": 4,
+ "nullable": true,
+ "type": "nvarchar(max)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__posts__3213E83F982F55CE",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ },
+ {
+ "name": "idx_posts_title",
+ "expressions": [
+ "title"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED",
+ "unique": true
+ },
+ {
+ "name": "idx_posts_user_id",
+ "expressions": [
+ "user_id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED"
+ }
+ ],
+ "foreign_keys": [
+ {
+ "name": "FK_posts_users",
+ "columns": [
+ "user_id"
+ ],
+ "referenced_schema": "test_schema",
+ "referenced_table": "users",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "NO ACTION"
+ }
+ ]
+ },
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int",
+ "is_identity": true,
+ "identity_seed": 1,
+ "identity_increment": 1
+ },
+ {
+ "name": "email",
+ "position": 2,
+ "type": "varchar(255)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "created_at",
+ "position": 3,
+ "default": "(getdate())",
+ "nullable": true,
+ "type": "datetime2(7)",
+ "default_constraint_name": "DF__users__created_a__38996AB5"
+ },
+ {
+ "name": "is_active",
+ "position": 4,
+ "default": "((1))",
+ "nullable": true,
+ "type": "bit",
+ "default_constraint_name": "DF__users__is_active__398D8EEE"
+ },
+ {
+ "name": "age",
+ "position": 5,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "computed_column",
+ "position": 6,
+ "nullable": true,
+ "type": "AS ([id]*(2)) PERSISTED"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__users__3213E83F9332C18C",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UQ__users__AB6E616484F069E2",
+ "expressions": [
+ "email"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED",
+ "unique": true,
+ "is_constraint": true
+ }
+ ],
+ "check_constraints": [
+ {
+ "name": "CK__users__age__3A81B327",
+ "expression": "([age]\u003e=(18))"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE SCHEMA [test_schema];
+ GO
+
+ CREATE TABLE [test_schema].[users] (
+ [id] int IDENTITY(1,1) NOT NULL,
+ [email] varchar(255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
+ [created_at] datetime2(7) DEFAULT (getdate()),
+ [is_active] bit DEFAULT ((1)),
+ [age] int,
+ [computed_column] AS ([id]*(2)) PERSISTED,
+ CONSTRAINT [PK__users__3213E83F9332C18C] PRIMARY KEY CLUSTERED ([id] ASC),
+ CONSTRAINT [UQ__users__AB6E616484F069E2] UNIQUE NONCLUSTERED ([email] ASC),
+ CONSTRAINT [CK__users__age__3A81B327] CHECK ([age]>=(18))
+ );
+
+ CREATE TABLE [test_schema].[posts] (
+ [id] int IDENTITY(1,1) NOT NULL,
+ [user_id] int NOT NULL,
+ [title] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
+ [content] nvarchar(max) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ CONSTRAINT [PK__posts__3213E83F982F55CE] PRIMARY KEY CLUSTERED ([id] ASC),
+ CONSTRAINT [FK_posts_users] FOREIGN KEY ([user_id]) REFERENCES [test_schema].[users] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION
+ );
+
+ CREATE UNIQUE NONCLUSTERED INDEX [idx_posts_title] ON
+ [test_schema].[posts] (
+ [title] ASC
+ );
+
+ CREATE NONCLUSTERED INDEX [idx_posts_user_id] ON
+ [test_schema].[posts] (
+ [user_id] ASC
+ );
+
+- description: views_with_dependencies
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "emp_id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "emp_name",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(100)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "department",
+ "position": 3,
+ "nullable": true,
+ "type": "varchar(50)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "salary",
+ "position": 4,
+ "nullable": true,
+ "type": "decimal(10, 2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__employee__1299A861D2E977EA",
+ "expressions": [
+ "emp_id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_employee_summary",
+ "definition": "CREATE VIEW dbo.v_employee_summary AS\nSELECT department, COUNT(*) as emp_count, AVG(salary) as avg_salary\nFROM dbo.employees\nGROUP BY department;",
+ "columns": [
+ {
+ "name": "department",
+ "position": 1,
+ "nullable": true,
+ "type": "varchar(50)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "emp_count",
+ "position": 2,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "avg_salary",
+ "position": 3,
+ "nullable": true,
+ "type": "decimal(38, 6)"
+ }
+ ]
+ },
+ {
+ "name": "v_high_earners",
+ "definition": "CREATE VIEW dbo.v_high_earners AS\nSELECT * FROM dbo.v_employee_summary\nWHERE avg_salary \u003e 50000;",
+ "columns": [
+ {
+ "name": "department",
+ "position": 1,
+ "nullable": true,
+ "type": "varchar(50)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "emp_count",
+ "position": 2,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "avg_salary",
+ "position": 3,
+ "nullable": true,
+ "type": "decimal(38, 6)"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[employees] (
+ [emp_id] int NOT NULL,
+ [emp_name] varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [department] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [salary] decimal(10, 2),
+ CONSTRAINT [PK__employee__1299A861D2E977EA] PRIMARY KEY CLUSTERED ([emp_id] ASC)
+ );
+
+ GO
+
+ CREATE VIEW dbo.v_employee_summary AS
+ SELECT department, COUNT(*) as emp_count, AVG(salary) as avg_salary
+ FROM dbo.employees
+ GROUP BY department;;
+
+ GO
+
+ CREATE VIEW dbo.v_high_earners AS
+ SELECT * FROM dbo.v_employee_summary
+ WHERE avg_salary > 50000;;
+
+ GO
+
+- description: functions_and_procedures
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "functions": [
+ {
+ "name": "GetFullName",
+ "definition": "CREATE FUNCTION dbo.GetFullName(@FirstName NVARCHAR(50), @LastName NVARCHAR(50))\nRETURNS NVARCHAR(100)\nAS\nBEGIN\n RETURN @FirstName + ' ' + @LastName;\nEND"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "UpdateSalary",
+ "definition": "CREATE PROCEDURE dbo.UpdateSalary\n @EmployeeId INT,\n @NewSalary DECIMAL(10,2)\nAS\nBEGIN\n UPDATE employees SET salary = @NewSalary WHERE emp_id = @EmployeeId;\nEND"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE FUNCTION dbo.GetFullName(@FirstName NVARCHAR(50), @LastName NVARCHAR(50))
+ RETURNS NVARCHAR(100)
+ AS
+ BEGIN
+ RETURN @FirstName + ' ' + @LastName;
+ END
+
+ GO
+
+ CREATE PROCEDURE dbo.UpdateSalary
+ @EmployeeId INT,
+ @NewSalary DECIMAL(10,2)
+ AS
+ BEGIN
+ UPDATE employees SET salary = @NewSalary WHERE emp_id = @EmployeeId;
+ END
+
+ GO
+
+- description: complex_indexes
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "product_id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "product_name",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(100)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "category",
+ "position": 3,
+ "nullable": true,
+ "type": "varchar(50)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__products__47027DF59BF03BB5",
+ "expressions": [
+ "product_id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ },
+ {
+ "name": "ncci_products",
+ "expressions": [
+ "product_name",
+ "category"
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "NONCLUSTERED COLUMNSTORE"
+ }
+ ]
+ },
+ {
+ "name": "sales",
+ "columns": [
+ {
+ "name": "sale_id",
+ "position": 1,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "product_id",
+ "position": 2,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "sale_date",
+ "position": 3,
+ "nullable": true,
+ "type": "date"
+ },
+ {
+ "name": "amount",
+ "position": 4,
+ "nullable": true,
+ "type": "decimal(10, 2)"
+ },
+ {
+ "name": "region",
+ "position": 5,
+ "nullable": true,
+ "type": "varchar(50)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "cci_sales",
+ "expressions": [
+ "sale_id",
+ "product_id",
+ "sale_date",
+ "amount",
+ "region"
+ ],
+ "descending": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ "type": "CLUSTERED COLUMNSTORE"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[products] (
+ [product_id] int NOT NULL,
+ [product_name] varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [category] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ CONSTRAINT [PK__products__47027DF59BF03BB5] PRIMARY KEY CLUSTERED ([product_id] ASC)
+ );
+
+ CREATE NONCLUSTERED COLUMNSTORE INDEX [ncci_products] ON [dbo].[products] (
+ [product_name],
+ [category]
+ );
+
+ CREATE TABLE [dbo].[sales] (
+ [sale_id] int,
+ [product_id] int,
+ [sale_date] date,
+ [amount] decimal(10, 2),
+ [region] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS
+ );
+
+ CREATE CLUSTERED COLUMNSTORE INDEX [cci_sales] ON [dbo].[sales];
+
+- description: temporal_tables
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "temporal_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(100)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "SysStartTime",
+ "position": 3,
+ "type": "datetime2(7)"
+ },
+ {
+ "name": "SysEndTime",
+ "position": 4,
+ "type": "datetime2(7)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__temporal__3213E83F3E461CC4",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ }
+ ]
+ },
+ {
+ "name": "temporal_test_history",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(100)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "SysStartTime",
+ "position": 3,
+ "type": "datetime2(7)"
+ },
+ {
+ "name": "SysEndTime",
+ "position": 4,
+ "type": "datetime2(7)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "ix_temporal_test_history",
+ "expressions": [
+ "SysEndTime",
+ "SysStartTime"
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "CLUSTERED"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[temporal_test] (
+ [id] int NOT NULL,
+ [name] varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [SysStartTime] datetime2(7) NOT NULL,
+ [SysEndTime] datetime2(7) NOT NULL,
+ CONSTRAINT [PK__temporal__3213E83F3E461CC4] PRIMARY KEY CLUSTERED ([id] ASC)
+ );
+
+ CREATE TABLE [dbo].[temporal_test_history] (
+ [id] int NOT NULL,
+ [name] varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [SysStartTime] datetime2(7) NOT NULL,
+ [SysEndTime] datetime2(7) NOT NULL
+ );
+
+ CREATE CLUSTERED INDEX [ix_temporal_test_history] ON
+ [dbo].[temporal_test_history] (
+ [SysEndTime] ASC,
+ [SysStartTime] ASC
+ );
+
+- description: spatial_indexes_geography
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo"
+ },
+ {
+ "name": "spatial_schema",
+ "tables": [
+ {
+ "name": "locations",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int",
+ "is_identity": true,
+ "identity_seed": 1,
+ "identity_increment": 1
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "nvarchar(200)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "location_point",
+ "position": 3,
+ "type": "geography"
+ },
+ {
+ "name": "boundary_polygon",
+ "position": 4,
+ "type": "geography"
+ },
+ {
+ "name": "route_line",
+ "position": 5,
+ "nullable": true,
+ "type": "geography"
+ },
+ {
+ "name": "description",
+ "position": 6,
+ "nullable": true,
+ "type": "nvarchar(max)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "created_at",
+ "position": 7,
+ "default": "(getdate())",
+ "nullable": true,
+ "type": "datetime2(7)",
+ "default_constraint_name": "DF__locations__creat__37A5467C"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__location__3213E83FC19EBDD5",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ },
+ {
+ "name": "idx_created_at",
+ "expressions": [
+ "created_at"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED"
+ },
+ {
+ "name": "idx_name",
+ "expressions": [
+ "name"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED"
+ },
+ {
+ "name": "idx_boundary_polygon",
+ "expressions": [
+ "boundary_polygon"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "LOW"
+ },
+ {
+ "level": 2,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 3,
+ "density": "HIGH"
+ },
+ {
+ "level": 4,
+ "density": "MEDIUM"
+ }
+ ],
+ "cells_per_object": 16
+ },
+ "storage": {
+ "fillfactor": 80,
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOGRAPHY"
+ }
+ }
+ },
+ {
+ "name": "idx_location_point",
+ "expressions": [
+ "location_point"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 2,
+ "density": "HIGH"
+ },
+ {
+ "level": 3,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 4,
+ "density": "LOW"
+ }
+ ],
+ "cells_per_object": 32
+ },
+ "storage": {
+ "fillfactor": 85,
+ "pad_index": true,
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOGRAPHY"
+ }
+ }
+ },
+ {
+ "name": "idx_route_line",
+ "expressions": [
+ "route_line"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "HIGH"
+ },
+ {
+ "level": 2,
+ "density": "HIGH"
+ },
+ {
+ "level": 3,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 4,
+ "density": "LOW"
+ }
+ ],
+ "cells_per_object": 64
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOGRAPHY"
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE SCHEMA [spatial_schema];
+ GO
+
+ CREATE TABLE [spatial_schema].[locations] (
+ [id] int IDENTITY(1,1) NOT NULL,
+ [name] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
+ [location_point] geography NOT NULL,
+ [boundary_polygon] geography NOT NULL,
+ [route_line] geography,
+ [description] nvarchar(max) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [created_at] datetime2(7) DEFAULT (getdate()),
+ CONSTRAINT [PK__location__3213E83FC19EBDD5] PRIMARY KEY CLUSTERED ([id] ASC)
+ );
+
+ CREATE NONCLUSTERED INDEX [idx_created_at] ON
+ [spatial_schema].[locations] (
+ [created_at] ASC
+ );
+
+ CREATE NONCLUSTERED INDEX [idx_name] ON
+ [spatial_schema].[locations] (
+ [name] ASC
+ );
+
+ CREATE SPATIAL INDEX [idx_boundary_polygon] ON [spatial_schema].[locations] ([boundary_polygon])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 16,
+ FILLFACTOR = 80
+ );
+
+ CREATE SPATIAL INDEX [idx_location_point] ON [spatial_schema].[locations] ([location_point])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 32,
+ PAD_INDEX = ON,
+ FILLFACTOR = 85
+ );
+
+ CREATE SPATIAL INDEX [idx_route_line] ON [spatial_schema].[locations] ([route_line])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 64
+ );
+
+- description: spatial_indexes_geometry
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo"
+ },
+ {
+ "name": "geom_schema",
+ "tables": [
+ {
+ "name": "shapes",
+ "columns": [
+ {
+ "name": "shape_id",
+ "position": 1,
+ "type": "int",
+ "is_identity": true,
+ "identity_seed": 1,
+ "identity_increment": 1
+ },
+ {
+ "name": "shape_name",
+ "position": 2,
+ "type": "nvarchar(100)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "shape_point",
+ "position": 3,
+ "type": "geometry"
+ },
+ {
+ "name": "shape_polygon",
+ "position": 4,
+ "type": "geometry"
+ },
+ {
+ "name": "shape_line",
+ "position": 5,
+ "nullable": true,
+ "type": "geometry"
+ },
+ {
+ "name": "area_size",
+ "position": 6,
+ "nullable": true,
+ "type": "AS ([shape_polygon].[STArea]()) PERSISTED"
+ },
+ {
+ "name": "center_x",
+ "position": 7,
+ "nullable": true,
+ "type": "AS ([shape_point].[STX]) PERSISTED"
+ },
+ {
+ "name": "center_y",
+ "position": 8,
+ "nullable": true,
+ "type": "AS ([shape_point].[STY]) PERSISTED"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__shapes__B2E98952FB942A88",
+ "expressions": [
+ "shape_id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ },
+ {
+ "name": "idx_shape_name",
+ "expressions": [
+ "shape_name"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED",
+ "unique": true
+ },
+ {
+ "name": "idx_shape_polygon",
+ "expressions": [
+ "shape_polygon"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_GRID",
+ "bounding_box": {
+ "xmin": -180,
+ "ymin": -90,
+ "xmax": 180,
+ "ymax": 90
+ },
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "HIGH"
+ },
+ {
+ "level": 2,
+ "density": "HIGH"
+ },
+ {
+ "level": 3,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 4,
+ "density": "LOW"
+ }
+ ],
+ "cells_per_object": 64
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOMETRY"
+ }
+ }
+ },
+ {
+ "name": "idx_shape_line",
+ "expressions": [
+ "shape_line"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_GRID",
+ "bounding_box": {
+ "xmin": -1000,
+ "ymin": -1000,
+ "xmax": 1000,
+ "ymax": 1000
+ },
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "LOW"
+ },
+ {
+ "level": 2,
+ "density": "LOW"
+ },
+ {
+ "level": 3,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 4,
+ "density": "HIGH"
+ }
+ ],
+ "cells_per_object": 8
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOMETRY"
+ }
+ }
+ },
+ {
+ "name": "idx_shape_point",
+ "expressions": [
+ "shape_point"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_GRID",
+ "bounding_box": {
+ "xmax": 100,
+ "ymax": 100
+ },
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 2,
+ "density": "HIGH"
+ },
+ {
+ "level": 3,
+ "density": "LOW"
+ },
+ {
+ "level": 4,
+ "density": "LOW"
+ }
+ ],
+ "cells_per_object": 16
+ },
+ "storage": {
+ "fillfactor": 90,
+ "pad_index": true,
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOMETRY"
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE SCHEMA [geom_schema];
+ GO
+
+ CREATE TABLE [geom_schema].[shapes] (
+ [shape_id] int IDENTITY(1,1) NOT NULL,
+ [shape_name] nvarchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
+ [shape_point] geometry NOT NULL,
+ [shape_polygon] geometry NOT NULL,
+ [shape_line] geometry,
+ [area_size] AS ([shape_polygon].[STArea]()) PERSISTED,
+ [center_x] AS ([shape_point].[STX]) PERSISTED,
+ [center_y] AS ([shape_point].[STY]) PERSISTED,
+ CONSTRAINT [PK__shapes__B2E98952FB942A88] PRIMARY KEY CLUSTERED ([shape_id] ASC)
+ );
+
+ CREATE UNIQUE NONCLUSTERED INDEX [idx_shape_name] ON
+ [geom_schema].[shapes] (
+ [shape_name] ASC
+ );
+
+ CREATE SPATIAL INDEX [idx_shape_polygon] ON [geom_schema].[shapes] ([shape_polygon])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-180, -90, 180, 90),
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = MEDIUM, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 64
+ );
+
+ CREATE SPATIAL INDEX [idx_shape_line] ON [geom_schema].[shapes] ([shape_line])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-1000, -1000, 1000, 1000),
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = MEDIUM, LEVEL_4 = HIGH),
+ CELLS_PER_OBJECT = 8
+ );
+
+ CREATE SPATIAL INDEX [idx_shape_point] ON [geom_schema].[shapes] ([shape_point])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (0, 0, 100, 100),
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = HIGH, LEVEL_3 = LOW, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 16,
+ PAD_INDEX = ON,
+ FILLFACTOR = 90
+ );
+
+- description: spatial_indexes_mixed_with_constraints
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "spatial_mixed",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int",
+ "is_identity": true,
+ "identity_seed": 1,
+ "identity_increment": 1
+ },
+ {
+ "name": "code",
+ "position": 2,
+ "type": "varchar(50)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "geo_location",
+ "position": 3,
+ "type": "geography"
+ },
+ {
+ "name": "geom_shape",
+ "position": 4,
+ "type": "geometry"
+ },
+ {
+ "name": "status",
+ "position": 5,
+ "nullable": true,
+ "type": "nvarchar(20)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "parent_id",
+ "position": 6,
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__spatial___3213E83FB94B9AA8",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UQ__spatial___357D4CF946883435",
+ "expressions": [
+ "code"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED",
+ "unique": true,
+ "is_constraint": true
+ },
+ {
+ "name": "idx_parent_id",
+ "expressions": [
+ "parent_id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED"
+ },
+ {
+ "name": "idx_status",
+ "expressions": [
+ "status"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED"
+ },
+ {
+ "name": "idx_geo_location_mixed",
+ "expressions": [
+ "geo_location"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 2,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 3,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 4,
+ "density": "MEDIUM"
+ }
+ ],
+ "cells_per_object": 16
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOGRAPHY"
+ }
+ }
+ },
+ {
+ "name": "idx_geom_shape_mixed",
+ "expressions": [
+ "geom_shape"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_GRID",
+ "bounding_box": {
+ "xmin": -100,
+ "ymin": -100,
+ "xmax": 100,
+ "ymax": 100
+ },
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "HIGH"
+ },
+ {
+ "level": 2,
+ "density": "LOW"
+ },
+ {
+ "level": 3,
+ "density": "HIGH"
+ },
+ {
+ "level": 4,
+ "density": "LOW"
+ }
+ ],
+ "cells_per_object": 32
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOMETRY"
+ }
+ }
+ }
+ ],
+ "foreign_keys": [
+ {
+ "name": "FK_spatial_mixed_parent",
+ "columns": [
+ "parent_id"
+ ],
+ "referenced_schema": "dbo",
+ "referenced_table": "spatial_mixed",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION"
+ }
+ ],
+ "check_constraints": [
+ {
+ "name": "CK__spatial_m__statu__38996AB5",
+ "expression": "([status]='pending' OR [status]='inactive' OR [status]='active')"
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_spatial_summary",
+ "definition": "-- Create a view using spatial functions\nCREATE VIEW dbo.v_spatial_summary AS\nSELECT\n id,\n code,\n geo_location.STAsText() AS geo_location_wkt,\n geom_shape.STAsText() AS geom_shape_wkt,\n geom_shape.STArea() AS shape_area,\n status\nFROM dbo.spatial_mixed\nWHERE status = 'active';",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "code",
+ "position": 2,
+ "type": "varchar(50)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "geo_location_wkt",
+ "position": 3,
+ "nullable": true,
+ "type": "nvarchar(max)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "geom_shape_wkt",
+ "position": 4,
+ "nullable": true,
+ "type": "nvarchar(max)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "shape_area",
+ "position": 5,
+ "nullable": true,
+ "type": "float(53)"
+ },
+ {
+ "name": "status",
+ "position": 6,
+ "nullable": true,
+ "type": "nvarchar(20)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE [dbo].[spatial_mixed] (
+ [id] int IDENTITY(1,1) NOT NULL,
+ [code] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
+ [geo_location] geography NOT NULL,
+ [geom_shape] geometry NOT NULL,
+ [status] nvarchar(20) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [parent_id] int,
+ CONSTRAINT [PK__spatial___3213E83FB94B9AA8] PRIMARY KEY CLUSTERED ([id] ASC),
+ CONSTRAINT [UQ__spatial___357D4CF946883435] UNIQUE NONCLUSTERED ([code] ASC),
+ CONSTRAINT [FK_spatial_mixed_parent] FOREIGN KEY ([parent_id]) REFERENCES [dbo].[spatial_mixed] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION,
+ CONSTRAINT [CK__spatial_m__statu__38996AB5] CHECK ([status]='pending' OR [status]='inactive' OR [status]='active')
+ );
+
+ CREATE NONCLUSTERED INDEX [idx_parent_id] ON
+ [dbo].[spatial_mixed] (
+ [parent_id] ASC
+ );
+
+ CREATE NONCLUSTERED INDEX [idx_status] ON
+ [dbo].[spatial_mixed] (
+ [status] ASC
+ );
+
+ CREATE SPATIAL INDEX [idx_geo_location_mixed] ON [dbo].[spatial_mixed] ([geo_location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 16
+ );
+
+ CREATE SPATIAL INDEX [idx_geom_shape_mixed] ON [dbo].[spatial_mixed] ([geom_shape])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-100, -100, 100, 100),
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = LOW, LEVEL_3 = HIGH, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 32
+ );
+
+ GO
+
+ -- Create a view using spatial functions
+ CREATE VIEW dbo.v_spatial_summary AS
+ SELECT
+ id,
+ code,
+ geo_location.STAsText() AS geo_location_wkt,
+ geom_shape.STAsText() AS geom_shape_wkt,
+ geom_shape.STArea() AS shape_area,
+ status
+ FROM dbo.spatial_mixed
+ WHERE status = 'active';;
+
+ GO
+
+- description: spatial_indexes_advanced_configurations
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "advanced_spatial",
+ "tables": [
+ {
+ "name": "geo_data",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "bigint",
+ "is_identity": true,
+ "identity_seed": 1,
+ "identity_increment": 1
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "nvarchar(255)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "current_location",
+ "position": 3,
+ "type": "geography"
+ },
+ {
+ "name": "delivery_route",
+ "position": 4,
+ "nullable": true,
+ "type": "geography"
+ },
+ {
+ "name": "service_area",
+ "position": 5,
+ "type": "geography"
+ },
+ {
+ "name": "building_footprint",
+ "position": 6,
+ "nullable": true,
+ "type": "geometry"
+ },
+ {
+ "name": "floor_plan",
+ "position": 7,
+ "nullable": true,
+ "type": "geometry"
+ },
+ {
+ "name": "category",
+ "position": 8,
+ "nullable": true,
+ "type": "varchar(100)",
+ "collation": "SQL_Latin1_General_CP1_CI_AS"
+ },
+ {
+ "name": "is_active",
+ "position": 9,
+ "default": "((1))",
+ "nullable": true,
+ "type": "bit",
+ "default_constraint_name": "DF__geo_data__is_act__37A5467C"
+ },
+ {
+ "name": "last_updated",
+ "position": 10,
+ "default": "(getdate())",
+ "nullable": true,
+ "type": "datetime2(7)",
+ "default_constraint_name": "DF__geo_data__last_u__38996AB5"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK__geo_data__3213E83F941B2A6B",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "CLUSTERED",
+ "unique": true,
+ "primary": true,
+ "is_constraint": true
+ },
+ {
+ "name": "idx_active_category",
+ "expressions": [
+ "category"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NONCLUSTERED"
+ },
+ {
+ "name": "ncci_geo_data",
+ "expressions": [
+ "id",
+ "name",
+ "category",
+ "is_active",
+ "last_updated"
+ ],
+ "descending": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ "type": "NONCLUSTERED COLUMNSTORE"
+ },
+ {
+ "name": "idx_building_footprint",
+ "expressions": [
+ "building_footprint"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_GRID",
+ "bounding_box": {
+ "xmin": -10000,
+ "ymin": -10000,
+ "xmax": 10000,
+ "ymax": 10000
+ },
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "LOW"
+ },
+ {
+ "level": 2,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 3,
+ "density": "HIGH"
+ },
+ {
+ "level": 4,
+ "density": "HIGH"
+ }
+ ],
+ "cells_per_object": 128
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOMETRY"
+ }
+ }
+ },
+ {
+ "name": "idx_current_location",
+ "expressions": [
+ "current_location"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "LOW"
+ },
+ {
+ "level": 2,
+ "density": "LOW"
+ },
+ {
+ "level": 3,
+ "density": "LOW"
+ },
+ {
+ "level": 4,
+ "density": "LOW"
+ }
+ ],
+ "cells_per_object": 1
+ },
+ "storage": {
+ "fillfactor": 100
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOGRAPHY"
+ }
+ }
+ },
+ {
+ "name": "idx_delivery_route",
+ "expressions": [
+ "delivery_route"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "HIGH"
+ },
+ {
+ "level": 2,
+ "density": "HIGH"
+ },
+ {
+ "level": 3,
+ "density": "HIGH"
+ },
+ {
+ "level": 4,
+ "density": "HIGH"
+ }
+ ],
+ "cells_per_object": 8192
+ },
+ "storage": {
+ "fillfactor": 50,
+ "pad_index": true,
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOGRAPHY"
+ }
+ }
+ },
+ {
+ "name": "idx_floor_plan",
+ "expressions": [
+ "floor_plan"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOMETRY_GRID",
+ "bounding_box": {
+ "xmax": 1000,
+ "ymax": 1000
+ },
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "HIGH"
+ },
+ {
+ "level": 2,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 3,
+ "density": "LOW"
+ },
+ {
+ "level": 4,
+ "density": "MEDIUM"
+ }
+ ],
+ "cells_per_object": 512
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOMETRY"
+ }
+ }
+ },
+ {
+ "name": "idx_service_area",
+ "expressions": [
+ "service_area"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "spatial_config": {
+ "method": "SPATIAL",
+ "tessellation": {
+ "scheme": "GEOGRAPHY_GRID",
+ "grid_levels": [
+ {
+ "level": 1,
+ "density": "MEDIUM"
+ },
+ {
+ "level": 2,
+ "density": "LOW"
+ },
+ {
+ "level": 3,
+ "density": "HIGH"
+ },
+ {
+ "level": 4,
+ "density": "MEDIUM"
+ }
+ ],
+ "cells_per_object": 256
+ },
+ "storage": {
+ "allow_row_locks": true,
+ "allow_page_locks": true
+ },
+ "dimensional": {
+ "dimensions": 2,
+ "data_type": "GEOGRAPHY"
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "dbo"
+ }
+ ]
+ }
+ expected: |+
+ CREATE SCHEMA [advanced_spatial];
+ GO
+
+ CREATE TABLE [advanced_spatial].[geo_data] (
+ [id] bigint IDENTITY(1,1) NOT NULL,
+ [name] nvarchar(255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
+ [current_location] geography NOT NULL,
+ [delivery_route] geography,
+ [service_area] geography NOT NULL,
+ [building_footprint] geometry,
+ [floor_plan] geometry,
+ [category] varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
+ [is_active] bit DEFAULT ((1)),
+ [last_updated] datetime2(7) DEFAULT (getdate()),
+ CONSTRAINT [PK__geo_data__3213E83F941B2A6B] PRIMARY KEY CLUSTERED ([id] ASC)
+ );
+
+ CREATE NONCLUSTERED INDEX [idx_active_category] ON
+ [advanced_spatial].[geo_data] (
+ [category] ASC
+ );
+
+ CREATE NONCLUSTERED COLUMNSTORE INDEX [ncci_geo_data] ON [advanced_spatial].[geo_data] (
+ [id],
+ [name],
+ [category],
+ [is_active],
+ [last_updated]
+ );
+
+ CREATE SPATIAL INDEX [idx_building_footprint] ON [advanced_spatial].[geo_data] ([building_footprint])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (-10000, -10000, 10000, 10000),
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = MEDIUM, LEVEL_3 = HIGH, LEVEL_4 = HIGH),
+ CELLS_PER_OBJECT = 128
+ );
+
+ CREATE SPATIAL INDEX [idx_current_location] ON [advanced_spatial].[geo_data] ([current_location])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = LOW, LEVEL_2 = LOW, LEVEL_3 = LOW, LEVEL_4 = LOW),
+ CELLS_PER_OBJECT = 1,
+ FILLFACTOR = 100,
+ ALLOW_ROW_LOCKS = OFF,
+ ALLOW_PAGE_LOCKS = OFF
+ );
+
+ CREATE SPATIAL INDEX [idx_delivery_route] ON [advanced_spatial].[geo_data] ([delivery_route])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = HIGH, LEVEL_3 = HIGH, LEVEL_4 = HIGH),
+ CELLS_PER_OBJECT = 8192,
+ PAD_INDEX = ON,
+ FILLFACTOR = 50
+ );
+
+ CREATE SPATIAL INDEX [idx_floor_plan] ON [advanced_spatial].[geo_data] ([floor_plan])
+ USING GEOMETRY_GRID
+ WITH (
+ BOUNDING_BOX = (0, 0, 1000, 1000),
+ GRIDS = (LEVEL_1 = HIGH, LEVEL_2 = MEDIUM, LEVEL_3 = LOW, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 512
+ );
+
+ CREATE SPATIAL INDEX [idx_service_area] ON [advanced_spatial].[geo_data] ([service_area])
+ USING GEOGRAPHY_GRID
+ WITH (
+ GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = LOW, LEVEL_3 = HIGH, LEVEL_4 = MEDIUM),
+ CELLS_PER_OBJECT = 256
+ );
+
diff --git a/backend/plugin/schema/mssql/test-data/test_get_database_metadata.yaml b/backend/plugin/schema/mssql/testdata/get_database_metadata.yaml
similarity index 96%
rename from backend/plugin/schema/mssql/test-data/test_get_database_metadata.yaml
rename to backend/plugin/schema/mssql/testdata/get_database_metadata.yaml
index e69911bdfb..cc5f0f5735 100644
--- a/backend/plugin/schema/mssql/test-data/test_get_database_metadata.yaml
+++ b/backend/plugin/schema/mssql/testdata/get_database_metadata.yaml
@@ -1,10 +1,11 @@
-- input: |
+- description: users
+ schema: |
CREATE TABLE dbo.users (
id INT IDENTITY(1,1) PRIMARY KEY,
name NVARCHAR(255) NOT NULL,
email NVARCHAR(255) UNIQUE
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -63,7 +64,8 @@
}
]
}
-- input: |
+- description: departments_employees
+ schema: |
CREATE TABLE dbo.departments (
dept_id INT PRIMARY KEY,
dept_name NVARCHAR(100) NOT NULL
@@ -76,7 +78,7 @@
CONSTRAINT FK_employees_departments FOREIGN KEY (dept_id)
REFERENCES dbo.departments(dept_id) ON DELETE CASCADE
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -165,13 +167,14 @@
}
]
}
-- input: |
+- description: products_1
+ schema: |
CREATE TABLE dbo.products (
product_id INT PRIMARY KEY,
price DECIMAL(10,2),
CONSTRAINT CK_price_positive CHECK (price > 0)
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -217,7 +220,8 @@
}
]
}
-- input: |
+- description: products_2
+ schema: |
CREATE TABLE dbo.products (
id INT PRIMARY KEY,
name NVARCHAR(255),
@@ -226,7 +230,7 @@
CREATE INDEX IX_products_category ON dbo.products (category);
CREATE UNIQUE INDEX UX_products_name ON dbo.products (name);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -291,7 +295,8 @@
}
]
}
-- input: |
+- description: orders
+ schema: |
CREATE TABLE dbo.orders (
order_id INT,
customer_id INT,
@@ -300,7 +305,7 @@
);
CREATE NONCLUSTERED INDEX IX_orders_customer ON dbo.orders (customer_id);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -358,12 +363,13 @@
}
]
}
-- input: |
+- description: active_users
+ schema: |
CREATE VIEW dbo.active_users AS
SELECT id, name, email
FROM users
WHERE is_active = 1;
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -377,14 +383,15 @@
}
]
}
-- input: |
+- description: getuserbyid
+ schema: |
CREATE PROCEDURE dbo.GetUserById
@UserId INT
AS
BEGIN
SELECT * FROM users WHERE id = @UserId;
END;
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -398,7 +405,8 @@
}
]
}
-- input: |
+- description: getfullname
+ schema: |
CREATE FUNCTION dbo.GetFullName
(
@FirstName NVARCHAR(50),
@@ -409,7 +417,7 @@
BEGIN
RETURN @FirstName + ' ' + @LastName;
END;
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -423,12 +431,13 @@
}
]
}
-- input: |
+- description: ordernumberseq
+ schema: |
CREATE SEQUENCE dbo.OrderNumberSeq
AS INT
START WITH 1000
INCREMENT BY 1;
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -442,7 +451,8 @@
}
]
}
-- input: |
+- description: sales_hr_orders
+ schema: |
CREATE SCHEMA sales;
CREATE SCHEMA hr;
@@ -455,7 +465,7 @@
emp_id INT PRIMARY KEY,
name NVARCHAR(100)
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -530,14 +540,15 @@
}
]
}
-- input: |
+- description: settings
+ schema: |
CREATE TABLE dbo.settings (
id INT PRIMARY KEY,
created_at DATETIME DEFAULT GETDATE(),
is_active BIT DEFAULT 1,
status NVARCHAR(20) DEFAULT N'pending'
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -592,7 +603,8 @@
}
]
}
-- input: |
+- description: logs
+ schema: |
CREATE TABLE dbo.logs (
id INT PRIMARY KEY,
user_id INT,
@@ -601,7 +613,7 @@
);
CREATE INDEX IX_logs_user_action ON dbo.logs (user_id ASC, action DESC, timestamp DESC);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -666,12 +678,13 @@
}
]
}
-- input: |
+- description: test_1
+ schema: |
CREATE TABLE dbo.test (
id INT NOT NULL PRIMARY KEY CLUSTERED,
email NVARCHAR(255) UNIQUE NONCLUSTERED
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -724,12 +737,13 @@
}
]
}
-- input: |
+- description: test_2
+ schema: |
CREATE TABLE dbo.test (
id INT CONSTRAINT PK_test_id PRIMARY KEY,
email NVARCHAR(255) CONSTRAINT UQ_test_email UNIQUE
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -780,7 +794,8 @@
}
]
}
-- input: |
+- description: customers
+ schema: |
CREATE TABLE dbo.customers (
customer_id INT IDENTITY(1,1) NOT NULL,
first_name VARCHAR(50) NOT NULL,
@@ -803,7 +818,7 @@
CREATE NONCLUSTERED INDEX IX_customers_name ON dbo.customers (last_name, first_name);
CREATE NONCLUSTERED INDEX IX_customers_email ON dbo.customers (email) WHERE email IS NOT NULL;
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -960,7 +975,8 @@
}
]
}
-- input: |
+- description: inventory
+ schema: |
CREATE TABLE dbo.inventory (
product_id INT NOT NULL,
warehouse_id INT NOT NULL,
@@ -969,7 +985,7 @@
CONSTRAINT PK_inventory PRIMARY KEY (product_id, warehouse_id),
CONSTRAINT CK_inventory_quantity CHECK (quantity >= 0)
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1029,7 +1045,8 @@
}
]
}
-- input: |
+- description: audit_log
+ schema: |
CREATE TABLE dbo.audit_log (
log_id BIGINT IDENTITY(1,1) PRIMARY KEY,
table_name SYSNAME NOT NULL,
@@ -1040,7 +1057,7 @@
new_values NVARCHAR(MAX),
CONSTRAINT CK_operation CHECK (operation IN ('I', 'U', 'D'))
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1119,7 +1136,8 @@
}
]
}
-- input: |
+- description: documents
+ schema: |
CREATE TABLE dbo.documents (
doc_id UNIQUEIDENTIFIER DEFAULT NEWID() PRIMARY KEY,
title NVARCHAR(200) NOT NULL,
@@ -1133,7 +1151,7 @@
version INT DEFAULT 1,
is_published BIT DEFAULT 0
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1229,7 +1247,8 @@
}
]
}
-- input: |
+- description: hierarchical_data
+ schema: |
CREATE TABLE dbo.hierarchical_data (
node_id INT IDENTITY(1,1) PRIMARY KEY,
parent_id INT NULL,
@@ -1241,7 +1260,7 @@
);
CREATE INDEX IX_hierarchical_path ON dbo.hierarchical_data (node_path);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1324,7 +1343,8 @@
}
]
}
-- input: |
+- description: edge_cases
+ schema: |
CREATE TABLE dbo.edge_cases (
[Column With Spaces] INT,
[Column-With-Dashes] NVARCHAR(50),
@@ -1334,7 +1354,7 @@
[FROM] VARCHAR(50),
[WHERE] BIT
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1391,7 +1411,8 @@
}
]
}
-- input: |
+- description: all_data_types
+ schema: |
CREATE TABLE dbo.all_data_types (
-- Exact numerics
col_bit BIT,
@@ -1443,7 +1464,7 @@
col_geometry GEOMETRY,
col_sql_variant SQL_VARIANT
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1674,7 +1695,8 @@
}
]
}
-- input: |
+- description: collation_test
+ schema: |
CREATE TABLE dbo.collation_test (
id INT PRIMARY KEY,
case_sensitive VARCHAR(50) COLLATE Latin1_General_CS_AS,
@@ -1683,7 +1705,7 @@
accent_insensitive NVARCHAR(50) COLLATE Latin1_General_CI_AI,
binary_sort VARCHAR(50) COLLATE Latin1_General_BIN2
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1752,7 +1774,8 @@
}
]
}
-- input: |
+- description: sales_data
+ schema: |
CREATE TABLE dbo.sales_data (
sale_id INT IDENTITY(1,1) PRIMARY KEY,
product_id INT NOT NULL,
@@ -1762,7 +1785,7 @@
);
CREATE CLUSTERED COLUMNSTORE INDEX CCI_sales_data ON dbo.sales_data;
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1823,7 +1846,8 @@
}
]
}
-- input: |
+- description: analytics_data
+ schema: |
CREATE TABLE dbo.analytics_data (
id INT NOT NULL,
year INT NOT NULL,
@@ -1833,7 +1857,7 @@
);
CREATE NONCLUSTERED COLUMNSTORE INDEX NCCI_analytics ON dbo.analytics_data (year, month, revenue, expenses);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1893,7 +1917,8 @@
}
]
}
-- input: |
+- description: fact_sales
+ schema: |
CREATE TABLE dbo.fact_sales (
sale_id INT NOT NULL,
product_id INT NOT NULL,
@@ -1902,7 +1927,7 @@
amount DECIMAL(10,2) NOT NULL,
INDEX IX_fact_sales CLUSTERED COLUMNSTORE
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -1948,7 +1973,8 @@
}
]
}
-- input: |
+- description: hybrid_table
+ schema: |
CREATE TABLE dbo.hybrid_table (
id INT PRIMARY KEY NONCLUSTERED,
category VARCHAR(50) NOT NULL,
@@ -1957,7 +1983,7 @@
INDEX IX_hybrid_columnstore NONCLUSTERED COLUMNSTORE (category, value, created_date),
INDEX IX_hybrid_regular NONCLUSTERED (category, created_date DESC)
);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -2035,8 +2061,9 @@
}
]
}
-- input: "CREATE TABLE dbo.products (\n id INT IDENTITY(1,1) PRIMARY KEY,\n name NVARCHAR(255) NOT NULL,\n price DECIMAL(10,2)\n);\n\n-- Add table comment\nEXEC sp_addextendedproperty \n 'MS_Description', 'Table storing product information',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products';\n\n-- Add column comments\nEXEC sp_addextendedproperty \n 'MS_Description', 'Unique product identifier',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products',\n 'COLUMN', 'id';\n\nEXEC sp_addextendedproperty \n 'MS_Description', 'Product display name',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products',\n 'COLUMN', 'name';\n\nEXEC sp_addextendedproperty \n 'MS_Description', 'Product price in USD',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products',\n 'COLUMN', 'price';\n"
- result: |-
+- description: products_3
+ schema: "CREATE TABLE dbo.products (\n id INT IDENTITY(1,1) PRIMARY KEY,\n name NVARCHAR(255) NOT NULL,\n price DECIMAL(10,2)\n);\n\n-- Add table comment\nEXEC sp_addextendedproperty \n 'MS_Description', 'Table storing product information',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products';\n\n-- Add column comments\nEXEC sp_addextendedproperty \n 'MS_Description', 'Unique product identifier',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products',\n 'COLUMN', 'id';\n\nEXEC sp_addextendedproperty \n 'MS_Description', 'Product display name',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products',\n 'COLUMN', 'name';\n\nEXEC sp_addextendedproperty \n 'MS_Description', 'Product price in USD',\n 'SCHEMA', 'dbo',\n 'TABLE', 'products',\n 'COLUMN', 'price';\n"
+ metadata: |
{
"schemas": [
{
@@ -2088,7 +2115,8 @@
}
]
}
-- input: |
+- description: locations
+ schema: |
CREATE TABLE dbo.locations (
id INT IDENTITY(1,1) PRIMARY KEY,
name NVARCHAR(100) NOT NULL,
@@ -2098,7 +2126,7 @@
CREATE SPATIAL INDEX idx_locations_position ON dbo.locations (position);
CREATE SPATIAL INDEX idx_locations_area ON dbo.locations (area);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -2187,7 +2215,8 @@
}
]
}
-- input: |
+- description: geo_world_map
+ schema: |
CREATE SCHEMA geo;
-- Multiple spatial indexes on same table
@@ -2212,7 +2241,7 @@
-- Also create regular indexes
CREATE INDEX idx_feature_name ON geo.world_map (feature_name);
CREATE INDEX idx_feature_type ON geo.world_map (feature_type);
- result: |-
+ metadata: |
{
"schemas": [
{
@@ -2395,7 +2424,8 @@
}
]
}
-- input: |
+- description: spatial_test
+ schema: |
-- Comprehensive spatial index test with full parameters
CREATE TABLE dbo.spatial_test (
id INT IDENTITY(1,1) PRIMARY KEY,
@@ -2435,7 +2465,7 @@
WITH (
CELLS_PER_OBJECT = 8
);
- result: |-
+ metadata: |
{
"schemas": [
{
diff --git a/backend/plugin/schema/mssql/testutil_test.go b/backend/plugin/schema/mssql/testutil_test.go
deleted file mode 100644
index 129069378c..0000000000
--- a/backend/plugin/schema/mssql/testutil_test.go
+++ /dev/null
@@ -1,124 +0,0 @@
-package mssql
-
-import (
- "context"
- "strings"
-
- "github.com/pkg/errors"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
- mssqldb "github.com/bytebase/bytebase/backend/plugin/db/mssql"
-)
-
-// createMSSQLDriver creates and opens a MSSQL driver connection
-func createMSSQLDriver(ctx context.Context, host, port, database string) (db.Driver, error) {
- driver := &mssqldb.Driver{}
- config := db.ConnectionConfig{
- DataSource: &storepb.DataSource{
- Type: storepb.DataSourceType_ADMIN,
- Username: "sa",
- Host: host,
- Port: port,
- Database: database,
- },
- Password: "Test123!",
- ConnectionContext: db.ConnectionContext{
- DatabaseName: database,
- },
- }
- return driver.Open(ctx, storepb.Engine_MSSQL, config)
-}
-
-// executeSQL executes SQL statements, handling GO separators
-func executeSQL(ctx context.Context, driver db.Driver, sql string) error {
- if strings.TrimSpace(sql) == "" {
- return nil
- }
-
- // Split by GO statements (case insensitive)
- statements := splitByGO(sql)
-
- for i, stmt := range statements {
- stmt = strings.TrimSpace(stmt)
- if stmt == "" {
- continue
- }
-
- if _, err := driver.Execute(ctx, stmt, db.ExecuteOptions{}); err != nil {
- return errors.Wrapf(err, "failed to execute statement %d: %s", i+1, stmt)
- }
- }
-
- return nil
-}
-
-// splitByGO splits SQL by GO statements (case insensitive) or by semicolons if no GO statements
-func splitByGO(sql string) []string {
- sql = strings.TrimSpace(sql)
- if sql == "" {
- return []string{}
- }
-
- // First check if there are any GO statements
- hasGOStatements := false
- lines := strings.Split(sql, "\n")
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if strings.EqualFold(trimmed, "GO") {
- hasGOStatements = true
- break
- }
- }
-
- if hasGOStatements {
- // Split by GO statements
- var statements []string
- var currentStatement strings.Builder
-
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if strings.EqualFold(trimmed, "GO") {
- if currentStatement.Len() > 0 {
- statements = append(statements, currentStatement.String())
- currentStatement.Reset()
- }
- } else {
- if currentStatement.Len() > 0 {
- currentStatement.WriteString("\n")
- }
- currentStatement.WriteString(line)
- }
- }
-
- if currentStatement.Len() > 0 {
- statements = append(statements, currentStatement.String())
- }
-
- return statements
- }
- // Split by semicolons for DDL statements
- statements := strings.Split(sql, ";")
- var result []string
- for _, stmt := range statements {
- stmt = strings.TrimSpace(stmt)
- if stmt != "" {
- // Check if this statement contains any non-comment SQL
- lines := strings.Split(stmt, "\n")
- hasSQL := false
- var sqlLines []string
- for _, line := range lines {
- line = strings.TrimSpace(line)
- if line != "" && !strings.HasPrefix(line, "--") {
- hasSQL = true
- sqlLines = append(sqlLines, line)
- }
- }
- // Only include if there's actual SQL (not just comments)
- if hasSQL {
- result = append(result, strings.Join(sqlLines, " "))
- }
- }
- }
- return result
-}
diff --git a/backend/plugin/schema/mysql/format_view_body_test.go b/backend/plugin/schema/mysql/format_view_body_test.go
index a8b6ee36c1..cfff796050 100644
--- a/backend/plugin/schema/mysql/format_view_body_test.go
+++ b/backend/plugin/schema/mysql/format_view_body_test.go
@@ -3,7 +3,7 @@ package mysql
// Unit tests for formatViewBodySDL, the whitespace-only pretty-printer the SDL dump
// applies to MySQL's one-line stored view bodies (writeViewSDL).
//
-// Golden corpus: testdata/format-view-body/<case>.stored.sql holds a REAL SHOW CREATE
+// Golden corpus: testdata/format_view_body/<case>.stored.sql holds a REAL SHOW CREATE
// VIEW line captured from a live oracle (8.0.32 / 5.7.25 — sakila, the stock sys
// schema, and hand-built edge views), and <case>.golden.sql pins the pretty body the
// dump emits for it (after stripViewBodyDatabaseQualifier, exactly like writeViewSDL).
@@ -79,7 +79,7 @@ func requireFormatProperties(t *testing.T, body string) string {
}
func TestFormatViewBodySDLGolden(t *testing.T) {
- stored, err := filepath.Glob(filepath.Join("testdata", "format-view-body", "*.stored.sql"))
+ stored, err := filepath.Glob(filepath.Join("testdata", "format_view_body", "*.stored.sql"))
require.NoError(t, err)
require.NotEmpty(t, stored, "no golden captures found")
@@ -89,7 +89,7 @@ func TestFormatViewBodySDLGolden(t *testing.T) {
db, def := loadStoredViewCase(t, path)
body := stripViewBodyDatabaseQualifier(def, db)
- golden, err := os.ReadFile(filepath.Join("testdata", "format-view-body", name+".golden.sql"))
+ golden, err := os.ReadFile(filepath.Join("testdata", "format_view_body", name+".golden.sql"))
require.NoError(t, err)
got := requireFormatProperties(t, body)
@@ -237,8 +237,8 @@ func TestFormatViewBodySDLShapes(t *testing.T) {
// TestWriteViewSDLPretty pins the full writeViewSDL statement framing around the pretty
// body: header, AS on the header line, body from column 0, terminating ";\n\n".
func TestWriteViewSDLPretty(t *testing.T) {
- db, def := loadStoredViewCase(t, filepath.Join("testdata", "format-view-body", "film_list_80.stored.sql"))
- golden, err := os.ReadFile(filepath.Join("testdata", "format-view-body", "film_list_80.golden.sql"))
+ db, def := loadStoredViewCase(t, filepath.Join("testdata", "format_view_body", "film_list_80.stored.sql"))
+ golden, err := os.ReadFile(filepath.Join("testdata", "format_view_body", "film_list_80.golden.sql"))
require.NoError(t, err)
var buf strings.Builder
diff --git a/backend/plugin/schema/mysql/generate_migration.go b/backend/plugin/schema/mysql/generate_migration.go
index 5ad601d750..33003ef9c1 100644
--- a/backend/plugin/schema/mysql/generate_migration.go
+++ b/backend/plugin/schema/mysql/generate_migration.go
@@ -2,6 +2,8 @@ package mysql
import (
"fmt"
+ "maps"
+ "slices"
"strings"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -171,17 +173,22 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {
}
}
- // Execute the deduplicated drop operations
- for tableName, drops := range dropsPerTable {
+ // Execute the deduplicated drop operations. Every map here is walked in name
+ // order: the same diff has to produce the same DDL, byte for byte, or a
+ // generated migration is unreviewable and unrepeatable.
+ for _, tableName := range slices.Sorted(maps.Keys(dropsPerTable)) {
+ drops := dropsPerTable[tableName]
+
// Drop check constraints
- for constraintName := range drops.checkConstraints {
+ for _, constraintName := range slices.Sorted(maps.Keys(drops.checkConstraints)) {
if err := writeDropCheckConstraint(buf, tableName, constraintName); err != nil {
return err
}
}
// Drop indexes (handle primary key specially)
- for _, index := range drops.indexes {
+ for _, indexName := range slices.Sorted(maps.Keys(drops.indexes)) {
+ index := drops.indexes[indexName]
if index.Primary {
if err := writeDropPrimaryKey(buf, tableName); err != nil {
return err
@@ -194,7 +201,7 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {
}
// Drop columns
- for columnName := range drops.columns {
+ for _, columnName := range slices.Sorted(maps.Keys(drops.columns)) {
if err := writeDropColumn(buf, tableName, columnName); err != nil {
return err
}
@@ -220,7 +227,8 @@ func dropTablesInDependencyOrder(diff *schema.MetadataDiff, buf *strings.Builder
// Add edges for foreign key dependencies
// Edge from table with FK to referenced table (for dropping order)
- for _, tableDiff := range tablesToDrop {
+ for _, name := range slices.Sorted(maps.Keys(tablesToDrop)) {
+ tableDiff := tablesToDrop[name]
if tableDiff.OldTable != nil {
for _, fk := range tableDiff.OldTable.ForeignKeys {
if _, exists := tablesToDrop[fk.ReferencedTable]; exists {
@@ -237,7 +245,8 @@ func dropTablesInDependencyOrder(diff *schema.MetadataDiff, buf *strings.Builder
if err != nil {
// If there's a cycle, fall back to dropping foreign keys first
// Drop all foreign keys from tables being dropped
- for _, tableDiff := range tablesToDrop {
+ for _, name := range slices.Sorted(maps.Keys(tablesToDrop)) {
+ tableDiff := tablesToDrop[name]
if tableDiff.OldTable != nil {
for _, fk := range tableDiff.OldTable.ForeignKeys {
if err := writeDropForeignKey(buf, tableDiff.TableName, fk.Name); err != nil {
@@ -247,9 +256,9 @@ func dropTablesInDependencyOrder(diff *schema.MetadataDiff, buf *strings.Builder
}
}
- // Then drop tables in any order
- for _, tableDiff := range tablesToDrop {
- if err := writeDropTable(buf, tableDiff.TableName); err != nil {
+ // Then drop tables in name order; the cycle leaves no better one.
+ for _, name := range slices.Sorted(maps.Keys(tablesToDrop)) {
+ if err := writeDropTable(buf, tablesToDrop[name].TableName); err != nil {
return err
}
}
diff --git a/backend/plugin/schema/mysql/generate_migration_test.go b/backend/plugin/schema/mysql/generate_migration_test.go
index a01b2d689c..fd8add65b9 100644
--- a/backend/plugin/schema/mysql/generate_migration_test.go
+++ b/backend/plugin/schema/mysql/generate_migration_test.go
@@ -1,1906 +1,81 @@
package mysql
import (
- "context"
"fmt"
- "slices"
"strings"
"testing"
- // Import MySQL driver
_ "github.com/go-sql-driver/mysql"
- "github.com/google/go-cmp/cmp"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/testing/protocmp"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "os"
+
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
)
-// TestGenerateMigrationWithTestcontainer tests the generate migration function
-// by applying migrations and rollback to verify the schema can be restored.
-//
-//nolint:tparallel
-func TestGenerateMigrationWithTestcontainer(t *testing.T) {
- if testing.Short() {
- t.Skip("Skipping MySQL testcontainer test in short mode")
- }
-
- ctx := context.Background()
-
- // Start shared MySQL container for all subtests
- container := testcontainer.SharedMySQLContainer(t)
-
- // Test cases with various schema changes
- testCases := []struct {
- name string
- initialSchema string
- migrationDDL string
- description string
- }{
- {
- name: "drop_table_with_dependencies",
- initialSchema: ``,
- migrationDDL: `
---
--- Table structure for authors
---
-CREATE TABLE authors (
- id int NOT NULL AUTO_INCREMENT,
- name varchar(100) NOT NULL,
- email varchar(100) DEFAULT NULL,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-
---
--- Table structure for books
---
-CREATE TABLE books (
- id int NOT NULL AUTO_INCREMENT,
- title varchar(200) NOT NULL,
- author_id int NOT NULL,
- isbn varchar(20) DEFAULT NULL,
- published_year int DEFAULT NULL,
- price decimal(8,2) DEFAULT NULL,
- PRIMARY KEY (id),
- KEY idx_author (author_id),
- KEY idx_year (published_year),
- UNIQUE KEY uk_isbn (isbn),
- CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors (id),
- CONSTRAINT chk_price_positive CHECK (price > 0),
- CONSTRAINT chk_year_valid CHECK ((published_year >= 1000) and (published_year <= 2100))
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-
-
---
--- Table structure for products
---
-CREATE TABLE products (
- id int NOT NULL AUTO_INCREMENT,
- name varchar(50) NOT NULL,
- price decimal(8,2) NOT NULL,
- description text DEFAULT NULL,
- category varchar(30) DEFAULT NULL,
- is_active tinyint(1) DEFAULT '1',
- PRIMARY KEY (id),
- KEY idx_category (category),
- KEY idx_price (price)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
- `,
- },
- {
- name: "create_tables_with_fk",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-`,
- migrationDDL: `
-DROP TABLE IF EXISTS posts;
-DROP TABLE IF EXISTS users;`,
- description: "Create tables with foreign key constraints",
- },
- {
- name: "basic_table_operations",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-`,
- migrationDDL: `
--- Add new column
-ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT true;
-
--- Create new table
-CREATE TABLE comments (
- id INT NOT NULL AUTO_INCREMENT,
- post_id INT NOT NULL,
- user_id INT NOT NULL,
- content TEXT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_post_user (post_id, user_id),
- CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
- CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-
--- Add new index
-CREATE INDEX idx_email_active ON users(email, is_active);
-
--- Add check constraint (MySQL 8.0.16+)
-ALTER TABLE posts ADD CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0);
-`,
- description: "Basic table operations with columns, constraints, and indexes",
- },
- {
- name: "views_and_triggers",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- stock INT DEFAULT 0,
- PRIMARY KEY (id),
- INDEX idx_name (name)
-) ENGINE=InnoDB;
-
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL,
- total DECIMAL(10, 2),
- order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Create view
-CREATE VIEW product_inventory AS
-SELECT
- p.id,
- p.name,
- p.price,
- p.stock,
- COALESCE(SUM(o.quantity), 0) AS total_ordered
-FROM products p
-LEFT JOIN orders o ON p.id = o.product_id
-GROUP BY p.id, p.name, p.price, p.stock;
-
--- Create another view
-CREATE VIEW low_stock_products AS
-SELECT * FROM products WHERE stock < 10;
-
--- Create trigger
-CREATE TRIGGER update_order_total
-BEFORE INSERT ON orders
-FOR EACH ROW
-BEGIN
- DECLARE product_price DECIMAL(10, 2);
- SELECT price INTO product_price FROM products WHERE id = NEW.product_id;
- SET NEW.total = NEW.quantity * product_price;
-END;
-
--- Create stored procedure
-CREATE PROCEDURE GetProductInventory(IN product_name VARCHAR(100))
-BEGIN
- SELECT * FROM product_inventory
- WHERE name LIKE CONCAT('%', product_name, '%');
-END;
-`,
- description: "Views, triggers, and stored procedures",
- },
- {
- name: "stored_functions",
- initialSchema: `
-CREATE TABLE sales (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- sale_date DATE NOT NULL,
- PRIMARY KEY (id),
- INDEX idx_product_date (product_id, sale_date)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Create stored function
-CREATE FUNCTION CalculateTotalSales(p_product_id INT, p_start_date DATE, p_end_date DATE)
-RETURNS DECIMAL(10, 2)
-DETERMINISTIC
-READS SQL DATA
-BEGIN
- DECLARE total DECIMAL(10, 2);
-
- SELECT COALESCE(SUM(quantity * unit_price), 0) INTO total
- FROM sales
- WHERE product_id = p_product_id
- AND sale_date BETWEEN p_start_date AND p_end_date;
-
- RETURN total;
-END;
-
--- Create another function
-CREATE FUNCTION GetTaxAmount(amount DECIMAL(10, 2), tax_rate DECIMAL(5, 2))
-RETURNS DECIMAL(10, 2)
-DETERMINISTIC
-NO SQL
-BEGIN
- RETURN amount * (tax_rate / 100);
-END;
-
--- Create table that uses functions
-CREATE TABLE sales_summary (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- month_year VARCHAR(7) NOT NULL,
- total_sales DECIMAL(10, 2),
- tax_amount DECIMAL(10, 2),
- PRIMARY KEY (id),
- UNIQUE KEY uk_product_month (product_id, month_year)
-) ENGINE=InnoDB;
-`,
- description: "Stored functions and dependent tables",
- },
- {
- name: "drop_indexes_and_constraints",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- category VARCHAR(50),
- price DECIMAL(10, 2),
- sku VARCHAR(50) NOT NULL,
- PRIMARY KEY (id),
- UNIQUE KEY uk_sku (sku),
- INDEX idx_name (name),
- INDEX idx_category (category),
- INDEX idx_price (price),
- CONSTRAINT chk_price_positive CHECK (price > 0),
- CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Drop indexes and constraints
-DROP INDEX idx_category ON products;
-DROP INDEX idx_price ON products;
-DROP INDEX uk_sku ON products;
-ALTER TABLE products DROP CHECK chk_price_positive;
-ALTER TABLE products DROP CHECK chk_name_length;
-`,
- description: "Drop indexes and constraints from tables",
- },
- {
- name: "drop_views_and_routines",
- initialSchema: `
-CREATE TABLE sales (
- id INT NOT NULL AUTO_INCREMENT,
- product_name VARCHAR(100) NOT NULL,
- sale_amount DECIMAL(10, 2) NOT NULL,
- sale_date DATE NOT NULL,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE VIEW monthly_sales AS
-SELECT
- YEAR(sale_date) AS year,
- MONTH(sale_date) AS month,
- SUM(sale_amount) AS total_sales
-FROM sales
-GROUP BY YEAR(sale_date), MONTH(sale_date);
-
-CREATE VIEW top_products AS
-SELECT
- product_name,
- COUNT(*) AS sale_count,
- SUM(sale_amount) AS total_revenue
-FROM sales
-GROUP BY product_name
-ORDER BY SUM(sale_amount) DESC;
-
-CREATE FUNCTION GetMonthlySalesTotal(year INT, month INT)
-RETURNS DECIMAL(10, 2)
-DETERMINISTIC
-READS SQL DATA
-BEGIN
- DECLARE total DECIMAL(10, 2);
- SELECT COALESCE(SUM(sale_amount), 0) INTO total
- FROM sales
- WHERE YEAR(sale_date) = year AND MONTH(sale_date) = month;
- RETURN total;
-END;
-
-CREATE PROCEDURE CalculateDiscount(IN amount DECIMAL(10, 2), OUT discount DECIMAL(10, 2))
-BEGIN
- SET discount = amount * 0.1;
-END;
-`,
- migrationDDL: `
--- Drop views and routines
-DROP VIEW top_products;
-DROP VIEW monthly_sales;
-DROP FUNCTION GetMonthlySalesTotal;
-DROP PROCEDURE CalculateDiscount;
-`,
- description: "Drop views and stored routines",
- },
- {
- name: "alter_table_columns",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(50) NOT NULL,
- price DECIMAL(8, 2) NOT NULL,
- description TEXT,
- category VARCHAR(30),
- is_active TINYINT(1) DEFAULT 1,
- PRIMARY KEY (id),
- INDEX idx_category (category),
- INDEX idx_price (price)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-`,
- migrationDDL: `
--- Alter table operations
-ALTER TABLE products ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-ALTER TABLE products ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
-ALTER TABLE products ADD COLUMN stock_quantity INT DEFAULT 0;
-ALTER TABLE products ADD COLUMN weight DECIMAL(5, 2);
-
--- Change column types and constraints
-ALTER TABLE products MODIFY COLUMN name VARCHAR(100) NOT NULL;
-ALTER TABLE products MODIFY COLUMN price DECIMAL(10, 2) NOT NULL;
-ALTER TABLE products MODIFY COLUMN description TEXT NOT NULL;
-ALTER TABLE products MODIFY COLUMN category VARCHAR(50);
-
--- Add constraints
-ALTER TABLE products ADD CONSTRAINT chk_price_positive CHECK (price > 0);
-ALTER TABLE products ADD CONSTRAINT chk_stock_non_negative CHECK (stock_quantity >= 0);
-
--- Add new indexes
-CREATE INDEX idx_created_at ON products(created_at);
-CREATE UNIQUE INDEX uk_name_category ON products(name, category);
-`,
- description: "Alter table with column additions, type changes, and constraints",
- },
- {
- name: "drop_and_recreate_constraints",
- initialSchema: `
-CREATE TABLE authors (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100),
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email)
-) ENGINE=InnoDB;
-
-CREATE TABLE books (
- id INT NOT NULL AUTO_INCREMENT,
- title VARCHAR(200) NOT NULL,
- author_id INT NOT NULL,
- isbn VARCHAR(20),
- published_year INT,
- price DECIMAL(8, 2),
- PRIMARY KEY (id),
- UNIQUE KEY uk_isbn (isbn),
- INDEX idx_author (author_id),
- INDEX idx_year (published_year),
- CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),
- CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),
- CONSTRAINT chk_price_positive CHECK (price > 0)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Drop and recreate foreign key with different options
-ALTER TABLE books DROP FOREIGN KEY fk_author;
-ALTER TABLE books ADD CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE;
-
--- Drop and modify check constraints
-ALTER TABLE books DROP CHECK chk_year_valid;
-ALTER TABLE books ADD CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030);
-
--- Add new constraints
-ALTER TABLE books ADD CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) >= 3);
-`,
- description: "Drop and recreate constraints with different definitions",
- },
- {
- name: "fulltext_and_spatial_indexes",
- initialSchema: `
-CREATE TABLE articles (
- id INT NOT NULL AUTO_INCREMENT,
- title VARCHAR(200) NOT NULL,
- content TEXT NOT NULL,
- tags VARCHAR(500),
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE TABLE locations (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- position POINT NOT NULL,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Create fulltext index
-ALTER TABLE articles ADD FULLTEXT idx_fulltext_content (title, content);
-
--- Create another fulltext index
-CREATE FULLTEXT INDEX idx_fulltext_tags ON articles(tags);
-
--- Create spatial index (InnoDB supports this from MySQL 5.7+)
-CREATE SPATIAL INDEX idx_spatial_position ON locations(position);
-
--- Create composite indexes
-CREATE INDEX idx_title_tags ON articles(title(50), tags(50));
-`,
- description: "FULLTEXT and SPATIAL indexes",
- },
- {
- name: "complex_view_dependencies",
- initialSchema: `
-CREATE TABLE departments (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- manager_id INT,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE TABLE employees (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- department_id INT,
- salary DECIMAL(10, 2),
- hire_date DATE,
- PRIMARY KEY (id),
- INDEX idx_dept (department_id),
- CONSTRAINT fk_dept FOREIGN KEY (department_id) REFERENCES departments(id)
-) ENGINE=InnoDB;
-
--- Add self-referencing foreign key
-ALTER TABLE departments ADD CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(id);
-`,
- migrationDDL: `
--- Create base view
-CREATE VIEW dept_employee_count AS
-SELECT d.id AS dept_id, d.name AS dept_name, COUNT(e.id) AS emp_count
-FROM departments d
-LEFT JOIN employees e ON d.id = e.department_id
-GROUP BY d.id, d.name;
-
--- Create dependent view
-CREATE VIEW dept_summary AS
-SELECT
- dept_id,
- dept_name,
- emp_count,
- 0 AS avg_salary,
- 0 AS max_salary,
- 0 AS min_salary
-FROM dept_employee_count;
-
--- Create highly dependent view
-CREATE VIEW dept_manager_summary AS
-SELECT
- ds.dept_id,
- ds.dept_name,
- ds.emp_count,
- ds.avg_salary,
- m.name AS manager_name
-FROM dept_summary ds JOIN departments d ON ds.dept_id = d.id LEFT JOIN employees m ON d.manager_id = m.id;
-
--- Create procedure using views
-CREATE PROCEDURE GetDepartmentReport(IN dept_name VARCHAR(100))
-BEGIN
- SELECT * FROM dept_manager_summary
- WHERE dept_name LIKE CONCAT('%', dept_name, '%');
-END;
-`,
- description: "Complex view dependencies with multiple levels",
- },
- {
- name: "circular_foreign_key_dependencies",
- initialSchema: `
-CREATE TABLE customers (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- preferred_order_id INT,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT,
- customer_id INT NOT NULL,
- order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
- total_amount DECIMAL(10, 2),
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Create circular foreign key dependencies
-ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;
-ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE;
-
--- Add more tables with complex relationships
-CREATE TABLE order_items (
- id INT NOT NULL AUTO_INCREMENT,
- order_id INT NOT NULL,
- product_name VARCHAR(100) NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- PRIMARY KEY (id),
- INDEX idx_order (order_id),
- CONSTRAINT fk_order_item FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
-) ENGINE=InnoDB;
-
--- Create trigger to update order total
-CREATE TRIGGER trg_update_order_total
-AFTER INSERT ON order_items
-FOR EACH ROW
-BEGIN
- UPDATE orders
- SET total_amount = (
- SELECT SUM(quantity * unit_price)
- FROM order_items
- WHERE order_id = NEW.order_id
- )
- WHERE id = NEW.order_id;
-END;
-`,
- description: "Circular foreign key dependencies and triggers",
- },
- {
- name: "partitioned_tables",
- initialSchema: `
-CREATE TABLE sales_data (
- id INT NOT NULL AUTO_INCREMENT,
- sale_date DATE NOT NULL,
- customer_id INT NOT NULL,
- product_id INT NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- region VARCHAR(50) NOT NULL,
- PRIMARY KEY (id, sale_date)
-) ENGINE=InnoDB
-PARTITION BY RANGE (YEAR(sale_date)) (
- PARTITION p2020 VALUES LESS THAN (2021),
- PARTITION p2021 VALUES LESS THAN (2022),
- PARTITION p2022 VALUES LESS THAN (2023),
- PARTITION p2023 VALUES LESS THAN (2024),
- PARTITION p_future VALUES LESS THAN MAXVALUE
-);
-`,
- migrationDDL: `
--- Add indexes to partitioned table
-CREATE INDEX idx_customer ON sales_data(customer_id);
-CREATE INDEX idx_product ON sales_data(product_id);
-CREATE INDEX idx_region_date ON sales_data(region, sale_date);
-
--- Create view on partitioned table
-CREATE VIEW regional_sales AS
-SELECT
- region,
- YEAR(sale_date) AS year,
- MONTH(sale_date) AS month,
- SUM(amount) AS total_sales,
- COUNT(DISTINCT customer_id) AS unique_customers
-FROM sales_data
-GROUP BY region, YEAR(sale_date), MONTH(sale_date);
-
--- Add constraint
-ALTER TABLE sales_data ADD CONSTRAINT chk_amount_positive CHECK (amount > 0);
-`,
- description: "Operations on partitioned tables",
- },
- {
- // The "partitioned_tables" case above only exercises the drop direction, which
- // generateMigration deduplicates on its own (see tableDrop). This case makes the
- // rollback re-add the constraints, so it covers the create/alter direction where
- // each partition used to contribute another copy of the table to the diff
- // (BYT-10057): the repeated ADD PRIMARY KEY failed with "Multiple primary key
- // defined" and the repeated CREATE INDEX with "Duplicate key name".
- name: "reverse_partitioned_table_constraints",
- initialSchema: `
-CREATE TABLE ads_member_asset_by_account_channel_d (
- dt DATE NOT NULL,
- member_id BIGINT NOT NULL,
- account_type VARCHAR(50) NOT NULL,
- net_asset_amount DECIMAL(38,10) DEFAULT NULL,
- PRIMARY KEY (dt, member_id, account_type),
- KEY sindex (dt, member_id, account_type)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
-PARTITION BY RANGE (TO_DAYS(dt)) (
- PARTITION p0 VALUES LESS THAN (739000),
- PARTITION p1 VALUES LESS THAN (739001),
- PARTITION p2 VALUES LESS THAN (739002),
- PARTITION p3 VALUES LESS THAN (739003),
- PARTITION p_future VALUES LESS THAN MAXVALUE
-);
-`,
- migrationDDL: `
-DROP INDEX sindex ON ads_member_asset_by_account_channel_d;
-ALTER TABLE ads_member_asset_by_account_channel_d DROP PRIMARY KEY;
-`,
- description: "Re-adding a primary key and an overlapping secondary index on a partitioned table",
- },
- {
- // Recreating the table exercises the partition clause itself: partitioning is
- // part of the table definition and cannot be added afterwards, so a generated
- // CREATE TABLE that omits it silently hands the target an unpartitioned copy.
- // The schema comparison at the end of this test is what catches that, since
- // partitions are not normalized away.
- name: "reverse_create_partitioned_table",
- initialSchema: `
-CREATE TABLE ads_member_asset_by_account_channel_d (
- dt DATE NOT NULL,
- member_id BIGINT NOT NULL,
- account_type VARCHAR(50) NOT NULL,
- net_asset_amount DECIMAL(38,10) DEFAULT NULL,
- PRIMARY KEY (dt, member_id, account_type),
- KEY sindex (dt, member_id, account_type)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
-PARTITION BY RANGE (TO_DAYS(dt)) (
- PARTITION p0 VALUES LESS THAN (739000),
- PARTITION p1 VALUES LESS THAN (739001),
- PARTITION p2 VALUES LESS THAN (739002),
- PARTITION p_future VALUES LESS THAN MAXVALUE
-);
-`,
- migrationDDL: `
-DROP TABLE ads_member_asset_by_account_channel_d;
-`,
- description: "Recreating a partitioned table from metadata",
- },
- {
- name: "generated_columns",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- tax_rate DECIMAL(5, 2) DEFAULT 8.0,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Add generated columns
-ALTER TABLE products ADD COLUMN price_with_tax DECIMAL(10, 2) AS (price * (1 + tax_rate / 100)) STORED;
-ALTER TABLE products ADD COLUMN name_upper VARCHAR(100) AS (UPPER(name)) VIRTUAL;
-
--- Create indexes on generated columns
-CREATE INDEX idx_price_with_tax ON products(price_with_tax);
-CREATE INDEX idx_name_upper ON products(name_upper);
-
--- Create table with generated columns
-CREATE TABLE order_summary (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- total_price DECIMAL(10, 2) AS (quantity * unit_price) STORED,
- order_date DATE NOT NULL,
- order_year INT AS (YEAR(order_date)) VIRTUAL,
- order_month INT AS (MONTH(order_date)) VIRTUAL,
- PRIMARY KEY (id),
- INDEX idx_year_month (order_year, order_month)
-) ENGINE=InnoDB;
-`,
- description: "Generated columns (virtual and stored)",
- },
- {
- name: "json_columns_and_indexes",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100) NOT NULL,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Add JSON columns
-ALTER TABLE users ADD COLUMN preferences JSON;
-ALTER TABLE users ADD COLUMN metadata JSON;
-
--- Create table with JSON columns and indexes
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- details JSON NOT NULL,
- tags JSON,
- PRIMARY KEY (id),
- CONSTRAINT chk_details_not_empty CHECK (JSON_TYPE(details) IS NOT NULL)
-) ENGINE=InnoDB;
-
--- Create indexes on JSON fields (MySQL 8.0+)
-CREATE INDEX idx_product_brand ON products((CAST(details->>'$.brand' AS CHAR(50))));
-CREATE INDEX idx_product_price ON products((CAST(details->>'$.price' AS DECIMAL(10,2))));
-
--- Create generated column from JSON
-ALTER TABLE products ADD COLUMN brand VARCHAR(50) AS (details->>'$.brand') VIRTUAL;
-CREATE INDEX idx_brand ON products(brand);
-`,
- description: "JSON columns and functional indexes",
- },
- {
- name: "complex_triggers",
- initialSchema: `
-CREATE TABLE inventory (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL DEFAULT 0,
- last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_product (product_id)
-) ENGINE=InnoDB;
-
-CREATE TABLE inventory_log (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- old_quantity INT,
- new_quantity INT,
- change_type VARCHAR(20),
- changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Create multiple triggers
-CREATE TRIGGER trg_inventory_insert
-AFTER INSERT ON inventory
-FOR EACH ROW
-BEGIN
- INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
- VALUES (NEW.product_id, NULL, NEW.quantity, 'INSERT');
-END;
-
-CREATE TRIGGER trg_inventory_update
-AFTER UPDATE ON inventory
-FOR EACH ROW
-BEGIN
- IF OLD.quantity != NEW.quantity THEN
- INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
- VALUES (NEW.product_id, OLD.quantity, NEW.quantity, 'UPDATE');
- END IF;
-END;
-
-CREATE TRIGGER trg_inventory_delete
-BEFORE DELETE ON inventory
-FOR EACH ROW
-BEGIN
- INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
- VALUES (OLD.product_id, OLD.quantity, NULL, 'DELETE');
-END;
-
--- Create view using log table
-CREATE VIEW inventory_changes AS
-SELECT
- product_id,
- COUNT(*) AS change_count,
- MAX(changed_at) AS last_changed
-FROM inventory_log
-GROUP BY product_id;
-`,
- description: "Multiple triggers and audit logging",
- },
- {
- name: "character_sets_and_collations",
- initialSchema: `
-CREATE TABLE messages (
- id INT NOT NULL AUTO_INCREMENT,
- content TEXT NOT NULL,
- PRIMARY KEY (id)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-`,
- migrationDDL: `
--- Add columns with different character sets and collations
-ALTER TABLE messages ADD COLUMN title VARCHAR(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-ALTER TABLE messages ADD COLUMN summary VARCHAR(500) CHARACTER SET latin1 COLLATE latin1_swedish_ci;
-
--- Create table with mixed character sets
-CREATE TABLE international_content (
- id INT NOT NULL AUTO_INCREMENT,
- english_text VARCHAR(1000) CHARACTER SET latin1,
- chinese_text VARCHAR(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
- emoji_text VARCHAR(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
--- Create indexes on columns with specific collations
-CREATE INDEX idx_title ON messages(title);
-`,
- description: "Different character sets and collations",
- },
- {
- name: "events_and_advanced_features",
- initialSchema: `
-CREATE TABLE system_stats (
- id INT NOT NULL AUTO_INCREMENT,
- stat_name VARCHAR(100) NOT NULL,
- stat_value DECIMAL(10, 2),
- recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Create event (requires event scheduler to be enabled)
-CREATE EVENT IF NOT EXISTS evt_cleanup_old_stats
-ON SCHEDULE EVERY 1 DAY
-STARTS CURRENT_TIMESTAMP
-DO
-BEGIN
- DELETE FROM system_stats
- WHERE recorded_at < DATE_SUB(NOW(), INTERVAL 30 DAY);
-END;
-
--- Create stored procedure with advanced features
-CREATE PROCEDURE RecordSystemStat(
- IN p_stat_name VARCHAR(100),
- IN p_stat_value DECIMAL(10, 2)
-)
-BEGIN
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- START TRANSACTION;
-
- INSERT INTO system_stats (stat_name, stat_value)
- VALUES (p_stat_name, p_stat_value);
-
- COMMIT;
-END;
-
--- Create function with error handling
-CREATE FUNCTION GetAverageStat(p_stat_name VARCHAR(100))
-RETURNS DECIMAL(10, 2)
-DETERMINISTIC
-READS SQL DATA
-BEGIN
- DECLARE avg_value DECIMAL(10, 2);
-
- SELECT AVG(stat_value) INTO avg_value
- FROM system_stats
- WHERE stat_name = p_stat_name
- AND recorded_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);
-
- RETURN COALESCE(avg_value, 0);
-END;
-`,
- description: "Events and advanced stored routines",
- },
- {
- name: "table_and_column_comments",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- description TEXT,
- category_id INT,
- PRIMARY KEY (id),
- INDEX idx_category (category_id)
-) ENGINE=InnoDB;
-
-CREATE TABLE categories (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(50) NOT NULL,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Add table comments
-ALTER TABLE products COMMENT = 'Product catalog table containing all product information';
-ALTER TABLE categories COMMENT = 'Product categories for organization';
-
--- Add column comments to existing table
-ALTER TABLE products MODIFY COLUMN name VARCHAR(100) NOT NULL COMMENT 'Product display name';
-ALTER TABLE products MODIFY COLUMN price DECIMAL(10, 2) NOT NULL COMMENT 'Product price in USD';
-ALTER TABLE products MODIFY COLUMN description TEXT COMMENT 'Detailed product description';
-ALTER TABLE products MODIFY COLUMN category_id INT COMMENT 'Foreign key reference to categories table';
-
--- Add column comments to categories table
-ALTER TABLE categories MODIFY COLUMN name VARCHAR(50) NOT NULL COMMENT 'Category display name';
-
--- Create new table with comments from the start
-CREATE TABLE suppliers (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Unique supplier identifier',
- company_name VARCHAR(100) NOT NULL COMMENT 'Legal company name',
- contact_email VARCHAR(100) COMMENT 'Primary contact email address',
- phone VARCHAR(20) COMMENT 'Business phone number',
- address TEXT COMMENT 'Full business address',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (contact_email)
-) ENGINE=InnoDB COMMENT = 'Supplier information and contact details';
-
--- Add new column with comment
-ALTER TABLE products ADD COLUMN supplier_id INT COMMENT 'Reference to supplier providing this product';
-`,
- description: "Add comments to tables and columns using MySQL COMMENT syntax",
- },
- {
- name: "modify_and_drop_comments",
- initialSchema: `
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Order unique identifier',
- customer_name VARCHAR(100) NOT NULL COMMENT 'Customer full name',
- order_date DATE NOT NULL COMMENT 'Date when order was placed',
- total_amount DECIMAL(10, 2) COMMENT 'Total order amount in USD',
- status VARCHAR(20) DEFAULT 'pending' COMMENT 'Current order status',
- notes TEXT COMMENT 'Additional order notes or special instructions',
- PRIMARY KEY (id),
- INDEX idx_date (order_date),
- INDEX idx_status (status)
-) ENGINE=InnoDB COMMENT = 'Customer orders and order details';
-
-CREATE TABLE order_items (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Line item identifier',
- order_id INT NOT NULL COMMENT 'Reference to parent order',
- product_name VARCHAR(100) NOT NULL COMMENT 'Name of ordered product',
- quantity INT NOT NULL COMMENT 'Number of items ordered',
- unit_price DECIMAL(10, 2) NOT NULL COMMENT 'Price per individual item',
- PRIMARY KEY (id),
- INDEX idx_order (order_id)
-) ENGINE=InnoDB COMMENT = 'Individual line items for each order';
-`,
- migrationDDL: `
--- Modify existing table comment
-ALTER TABLE orders COMMENT = 'Customer purchase orders with tracking information';
-
--- Modify existing column comments
-ALTER TABLE orders MODIFY COLUMN customer_name VARCHAR(100) NOT NULL COMMENT 'Full name of the purchasing customer';
-ALTER TABLE orders MODIFY COLUMN status VARCHAR(20) DEFAULT 'pending' COMMENT 'Order processing status (pending, processing, shipped, delivered, cancelled)';
-ALTER TABLE orders MODIFY COLUMN notes TEXT COMMENT 'Special delivery instructions and customer notes';
-
--- Remove comments by setting them to empty string
-ALTER TABLE orders MODIFY COLUMN total_amount DECIMAL(10, 2) COMMENT '';
-ALTER TABLE orders MODIFY COLUMN order_date DATE NOT NULL COMMENT '';
-
--- Modify column type and comment simultaneously
-ALTER TABLE order_items MODIFY COLUMN product_name VARCHAR(150) NOT NULL COMMENT 'Full product name including variant details';
-ALTER TABLE order_items MODIFY COLUMN quantity INT NOT NULL COMMENT 'Quantity ordered (must be positive)';
-
--- Remove table comment
-ALTER TABLE order_items COMMENT = '';
-
--- Remove column comment
-ALTER TABLE order_items MODIFY COLUMN unit_price DECIMAL(10, 2) NOT NULL COMMENT '';
-`,
- description: "Modify existing comments and remove comments by setting to empty string",
- },
- {
- name: "comments_with_special_characters",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- bio TEXT,
- preferences JSON,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email)
-) ENGINE=InnoDB;
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content LONGTEXT,
- metadata JSON,
- PRIMARY KEY (id),
- INDEX idx_user (user_id)
-) ENGINE=InnoDB;
-`,
- migrationDDL: `
--- Comments with single quotes - need proper escaping
-ALTER TABLE users COMMENT = 'User accounts - stores user''s personal information and preferences';
-
--- Comments with double quotes and mixed quotes
-ALTER TABLE users MODIFY COLUMN username VARCHAR(50) NOT NULL COMMENT 'User''s chosen "display name" for the platform';
-ALTER TABLE users MODIFY COLUMN email VARCHAR(100) NOT NULL COMMENT 'Primary email address - must be "unique" across all users';
-
--- Multi-line comment using literal newlines
-ALTER TABLE users MODIFY COLUMN bio TEXT COMMENT 'User biography text
-Can contain multiple lines
-and various formatting';
-
--- Comment with special characters and symbols
-ALTER TABLE users MODIFY COLUMN preferences JSON COMMENT 'User settings: theme, notifications, privacy & security options (@, #, $, %, ^, &, *, +, =, |, \\, /, ?, <, >)';
-
--- Comments with Unicode characters
-ALTER TABLE posts COMMENT = 'Blog posts and articles - supports international content (中文, العربية, Русский, 日本語, 한국어, Français, Español, Deutsch)';
-ALTER TABLE posts MODIFY COLUMN title VARCHAR(200) NOT NULL COMMENT 'Post title - supports emojis 📝✨🔥💡🎉 and Unicode characters';
-
--- Comment with HTML/XML-like content
-ALTER TABLE posts MODIFY COLUMN content LONGTEXT COMMENT 'Post content in HTML format: <p>, <strong>, <em>, <a href="...">, <img src="..."/>';
-
--- Comment with JSON-like structure
-ALTER TABLE posts MODIFY COLUMN metadata JSON COMMENT 'Post metadata: {"tags": ["tag1", "tag2"], "category": "tech", "featured": true, "views": 0}';
-
--- Create table with complex comments
-CREATE TABLE analytics (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Primary key (auto-increment)',
- event_name VARCHAR(100) NOT NULL COMMENT 'Event identifier - format: "page_view", "button_click", etc.',
- event_data JSON COMMENT 'Event payload: {"user_id": 123, "timestamp": "2023-12-01T10:30:00Z", "properties": {...}}',
- ip_address VARCHAR(45) COMMENT 'Client IP address (IPv4: xxx.xxx.xxx.xxx or IPv6: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx)',
- user_agent TEXT COMMENT 'Browser user agent string - may contain "Mozilla/5.0", various browser/OS info',
- referrer VARCHAR(500) COMMENT 'HTTP referrer URL - where user came from (can be NULL)',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Event timestamp - UTC timezone',
- processed BOOLEAN DEFAULT FALSE COMMENT 'Processing status: TRUE = processed, FALSE = pending',
- PRIMARY KEY (id),
- INDEX idx_event_date (event_name, created_at),
- INDEX idx_processed (processed)
-) ENGINE=InnoDB COMMENT = 'Analytics events tracking - stores user interactions & system events. Data retention: 2 years. Access level: "admin" & "analyst" roles only.';
-`,
- description: "Test comments with special characters, quotes, multiline text, and Unicode",
- },
- // Reverse test cases
- {
- name: "reverse_drop_table_with_dependencies",
- initialSchema: `
-CREATE TABLE authors (
- id int NOT NULL AUTO_INCREMENT,
- name varchar(100) NOT NULL,
- email varchar(100) DEFAULT NULL,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-
-CREATE TABLE books (
- id int NOT NULL AUTO_INCREMENT,
- title varchar(200) NOT NULL,
- author_id int NOT NULL,
- isbn varchar(20) DEFAULT NULL,
- published_year int DEFAULT NULL,
- price decimal(8,2) DEFAULT NULL,
- PRIMARY KEY (id),
- KEY idx_author (author_id),
- KEY idx_year (published_year),
- UNIQUE KEY uk_isbn (isbn),
- CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors (id),
- CONSTRAINT chk_price_positive CHECK (price > 0),
- CONSTRAINT chk_year_valid CHECK ((published_year >= 1000) and (published_year <= 2100))
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-
-CREATE TABLE products (
- id int NOT NULL AUTO_INCREMENT,
- name varchar(50) NOT NULL,
- price decimal(8,2) NOT NULL,
- description text DEFAULT NULL,
- category varchar(30) DEFAULT NULL,
- is_active tinyint(1) DEFAULT '1',
- PRIMARY KEY (id),
- KEY idx_category (category),
- KEY idx_price (price)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
- `,
- migrationDDL: `
-DROP TABLE books;
-DROP TABLE authors;
-DROP TABLE products;
- `,
- description: "Reverse: Drop tables with foreign key dependencies",
- },
- {
- name: "reverse_create_tables_with_fk",
- initialSchema: ``,
- migrationDDL: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
- `,
- description: "Reverse: Create tables with foreign key constraints",
- },
- {
- name: "reverse_basic_table_operations",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- is_active BOOLEAN DEFAULT true,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username),
- INDEX idx_email_active (email, is_active)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
- CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-
-CREATE TABLE comments (
- id INT NOT NULL AUTO_INCREMENT,
- post_id INT NOT NULL,
- user_id INT NOT NULL,
- content TEXT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_post_user (post_id, user_id),
- CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
- CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
- `,
- migrationDDL: `
--- Drop table
-DROP TABLE comments;
-
--- Remove constraints
-ALTER TABLE posts DROP CHECK chk_title_length;
-
--- Drop index
-DROP INDEX idx_email_active ON users;
-
--- Drop column
-ALTER TABLE users DROP COLUMN is_active;
- `,
- description: "Reverse: Basic table operations",
- },
- {
- name: "reverse_views_and_triggers",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- stock INT DEFAULT 0,
- PRIMARY KEY (id),
- INDEX idx_name (name)
-) ENGINE=InnoDB;
-
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL,
- total DECIMAL(10, 2),
- order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
-) ENGINE=InnoDB;
-
-CREATE VIEW product_inventory AS
-SELECT
- p.id,
- p.name,
- p.price,
- p.stock,
- COALESCE(SUM(o.quantity), 0) AS total_ordered
-FROM products p
-LEFT JOIN orders o ON p.id = o.product_id
-GROUP BY p.id, p.name, p.price, p.stock;
-
-CREATE VIEW low_stock_products AS
-SELECT * FROM products WHERE stock < 10;
-
-CREATE TRIGGER update_order_total
-BEFORE INSERT ON orders
-FOR EACH ROW
-BEGIN
- DECLARE product_price DECIMAL(10, 2);
- SELECT price INTO product_price FROM products WHERE id = NEW.product_id;
- SET NEW.total = NEW.quantity * product_price;
-END;
-
-CREATE PROCEDURE GetProductInventory(IN product_name VARCHAR(100))
-BEGIN
- SELECT * FROM product_inventory
- WHERE name LIKE CONCAT('%', product_name, '%');
-END;
- `,
- migrationDDL: `
--- Drop procedure
-DROP PROCEDURE GetProductInventory;
-
--- Drop trigger
-DROP TRIGGER update_order_total;
-
--- Drop views
-DROP VIEW low_stock_products;
-DROP VIEW product_inventory;
- `,
- description: "Reverse: Views and triggers",
- },
- {
- name: "reverse_stored_functions",
- initialSchema: `
-CREATE TABLE sales (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- sale_date DATE NOT NULL,
- PRIMARY KEY (id),
- INDEX idx_product_date (product_id, sale_date)
-) ENGINE=InnoDB;
-
-CREATE TABLE sales_summary (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- month_year VARCHAR(7) NOT NULL,
- total_sales DECIMAL(10, 2),
- tax_amount DECIMAL(10, 2),
- PRIMARY KEY (id),
- UNIQUE KEY uk_product_month (product_id, month_year)
-) ENGINE=InnoDB;
-
-CREATE FUNCTION CalculateTotalSales(p_product_id INT, p_start_date DATE, p_end_date DATE)
-RETURNS DECIMAL(10, 2)
-DETERMINISTIC
-READS SQL DATA
-BEGIN
- DECLARE total DECIMAL(10, 2);
-
- SELECT COALESCE(SUM(quantity * unit_price), 0) INTO total
- FROM sales
- WHERE product_id = p_product_id
- AND sale_date BETWEEN p_start_date AND p_end_date;
-
- RETURN total;
-END;
-
-CREATE FUNCTION GetTaxAmount(amount DECIMAL(10, 2), tax_rate DECIMAL(5, 2))
-RETURNS DECIMAL(10, 2)
-DETERMINISTIC
-NO SQL
-BEGIN
- RETURN amount * (tax_rate / 100);
-END;
- `,
- migrationDDL: `
--- Drop functions
-DROP FUNCTION CalculateTotalSales;
-DROP FUNCTION GetTaxAmount;
-
--- Drop table
-DROP TABLE sales_summary;
- `,
- description: "Reverse: Stored functions",
- },
- {
- name: "reverse_drop_indexes_and_constraints",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- category VARCHAR(50),
- price DECIMAL(10, 2),
- sku VARCHAR(50) NOT NULL,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
- `,
- migrationDDL: `
--- Add indexes and constraints
-CREATE INDEX idx_name ON products(name);
-CREATE INDEX idx_category ON products(category);
-CREATE INDEX idx_price ON products(price);
-ALTER TABLE products ADD UNIQUE KEY uk_sku (sku);
-ALTER TABLE products ADD CONSTRAINT chk_price_positive CHECK (price > 0);
-ALTER TABLE products ADD CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3);
- `,
- description: "Reverse: Add indexes and constraints",
- },
- {
- name: "reverse_alter_table_columns",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- description TEXT NOT NULL,
- category VARCHAR(50),
- is_active TINYINT(1) DEFAULT 1,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- stock_quantity INT DEFAULT 0,
- weight DECIMAL(5, 2),
- PRIMARY KEY (id),
- INDEX idx_category (category),
- INDEX idx_price (price),
- INDEX idx_created_at (created_at),
- UNIQUE INDEX uk_name_category (name, category),
- CONSTRAINT chk_price_positive CHECK (price > 0),
- CONSTRAINT chk_stock_non_negative CHECK (stock_quantity >= 0)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
- `,
- migrationDDL: `
--- Drop constraints
-ALTER TABLE products DROP CHECK chk_price_positive;
-ALTER TABLE products DROP CHECK chk_stock_non_negative;
-
--- Drop indexes
-DROP INDEX idx_created_at ON products;
-DROP INDEX uk_name_category ON products;
-
--- Drop columns
-ALTER TABLE products DROP COLUMN created_at;
-ALTER TABLE products DROP COLUMN updated_at;
-ALTER TABLE products DROP COLUMN stock_quantity;
-ALTER TABLE products DROP COLUMN weight;
-
--- Modify columns
-ALTER TABLE products MODIFY COLUMN name VARCHAR(50) NOT NULL;
-ALTER TABLE products MODIFY COLUMN price DECIMAL(8, 2) NOT NULL;
-ALTER TABLE products MODIFY COLUMN description TEXT;
-ALTER TABLE products MODIFY COLUMN category VARCHAR(30);
- `,
- description: "Reverse: Alter table columns",
- },
- {
- name: "reverse_fulltext_and_spatial_indexes",
- initialSchema: `
-CREATE TABLE articles (
- id INT NOT NULL AUTO_INCREMENT,
- title VARCHAR(200) NOT NULL,
- content TEXT NOT NULL,
- tags VARCHAR(500),
- PRIMARY KEY (id),
- FULLTEXT idx_fulltext_content (title, content),
- FULLTEXT idx_fulltext_tags (tags),
- INDEX idx_title_tags (title(50), tags(50))
-) ENGINE=InnoDB;
-
-CREATE TABLE locations (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- position POINT NOT NULL,
- PRIMARY KEY (id),
- SPATIAL INDEX idx_spatial_position (position)
-) ENGINE=InnoDB;
- `,
- migrationDDL: `
--- Drop indexes
-DROP INDEX idx_fulltext_content ON articles;
-DROP INDEX idx_fulltext_tags ON articles;
-DROP INDEX idx_title_tags ON articles;
-DROP INDEX idx_spatial_position ON locations;
- `,
- description: "Reverse: Drop FULLTEXT and SPATIAL indexes",
- },
- {
- name: "reverse_generated_columns",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- tax_rate DECIMAL(5, 2) DEFAULT 8.0,
- price_with_tax DECIMAL(10, 2) AS (price * (1 + tax_rate / 100)) STORED,
- name_upper VARCHAR(100) AS (UPPER(name)) VIRTUAL,
- PRIMARY KEY (id),
- INDEX idx_price_with_tax (price_with_tax),
- INDEX idx_name_upper (name_upper)
-) ENGINE=InnoDB;
-
-CREATE TABLE order_summary (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- total_price DECIMAL(10, 2) AS (quantity * unit_price) STORED,
- order_date DATE NOT NULL,
- order_year INT AS (YEAR(order_date)) VIRTUAL,
- order_month INT AS (MONTH(order_date)) VIRTUAL,
- PRIMARY KEY (id),
- INDEX idx_year_month (order_year, order_month)
-) ENGINE=InnoDB;
- `,
- migrationDDL: `
--- Drop table
-DROP TABLE order_summary;
-
--- Drop indexes
-DROP INDEX idx_price_with_tax ON products;
-DROP INDEX idx_name_upper ON products;
-
--- Drop generated columns
-ALTER TABLE products DROP COLUMN price_with_tax;
-ALTER TABLE products DROP COLUMN name_upper;
- `,
- description: "Reverse: Drop generated columns",
- },
- {
- name: "reverse_json_columns_and_indexes",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100) NOT NULL,
- preferences JSON,
- metadata JSON,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- details JSON NOT NULL,
- tags JSON,
- brand VARCHAR(50) AS (details->>'$.brand') VIRTUAL,
- PRIMARY KEY (id),
- INDEX idx_product_brand ((CAST(details->>'$.brand' AS CHAR(50)))),
- INDEX idx_product_price ((CAST(details->>'$.price' AS DECIMAL(10,2)))),
- INDEX idx_brand (brand),
- CONSTRAINT chk_details_not_empty CHECK (JSON_TYPE(details) IS NOT NULL)
-) ENGINE=InnoDB;
- `,
- migrationDDL: `
--- Drop table
-DROP TABLE products;
-
--- Drop columns
-ALTER TABLE users DROP COLUMN preferences;
-ALTER TABLE users DROP COLUMN metadata;
- `,
- description: "Reverse: Drop JSON columns and indexes",
- },
- {
- name: "reverse_complex_triggers",
- initialSchema: `
-CREATE TABLE inventory (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- quantity INT NOT NULL DEFAULT 0,
- last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_product (product_id)
-) ENGINE=InnoDB;
-
-CREATE TABLE inventory_log (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- old_quantity INT,
- new_quantity INT,
- change_type VARCHAR(20),
- changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE TRIGGER trg_inventory_insert
-AFTER INSERT ON inventory
-FOR EACH ROW
-BEGIN
- INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
- VALUES (NEW.product_id, NULL, NEW.quantity, 'INSERT');
-END;
-
-CREATE TRIGGER trg_inventory_update
-AFTER UPDATE ON inventory
-FOR EACH ROW
-BEGIN
- IF OLD.quantity != NEW.quantity THEN
- INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
- VALUES (NEW.product_id, OLD.quantity, NEW.quantity, 'UPDATE');
- END IF;
-END;
-
-CREATE TRIGGER trg_inventory_delete
-BEFORE DELETE ON inventory
-FOR EACH ROW
-BEGIN
- INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
- VALUES (OLD.product_id, OLD.quantity, NULL, 'DELETE');
-END;
-
-CREATE VIEW inventory_changes AS
-SELECT
- product_id,
- COUNT(*) AS change_count,
- MAX(changed_at) AS last_changed
-FROM inventory_log
-GROUP BY product_id;
- `,
- migrationDDL: `
--- Drop view
-DROP VIEW inventory_changes;
-
--- Drop triggers
-DROP TRIGGER trg_inventory_delete;
-DROP TRIGGER trg_inventory_update;
-DROP TRIGGER trg_inventory_insert;
- `,
- description: "Reverse: Drop triggers and views",
- },
- {
- name: "reverse_events_and_advanced_features",
- initialSchema: `
-CREATE TABLE system_stats (
- id INT NOT NULL AUTO_INCREMENT,
- stat_name VARCHAR(100) NOT NULL,
- stat_value DECIMAL(10, 2),
- recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE EVENT IF NOT EXISTS evt_cleanup_old_stats
-ON SCHEDULE EVERY 1 DAY
-STARTS CURRENT_TIMESTAMP
-DO
-BEGIN
- DELETE FROM system_stats
- WHERE recorded_at < DATE_SUB(NOW(), INTERVAL 30 DAY);
-END;
-
-CREATE PROCEDURE RecordSystemStat(
- IN p_stat_name VARCHAR(100),
- IN p_stat_value DECIMAL(10, 2)
-)
-BEGIN
- DECLARE EXIT HANDLER FOR SQLEXCEPTION
- BEGIN
- ROLLBACK;
- RESIGNAL;
- END;
-
- START TRANSACTION;
-
- INSERT INTO system_stats (stat_name, stat_value)
- VALUES (p_stat_name, p_stat_value);
-
- COMMIT;
-END;
-
-CREATE FUNCTION GetAverageStat(p_stat_name VARCHAR(100))
-RETURNS DECIMAL(10, 2)
-DETERMINISTIC
-READS SQL DATA
-BEGIN
- DECLARE avg_value DECIMAL(10, 2);
-
- SELECT AVG(stat_value) INTO avg_value
- FROM system_stats
- WHERE stat_name = p_stat_name
- AND recorded_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);
-
- RETURN COALESCE(avg_value, 0);
-END;
- `,
- migrationDDL: `
--- Drop event
-DROP EVENT IF EXISTS evt_cleanup_old_stats;
-
--- Drop procedure
-DROP PROCEDURE RecordSystemStat;
-
--- Drop function
-DROP FUNCTION GetAverageStat;
- `,
- description: "Reverse: Drop events and advanced features",
- },
- {
- name: "no_diff_identical_schemas",
- initialSchema: `
--- Test that identical schemas don't generate unnecessary migrations
--- This tests the fixes for primary key, index type, check constraints, and DEFAULT NULL
-
-CREATE TABLE test_table (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) DEFAULT NULL,
- email VARCHAR(100),
- status VARCHAR(20) DEFAULT 'active',
- age INT DEFAULT NULL,
- score DECIMAL(5,2),
- PRIMARY KEY (id),
- INDEX idx_name (name),
- INDEX idx_status_hash (status) USING HASH,
- UNIQUE KEY uk_email (email),
- CONSTRAINT chk_age CHECK (age >= 18),
- CONSTRAINT chk_status CHECK (status IN ('active', 'inactive', 'pending'))
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-
--- Table with various column types and defaults
-CREATE TABLE t (
- id INT NOT NULL AUTO_INCREMENT,
- name CHAR(255) DEFAULT NULL,
- PRIMARY KEY (id)
-) ENGINE=InnoDB;
-
-CREATE TABLE t1 (
- id INT NOT NULL,
- a INT NOT NULL,
- b INT DEFAULT NULL,
- c INT,
- PRIMARY KEY (id),
- INDEX b (b) USING HASH
-) ENGINE=InnoDB;
-
--- Table with check constraint that has spaces
-CREATE TABLE some_table (
- id INT PRIMARY KEY,
- a INT NOT NULL,
- CONSTRAINT some_table_chk_1 CHECK (a IN (1, 2, 3))
-) ENGINE=InnoDB;
- `,
- migrationDDL: `
--- No changes - schemas should be identical
--- This simulates running the exact same CREATE statements again
--- The test verifies that no migration DDL is generated
- `,
- description: "Verify no migration generated for identical schemas (tests primary key, index, check constraints, DEFAULT NULL fixes)",
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
-
- // Step 1: Initialize the database schema and get schema result A
- // Create a unique test database for parallel execution
- testDBName := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", testDBName))
- require.NoError(t, err)
-
- // Create MySQL driver for this test's database
- driver, err := createMySQLDriver(ctx, container.GetHost(), container.GetPort(), testDBName)
- require.NoError(t, err)
- defer driver.Close(ctx)
-
- // Execute initial schema
- if strings.TrimSpace(tc.initialSchema) != "" {
- if _, err := driver.Execute(ctx, tc.initialSchema, db.ExecuteOptions{}); err != nil {
- t.Fatalf("Failed to execute initial schema: %v", err)
- }
- }
-
- schemaA, err := driver.SyncDBSchema(ctx)
+type generateMigrationCase struct {
+ Description string `yaml:"description"`
+ OldSchema string `yaml:"oldSchema"`
+ NewSchema string `yaml:"newSchema"`
+ Expected string `yaml:"expected"`
+}
+
+// TestGenerateMigration pins the DDL that takes oldSchema to newSchema. Cases come
+// in both directions for each schema pair, so an object appears once as a create
+// and once as a drop.
+func TestGenerateMigration(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/generate_migration.yaml"
+ )
+
+ var tests []generateMigrationCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
+
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_MYSQL,
+ parseSchema(t, tc.OldSchema), parseSchema(t, tc.NewSchema))
require.NoError(t, err)
- // Step 2: Do some migration and get schema result B
- if _, err := driver.Execute(ctx, tc.migrationDDL, db.ExecuteOptions{}); err != nil {
- t.Fatalf("Failed to execute migration DDL: %v", err)
- }
-
- schemaB, err := driver.SyncDBSchema(ctx)
+ migration, err := schema.GenerateMigration(storepb.Engine_MYSQL, diff)
require.NoError(t, err)
- // Step 3: Call generate migration to get the rollback DDL
- // Convert to model.DatabaseSchema
- dbMetadataA := model.NewDatabaseMetadata(schemaA, nil, nil, storepb.Engine_MYSQL, false)
- dbMetadataB := model.NewDatabaseMetadata(schemaB, nil, nil, storepb.Engine_MYSQL, false)
-
- // Get diff from B to A (to generate rollback)
- diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_MYSQL, dbMetadataB, dbMetadataA)
- require.NoError(t, err)
-
- // Log the diff for debugging
- t.Logf("Test case: %s", tc.description)
- t.Logf("Table changes: %d", len(diff.TableChanges))
- for _, tc := range diff.TableChanges {
- t.Logf(" Table: %s, Action: %v", tc.TableName, tc.Action)
- }
- t.Logf("View changes: %d", len(diff.ViewChanges))
- for _, vc := range diff.ViewChanges {
- t.Logf(" View: %s, Action: %v", vc.ViewName, vc.Action)
- }
- t.Logf("Function changes: %d", len(diff.FunctionChanges))
- for _, fc := range diff.FunctionChanges {
- t.Logf(" Function: %s, Action: %v", fc.FunctionName, fc.Action)
- }
-
- // Generate rollback migration
- rollbackDDL, err := schema.GenerateMigration(storepb.Engine_MYSQL, diff)
- require.NoError(t, err)
-
- t.Logf("Rollback DDL:\n%s", rollbackDDL)
-
- // Special handling for the no-diff test case
- if tc.name == "no_diff_identical_schemas" {
- // For identical schemas, we expect no migration DDL to be generated
- if strings.TrimSpace(rollbackDDL) != "" {
- t.Errorf("Expected no migration DDL for identical schemas, but got:\n%s", rollbackDDL)
- }
+ if record {
+ tests[i].Expected = migration
return
}
-
- // Step 4: Run rollback DDL and get schema result C
- if _, err := driver.Execute(ctx, rollbackDDL, db.ExecuteOptions{}); err != nil {
- t.Fatalf("Failed to execute rollback DDL: %v", err)
- }
-
- schemaC, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Step 5: Compare schema result A and C to ensure they are the same
- normalizeMetadataForComparison(schemaA)
- normalizeMetadataForComparison(schemaC)
-
- // Use cmp with protocmp for proto message comparison
- if diff := cmp.Diff(schemaA, schemaC, protocmp.Transform()); diff != "" {
- t.Errorf("Schema mismatch after rollback (-want +got):\n%s", diff)
- }
+ require.Equal(t, tc.Expected, migration)
})
}
-}
-
-// normalizeMetadataForComparison normalizes metadata to ignore differences that don't affect schema equality
-func normalizeMetadataForComparison(metadata *storepb.DatabaseSchemaMetadata) {
- // Clear database name as it might differ
- metadata.Name = ""
-
- // Normalize schemas
- for _, schema := range metadata.Schemas {
- // Normalize tables
- for _, table := range schema.Tables {
- table.DataSize = 0
- table.IndexSize = 0
- table.RowCount = 0
- // Clear auto-increment values as they might differ
- for _, col := range table.Columns {
- if col.Default == "AUTO_INCREMENT" {
- // Keep the AUTO_INCREMENT marker but clear any current value
- col.Default = "AUTO_INCREMENT"
- }
- }
-
- // Sort columns by name for consistent comparison
- sortColumnsByName(table.Columns)
-
- // Sort indexes by name
- sortIndexesByName(table.Indexes)
-
- // Sort foreign keys by name
- sortForeignKeysByName(table.ForeignKeys)
-
- // Sort check constraints by name
- sortCheckConstraintsByName(table.CheckConstraints)
-
- // Sort triggers by name
- sortTriggersByName(table.Triggers)
- }
-
- // Sort all collections for consistent comparison
- sortTablesByName(schema.Tables)
- sortViewsByName(schema.Views)
- sortFunctionsByName(schema.Functions)
- sortProceduresByName(schema.Procedures)
+ if record {
+ yamltest.Record(t, filepath, tests)
}
-
- // Sort schemas by name
- sortSchemasByName(metadata.Schemas)
-
- // Sort extensions by name
- sortExtensionsByName(metadata.Extensions)
}
-// Sorting helper functions
-func sortSchemasByName(schemas []*storepb.SchemaMetadata) {
- slices.SortFunc(schemas, func(a, b *storepb.SchemaMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
+// parseSchema reads a schema text into the model the differ takes. Empty text is
+// an empty database rather than a parse, which is how create-from-nothing and
+// drop-everything cases are written.
+func parseSchema(t *testing.T, text string) *model.DatabaseMetadata {
+ t.Helper()
-func sortTablesByName(tables []*storepb.TableMetadata) {
- slices.SortFunc(tables, func(a, b *storepb.TableMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortColumnsByName(columns []*storepb.ColumnMetadata) {
- slices.SortFunc(columns, func(a, b *storepb.ColumnMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortIndexesByName(indexes []*storepb.IndexMetadata) {
- slices.SortFunc(indexes, func(a, b *storepb.IndexMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortForeignKeysByName(fks []*storepb.ForeignKeyMetadata) {
- slices.SortFunc(fks, func(a, b *storepb.ForeignKeyMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortCheckConstraintsByName(checks []*storepb.CheckConstraintMetadata) {
- slices.SortFunc(checks, func(a, b *storepb.CheckConstraintMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortViewsByName(views []*storepb.ViewMetadata) {
- slices.SortFunc(views, func(a, b *storepb.ViewMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortFunctionsByName(functions []*storepb.FunctionMetadata) {
- slices.SortFunc(functions, func(a, b *storepb.FunctionMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortProceduresByName(procedures []*storepb.ProcedureMetadata) {
- slices.SortFunc(procedures, func(a, b *storepb.ProcedureMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortExtensionsByName(extensions []*storepb.ExtensionMetadata) {
- slices.SortFunc(extensions, func(a, b *storepb.ExtensionMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortTriggersByName(triggers []*storepb.TriggerMetadata) {
- slices.SortFunc(triggers, func(a, b *storepb.TriggerMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
+ metadata := &storepb.DatabaseSchemaMetadata{Schemas: []*storepb.SchemaMetadata{{}}}
+ if text != "" {
+ parsed, err := GetDatabaseMetadata(text)
+ require.NoError(t, err)
+ metadata = parsed
+ }
+ return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_MYSQL, false)
}
-// partitionedTable is the shape reported in BYT-10057: a daily BI table with a composite
-// primary key, a secondary index over the same ordered columns, and one range partition
-// per day. Each partition used to add another copy of the table to the diff, so the
-// generated script repeated the whole DDL block once per partition and died on the second
-// copy with "Duplicate key name" (1061) or "Multiple primary key defined" (1068).
func partitionedTable(partitionCount int) *storepb.TableMetadata {
table := &storepb.TableMetadata{
Name: "ads_member_asset_by_account_channel_d",
@@ -1927,7 +102,6 @@ func partitionedTable(partitionCount int) *storepb.TableMetadata {
}
return table
}
-
func databaseOf(tables ...*storepb.TableMetadata) *model.DatabaseMetadata {
return model.NewDatabaseMetadata(&storepb.DatabaseSchemaMetadata{
Name: "db",
diff --git a/backend/plugin/schema/mysql/get_database_definition_test.go b/backend/plugin/schema/mysql/get_database_definition_test.go
index 396ce4f0bd..e43dfe8021 100644
--- a/backend/plugin/schema/mysql/get_database_definition_test.go
+++ b/backend/plugin/schema/mysql/get_database_definition_test.go
@@ -1,21 +1,19 @@
package mysql
import (
- "context"
- "fmt"
"strings"
"testing"
- // Import MySQL driver
_ "github.com/go-sql-driver/mysql"
- "github.com/google/go-cmp/cmp"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/testing/protocmp"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "os"
+
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/schema"
)
@@ -479,508 +477,90 @@ func TestWriteColumnDefinitionBodyGeneratedOrder(t *testing.T) {
render(&storepb.ColumnMetadata{Name: "loc", Type: "point", Nullable: false, Srid: srid(4326)}))
}
-//nolint:tparallel
-func TestGetDatabaseDefinition(t *testing.T) {
- if testing.Short() {
- t.Skip("Skipping MySQL testcontainer test in short mode")
- }
-
- ctx := context.Background()
-
- // Start shared MySQL container for all subtests
- container := testcontainer.SharedMySQLContainer(t)
-
- type testCase struct {
- description string
- originalDDL string
- }
-
- testCases := []testCase{
- {
- description: "Basic tables with various column types",
- originalDDL: `
-CREATE TABLE users (
- id INT PRIMARY KEY AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL UNIQUE,
- email VARCHAR(100) NOT NULL,
- age INT CHECK (age >= 18),
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- profile JSON,
- is_active BOOLEAN DEFAULT TRUE,
- INDEX idx_email (email),
- INDEX idx_created_at (created_at)
-);
-
-CREATE TABLE posts (
- id INT PRIMARY KEY AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE,
- INDEX idx_user_published (user_id, published_at)
-);
-`,
- },
- {
- description: "Generated columns and complex indexes",
- originalDDL: `
-CREATE TABLE products (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- tax_rate DECIMAL(5, 2) NOT NULL DEFAULT 0.08,
- price_with_tax DECIMAL(10, 2) AS (price * (1 + tax_rate)) STORED,
- description TEXT,
- tags JSON,
- FULLTEXT idx_fulltext (name, description)
-);
-
-CREATE TABLE inventory (
- id INT PRIMARY KEY AUTO_INCREMENT,
- product_id INT NOT NULL,
- warehouse VARCHAR(50) NOT NULL,
- quantity INT NOT NULL DEFAULT 0,
- last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- UNIQUE KEY uk_product_warehouse (product_id, warehouse),
- FOREIGN KEY (product_id) REFERENCES products(id)
-);
-`,
- },
- {
- description: "Views and triggers",
- originalDDL: `
-CREATE TABLE orders (
- id INT PRIMARY KEY AUTO_INCREMENT,
- order_number VARCHAR(20) NOT NULL UNIQUE,
- customer_name VARCHAR(100) NOT NULL,
- total_amount DECIMAL(10, 2) NOT NULL,
- status VARCHAR(20) DEFAULT 'pending',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE order_history (
- id INT PRIMARY KEY AUTO_INCREMENT,
- order_id INT NOT NULL,
- old_status VARCHAR(20),
- new_status VARCHAR(20),
- changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (order_id) REFERENCES orders(id)
-);
-
-CREATE VIEW pending_orders AS
-SELECT id, order_number, customer_name, total_amount, created_at
-FROM orders
-WHERE status = 'pending'
-ORDER BY created_at DESC;
-
-CREATE TRIGGER order_status_change
-AFTER UPDATE ON orders
-FOR EACH ROW
-BEGIN
- IF OLD.status != NEW.status THEN
- INSERT INTO order_history (order_id, old_status, new_status)
- VALUES (NEW.id, OLD.status, NEW.status);
- END IF;
-END;
-`,
- },
- {
- description: "Stored procedures and functions",
- originalDDL: `
-CREATE TABLE accounts (
- id INT PRIMARY KEY AUTO_INCREMENT,
- account_number VARCHAR(20) NOT NULL UNIQUE,
- balance DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-DELIMITER $$
-
-CREATE FUNCTION calculate_interest(principal DECIMAL(15, 2), rate DECIMAL(5, 4), years INT)
-RETURNS DECIMAL(15, 2)
-DETERMINISTIC
-READS SQL DATA
-BEGIN
- RETURN principal * POW(1 + rate, years);
-END$$
-
-CREATE PROCEDURE transfer_funds(
- IN from_account VARCHAR(20),
- IN to_account VARCHAR(20),
- IN amount DECIMAL(15, 2)
-)
-BEGIN
- DECLARE from_balance DECIMAL(15, 2);
-
- START TRANSACTION;
-
- SELECT balance INTO from_balance
- FROM accounts
- WHERE account_number = from_account
- FOR UPDATE;
-
- IF from_balance >= amount THEN
- UPDATE accounts
- SET balance = balance - amount
- WHERE account_number = from_account;
-
- UPDATE accounts
- SET balance = balance + amount
- WHERE account_number = to_account;
-
- COMMIT;
- ELSE
- ROLLBACK;
- SIGNAL SQLSTATE '45000'
- SET MESSAGE_TEXT = 'Insufficient funds';
- END IF;
-END$$
-
-DELIMITER ;
-`,
- },
- {
- description: "Partitioned tables",
- originalDDL: `
--- RANGE partition
-CREATE TABLE sales (
- id INT NOT NULL AUTO_INCREMENT,
- sale_date DATE NOT NULL,
- product_id INT NOT NULL,
- quantity INT NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- PRIMARY KEY (id, sale_date)
-) PARTITION BY RANGE (YEAR(sale_date)) (
- PARTITION p2022 VALUES LESS THAN (2023),
- PARTITION p2023 VALUES LESS THAN (2024),
- PARTITION p2024 VALUES LESS THAN (2025),
- PARTITION p_future VALUES LESS THAN MAXVALUE
-);
-
--- HASH partition
-CREATE TABLE employees (
- id INT NOT NULL,
- name VARCHAR(100) NOT NULL,
- department_id INT NOT NULL,
- hired_date DATE,
- PRIMARY KEY (id)
-) PARTITION BY HASH(id) PARTITIONS 4;
-
--- LIST partition
-CREATE TABLE customer_regions (
- id INT NOT NULL AUTO_INCREMENT,
- customer_name VARCHAR(100) NOT NULL,
- region VARCHAR(20) NOT NULL,
- sales_amount DECIMAL(10, 2),
- PRIMARY KEY (id, region)
-) PARTITION BY LIST COLUMNS(region) (
- PARTITION p_north VALUES IN ('north', 'northeast', 'northwest'),
- PARTITION p_south VALUES IN ('south', 'southeast', 'southwest'),
- PARTITION p_east VALUES IN ('east'),
- PARTITION p_west VALUES IN ('west'),
- PARTITION p_central VALUES IN ('central')
-);
-
--- KEY partition
-CREATE TABLE user_sessions (
- session_id VARCHAR(64) NOT NULL,
- user_id INT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (session_id)
-) PARTITION BY KEY() PARTITIONS 8;
-
--- RANGE COLUMNS partition
-CREATE TABLE order_archive (
- order_id INT NOT NULL,
- order_date DATE NOT NULL,
- customer_id INT NOT NULL,
- status VARCHAR(20) NOT NULL,
- total_amount DECIMAL(10, 2),
- PRIMARY KEY (order_id, order_date)
-) PARTITION BY RANGE COLUMNS(order_date) (
- PARTITION p_2022_q1 VALUES LESS THAN ('2022-04-01'),
- PARTITION p_2022_q2 VALUES LESS THAN ('2022-07-01'),
- PARTITION p_2022_q3 VALUES LESS THAN ('2022-10-01'),
- PARTITION p_2022_q4 VALUES LESS THAN ('2023-01-01'),
- PARTITION p_2023_and_later VALUES LESS THAN (MAXVALUE)
-);
-`,
- },
- {
- description: "Events",
- originalDDL: `
-CREATE TABLE daily_stats (
- id INT PRIMARY KEY AUTO_INCREMENT,
- stat_date DATE NOT NULL UNIQUE,
- total_orders INT DEFAULT 0,
- total_revenue DECIMAL(15, 2) DEFAULT 0.00,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE EVENT IF NOT EXISTS update_daily_stats
-ON SCHEDULE EVERY 1 DAY
-STARTS CURRENT_TIMESTAMP
-DO
- INSERT INTO daily_stats (stat_date, total_orders, total_revenue)
- VALUES (CURDATE() - INTERVAL 1 DAY, 0, 0.00)
- ON DUPLICATE KEY UPDATE
- total_orders = VALUES(total_orders),
- total_revenue = VALUES(total_revenue);
-`,
- },
- {
- description: "Character sets and collations",
- originalDDL: `
-CREATE TABLE translations (
- id INT PRIMARY KEY AUTO_INCREMENT,
- language_code VARCHAR(5) CHARACTER SET ascii NOT NULL,
- content_key VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
- translation TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
- UNIQUE KEY uk_lang_key (language_code, content_key)
-) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-`,
- },
- {
- description: "Check constraints with string literals and function with multiline parameters",
- originalDDL: `
-CREATE TABLE transactions (
- id INT PRIMARY KEY AUTO_INCREMENT,
- type VARCHAR(10),
- amount DECIMAL(10, 2),
- CONSTRAINT c1 CHECK (type = 'A' AND amount IS NOT NULL)
-);
-
-DELIMITER $$
-
-CREATE FUNCTION lookup_token(
- p_a BIGINT,
- p_b VARCHAR(36)
-) RETURNS CHAR(36) CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci
- NO SQL
- DETERMINISTIC
-BEGIN
- RETURN p_b;
-END$$
-
-DELIMITER ;
-`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.description, func(t *testing.T) {
- t.Parallel()
-
- // Create unique test databases for parallel execution
- testDBName := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- newDBName := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
-
- // Create initial test database
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", testDBName))
- require.NoError(t, err)
-
- // Step 1: Initialize the database schema and get metadata A
- driverA, err := createMySQLDriver(ctx, container.GetHost(), container.GetPort(), testDBName)
- require.NoError(t, err)
- defer driverA.Close(ctx)
-
- _, err = driverA.Execute(ctx, tc.originalDDL, db.ExecuteOptions{})
- require.NoError(t, err)
-
- metadataA, err := driverA.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Step 2: Call GetDatabaseDefinition to generate the database definition X
- defCtx := schema.GetDefinitionContext{
- SkipBackupSchema: false,
- PrintHeader: true,
- }
- definitionX, err := schema.GetDatabaseDefinition(storepb.Engine_MYSQL, defCtx, metadataA)
- require.NoError(t, err)
- require.NotEmpty(t, definitionX)
-
- // Step 3: Create a new database and apply the generated DDL
- _, err = container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", newDBName))
- require.NoError(t, err)
-
- driverB, err := createMySQLDriver(ctx, container.GetHost(), container.GetPort(), newDBName)
- require.NoError(t, err)
- defer driverB.Close(ctx)
-
- _, err = driverB.Execute(ctx, definitionX, db.ExecuteOptions{})
- require.NoError(t, err)
-
- metadataB, err := driverB.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Step 4: Compare the database metadata A and B, should be the same
- normalizeMetadata(metadataA)
- normalizeMetadata(metadataB)
-
- opts := []cmp.Option{
- protocmp.Transform(),
- protocmp.IgnoreFields(&storepb.TableMetadata{}, "row_count", "data_size", "index_size", "data_free"),
- }
-
- // Add custom ignored fields for specific test cases (for events test)
- if tc.description == "Events" {
- // Ignore time-specific fields that vary between runs
- opts = append(opts, protocmp.IgnoreFields(&storepb.EventMetadata{}, "time_zone", "sql_mode", "character_set_client"))
- }
-
- if diff := cmp.Diff(metadataA, metadataB, opts...); diff != "" {
- t.Errorf("Metadata mismatch (-want +got):\n%s", diff)
- }
- })
- }
+type getDatabaseDefinitionCase struct {
+ Description string `yaml:"description"`
+ Metadata string `yaml:"metadata"`
+ Expected string `yaml:"expected"`
}
-// normalizeMetadata normalizes the metadata to ignore differences that don't affect schema equivalence
-func normalizeMetadata(metadata *storepb.DatabaseSchemaMetadata) {
- // Clear database name as it will differ between original and recreated
- metadata.Name = ""
-
- // Normalize AUTO_INCREMENT values to 0 as they can differ
- for _, schema := range metadata.Schemas {
- for _, table := range schema.Tables {
- // Clear runtime-specific values
- table.RowCount = 0
- table.DataSize = 0
- table.IndexSize = 0
- table.DataFree = 0
-
- // Normalize column defaults
- for _, column := range table.Columns {
- // MySQL might represent defaults differently
- if def := column.GetDefault(); def != "" {
- // Normalize CURRENT_TIMESTAMP variations
- if def == "CURRENT_TIMESTAMP" ||
- def == "current_timestamp()" ||
- def == "now()" {
- column.Default = "CURRENT_TIMESTAMP"
- }
- }
- }
+// TestGetDatabaseDefinition pins the DDL generated for each metadata input,
+// and re-parses that DDL to prove it is valid MySQL syntax.
+//
+// The input is metadata rather than a schema text on purpose: deriving it by
+// parsing would cap this test's reach at whatever GetDatabaseMetadata happens to
+// extract, so any generator branch the parser cannot feed would go untested.
+// unbalancedDelimiterBlocks names the cases whose definition ends a routine with
+// ";;" without a DELIMITER directive having made ";;" the terminator. writeEvent,
+// writeTrigger and writeProcedure all emit the opening "DELIMITER ;;"; only
+// writeFunction leaves it out, so a client restoring such a dump ends the
+// function at the first semicolon in its body. The golden records that output;
+// giving writeFunction the opener empties this map.
+var unbalancedDelimiterBlocks = map[string]bool{
+ "Stored procedures and functions": true,
+ "Check constraints with string literals and function with multiline parameters": true,
+}
- // Remove duplicate check constraints (sometimes appear as both message and string)
- seen := make(map[string]bool)
- var uniqueChecks []*storepb.CheckConstraintMetadata
- for _, check := range table.CheckConstraints {
- key := fmt.Sprintf("%s:%s", check.Name, check.Expression)
- if !seen[key] {
- seen[key] = true
- uniqueChecks = append(uniqueChecks, check)
- }
- }
- table.CheckConstraints = uniqueChecks
+// requireDelimiterDiscipline checks what a mysql client relies on to restore a
+// dump: a line ending in ";;" terminates a statement only while a DELIMITER
+// directive has ";;" active.
+func requireDelimiterDiscipline(t *testing.T, definition string) {
+ t.Helper()
+
+ active := ";"
+ for i, line := range strings.Split(definition, "\n") {
+ trimmed := strings.TrimSpace(line)
+ if directive, ok := strings.CutPrefix(trimmed, "DELIMITER "); ok {
+ active = strings.TrimSpace(directive)
+ continue
+ }
+ if strings.HasSuffix(trimmed, ";;") && active != ";;" {
+ t.Fatalf("line %d ends a statement with %q while %q is the active delimiter, so a client cuts it short: %s",
+ i+1, ";;", active, trimmed)
}
}
}
-// TestGetDatabaseDefinitionWithConnectedDeps tests the ability to handle complex foreign key dependencies
-func TestGetDatabaseDefinitionWithConnectedDeps(t *testing.T) {
- if testing.Short() {
- t.Skip("Skipping MySQL testcontainer test in short mode")
- }
-
- // Unique per run: TestMain keeps one container for the whole package, so a
- // fixed name collides with itself under go test -count=2.
- databaseName := fmt.Sprintf("test_complex_deps_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
-
+func TestGetDatabaseDefinition(t *testing.T) {
const (
- originalDDL = `
-CREATE TABLE department (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- parent_id INT,
- FOREIGN KEY (parent_id) REFERENCES department(id) ON DELETE SET NULL
-);
-
-CREATE TABLE employee (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- department_id INT,
- manager_id INT,
- FOREIGN KEY (department_id) REFERENCES department(id) ON DELETE SET NULL,
- FOREIGN KEY (manager_id) REFERENCES employee(id) ON DELETE SET NULL
-);
-
-CREATE TABLE project (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- lead_id INT NOT NULL,
- department_id INT NOT NULL,
- FOREIGN KEY (lead_id) REFERENCES employee(id),
- FOREIGN KEY (department_id) REFERENCES department(id)
-);
-
-CREATE TABLE project_member (
- project_id INT NOT NULL,
- employee_id INT NOT NULL,
- role VARCHAR(50),
- PRIMARY KEY (project_id, employee_id),
- FOREIGN KEY (project_id) REFERENCES project(id) ON DELETE CASCADE,
- FOREIGN KEY (employee_id) REFERENCES employee(id) ON DELETE CASCADE
-);
-`
+ record = false
+ filepath = "testdata/get_database_definition.yaml"
)
- ctx := context.Background()
-
- // Start MySQL container
- container := testcontainer.SharedMySQLContainer(t)
-
- // Create test database
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s`", databaseName))
- require.NoError(t, err)
-
- // Step 1: Initialize the database schema
- driverA, err := createMySQLDriver(ctx, container.GetHost(), container.GetPort(), databaseName)
- require.NoError(t, err)
- defer driverA.Close(ctx)
-
- _, err = driverA.Execute(ctx, originalDDL, db.ExecuteOptions{})
+ var tests []getDatabaseDefinitionCase
+ content, err := os.ReadFile(filepath)
require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
- metadataA, err := driverA.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Step 2: Generate definition
- defCtx := schema.GetDefinitionContext{
- SkipBackupSchema: false,
- PrintHeader: true,
- }
- definitionX, err := schema.GetDatabaseDefinition(storepb.Engine_MYSQL, defCtx, metadataA)
- require.NoError(t, err)
-
- // Step 3: Create new database and apply definition
- newDBName := fmt.Sprintf("%s_recreated", databaseName)
- _, err = container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", newDBName))
- require.NoError(t, err)
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ var metadata storepb.DatabaseSchemaMetadata
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Metadata), &metadata))
- driverB, err := createMySQLDriver(ctx, container.GetHost(), container.GetPort(), newDBName)
- require.NoError(t, err)
- defer driverB.Close(ctx)
-
- _, err = driverB.Execute(ctx, definitionX, db.ExecuteOptions{})
- require.NoError(t, err)
-
- metadataB, err := driverB.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Compare
- normalizeMetadata(metadataA)
- normalizeMetadata(metadataB)
+ definition, err := GetDatabaseDefinition(schema.GetDefinitionContext{PrintHeader: true}, &metadata)
+ require.NoError(t, err)
+ require.NotEmpty(t, definition)
+
+ // Routines are emitted inside DELIMITER blocks, which is mysql-client
+ // script syntax the schema parser does not accept, so those
+ // definitions are checked for delimiter discipline instead.
+ if strings.Contains(definition, "DELIMITER") {
+ if !unbalancedDelimiterBlocks[tc.Description] {
+ requireDelimiterDiscipline(t, definition)
+ }
+ } else {
+ _, err = GetDatabaseMetadata(definition)
+ require.NoError(t, err, "generated definition should parse")
+ }
- opts := []cmp.Option{
- protocmp.Transform(),
- protocmp.IgnoreFields(&storepb.TableMetadata{}, "row_count", "data_size", "index_size", "data_free"),
+ if record {
+ tests[i].Expected = definition
+ return
+ }
+ require.Equal(t, tc.Expected, definition)
+ })
}
- if diff := cmp.Diff(metadataA, metadataB, opts...); diff != "" {
- t.Errorf("Metadata mismatch (-want +got):\n%s", diff)
+ if record {
+ yamltest.Record(t, filepath, tests)
}
}
diff --git a/backend/plugin/schema/mysql/get_database_metadata_test.go b/backend/plugin/schema/mysql/get_database_metadata_test.go
index f043f5f8df..84a41534d1 100644
--- a/backend/plugin/schema/mysql/get_database_metadata_test.go
+++ b/backend/plugin/schema/mysql/get_database_metadata_test.go
@@ -1,937 +1,54 @@
package mysql
import (
- "context"
- "fmt"
- "regexp"
- "strings"
+ "encoding/json"
+ "os"
"testing"
- _ "github.com/go-sql-driver/mysql"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
)
-// TestGetDatabaseMetadataWithTestcontainer tests the get_database_metadata function
-// by comparing its output with the metadata retrieved from a real MySQL instance.
-//
-//nolint:tparallel
-func TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {
- ctx := context.Background()
-
- // Start shared MySQL container for all subtests
- container := testcontainer.SharedMySQLContainer(t)
-
- // Test cases with various MySQL features
- testCases := []struct {
- name string
- ddl string
- }{
- {
- name: "basic_table_creation1",
- ddl: `
- CREATE TABLE users(
- id INT PRIMARY KEY AUTO_INCREMENT,
- name varchar(220)
- );
- `,
- },
- {
- name: "basic_table_creation2",
- ddl: `
- CREATE TABLE users(
- id INT PRIMARY KEY AUTO_INCREMENT
- );
- `,
- },
- {
- name: "basic_tables_with_constraints",
- ddl: `
-CREATE TABLE users (
- id INT AUTO_INCREMENT PRIMARY KEY,
- username VARCHAR(50) NOT NULL UNIQUE,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
-);
-
-CREATE TABLE posts (
- id INT AUTO_INCREMENT PRIMARY KEY,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published BOOLEAN DEFAULT false,
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
- INDEX idx_user_id (user_id),
- INDEX idx_published (published)
-);
-`,
- },
- {
- name: "table_with_various_data_types",
- ddl: `
-CREATE TABLE data_types_test (
- id INT AUTO_INCREMENT PRIMARY KEY,
- tiny_int_col TINYINT,
- small_int_col SMALLINT,
- medium_int_col MEDIUMINT,
- int_col INT,
- big_int_col BIGINT,
- decimal_col DECIMAL(10, 2),
- float_col FLOAT,
- double_col DOUBLE,
- bit_col BIT(8),
- bool_col BOOLEAN,
- char_col CHAR(10),
- varchar_col VARCHAR(255),
- binary_col BINARY(16),
- varbinary_col VARBINARY(255),
- tinyblob_col TINYBLOB,
- blob_col BLOB,
- mediumblob_col MEDIUMBLOB,
- longblob_col LONGBLOB,
- tinytext_col TINYTEXT,
- text_col TEXT,
- mediumtext_col MEDIUMTEXT,
- longtext_col LONGTEXT,
- enum_col ENUM('small', 'medium', 'large'),
- set_col SET('red', 'green', 'blue'),
- date_col DATE,
- time_col TIME,
- datetime_col DATETIME,
- timestamp_col TIMESTAMP,
- year_col YEAR,
- json_col JSON
-);
-`,
- },
- {
- name: "views_and_generated_columns",
- ddl: `
-CREATE TABLE employees (
- id INT AUTO_INCREMENT PRIMARY KEY,
- first_name VARCHAR(50) NOT NULL,
- last_name VARCHAR(50) NOT NULL,
- full_name VARCHAR(101) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) STORED,
- email VARCHAR(100) GENERATED ALWAYS AS (CONCAT(LOWER(first_name), '.', LOWER(last_name), '@company.com')) VIRTUAL,
- department VARCHAR(50),
- salary DECIMAL(10, 2)
-);
-
-CREATE VIEW active_employees AS
-SELECT id, first_name, last_name, full_name, department
-FROM employees
-WHERE department IS NOT NULL;
-
-CREATE VIEW high_earners AS
-SELECT id, full_name, salary
-FROM employees
-WHERE salary > 100000;
-`,
- },
- {
- name: "functions_and_procedures",
- ddl: `
-DELIMITER //
-
-CREATE FUNCTION get_employee_count(dept VARCHAR(50))
-RETURNS INT
-DETERMINISTIC
-READS SQL DATA
-BEGIN
- DECLARE emp_count INT;
- SELECT COUNT(*) INTO emp_count
- FROM employees
- WHERE department = dept;
- RETURN emp_count;
-END//
-
-CREATE PROCEDURE update_employee_salary(
- IN emp_id INT,
- IN new_salary DECIMAL(10, 2)
-)
-BEGIN
- UPDATE employees
- SET salary = new_salary
- WHERE id = emp_id;
-END//
-
-DELIMITER ;
-`,
- },
- {
- name: "partitioned_tables",
- ddl: `
-CREATE TABLE sales (
- id INT AUTO_INCREMENT,
- sale_date DATE NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- region VARCHAR(50) NOT NULL,
- PRIMARY KEY (id, sale_date)
-) PARTITION BY RANGE (YEAR(sale_date)) (
- PARTITION p2021 VALUES LESS THAN (2022),
- PARTITION p2022 VALUES LESS THAN (2023),
- PARTITION p2023 VALUES LESS THAN (2024),
- PARTITION p2024 VALUES LESS THAN (2025)
-);
-
-CREATE TABLE user_logs (
- id INT AUTO_INCREMENT,
- user_id INT NOT NULL,
- log_date DATE NOT NULL,
- action VARCHAR(100),
- PRIMARY KEY (id, user_id)
-) PARTITION BY HASH(user_id) PARTITIONS 4;
-
-CREATE TABLE regions (
- id INT AUTO_INCREMENT,
- region_code VARCHAR(10) NOT NULL,
- region_name VARCHAR(100),
- PRIMARY KEY (id, region_code)
-) PARTITION BY KEY(region_code) PARTITIONS 3;
-
-CREATE TABLE products (
- id INT AUTO_INCREMENT,
- category VARCHAR(50) NOT NULL,
- name VARCHAR(100),
- price DECIMAL(10, 2),
- PRIMARY KEY (id, category)
-) PARTITION BY LIST COLUMNS(category) (
- PARTITION p_electronics VALUES IN ('laptop', 'phone', 'tablet'),
- PARTITION p_clothing VALUES IN ('shirt', 'pants', 'shoes'),
- PARTITION p_food VALUES IN ('fruit', 'vegetable', 'meat')
-);
-`,
- },
- {
- name: "indexes_with_various_types",
- ddl: `
-CREATE TABLE orders (
- id INT AUTO_INCREMENT PRIMARY KEY,
- customer_id INT NOT NULL,
- order_date DATE NOT NULL,
- total_amount DECIMAL(10, 2) NOT NULL,
- status VARCHAR(20),
- notes TEXT,
- INDEX idx_customer (customer_id),
- INDEX idx_date_desc (order_date DESC),
- INDEX idx_customer_date (customer_id ASC, order_date DESC),
- UNIQUE INDEX idx_unique_customer_status (customer_id, status),
- FULLTEXT INDEX idx_fulltext_notes (notes)
-);
-`,
- },
- {
- name: "check_constraints",
- ddl: `
-CREATE TABLE products_with_checks (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- quantity INT NOT NULL,
- category VARCHAR(50),
- CONSTRAINT chk_price CHECK (price > 0),
- CONSTRAINT chk_quantity CHECK (quantity >= 0),
- CONSTRAINT chk_category CHECK (category IN ('electronics', 'clothing', 'food', 'other'))
-);
-`,
- },
- {
- name: "triggers",
- ddl: `
-CREATE TABLE users (
- id INT AUTO_INCREMENT PRIMARY KEY,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL
-);
-
-CREATE TABLE audit_log (
- id INT AUTO_INCREMENT PRIMARY KEY,
- table_name VARCHAR(100),
- action VARCHAR(10),
- user VARCHAR(100),
- timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-DELIMITER //
-
-CREATE TRIGGER users_after_insert
-AFTER INSERT ON users
-FOR EACH ROW
-BEGIN
- INSERT INTO audit_log (table_name, action, user)
- VALUES ('users', 'INSERT', USER());
-END//
-
-CREATE TRIGGER users_after_update
-AFTER UPDATE ON users
-FOR EACH ROW
-BEGIN
- INSERT INTO audit_log (table_name, action, user)
- VALUES ('users', 'UPDATE', USER());
-END//
-
-DELIMITER ;
-`,
- },
- {
- name: "table_with_comments",
- ddl: `
-CREATE TABLE documented_table (
- id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
- name VARCHAR(100) NOT NULL COMMENT 'The name of the item',
- description TEXT COMMENT 'Detailed description',
- price DECIMAL(10, 2) COMMENT 'Price in USD',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation timestamp',
- INDEX idx_name (name) COMMENT 'Index on name for faster lookups'
-) COMMENT='This table stores documented items';
-`,
- },
- {
- name: "complex_foreign_keys",
- ddl: `
-CREATE TABLE departments (
- dept_id INT PRIMARY KEY,
- dept_name VARCHAR(100) NOT NULL
-);
-
-CREATE TABLE employees_fk (
- emp_id INT PRIMARY KEY,
- emp_name VARCHAR(100) NOT NULL,
- dept_id INT,
- manager_id INT,
- CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees_fk(emp_id) ON DELETE RESTRICT ON UPDATE RESTRICT
-);
-`,
- },
- {
- name: "advanced_column_attributes",
- ddl: `
-CREATE TABLE advanced_columns (
- id INT AUTO_INCREMENT PRIMARY KEY,
- unsigned_int INT UNSIGNED NOT NULL,
- zerofill_int INT(8) ZEROFILL,
- unsigned_zerofill INT UNSIGNED ZEROFILL,
- tiny_unsigned TINYINT UNSIGNED,
- big_unsigned BIGINT UNSIGNED,
- decimal_unsigned DECIMAL(10,2) UNSIGNED,
- float_unsigned FLOAT UNSIGNED,
- double_unsigned DOUBLE UNSIGNED,
- bit_field BIT(16),
- char_binary CHAR(10) BINARY,
- varchar_binary VARCHAR(50) BINARY,
- text_collate TEXT COLLATE utf8mb4_unicode_ci,
- varchar_collate VARCHAR(100) COLLATE utf8mb4_bin,
- datetime_precision DATETIME(6),
- timestamp_precision TIMESTAMP(3),
- time_precision TIME(2)
-);
-`,
- },
- {
- name: "spatial_data_types",
- ddl: `
-CREATE TABLE spatial_test (
- id INT AUTO_INCREMENT PRIMARY KEY,
- location GEOMETRY NOT NULL,
- point_col POINT NOT NULL,
- line_col LINESTRING NOT NULL,
- polygon_col POLYGON NOT NULL,
- multipoint_col MULTIPOINT NOT NULL,
- multiline_col MULTILINESTRING NOT NULL,
- multipolygon_col MULTIPOLYGON NOT NULL,
- geocollection_col GEOMETRYCOLLECTION NOT NULL,
- SPATIAL INDEX idx_location (location),
- SPATIAL INDEX idx_point (point_col)
-);
-`,
- },
- {
- name: "mysql8_invisible_indexes",
- ddl: `
-CREATE TABLE invisible_index_test (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100),
- status VARCHAR(20),
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- INDEX idx_name (name),
- INDEX idx_email (email) INVISIBLE,
- INDEX idx_status_invisible (status) INVISIBLE,
- INDEX idx_composite (name, email) INVISIBLE
-);
-`,
- },
- {
- name: "advanced_indexes",
- ddl: `
-CREATE TABLE advanced_index_test (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- description TEXT,
- price DECIMAL(10,2),
- category VARCHAR(50),
- tags JSON,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- INDEX idx_name_prefix (name(10)),
- INDEX idx_price_desc (price DESC),
- INDEX idx_composite_mixed (category ASC, price DESC),
- UNIQUE INDEX idx_unique_name_category (name, category),
- FULLTEXT INDEX idx_fulltext_desc (description),
- INDEX idx_expression ((YEAR(created_at)))
-);
-`,
- },
- {
- name: "table_level_options",
- ddl: `
-CREATE TABLE table_options_test (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- data TEXT
-) ENGINE=InnoDB
- DEFAULT CHARSET=utf8mb4
- COLLATE=utf8mb4_unicode_ci
- ROW_FORMAT=DYNAMIC
- AUTO_INCREMENT=1000
- COMMENT='Table with various options';
-`,
- },
- {
- name: "advanced_partitioning_maxvalue",
- ddl: `
-CREATE TABLE sales_maxvalue (
- id INT AUTO_INCREMENT,
- sale_date DATE NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- region VARCHAR(50) NOT NULL,
- PRIMARY KEY (id, sale_date)
-) PARTITION BY RANGE (YEAR(sale_date)) (
- PARTITION p2021 VALUES LESS THAN (2022),
- PARTITION p2022 VALUES LESS THAN (2023),
- PARTITION p2023 VALUES LESS THAN (2024),
- PARTITION p_future VALUES LESS THAN MAXVALUE
-);
-`,
- },
- {
- name: "multi_column_partitioning",
- ddl: `
-CREATE TABLE multi_column_partition (
- id INT AUTO_INCREMENT,
- year_col INT NOT NULL,
- month_col INT NOT NULL,
- data VARCHAR(100),
- PRIMARY KEY (id, year_col, month_col)
-) PARTITION BY RANGE COLUMNS(year_col, month_col) (
- PARTITION p202101 VALUES LESS THAN (2021, 7),
- PARTITION p202107 VALUES LESS THAN (2022, 1),
- PARTITION p202201 VALUES LESS THAN (2022, 7),
- PARTITION p202207 VALUES LESS THAN (2023, 1)
-);
-`,
- },
- {
- name: "self_referencing_foreign_keys",
- ddl: `
-CREATE TABLE hierarchical_data (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- parent_id INT,
- manager_id INT,
- CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES hierarchical_data(id) ON DELETE CASCADE,
- CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES hierarchical_data(id) ON DELETE SET NULL
-);
-`,
- },
- {
- name: "complex_generated_columns",
- ddl: `
-CREATE TABLE complex_generated (
- id INT AUTO_INCREMENT PRIMARY KEY,
- first_name VARCHAR(50) NOT NULL,
- last_name VARCHAR(50) NOT NULL,
- birth_date DATE NOT NULL,
- salary DECIMAL(10,2),
- full_name VARCHAR(101) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) STORED,
- email VARCHAR(150) GENERATED ALWAYS AS (CONCAT(LOWER(first_name), '.', LOWER(last_name), '@company.com')) VIRTUAL,
- age_years INT GENERATED ALWAYS AS (TIMESTAMPDIFF(YEAR, birth_date, '2024-01-01')) VIRTUAL,
- salary_category VARCHAR(20) GENERATED ALWAYS AS (
- CASE
- WHEN salary < 50000 THEN 'junior'
- WHEN salary < 100000 THEN 'mid'
- ELSE 'senior'
- END
- ) STORED,
- INDEX idx_full_name (full_name),
- INDEX idx_age (age_years),
- INDEX idx_salary_cat (salary_category)
-);
-`,
- },
- {
- name: "quoted_identifiers_special_chars",
- ddl: `
-CREATE TABLE ` + "`special-table`" + ` (
- ` + "`id-field`" + ` INT AUTO_INCREMENT PRIMARY KEY,
- ` + "`first name`" + ` VARCHAR(50) NOT NULL,
- ` + "`email@domain`" + ` VARCHAR(100),
- ` + "`order`" + ` INT COMMENT 'Reserved keyword as column name',
- ` + "`group`" + ` VARCHAR(50) COMMENT 'Another reserved keyword',
- INDEX ` + "`idx-name`" + ` (` + "`first name`" + `),
- UNIQUE INDEX ` + "`idx-email`" + ` (` + "`email@domain`" + `)
-) COMMENT='Table with special characters in identifiers';
-`,
- },
- {
- name: "json_and_array_features",
- ddl: `
-CREATE TABLE json_features (
- id INT AUTO_INCREMENT PRIMARY KEY,
- metadata JSON,
- config JSON,
- tags JSON,
- name_from_json VARCHAR(100) GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(metadata, '$.name'))) STORED,
- tag_count INT GENERATED ALWAYS AS (JSON_LENGTH(tags)) VIRTUAL,
- CHECK (JSON_VALID(metadata)),
- CHECK (JSON_VALID(config)),
- INDEX idx_name_json (name_from_json),
- INDEX idx_tag_count (tag_count)
-);
-`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
-
- // Create unique test database for parallel execution
- testDBName := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err := container.GetDB().ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", testDBName))
- require.NoError(t, err)
-
- // Create MySQL driver for this test's database
- driver, err := createMySQLDriver(ctx, container.GetHost(), container.GetPort(), testDBName)
- require.NoError(t, err)
- defer driver.Close(ctx)
-
- // Execute DDL using the driver
- _, err = driver.Execute(ctx, tc.ddl, db.ExecuteOptions{})
- require.NoError(t, err)
-
- // Get metadata from live database using driver
- dbMetadata, err := driver.SyncDBSchema(ctx)
+type getDatabaseMetadataCase struct {
+ Description string `yaml:"description"`
+ Schema string `yaml:"schema"`
+ Metadata string `yaml:"metadata"`
+}
+
+// TestGetDatabaseMetadata pins what the parser extracts from each schema text.
+// The goldens describe this package's own output, not MySQL's catalog: whether
+// the parser agrees with a live server is engine conformance and belongs in omni.
+func TestGetDatabaseMetadata(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/get_database_metadata.yaml"
+ )
+
+ var tests []getDatabaseMetadataCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
+
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ metadata, err := GetDatabaseMetadata(tc.Schema)
require.NoError(t, err)
- // Get metadata from the omni parser, the function registered for
- // the production diff path (see get_database_metadata.go).
- parsedMetadata, err := GetDatabaseMetadata(tc.ddl)
+ encoded, err := json.MarshalIndent(metadata, "", " ")
require.NoError(t, err)
+ result := string(encoded) + "\n"
- // Compare metadata
- compareMetadata(t, dbMetadata, parsedMetadata, tc.name)
- })
- }
-}
-
-// compareMetadata compares the metadata from the live database with the parsed metadata
-func compareMetadata(t *testing.T, dbMeta, parsedMeta *storepb.DatabaseSchemaMetadata, testName string) {
- // For MySQL, we only have one schema
- require.Equal(t, 1, len(parsedMeta.Schemas), "parsed metadata should have exactly one schema")
-
- dbMetadata := dbMeta.Schemas[0]
- parsedSchema := parsedMeta.Schemas[0]
-
- // Compare tables
- require.Equal(t, len(dbMetadata.Tables), len(parsedSchema.Tables),
- "mismatch in number of tables for test %s", testName)
-
- // Create a map for easier lookup
- dbTableMap := make(map[string]*storepb.TableMetadata)
- for _, table := range dbMetadata.Tables {
- dbTableMap[table.Name] = table
- }
-
- for _, parsedTable := range parsedSchema.Tables {
- dbTable, exists := dbTableMap[parsedTable.Name]
- require.True(t, exists, "table %s not found in database metadata", parsedTable.Name)
-
- // Compare columns
- compareColumns(t, dbTable.Columns, parsedTable.Columns, parsedTable.Name)
-
- // Compare indexes
- compareIndexes(t, dbTable.Indexes, parsedTable.Indexes, parsedTable.Name)
-
- // Compare foreign keys
- compareForeignKeys(t, dbTable.ForeignKeys, parsedTable.ForeignKeys, parsedTable.Name)
-
- // Compare check constraints (MySQL 8.0+)
- compareCheckConstraints(t, dbTable.CheckConstraints, parsedTable.CheckConstraints, parsedTable.Name)
-
- // Compare partitions
- comparePartitions(t, dbTable.Partitions, parsedTable.Partitions, parsedTable.Name)
- }
-
- // Compare views
- compareViews(t, dbMetadata.Views, parsedSchema.Views)
-
- // Compare functions
- compareFunctions(t, dbMetadata.Functions, parsedSchema.Functions)
-
- // Compare procedures
- compareProcedures(t, dbMetadata.Procedures, parsedSchema.Procedures)
-}
-
-func compareColumns(t *testing.T, dbColumns, parsedColumns []*storepb.ColumnMetadata, tableName string) {
- require.Equal(t, len(dbColumns), len(parsedColumns),
- "mismatch in number of columns for table %s", tableName)
-
- // Create a map for easier lookup
- dbColumnMap := make(map[string]*storepb.ColumnMetadata)
- for _, col := range dbColumns {
- dbColumnMap[col.Name] = col
- }
-
- for _, parsedCol := range parsedColumns {
- dbCol, exists := dbColumnMap[parsedCol.Name]
- require.True(t, exists, "column %s.%s not found in database metadata", tableName, parsedCol.Name)
-
- // Compare column properties (normalize types to lowercase)
- dbType := strings.ToLower(dbCol.Type)
- parsedType := strings.ToLower(parsedCol.Type)
- require.Equal(t, dbType, parsedType,
- "type mismatch for column %s.%s", tableName, parsedCol.Name)
- require.Equal(t, dbCol.Nullable, parsedCol.Nullable,
- "nullable mismatch for column %s.%s", tableName, parsedCol.Name)
-
- // Compare default values (allowing for some normalization differences)
- compareDefaultValues(t, dbCol, parsedCol, tableName, parsedCol.Name)
-
- // Compare comments
- require.Equal(t, dbCol.Comment, parsedCol.Comment,
- "comment mismatch for column %s.%s", tableName, parsedCol.Name)
- }
-}
-
-func compareDefaultValues(t *testing.T, dbDefault, parsedDefault any, tableName, columnName string) {
- if dbDefault == nil && parsedDefault == nil {
- return
- }
-
- if dbDefault == nil || parsedDefault == nil {
- t.Errorf("default value mismatch for column %s.%s: db=%v, parsed=%v",
- tableName, columnName, dbDefault, parsedDefault)
- return
- }
-
- // Extract default expressions
- dbExpr := ""
- parsedExpr := ""
-
- // Handle database default
- if dbCol, ok := dbDefault.(*storepb.ColumnMetadata); ok {
- if dbCol.Default != "" {
- dbExpr = dbCol.Default
- }
- }
-
- // Handle parsed default
- if parsedCol, ok := parsedDefault.(*storepb.ColumnMetadata); ok {
- if parsedCol.Default != "" {
- parsedExpr = parsedCol.Default
- }
- }
-
- // Normalize and compare
- dbExpr = normalizeDefaultExpression(dbExpr)
- parsedExpr = normalizeDefaultExpression(parsedExpr)
-
- require.Equal(t, dbExpr, parsedExpr,
- "default value mismatch for column %s.%s", tableName, columnName)
-}
-
-func normalizeDefaultExpression(expr string) string {
- // Normalize common variations
- expr = strings.TrimSpace(expr)
- expr = strings.ToUpper(expr)
-
- // Handle CURRENT_TIMESTAMP variations
- if strings.Contains(expr, "CURRENT_TIMESTAMP") || strings.Contains(expr, "NOW()") {
- return "CURRENT_TIMESTAMP"
- }
-
- // Handle AUTO_INCREMENT
- if expr == "AUTO_INCREMENT" {
- return "AUTO_INCREMENT"
- }
-
- // Remove parentheses from simple expressions
- if strings.HasPrefix(expr, "(") && strings.HasSuffix(expr, ")") {
- expr = expr[1 : len(expr)-1]
- }
-
- return expr
-}
-
-func compareIndexes(t *testing.T, dbIndexes, parsedIndexes []*storepb.IndexMetadata, tableName string) {
- require.Equal(t, len(dbIndexes), len(parsedIndexes),
- "mismatch in number of indexes for table %s", tableName)
-
- // Create maps for easier lookup
- dbIndexMap := make(map[string]*storepb.IndexMetadata)
- for _, idx := range dbIndexes {
- dbIndexMap[idx.Name] = idx
- }
-
- // Check that all parsed indexes exist in db with exact match
- for _, parsedIdx := range parsedIndexes {
- dbIdx, exists := dbIndexMap[parsedIdx.Name]
- require.True(t, exists, "index %s on table %s not found in database metadata", parsedIdx.Name, tableName)
-
- // Compare all IndexMetadata members for complete consistency
-
- // 1. Name (already validated above through map lookup)
- require.Equal(t, dbIdx.Name, parsedIdx.Name,
- "name mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 2. Type (index type: BTREE, HASH, FULLTEXT, SPATIAL, etc.)
- require.Equal(t, dbIdx.Type, parsedIdx.Type,
- "type mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 3. Primary (whether the index is a primary key index)
- require.Equal(t, dbIdx.Primary, parsedIdx.Primary,
- "primary mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 4. Unique (whether the index is unique)
- require.Equal(t, dbIdx.Unique, parsedIdx.Unique,
- "unique mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 5. Visible (whether the index is visible - MySQL 8.0+ feature)
- require.Equal(t, dbIdx.Visible, parsedIdx.Visible,
- "visible mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 6. Comment (index comment)
- require.Equal(t, dbIdx.Comment, parsedIdx.Comment,
- "comment mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 7. Expressions (columns or expressions that the index is on)
- require.Equal(t, len(dbIdx.Expressions), len(parsedIdx.Expressions),
- "expression count mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- for i, expr := range parsedIdx.Expressions {
- if i < len(dbIdx.Expressions) {
- // Normalize expressions for comparison
- dbExpr := normalizeIndexExpression(dbIdx.Expressions[i])
- parsedExpr := normalizeIndexExpression(expr)
- require.Equal(t, dbExpr, parsedExpr,
- "expression mismatch for index %s on table %s at position %d", parsedIdx.Name, tableName, i)
+ if record {
+ tests[i].Metadata = result
+ return
}
- }
-
- // 8. KeyLength (key lengths for each expression, -1 if not specified)
- require.Equal(t, len(dbIdx.KeyLength), len(parsedIdx.KeyLength),
- "key length count mismatch for index %s on table %s", parsedIdx.Name, tableName)
- require.Equal(t, dbIdx.KeyLength, parsedIdx.KeyLength,
- "key length mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 9. Descending (descending flags for each expression)
- require.Equal(t, len(dbIdx.Descending), len(parsedIdx.Descending),
- "descending flag count mismatch for index %s on table %s", parsedIdx.Name, tableName)
- require.Equal(t, dbIdx.Descending, parsedIdx.Descending,
- "descending flags mismatch for index %s on table %s", parsedIdx.Name, tableName)
-
- // 10. Definition (the full index definition - may be empty for some parsers)
- // Note: We only compare if both have non-empty definitions as some parsers may not populate this
- if dbIdx.Definition != "" && parsedIdx.Definition != "" {
- require.Equal(t, dbIdx.Definition, parsedIdx.Definition,
- "definition mismatch for index %s on table %s", parsedIdx.Name, tableName)
- }
-
- // Note: Other fields like ParentIndexSchema, ParentIndexName, Granularity, and SupportNullScan
- // are database-specific and may not apply to MySQL, so we don't validate them here
- }
-}
-
-// normalizeIndexExpression normalizes index expressions for comparison
-func normalizeIndexExpression(expr string) string {
- // Remove backticks
- expr = strings.ReplaceAll(expr, "`", "")
-
- // Remove outer parentheses from expressions like "(year(created_at))"
- if strings.HasPrefix(expr, "(") && strings.HasSuffix(expr, ")") {
- expr = expr[1 : len(expr)-1]
- }
-
- // Convert to uppercase for case-insensitive comparison
- expr = strings.ToUpper(expr)
-
- return expr
-}
-
-func compareForeignKeys(t *testing.T, dbFKs, parsedFKs []*storepb.ForeignKeyMetadata, tableName string) {
- require.Equal(t, len(dbFKs), len(parsedFKs),
- "mismatch in number of foreign keys for table %s", tableName)
-
- // Create a map for easier lookup
- dbFKMap := make(map[string]*storepb.ForeignKeyMetadata)
- for _, fk := range dbFKs {
- dbFKMap[fk.Name] = fk
- }
-
- for _, parsedFK := range parsedFKs {
- dbFK, exists := dbFKMap[parsedFK.Name]
- require.True(t, exists, "foreign key %s on table %s not found in database metadata",
- parsedFK.Name, tableName)
-
- // Compare foreign key properties
- require.Equal(t, dbFK.Columns, parsedFK.Columns,
- "columns mismatch for foreign key %s on table %s", parsedFK.Name, tableName)
- require.Equal(t, dbFK.ReferencedTable, parsedFK.ReferencedTable,
- "referenced table mismatch for foreign key %s on table %s", parsedFK.Name, tableName)
- require.Equal(t, dbFK.ReferencedColumns, parsedFK.ReferencedColumns,
- "referenced columns mismatch for foreign key %s on table %s", parsedFK.Name, tableName)
- require.Equal(t, dbFK.OnDelete, parsedFK.OnDelete,
- "on delete mismatch for foreign key %s on table %s", parsedFK.Name, tableName)
- require.Equal(t, dbFK.OnUpdate, parsedFK.OnUpdate,
- "on update mismatch for foreign key %s on table %s", parsedFK.Name, tableName)
- }
-}
-
-func compareCheckConstraints(t *testing.T, dbChecks, parsedChecks []*storepb.CheckConstraintMetadata, tableName string) {
- // MySQL 8.0+ supports check constraints
- // For older versions, this might be empty
- if len(dbChecks) == 0 && len(parsedChecks) == 0 {
- return
- }
-
- require.Equal(t, len(dbChecks), len(parsedChecks),
- "mismatch in number of check constraints for table %s", tableName)
-
- // Create a map for easier lookup
- dbCheckMap := make(map[string]*storepb.CheckConstraintMetadata)
- for _, chk := range dbChecks {
- dbCheckMap[chk.Name] = chk
- }
-
- for _, parsedCheck := range parsedChecks {
- dbCheck, exists := dbCheckMap[parsedCheck.Name]
- require.True(t, exists, "check constraint %s on table %s not found in database metadata",
- parsedCheck.Name, tableName)
-
- // Compare expressions (allowing for some normalization)
- dbExpr := normalizeCheckExpression(dbCheck.Expression)
- parsedExpr := normalizeCheckExpression(parsedCheck.Expression)
- require.Equal(t, dbExpr, parsedExpr,
- "expression mismatch for check constraint %s on table %s", parsedCheck.Name, tableName)
- }
-}
-
-func normalizeCheckExpression(expr string) string {
- // Normalize check constraint expressions
- expr = strings.TrimSpace(expr)
-
- // Remove outer parentheses if present (MySQL normalizes this way)
- if strings.HasPrefix(expr, "(") && strings.HasSuffix(expr, ")") {
- expr = expr[1 : len(expr)-1]
- }
-
- expr = strings.ReplaceAll(expr, "`", "")
- expr = strings.ReplaceAll(expr, " ", "")
-
- // Remove character set introducers attached to string literals, like
- // _utf8mb4'...' (synced metadata) or _utf8mb4\'...\' (legacy escaped form)
- re := regexp.MustCompile(`_[a-zA-Z0-9]+\\?'`)
- expr = re.ReplaceAllString(expr, "'")
-
- // Remove escaped quotes
- expr = strings.ReplaceAll(expr, `\'`, `'`)
- expr = strings.ReplaceAll(expr, `\"`, `"`)
-
- expr = strings.ToLower(expr)
- return expr
-}
-
-func comparePartitions(t *testing.T, dbPartitions, parsedPartitions []*storepb.TablePartitionMetadata, tableName string) {
- require.Equal(t, len(dbPartitions), len(parsedPartitions),
- "mismatch in number of partitions for table %s", tableName)
-
- // Create a map for easier lookup
- dbPartMap := make(map[string]*storepb.TablePartitionMetadata)
- for _, part := range dbPartitions {
- dbPartMap[part.Name] = part
- }
-
- for _, parsedPart := range parsedPartitions {
- dbPart, exists := dbPartMap[parsedPart.Name]
- require.True(t, exists, "partition %s on table %s not found in database metadata",
- parsedPart.Name, tableName)
-
- // Compare partition properties
- // Note: Expression comparison might need normalization
- require.NotEmpty(t, dbPart.Expression, "partition expression should not be empty for %s", parsedPart.Name)
- require.NotEmpty(t, parsedPart.Expression, "parsed partition expression should not be empty for %s", parsedPart.Name)
- }
-}
-
-func compareViews(t *testing.T, dbViews, parsedViews []*storepb.ViewMetadata) {
- require.Equal(t, len(dbViews), len(parsedViews), "mismatch in number of views")
-
- // Create a map for easier lookup
- dbViewMap := make(map[string]*storepb.ViewMetadata)
- for _, view := range dbViews {
- dbViewMap[view.Name] = view
- }
-
- for _, parsedView := range parsedViews {
- dbView, exists := dbViewMap[parsedView.Name]
- require.True(t, exists, "view %s not found in database metadata", parsedView.Name)
-
- // View definitions might differ in formatting, so just check they're non-empty
- require.NotEmpty(t, dbView.Definition, "database view definition should not be empty")
- require.NotEmpty(t, parsedView.Definition, "parsed view definition should not be empty")
- }
-}
-
-func compareFunctions(t *testing.T, dbFuncs, parsedFuncs []*storepb.FunctionMetadata) {
- require.Equal(t, len(dbFuncs), len(parsedFuncs), "mismatch in number of functions")
-
- // Create a map for easier lookup
- dbFuncMap := make(map[string]*storepb.FunctionMetadata)
- for _, fn := range dbFuncs {
- dbFuncMap[fn.Name] = fn
- }
-
- for _, parsedFunc := range parsedFuncs {
- dbFunc, exists := dbFuncMap[parsedFunc.Name]
- require.True(t, exists, "function %s not found in database metadata", parsedFunc.Name)
-
- // Function definitions might differ in formatting, so just check they're non-empty
- require.NotEmpty(t, dbFunc.Definition, "database function definition should not be empty")
- require.NotEmpty(t, parsedFunc.Definition, "parsed function definition should not be empty")
- }
-}
-
-func compareProcedures(t *testing.T, dbProcs, parsedProcs []*storepb.ProcedureMetadata) {
- require.Equal(t, len(dbProcs), len(parsedProcs), "mismatch in number of procedures")
-
- // Create a map for easier lookup
- dbProcMap := make(map[string]*storepb.ProcedureMetadata)
- for _, proc := range dbProcs {
- dbProcMap[proc.Name] = proc
+ require.Equal(t, tc.Metadata, result)
+ })
}
- for _, parsedProc := range parsedProcs {
- dbProc, exists := dbProcMap[parsedProc.Name]
- require.True(t, exists, "procedure %s not found in database metadata", parsedProc.Name)
-
- // Procedure definitions might differ in formatting, so just check they're non-empty
- require.NotEmpty(t, dbProc.Definition, "database procedure definition should not be empty")
- require.NotEmpty(t, parsedProc.Definition, "parsed procedure definition should not be empty")
+ if record {
+ yamltest.Record(t, filepath, tests)
}
}
diff --git a/backend/plugin/schema/mysql/main_test.go b/backend/plugin/schema/mysql/main_test.go
deleted file mode 100644
index 0a9c4993be..0000000000
--- a/backend/plugin/schema/mysql/main_test.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package mysql
-
-import (
- "testing"
-
- "github.com/bytebase/bytebase/backend/common/testcontainer"
-)
-
-func TestMain(m *testing.M) { testcontainer.Main(m) }
diff --git a/backend/plugin/schema/mysql/sdl_migration_test.go b/backend/plugin/schema/mysql/sdl_migration_test.go
index b1bca794fd..4e88a2420e 100644
--- a/backend/plugin/schema/mysql/sdl_migration_test.go
+++ b/backend/plugin/schema/mysql/sdl_migration_test.go
@@ -425,7 +425,7 @@ const liveOraclePassword = "010424"
// (literal, CURRENT_TIMESTAMP, ON UPDATE), a secondary index, a foreign key, a
// STORED generated column, and a view.
//
-//go:embed testdata/sdl/representative_ddl.sql
+//go:embed testdata/sdl_migration/representative_ddl.sql
var representativeDDL string
// statementCount counts the non-empty ";"-separated statements in generated DDL.
@@ -1497,7 +1497,7 @@ func TestSDLSessionContextNoChurnLive(t *testing.T) {
// - schema.SDLDropAdvices(MYSQL, userSDL, syncedMetadata, engineVersion),
// - the real db/mysql sync + schema.MetadataToSDL dumper.
//
-// The schemas are embedded preprocessed fixtures (testdata/realworld/*.sql) so the test is
+// The schemas are embedded preprocessed fixtures (testdata/sdl_migration/*.sql) so the test is
// self-contained. Sakila is THE priority: it carries real view / function / procedure /
// trigger bodies (incl. a SQL SECURITY INVOKER view with fully schema-qualified references),
// which is where the at-scale view/routine round-trip is won or lost.
@@ -1527,19 +1527,19 @@ func TestSDLSessionContextNoChurnLive(t *testing.T) {
// /*$wgDBTableOptions*/ -> "ENGINE=InnoDB DEFAULT CHARSET=binary",
// /*$wgDBprefix*/ -> empty. 58 tables incl. a MyISAM FULLTEXT searchindex.
-//go:embed testdata/realworld/sakila.sql
+//go:embed testdata/sdl_migration/sakila.sql
var sakilaSchema string
-//go:embed testdata/realworld/employees.sql
+//go:embed testdata/sdl_migration/employees.sql
var employeesSchema string
-//go:embed testdata/realworld/employees_part.sql
+//go:embed testdata/sdl_migration/employees_part.sql
var employeesPartSchema string
-//go:embed testdata/realworld/roundcube.sql
+//go:embed testdata/sdl_migration/roundcube.sql
var roundcubeSchema string
-//go:embed testdata/realworld/mediawiki.sql
+//go:embed testdata/sdl_migration/mediawiki.sql
var mediawikiSchema string
// omniViewParseBug is the precise classification for the (B) omni SDL-parser limitation that
@@ -2452,7 +2452,7 @@ func applyDDL(ctx context.Context, t *testing.T, srv liveServer, dbName, ddl str
// tables exist (the SDL loader disables foreign_key_checks, but the live setup apply does
// not).
//
-//go:embed testdata/sdl/big_schema_core.sql
+//go:embed testdata/sdl_migration/big_schema_core.sql
var bigSchemaCore string
// circularFKClose closes the department<->employee circular dependency after both
@@ -2515,7 +2515,7 @@ func bigSchemaUserSDL(version string) string {
// bigSchemaUserSDLCore is the table/routine/trigger body the user authors, sans the
// version-specific project-load view (appended by bigSchemaUserSDL).
//
-//go:embed testdata/sdl/big_schema_user_sdl_core.sql
+//go:embed testdata/sdl_migration/big_schema_user_sdl_core.sql
var bigSchemaUserSDLCore string
// TestSDLStressLargeSchemaIdempotence is the headline at-scale idempotence proof. One
@@ -2842,7 +2842,7 @@ func TestSDLStressTableCreateOptions(t *testing.T) {
// multiChangeBase is the baseline schema for the multi-change release.
//
-//go:embed testdata/sdl/multi_change_base.sql
+//go:embed testdata/sdl_migration/multi_change_base.sql
var multiChangeBase string
// multiChangeTarget applies MANY simultaneous changes in ONE diff:
@@ -2858,12 +2858,12 @@ var multiChangeBase string
//
// The 8.0 variant includes the CHECK; multiChangeTarget57 omits it.
//
-//go:embed testdata/sdl/multi_change_target_80.sql
+//go:embed testdata/sdl_migration/multi_change_target_80.sql
var multiChangeTarget80 string
// multiChangeTarget57 is multiChangeTarget80 without the CHECK constraint (5.7 ignores CHECK).
//
-//go:embed testdata/sdl/multi_change_target_57.sql
+//go:embed testdata/sdl_migration/multi_change_target_57.sql
var multiChangeTarget57 string
// indexOf returns the byte index of the first occurrence of substr in s, or -1. Used to
@@ -2953,14 +2953,14 @@ func TestSDLStressMultiChange(t *testing.T) {
// dropHeavyBase has tables, indexes, views, and routines to drop.
//
-//go:embed testdata/sdl/drop_heavy_base.sql
+//go:embed testdata/sdl_migration/drop_heavy_base.sql
var dropHeavyBase string
// dropHeavyTarget drops scratch_table (whole table), a.scratch column (+ its index),
// a.idx_a_name index, the v_a view, f_double function, and p_reset procedure. Table b
// loses its FK target only if a is dropped — here a survives, b survives.
//
-//go:embed testdata/sdl/drop_heavy_target.sql
+//go:embed testdata/sdl_migration/drop_heavy_target.sql
var dropHeavyTarget string
// TestSDLStressDropHeavy asserts SDLDropAdvices emits WARNING advices for each destructive
@@ -3087,12 +3087,12 @@ CREATE FUNCTION f(x INT) RETURNS INT DETERMINISTIC RETURN x*2;`
// divergeSchema authors constructs whose stored form diverges by version: bare utf8mb4
// (collation), utf8 (mb3 on 8.0), int widths, and a CHECK (8.0 only).
//
-//go:embed testdata/sdl/diverge_schema.sql
+//go:embed testdata/sdl_migration/diverge_schema.sql
var divergeSchema string
// divergeSchemaWithCheck adds a CHECK (8.0 honors it; 5.7 parses-and-ignores).
//
-//go:embed testdata/sdl/diverge_schema_with_check.sql
+//go:embed testdata/sdl_migration/diverge_schema_with_check.sql
var divergeSchemaWithCheck string
// TestSDLStressVersionDivergence confirms each version is idempotent against its OWN
@@ -3932,26 +3932,26 @@ func (s chainStep) target(version string) string {
// chainS0: a small starting schema — customer + order with an FK, one view.
//
-//go:embed testdata/sdl/chain_s0.sql
+//go:embed testdata/sdl_migration/chain_s0.sql
var chainS0 string
// chainS1: add table `order_item` + FK to ord (and to a new `product` table).
//
-//go:embed testdata/sdl/chain_s1_common.sql
+//go:embed testdata/sdl_migration/chain_s1_common.sql
var chainS1Common string
// chainS2: add a column (customer.loyalty_points) + an index (ord.idx_ord_created) + a
// generated column (order_item.line_total references qty — but needs price; keep it simple:
// generated col on product: price_with_tax).
//
-//go:embed testdata/sdl/chain_s2_common.sql
+//go:embed testdata/sdl_migration/chain_s2_common.sql
var chainS2Common string
// chainS3: modify a column type (ord.total DECIMAL(10,2)->DECIMAL(14,4)) + widen a VARCHAR
// (customer.name VARCHAR(100)->VARCHAR(200)) + change a default (customer.loyalty_points
// DEFAULT 0 -> DEFAULT 100).
//
-//go:embed testdata/sdl/chain_s3_common.sql
+//go:embed testdata/sdl_migration/chain_s3_common.sql
var chainS3Common string
// chainS4: drop a column WITH its index (drop product.price_with_tax generated col), drop a
@@ -3964,7 +3964,7 @@ var chainS3Common string
// S4 also changes order_item to remove product linkage, replaces v_cust_orders, adds a
// trigger on ord, and (8.0) adds a CHECK on ord.total.
//
-//go:embed testdata/sdl/chain_s4_base.sql
+//go:embed testdata/sdl_migration/chain_s4_base.sql
var chainS4Base string
func chainSteps() []chainStep {
@@ -4285,16 +4285,16 @@ func TestSDLDeepScale(t *testing.T) {
// paren-subquery operand continuation #366) — both fixed and pinned.
// ----------------------------------------------------------------------------
-//go:embed testdata/enterprise/zabbix.sql
+//go:embed testdata/sdl_migration/zabbix.sql
var entZabbixSQL string
-//go:embed testdata/enterprise/prestashop.sql
+//go:embed testdata/sdl_migration/prestashop.sql
var entPrestashopSQL string
-//go:embed testdata/enterprise/openemr.sql
+//go:embed testdata/sdl_migration/openemr.sql
var entOpenemrSQL string
-//go:embed testdata/enterprise/sys.sql
+//go:embed testdata/sdl_migration/sys.sql
var entSysSQL string
// entCorpus is one embedded enterprise schema.
@@ -4803,7 +4803,7 @@ func TestSDLEnterpriseBaseline(t *testing.T) {
// entA1Aux seeds the slice with one object of each kind that needs a pre-existing
// instance to modify/drop, plus a RANGE-partitioned table for the partition kind.
//
-//go:embed testdata/sdl/ent_a1_aux.sql
+//go:embed testdata/sdl_migration/ent_a1_aux.sql
var entA1Aux string
// entCRUDPhase is one oracle round (create / modify / drop) within a kind.
@@ -5877,7 +5877,7 @@ CREATE TABLE ent_ab_t (
// entA5cAux seeds the view/function the combined release modifies.
//
-//go:embed testdata/sdl/ent_a5c_aux.sql
+//go:embed testdata/sdl_migration/ent_a5c_aux.sql
var entA5cAux string
//nolint:tparallel
@@ -6367,7 +6367,7 @@ func TestSDLEnterpriseCrossVersionUpgrade(t *testing.T) {
// them faithfully (0xFF61 on 8.0; a significant trailing NUL, 0x6100, on 5.7).
// ----------------------------------------------------------------------------
-//go:embed testdata/sdl/ent_upg_binary_default_ddl.sql
+//go:embed testdata/sdl_migration/ent_upg_binary_default_ddl.sql
var entUpgBinaryDefaultDDL string
//nolint:tparallel
@@ -6478,7 +6478,7 @@ var entFuzzSliceTables = append(append([]string{}, entSliceCoreTables...),
// entFuzzAux seeds the droppable/modifiable object pool the menu needs: two views, one
// function, one procedure, and a partitioned table (the departition target).
//
-//go:embed testdata/sdl/ent_fuzz_aux.sql
+//go:embed testdata/sdl_migration/ent_fuzz_aux.sql
var entFuzzAux string
// entFzProtectedTables are never touched by column-level mutations: the changelog
@@ -7412,10 +7412,10 @@ const (
// INVISIBLE, CHECK) and is appended on 8.0 only.
// ----------------------------------------------------------------------------
-//go:embed testdata/sdl/ent_sf_aux_common.sql
+//go:embed testdata/sdl_migration/ent_sf_aux_common.sql
var entSfAuxCommon string
-//go:embed testdata/sdl/ent_sf_aux_80.sql
+//go:embed testdata/sdl_migration/ent_sf_aux_80.sql
var entSfAux80 string
func entSfBaseDDL(t *testing.T, srv liveServer) string {
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/actor_info_80.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/actor_info_80.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/actor_info_80.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/actor_info_80.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/actor_info_80.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/actor_info_80.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/actor_info_80.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/actor_info_80.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/check_option_80.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/check_option_80.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/check_option_80.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/check_option_80.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/check_option_80.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/check_option_80.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/check_option_80.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/check_option_80.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/cte_limit_80.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/cte_limit_80.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/cte_limit_80.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/cte_limit_80.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/cte_limit_80.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/cte_limit_80.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/cte_limit_80.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/cte_limit_80.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/derived_table_57.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/derived_table_57.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/derived_table_57.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/derived_table_57.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/derived_table_57.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/derived_table_57.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/derived_table_57.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/derived_table_57.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/film_list_80.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/film_list_80.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/film_list_80.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/film_list_80.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/film_list_80.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/film_list_80.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/film_list_80.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/film_list_80.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/string_literals_57.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/string_literals_57.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/string_literals_57.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/string_literals_57.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/string_literals_57.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/string_literals_57.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/string_literals_57.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/string_literals_57.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/sys_metrics_union_all_80.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/sys_metrics_union_all_80.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/sys_metrics_union_all_80.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/sys_metrics_union_all_80.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/sys_metrics_union_all_80.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/sys_metrics_union_all_80.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/sys_metrics_union_all_80.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/sys_metrics_union_all_80.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/sys_schema_object_overview_union_80.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/sys_schema_object_overview_union_80.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/sys_schema_object_overview_union_80.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/sys_schema_object_overview_union_80.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/sys_schema_object_overview_union_80.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/sys_schema_object_overview_union_80.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/sys_schema_object_overview_union_80.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/sys_schema_object_overview_union_80.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/sys_x_schema_flattened_keys_80.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/sys_x_schema_flattened_keys_80.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/sys_x_schema_flattened_keys_80.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/sys_x_schema_flattened_keys_80.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/sys_x_schema_flattened_keys_80.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/sys_x_schema_flattened_keys_80.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/sys_x_schema_flattened_keys_80.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/sys_x_schema_flattened_keys_80.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/union_all_57.golden.sql b/backend/plugin/schema/mysql/testdata/format_view_body/union_all_57.golden.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/union_all_57.golden.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/union_all_57.golden.sql
diff --git a/backend/plugin/schema/mysql/testdata/format-view-body/union_all_57.stored.sql b/backend/plugin/schema/mysql/testdata/format_view_body/union_all_57.stored.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/format-view-body/union_all_57.stored.sql
rename to backend/plugin/schema/mysql/testdata/format_view_body/union_all_57.stored.sql
diff --git a/backend/plugin/schema/mysql/testdata/generate_migration.yaml b/backend/plugin/schema/mysql/testdata/generate_migration.yaml
new file mode 100644
index 0000000000..6e80084910
--- /dev/null
+++ b/backend/plugin/schema/mysql/testdata/generate_migration.yaml
@@ -0,0 +1,2288 @@
+- description: drop_table_with_dependencies
+ oldSchema: |
+ CREATE TABLE authors (
+ id int NOT NULL AUTO_INCREMENT,
+ name varchar(100) NOT NULL,
+ email varchar(100) DEFAULT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ CREATE TABLE books (
+ id int NOT NULL AUTO_INCREMENT,
+ title varchar(200) NOT NULL,
+ author_id int NOT NULL,
+ isbn varchar(20) DEFAULT NULL,
+ published_year int DEFAULT NULL,
+ price decimal(8,2) DEFAULT NULL,
+ PRIMARY KEY (id),
+ KEY idx_author (author_id),
+ KEY idx_year (published_year),
+ UNIQUE KEY uk_isbn (isbn),
+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors (id),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_year_valid CHECK ((published_year >= 1000) and (published_year <= 2100))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ CREATE TABLE products (
+ id int NOT NULL AUTO_INCREMENT,
+ name varchar(50) NOT NULL,
+ price decimal(8,2) NOT NULL,
+ description text DEFAULT NULL,
+ category varchar(30) DEFAULT NULL,
+ is_active tinyint(1) DEFAULT '1',
+ PRIMARY KEY (id),
+ KEY idx_category (category),
+ KEY idx_price (price)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+ newSchema: ""
+ expected: |+
+ DROP TABLE IF EXISTS `books`;
+
+ DROP TABLE IF EXISTS `products`;
+
+ DROP TABLE IF EXISTS `authors`;
+
+- description: Create tables with foreign key constraints
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ expected: |+
+ CREATE TABLE IF NOT EXISTS `posts` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `user_id` int NOT NULL,
+ `title` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
+ `content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+ `published_at` datetime DEFAULT NULL,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ CREATE INDEX `idx_user_id` ON `posts` (`user_id`);
+
+
+ CREATE TABLE IF NOT EXISTS `users` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
+ `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_email` (`email`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ CREATE INDEX `idx_username` ON `users` (`username`);
+
+
+ ALTER TABLE `posts` ADD CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE;
+
+- description: Basic table operations with columns, constraints, and indexes
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ is_active BOOLEAN DEFAULT true,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username),
+ INDEX idx_email_active (email, is_active)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE comments (
+ id INT NOT NULL AUTO_INCREMENT,
+ post_id INT NOT NULL,
+ user_id INT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_post_user (post_id, user_id),
+ CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ expected: |+
+ DROP TABLE IF EXISTS `comments`;
+
+ ALTER TABLE `posts` DROP CONSTRAINT `chk_title_length`;
+
+ DROP INDEX `idx_email_active` ON `users`;
+
+ ALTER TABLE `users` DROP COLUMN `is_active`;
+
+
+- description: Views, triggers, and stored procedures
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ ) ENGINE=InnoDB;
+
+ CREATE VIEW product_inventory AS
+ SELECT
+ p.id,
+ p.name,
+ p.price,
+ p.stock,
+ COALESCE(SUM(o.quantity), 0) AS total_ordered
+ FROM products p
+ LEFT JOIN orders o ON p.id = o.product_id
+ GROUP BY p.id, p.name, p.price, p.stock;
+
+ CREATE VIEW low_stock_products AS
+ SELECT * FROM products WHERE stock < 10;
+
+ CREATE TRIGGER update_order_total
+ BEFORE INSERT ON orders
+ FOR EACH ROW
+ BEGIN
+ DECLARE product_price DECIMAL(10, 2);
+ SELECT price INTO product_price FROM products WHERE id = NEW.product_id;
+ SET NEW.total = NEW.quantity * product_price;
+ END;
+
+ CREATE PROCEDURE GetProductInventory(IN product_name VARCHAR(100))
+ BEGIN
+ SELECT * FROM product_inventory
+ WHERE name LIKE CONCAT('%', product_name, '%');
+ END;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP TRIGGER IF EXISTS `update_order_total`;
+
+ CREATE OR REPLACE VIEW `low_stock_products` AS SELECT 1;
+
+ CREATE OR REPLACE VIEW `product_inventory` AS SELECT 1;
+
+ DROP VIEW IF EXISTS `low_stock_products`;
+
+ DROP VIEW IF EXISTS `product_inventory`;
+
+ DROP PROCEDURE IF EXISTS `GetProductInventory`;
+
+
+- description: Stored functions and dependent tables
+ oldSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_id, sale_date)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE sales_summary (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ month_year VARCHAR(7) NOT NULL,
+ total_sales DECIMAL(10, 2),
+ tax_amount DECIMAL(10, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_product_month (product_id, month_year)
+ ) ENGINE=InnoDB;
+
+ CREATE FUNCTION CalculateTotalSales(p_product_id INT, p_start_date DATE, p_end_date DATE)
+ RETURNS DECIMAL(10, 2)
+ DETERMINISTIC
+ READS SQL DATA
+ BEGIN
+ DECLARE total DECIMAL(10, 2);
+
+ SELECT COALESCE(SUM(quantity * unit_price), 0) INTO total
+ FROM sales
+ WHERE product_id = p_product_id
+ AND sale_date BETWEEN p_start_date AND p_end_date;
+
+ RETURN total;
+ END;
+
+ CREATE FUNCTION GetTaxAmount(amount DECIMAL(10, 2), tax_rate DECIMAL(5, 2))
+ RETURNS DECIMAL(10, 2)
+ DETERMINISTIC
+ NO SQL
+ BEGIN
+ RETURN amount * (tax_rate / 100);
+ END;
+ newSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_id, sale_date)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP FUNCTION IF EXISTS `CalculateTotalSales`;
+
+ DROP FUNCTION IF EXISTS `GetTaxAmount`;
+
+ DROP TABLE IF EXISTS `sales_summary`;
+
+- description: Drop indexes and constraints from tables
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category VARCHAR(50),
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category VARCHAR(50),
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_sku (sku),
+ INDEX idx_name (name),
+ INDEX idx_category (category),
+ INDEX idx_price (price),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
+ ) ENGINE=InnoDB;
+ expected: |+
+ CREATE INDEX `idx_category` ON `products` (`category`);
+
+ CREATE INDEX `idx_name` ON `products` (`name`);
+
+ CREATE INDEX `idx_price` ON `products` (`price`);
+
+ ALTER TABLE `products` ADD UNIQUE KEY `uk_sku` (`sku`);
+
+ ALTER TABLE `products` ADD CONSTRAINT `chk_name_length` CHECK (char_length(`name`) >= 3);
+
+ ALTER TABLE `products` ADD CONSTRAINT `chk_price_positive` CHECK (`price` > 0);
+
+- description: Drop views and stored routines
+ oldSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_name VARCHAR(100) NOT NULL,
+ sale_amount DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_name VARCHAR(100) NOT NULL,
+ sale_amount DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE VIEW monthly_sales AS
+ SELECT
+ YEAR(sale_date) AS year,
+ MONTH(sale_date) AS month,
+ SUM(sale_amount) AS total_sales
+ FROM sales
+ GROUP BY YEAR(sale_date), MONTH(sale_date);
+
+ CREATE VIEW top_products AS
+ SELECT
+ product_name,
+ COUNT(*) AS sale_count,
+ SUM(sale_amount) AS total_revenue
+ FROM sales
+ GROUP BY product_name
+ ORDER BY SUM(sale_amount) DESC;
+
+ CREATE FUNCTION GetMonthlySalesTotal(year INT, month INT)
+ RETURNS DECIMAL(10, 2)
+ DETERMINISTIC
+ READS SQL DATA
+ BEGIN
+ DECLARE total DECIMAL(10, 2);
+ SELECT COALESCE(SUM(sale_amount), 0) INTO total
+ FROM sales
+ WHERE YEAR(sale_date) = year AND MONTH(sale_date) = month;
+ RETURN total;
+ END;
+
+ CREATE PROCEDURE CalculateDiscount(IN amount DECIMAL(10, 2), OUT discount DECIMAL(10, 2))
+ BEGIN
+ SET discount = amount * 0.1;
+ END;
+ expected: |+
+ CREATE VIEW `monthly_sales` AS SELECT 1;
+
+ CREATE VIEW `top_products` AS SELECT 1;
+
+ CREATE OR REPLACE VIEW `monthly_sales` AS select year(`sales`.`sale_date`) AS `year`,month(`sales`.`sale_date`) AS `month`,sum(`sales`.`sale_amount`) AS `total_sales` from `sales` group by year(`sales`.`sale_date`),month(`sales`.`sale_date`);
+
+ CREATE OR REPLACE VIEW `top_products` AS select `sales`.`product_name` AS `product_name`,count(0) AS `sale_count`,sum(`sales`.`sale_amount`) AS `total_revenue` from `sales` group by `sales`.`product_name` order by sum(`sales`.`sale_amount`) desc;
+
+ BEGIN
+ DECLARE total DECIMAL(10, 2);
+ SELECT COALESCE(SUM(sale_amount), 0) INTO total
+ FROM sales
+ WHERE YEAR(sale_date) = year AND MONTH(sale_date) = month;
+ RETURN total;
+ END;
+
+ BEGIN
+ SET discount = amount * 0.1;
+ END;
+
+- description: Alter table with column additions, type changes, and constraints
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ description TEXT NOT NULL,
+ category VARCHAR(50),
+ is_active TINYINT(1) DEFAULT 1,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ stock_quantity INT DEFAULT 0,
+ weight DECIMAL(5, 2),
+ PRIMARY KEY (id),
+ INDEX idx_category (category),
+ INDEX idx_price (price),
+ INDEX idx_created_at (created_at),
+ UNIQUE INDEX uk_name_category (name, category),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_stock_non_negative CHECK (stock_quantity >= 0)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL,
+ price DECIMAL(8, 2) NOT NULL,
+ description TEXT,
+ category VARCHAR(30),
+ is_active TINYINT(1) DEFAULT 1,
+ PRIMARY KEY (id),
+ INDEX idx_category (category),
+ INDEX idx_price (price)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+ expected: |+
+ ALTER TABLE `products` DROP CONSTRAINT `chk_price_positive`;
+
+ ALTER TABLE `products` DROP CONSTRAINT `chk_stock_non_negative`;
+
+ DROP INDEX `idx_created_at` ON `products`;
+
+ DROP INDEX `uk_name_category` ON `products`;
+
+ ALTER TABLE `products` DROP COLUMN `created_at`;
+
+ ALTER TABLE `products` DROP COLUMN `stock_quantity`;
+
+ ALTER TABLE `products` DROP COLUMN `updated_at`;
+
+ ALTER TABLE `products` DROP COLUMN `weight`;
+
+
+ ALTER TABLE `products` MODIFY COLUMN `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `price` decimal(8,2) NOT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `category` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+- description: Drop and recreate constraints with different definitions
+ oldSchema: |+
+ --
+ -- Table structure for `authors`
+ --
+ CREATE TABLE `authors` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `email` varchar(100) DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_email` (`email`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `books`
+ --
+ CREATE TABLE `books` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `title` varchar(200) NOT NULL,
+ `author_id` int NOT NULL,
+ `isbn` varchar(20) DEFAULT (NULL),
+ `published_year` int DEFAULT (NULL),
+ `price` decimal(8,2) DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_isbn` (`isbn`),
+ KEY `idx_author` (`author_id`),
+ KEY `idx_year` (`published_year`),
+ CONSTRAINT `fk_author_new` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT `chk_price_positive` CHECK (`price` > 0),
+ CONSTRAINT `chk_year_extended` CHECK ((`published_year` >= 1000) and (`published_year` <= 2030)),
+ CONSTRAINT `chk_title_length` CHECK (char_length(`title`) >= 3)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ newSchema: |
+ CREATE TABLE authors (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE books (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ author_id INT NOT NULL,
+ isbn VARCHAR(20),
+ published_year INT,
+ price DECIMAL(8, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_isbn (isbn),
+ INDEX idx_author (author_id),
+ INDEX idx_year (published_year),
+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),
+ CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),
+ CONSTRAINT chk_price_positive CHECK (price > 0)
+ ) ENGINE=InnoDB;
+ expected: |+
+ ALTER TABLE `books` DROP FOREIGN KEY `fk_author_new`;
+
+ ALTER TABLE `books` DROP CONSTRAINT `chk_title_length`;
+
+ ALTER TABLE `books` DROP CONSTRAINT `chk_year_extended`;
+
+
+ ALTER TABLE `authors` MODIFY COLUMN `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `books` MODIFY COLUMN `isbn` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `books` MODIFY COLUMN `published_year` int DEFAULT NULL;
+
+ ALTER TABLE `books` MODIFY COLUMN `price` decimal(8,2) DEFAULT NULL;
+
+ ALTER TABLE `books` ADD CONSTRAINT `chk_year_valid` CHECK ((`published_year` >= 1000) and (`published_year` <= 2100));
+
+ ALTER TABLE `books` ADD CONSTRAINT `fk_author` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION;
+
+- description: FULLTEXT and SPATIAL indexes
+ oldSchema: |
+ CREATE TABLE articles (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ content TEXT NOT NULL,
+ tags VARCHAR(500),
+ PRIMARY KEY (id),
+ FULLTEXT idx_fulltext_content (title, content),
+ FULLTEXT idx_fulltext_tags (tags),
+ INDEX idx_title_tags (title(50), tags(50))
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE locations (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ position POINT NOT NULL,
+ PRIMARY KEY (id),
+ SPATIAL INDEX idx_spatial_position (position)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE articles (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ content TEXT NOT NULL,
+ tags VARCHAR(500),
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE locations (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ position POINT NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP INDEX `idx_fulltext_content` ON `articles`;
+
+ DROP INDEX `idx_fulltext_tags` ON `articles`;
+
+ DROP INDEX `idx_title_tags` ON `articles`;
+
+ DROP INDEX `idx_spatial_position` ON `locations`;
+
+
+- description: Complex view dependencies with multiple levels
+ oldSchema: |+
+ --
+ -- Temporary view structure for `dept_employee_count`
+ --
+ -- `dept_employee_count` references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+
+ --
+ -- Temporary view structure for `dept_manager_summary`
+ --
+ -- `dept_manager_summary` references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+
+ --
+ -- Temporary view structure for `dept_summary`
+ --
+ -- `dept_summary` references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+
+ --
+ -- Table structure for `departments`
+ --
+ CREATE TABLE `departments` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `manager_id` int DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ KEY `fk_manager` (`manager_id`),
+ CONSTRAINT `fk_manager` FOREIGN KEY (`manager_id`) REFERENCES `employees` (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `employees`
+ --
+ CREATE TABLE `employees` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `department_id` int DEFAULT (NULL),
+ `salary` decimal(10,2) DEFAULT (NULL),
+ `hire_date` date DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ KEY `idx_dept` (`department_id`),
+ CONSTRAINT `fk_dept` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- View structure for `dept_employee_count`
+ --
+ CREATE OR REPLACE VIEW `dept_employee_count` AS select `d`.`id` AS `dept_id`,`d`.`name` AS `dept_name`,count(`e`.`id`) AS `emp_count` from (`departments` `d` left join `employees` `e` on((`d`.`id` = `e`.`department_id`))) group by `d`.`id`,`d`.`name`;
+
+ --
+ -- View structure for `dept_manager_summary`
+ --
+ CREATE OR REPLACE VIEW `dept_manager_summary` AS select `ds`.`dept_id` AS `dept_id`,`ds`.`dept_name` AS `dept_name`,`ds`.`emp_count` AS `emp_count`,`ds`.`avg_salary` AS `avg_salary`,`m`.`name` AS `manager_name` from ((`dept_summary` `ds` join `departments` `d` on((`ds`.`dept_id` = `d`.`id`))) left join `employees` `m` on((`d`.`manager_id` = `m`.`id`)));
+
+ --
+ -- View structure for `dept_summary`
+ --
+ CREATE OR REPLACE VIEW `dept_summary` AS select `dept_employee_count`.`dept_id` AS `dept_id`,`dept_employee_count`.`dept_name` AS `dept_name`,`dept_employee_count`.`emp_count` AS `emp_count`,0 AS `avg_salary`,0 AS `max_salary`,0 AS `min_salary` from `dept_employee_count`;
+
+ newSchema: |
+ CREATE TABLE departments (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ manager_id INT,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE employees (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ department_id INT,
+ salary DECIMAL(10, 2),
+ hire_date DATE,
+ PRIMARY KEY (id),
+ INDEX idx_dept (department_id),
+ CONSTRAINT fk_dept FOREIGN KEY (department_id) REFERENCES departments(id)
+ ) ENGINE=InnoDB;
+
+ -- Add self-referencing foreign key
+ ALTER TABLE departments ADD CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(id);
+ expected: |+
+ CREATE OR REPLACE VIEW `dept_employee_count` AS SELECT 1;
+
+ CREATE OR REPLACE VIEW `dept_manager_summary` AS SELECT 1;
+
+ CREATE OR REPLACE VIEW `dept_summary` AS SELECT 1;
+
+ DROP VIEW IF EXISTS `dept_employee_count`;
+
+ DROP VIEW IF EXISTS `dept_manager_summary`;
+
+ DROP VIEW IF EXISTS `dept_summary`;
+
+
+ ALTER TABLE `departments` MODIFY COLUMN `manager_id` int DEFAULT NULL;
+
+ ALTER TABLE `employees` MODIFY COLUMN `department_id` int DEFAULT NULL;
+
+ ALTER TABLE `employees` MODIFY COLUMN `salary` decimal(10,2) DEFAULT NULL;
+
+ ALTER TABLE `employees` MODIFY COLUMN `hire_date` date DEFAULT NULL;
+
+- description: Circular foreign key dependencies and triggers
+ oldSchema: |+
+ --
+ -- Table structure for `customers`
+ --
+ CREATE TABLE `customers` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `preferred_order_id` int DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ KEY `fk_preferred_order` (`preferred_order_id`),
+ CONSTRAINT `fk_preferred_order` FOREIGN KEY (`preferred_order_id`) REFERENCES `orders` (`id`) ON DELETE SET NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `order_items`
+ --
+ CREATE TABLE `order_items` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `order_id` int NOT NULL,
+ `product_name` varchar(100) NOT NULL,
+ `quantity` int NOT NULL,
+ `unit_price` decimal(10,2) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `idx_order` (`order_id`),
+ CONSTRAINT `fk_order_item` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `orders`
+ --
+ CREATE TABLE `orders` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `customer_id` int NOT NULL,
+ `order_date` datetime DEFAULT CURRENT_TIMESTAMP,
+ `total_amount` decimal(10,2) DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ KEY `fk_customer` (`customer_id`),
+ CONSTRAINT `fk_customer` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Trigger structure for `trg_update_order_total`
+ --
+ DELIMITER ;;
+ CREATE TRIGGER `trg_update_order_total`
+ AFTER INSERT ON `order_items` FOR EACH ROW
+ BEGIN
+ UPDATE orders
+ SET total_amount = (
+ SELECT SUM(quantity * unit_price)
+ FROM order_items
+ WHERE order_id = NEW.order_id
+ )
+ WHERE id = NEW.order_id;
+ END;;
+ DELIMITER ;
+
+ newSchema: |
+ CREATE TABLE customers (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ preferred_order_id INT,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ customer_id INT NOT NULL,
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ total_amount DECIMAL(10, 2),
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP TRIGGER IF EXISTS `trg_update_order_total`;
+
+ ALTER TABLE `customers` DROP FOREIGN KEY `fk_preferred_order`;
+
+ ALTER TABLE `orders` DROP FOREIGN KEY `fk_customer`;
+
+ DROP TABLE IF EXISTS `order_items`;
+
+ DROP INDEX `fk_preferred_order` ON `customers`;
+
+ DROP INDEX `fk_customer` ON `orders`;
+
+
+ ALTER TABLE `customers` MODIFY COLUMN `preferred_order_id` int DEFAULT NULL;
+
+ ALTER TABLE `orders` MODIFY COLUMN `total_amount` decimal(10,2) DEFAULT NULL;
+
+- description: Operations on partitioned tables
+ oldSchema: |+
+ --
+ -- Temporary view structure for `regional_sales`
+ --
+ -- `regional_sales` references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+
+ --
+ -- Table structure for `sales_data`
+ --
+ CREATE TABLE `sales_data` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `sale_date` date NOT NULL,
+ `customer_id` int NOT NULL,
+ `product_id` int NOT NULL,
+ `amount` decimal(10,2) NOT NULL,
+ `region` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`, `sale_date`),
+ KEY `idx_customer` (`customer_id`),
+ KEY `idx_product` (`product_id`),
+ KEY `idx_region_date` (`region`, `sale_date`),
+ CONSTRAINT `chk_amount_positive` CHECK (`amount` > 0)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- View structure for `regional_sales`
+ --
+ CREATE OR REPLACE VIEW `regional_sales` AS select `sales_data`.`region` AS `region`,year(`sales_data`.`sale_date`) AS `year`,month(`sales_data`.`sale_date`) AS `month`,sum(`sales_data`.`amount`) AS `total_sales`,count(distinct `sales_data`.`customer_id`) AS `unique_customers` from `sales_data` group by `sales_data`.`region`,year(`sales_data`.`sale_date`),month(`sales_data`.`sale_date`);
+
+ newSchema: |
+ CREATE TABLE sales_data (
+ id INT NOT NULL AUTO_INCREMENT,
+ sale_date DATE NOT NULL,
+ customer_id INT NOT NULL,
+ product_id INT NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ region VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id, sale_date)
+ ) ENGINE=InnoDB
+ PARTITION BY RANGE (YEAR(sale_date)) (
+ PARTITION p2020 VALUES LESS THAN (2021),
+ PARTITION p2021 VALUES LESS THAN (2022),
+ PARTITION p2022 VALUES LESS THAN (2023),
+ PARTITION p2023 VALUES LESS THAN (2024),
+ PARTITION p_future VALUES LESS THAN MAXVALUE
+ );
+ expected: |+
+ CREATE OR REPLACE VIEW `regional_sales` AS SELECT 1;
+
+ DROP VIEW IF EXISTS `regional_sales`;
+
+ ALTER TABLE `sales_data` DROP CONSTRAINT `chk_amount_positive`;
+
+ DROP INDEX `idx_customer` ON `sales_data`;
+
+ DROP INDEX `idx_product` ON `sales_data`;
+
+ DROP INDEX `idx_region_date` ON `sales_data`;
+
+
+- description: Re-adding a primary key and an overlapping secondary index on a partitioned table
+ oldSchema: |+
+ --
+ -- Table structure for `ads_member_asset_by_account_channel_d`
+ --
+ CREATE TABLE `ads_member_asset_by_account_channel_d` (
+ `dt` date NOT NULL,
+ `member_id` bigint NOT NULL,
+ `account_type` varchar(50) NOT NULL,
+ `net_asset_amount` decimal(38,10) DEFAULT (NULL)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ newSchema: |
+ CREATE TABLE ads_member_asset_by_account_channel_d (
+ dt DATE NOT NULL,
+ member_id BIGINT NOT NULL,
+ account_type VARCHAR(50) NOT NULL,
+ net_asset_amount DECIMAL(38,10) DEFAULT NULL,
+ PRIMARY KEY (dt, member_id, account_type),
+ KEY sindex (dt, member_id, account_type)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
+ PARTITION BY RANGE (TO_DAYS(dt)) (
+ PARTITION p0 VALUES LESS THAN (739000),
+ PARTITION p1 VALUES LESS THAN (739001),
+ PARTITION p2 VALUES LESS THAN (739002),
+ PARTITION p3 VALUES LESS THAN (739003),
+ PARTITION p_future VALUES LESS THAN MAXVALUE
+ );
+ expected: |+
+ ALTER TABLE `ads_member_asset_by_account_channel_d` MODIFY COLUMN `net_asset_amount` decimal(38,10) DEFAULT NULL;
+
+ ALTER TABLE `ads_member_asset_by_account_channel_d` ADD PRIMARY KEY (`dt`, `member_id`, `account_type`);
+
+ CREATE INDEX `sindex` ON `ads_member_asset_by_account_channel_d` (`dt`, `member_id`, `account_type`);
+
+- description: Recreating a partitioned table from metadata
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE ads_member_asset_by_account_channel_d (
+ dt DATE NOT NULL,
+ member_id BIGINT NOT NULL,
+ account_type VARCHAR(50) NOT NULL,
+ net_asset_amount DECIMAL(38,10) DEFAULT NULL,
+ PRIMARY KEY (dt, member_id, account_type),
+ KEY sindex (dt, member_id, account_type)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
+ PARTITION BY RANGE (TO_DAYS(dt)) (
+ PARTITION p0 VALUES LESS THAN (739000),
+ PARTITION p1 VALUES LESS THAN (739001),
+ PARTITION p2 VALUES LESS THAN (739002),
+ PARTITION p_future VALUES LESS THAN MAXVALUE
+ );
+ expected: |+
+ CREATE TABLE IF NOT EXISTS `ads_member_asset_by_account_channel_d` (
+ `dt` date NOT NULL,
+ `member_id` bigint NOT NULL,
+ `account_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
+ `net_asset_amount` decimal(38,10) DEFAULT NULL,
+ PRIMARY KEY (`dt`, `member_id`, `account_type`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
+ /*!50100 PARTITION BY RANGE (to_days(`dt`))
+ (PARTITION `p0` VALUES LESS THAN (739000) ENGINE=InnoDB,
+ PARTITION `p1` VALUES LESS THAN (739001) ENGINE=InnoDB,
+ PARTITION `p2` VALUES LESS THAN (739002) ENGINE=InnoDB,
+ PARTITION `p_future` VALUES LESS THAN MAXVALUE ENGINE=InnoDB) */;
+ CREATE INDEX `sindex` ON `ads_member_asset_by_account_channel_d` (`dt`, `member_id`, `account_type`);
+
+
+- description: Generated columns (virtual and stored)
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ tax_rate DECIMAL(5, 2) DEFAULT 8.0,
+ price_with_tax DECIMAL(10, 2) AS (price * (1 + tax_rate / 100)) STORED,
+ name_upper VARCHAR(100) AS (UPPER(name)) VIRTUAL,
+ PRIMARY KEY (id),
+ INDEX idx_price_with_tax (price_with_tax),
+ INDEX idx_name_upper (name_upper)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE order_summary (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ total_price DECIMAL(10, 2) AS (quantity * unit_price) STORED,
+ order_date DATE NOT NULL,
+ order_year INT AS (YEAR(order_date)) VIRTUAL,
+ order_month INT AS (MONTH(order_date)) VIRTUAL,
+ PRIMARY KEY (id),
+ INDEX idx_year_month (order_year, order_month)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ tax_rate DECIMAL(5, 2) DEFAULT 8.0,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP TABLE IF EXISTS `order_summary`;
+
+ DROP INDEX `idx_name_upper` ON `products`;
+
+ DROP INDEX `idx_price_with_tax` ON `products`;
+
+ ALTER TABLE `products` DROP COLUMN `name_upper`;
+
+ ALTER TABLE `products` DROP COLUMN `price_with_tax`;
+
+
+- description: JSON columns and functional indexes
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ preferences JSON,
+ metadata JSON,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ details JSON NOT NULL,
+ tags JSON,
+ brand VARCHAR(50) AS (details->>'$.brand') VIRTUAL,
+ PRIMARY KEY (id),
+ INDEX idx_product_brand ((CAST(details->>'$.brand' AS CHAR(50)))),
+ INDEX idx_product_price ((CAST(details->>'$.price' AS DECIMAL(10,2)))),
+ INDEX idx_brand (brand),
+ CONSTRAINT chk_details_not_empty CHECK (JSON_TYPE(details) IS NOT NULL)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP TABLE IF EXISTS `products`;
+
+ ALTER TABLE `users` DROP COLUMN `metadata`;
+
+ ALTER TABLE `users` DROP COLUMN `preferences`;
+
+
+- description: Multiple triggers and audit logging
+ oldSchema: |
+ CREATE TABLE inventory (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL DEFAULT 0,
+ last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_product (product_id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE inventory_log (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ old_quantity INT,
+ new_quantity INT,
+ change_type VARCHAR(20),
+ changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TRIGGER trg_inventory_insert
+ AFTER INSERT ON inventory
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (NEW.product_id, NULL, NEW.quantity, 'INSERT');
+ END;
+
+ CREATE TRIGGER trg_inventory_update
+ AFTER UPDATE ON inventory
+ FOR EACH ROW
+ BEGIN
+ IF OLD.quantity != NEW.quantity THEN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (NEW.product_id, OLD.quantity, NEW.quantity, 'UPDATE');
+ END IF;
+ END;
+
+ CREATE TRIGGER trg_inventory_delete
+ BEFORE DELETE ON inventory
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (OLD.product_id, OLD.quantity, NULL, 'DELETE');
+ END;
+
+ CREATE VIEW inventory_changes AS
+ SELECT
+ product_id,
+ COUNT(*) AS change_count,
+ MAX(changed_at) AS last_changed
+ FROM inventory_log
+ GROUP BY product_id;
+ newSchema: |
+ CREATE TABLE inventory (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL DEFAULT 0,
+ last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_product (product_id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE inventory_log (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ old_quantity INT,
+ new_quantity INT,
+ change_type VARCHAR(20),
+ changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP TRIGGER IF EXISTS `trg_inventory_delete`;
+
+ DROP TRIGGER IF EXISTS `trg_inventory_insert`;
+
+ DROP TRIGGER IF EXISTS `trg_inventory_update`;
+
+ CREATE OR REPLACE VIEW `inventory_changes` AS SELECT 1;
+
+ DROP VIEW IF EXISTS `inventory_changes`;
+
+
+- description: Different character sets and collations
+ oldSchema: |+
+ --
+ -- Table structure for `international_content`
+ --
+ CREATE TABLE `international_content` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `english_text` varchar(1000) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL,
+ `chinese_text` varchar(1000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+ `emoji_text` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `messages`
+ --
+ CREATE TABLE `messages` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `content` text NOT NULL,
+ `title` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+ `summary` varchar(500) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `idx_title` (`title`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ newSchema: |
+ CREATE TABLE messages (
+ id INT NOT NULL AUTO_INCREMENT,
+ content TEXT NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+ expected: |+
+ DROP TABLE IF EXISTS `international_content`;
+
+ DROP INDEX `idx_title` ON `messages`;
+
+ ALTER TABLE `messages` DROP COLUMN `summary`;
+
+ ALTER TABLE `messages` DROP COLUMN `title`;
+
+
+- description: Events and advanced stored routines
+ oldSchema: |
+ CREATE TABLE system_stats (
+ id INT NOT NULL AUTO_INCREMENT,
+ stat_name VARCHAR(100) NOT NULL,
+ stat_value DECIMAL(10, 2),
+ recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE EVENT IF NOT EXISTS evt_cleanup_old_stats
+ ON SCHEDULE EVERY 1 DAY
+ STARTS CURRENT_TIMESTAMP
+ DO
+ BEGIN
+ DELETE FROM system_stats
+ WHERE recorded_at < DATE_SUB(NOW(), INTERVAL 30 DAY);
+ END;
+
+ CREATE PROCEDURE RecordSystemStat(
+ IN p_stat_name VARCHAR(100),
+ IN p_stat_value DECIMAL(10, 2)
+ )
+ BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ INSERT INTO system_stats (stat_name, stat_value)
+ VALUES (p_stat_name, p_stat_value);
+
+ COMMIT;
+ END;
+
+ CREATE FUNCTION GetAverageStat(p_stat_name VARCHAR(100))
+ RETURNS DECIMAL(10, 2)
+ DETERMINISTIC
+ READS SQL DATA
+ BEGIN
+ DECLARE avg_value DECIMAL(10, 2);
+
+ SELECT AVG(stat_value) INTO avg_value
+ FROM system_stats
+ WHERE stat_name = p_stat_name
+ AND recorded_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);
+
+ RETURN COALESCE(avg_value, 0);
+ END;
+ newSchema: |
+ CREATE TABLE system_stats (
+ id INT NOT NULL AUTO_INCREMENT,
+ stat_name VARCHAR(100) NOT NULL,
+ stat_value DECIMAL(10, 2),
+ recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP EVENT IF EXISTS `evt_cleanup_old_stats`;
+
+ DROP PROCEDURE IF EXISTS `RecordSystemStat`;
+
+ DROP FUNCTION IF EXISTS `GetAverageStat`;
+
+- description: Add comments to tables and columns using MySQL COMMENT syntax
+ oldSchema: |+
+ --
+ -- Table structure for `categories`
+ --
+ CREATE TABLE `categories` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) NOT NULL COMMENT 'Category display name',
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Product categories for organization';
+
+ --
+ -- Table structure for `products`
+ --
+ CREATE TABLE `products` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL COMMENT 'Product display name',
+ `price` decimal(10,2) NOT NULL COMMENT 'Product price in USD',
+ `description` text DEFAULT NULL COMMENT 'Detailed product description',
+ `category_id` int DEFAULT NULL COMMENT 'Foreign key reference to categories table',
+ `supplier_id` int DEFAULT NULL COMMENT 'Reference to supplier providing this product',
+ PRIMARY KEY (`id`),
+ KEY `idx_category` (`category_id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Product catalog table containing all product information';
+
+ --
+ -- Table structure for `suppliers`
+ --
+ CREATE TABLE `suppliers` (
+ `id` int NOT NULL AUTO_INCREMENT COMMENT 'Unique supplier identifier',
+ `company_name` varchar(100) NOT NULL COMMENT 'Legal company name',
+ `contact_email` varchar(100) DEFAULT NULL COMMENT 'Primary contact email address',
+ `phone` varchar(20) DEFAULT NULL COMMENT 'Business phone number',
+ `address` text DEFAULT NULL COMMENT 'Full business address',
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_email` (`contact_email`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Supplier information and contact details';
+
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ description TEXT,
+ category_id INT,
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP TABLE IF EXISTS `suppliers`;
+
+ ALTER TABLE `products` DROP COLUMN `supplier_id`;
+
+
+ ALTER TABLE `categories` MODIFY COLUMN `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `categories` COMMENT = '';
+
+ ALTER TABLE `products` MODIFY COLUMN `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `price` decimal(10,2) NOT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `category_id` int DEFAULT NULL;
+
+ ALTER TABLE `products` COMMENT = '';
+
+- description: Modify existing comments and remove comments by setting to empty string
+ oldSchema: |+
+ --
+ -- Table structure for `order_items`
+ --
+ CREATE TABLE `order_items` (
+ `id` int NOT NULL AUTO_INCREMENT COMMENT 'Line item identifier',
+ `order_id` int NOT NULL COMMENT 'Reference to parent order',
+ `product_name` varchar(150) NOT NULL COMMENT 'Full product name including variant details',
+ `quantity` int NOT NULL COMMENT 'Quantity ordered (must be positive)',
+ `unit_price` decimal(10,2) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `idx_order` (`order_id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `orders`
+ --
+ CREATE TABLE `orders` (
+ `id` int NOT NULL AUTO_INCREMENT COMMENT 'Order unique identifier',
+ `customer_name` varchar(100) NOT NULL COMMENT 'Full name of the purchasing customer',
+ `order_date` date NOT NULL,
+ `total_amount` decimal(10,2) DEFAULT NULL,
+ `status` varchar(20) DEFAULT 'pending' COMMENT 'Order processing status (pending, processing, shipped, delivered, cancelled)',
+ `notes` text DEFAULT NULL COMMENT 'Special delivery instructions and customer notes',
+ PRIMARY KEY (`id`),
+ KEY `idx_date` (`order_date`),
+ KEY `idx_status` (`status`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Customer purchase orders with tracking information';
+
+ newSchema: |
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Order unique identifier',
+ customer_name VARCHAR(100) NOT NULL COMMENT 'Customer full name',
+ order_date DATE NOT NULL COMMENT 'Date when order was placed',
+ total_amount DECIMAL(10, 2) COMMENT 'Total order amount in USD',
+ status VARCHAR(20) DEFAULT 'pending' COMMENT 'Current order status',
+ notes TEXT COMMENT 'Additional order notes or special instructions',
+ PRIMARY KEY (id),
+ INDEX idx_date (order_date),
+ INDEX idx_status (status)
+ ) ENGINE=InnoDB COMMENT = 'Customer orders and order details';
+
+ CREATE TABLE order_items (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Line item identifier',
+ order_id INT NOT NULL COMMENT 'Reference to parent order',
+ product_name VARCHAR(100) NOT NULL COMMENT 'Name of ordered product',
+ quantity INT NOT NULL COMMENT 'Number of items ordered',
+ unit_price DECIMAL(10, 2) NOT NULL COMMENT 'Price per individual item',
+ PRIMARY KEY (id),
+ INDEX idx_order (order_id)
+ ) ENGINE=InnoDB COMMENT = 'Individual line items for each order';
+ expected: |+
+ ALTER TABLE `order_items` MODIFY COLUMN `product_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Name of ordered product';
+
+ ALTER TABLE `order_items` MODIFY COLUMN `quantity` int NOT NULL COMMENT 'Number of items ordered';
+
+ ALTER TABLE `order_items` MODIFY COLUMN `unit_price` decimal(10,2) NOT NULL COMMENT 'Price per individual item';
+
+ ALTER TABLE `order_items` COMMENT = 'Individual line items for each order';
+
+ ALTER TABLE `orders` MODIFY COLUMN `customer_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'Customer full name';
+
+ ALTER TABLE `orders` MODIFY COLUMN `order_date` date NOT NULL COMMENT 'Date when order was placed';
+
+ ALTER TABLE `orders` MODIFY COLUMN `total_amount` decimal(10,2) DEFAULT NULL COMMENT 'Total order amount in USD';
+
+ ALTER TABLE `orders` MODIFY COLUMN `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT 'pending' COMMENT 'Current order status';
+
+ ALTER TABLE `orders` MODIFY COLUMN `notes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT 'Additional order notes or special instructions';
+
+ ALTER TABLE `orders` COMMENT = 'Customer orders and order details';
+
+- description: Test comments with special characters, quotes, multiline text, and Unicode
+ oldSchema: "--\n-- Table structure for `analytics`\n--\nCREATE TABLE `analytics` (\n `id` int NOT NULL AUTO_INCREMENT COMMENT 'Primary key (auto-increment)',\n `event_name` varchar(100) NOT NULL COMMENT 'Event identifier - format: \"page_view\", \"button_click\", etc.',\n `event_data` json COMMENT 'Event payload: {\"user_id\": 123, \"timestamp\": \"2023-12-01T10:30:00Z\", \"properties\": {...}}',\n `ip_address` varchar(45) DEFAULT NULL COMMENT 'Client IP address (IPv4: xxx.xxx.xxx.xxx or IPv6: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx)',\n `user_agent` text DEFAULT NULL COMMENT 'Browser user agent string - may contain \"Mozilla/5.0\", various browser/OS info',\n `referrer` varchar(500) DEFAULT NULL COMMENT 'HTTP referrer URL - where user came from (can be NULL)',\n `created_at` timestamp DEFAULT CURRENT_TIMESTAMP COMMENT 'Event timestamp - UTC timezone',\n `processed` tinyint(1) DEFAULT '0' COMMENT 'Processing status: TRUE = processed, FALSE = pending',\n PRIMARY KEY (`id`),\n KEY `idx_event_date` (`event_name`, `created_at`),\n KEY `idx_processed` (`processed`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Analytics events tracking - stores user interactions & system events. Data retention: 2 years. Access level: \"admin\" & \"analyst\" roles only.';\n\n--\n-- Table structure for `posts`\n--\nCREATE TABLE `posts` (\n `id` int NOT NULL AUTO_INCREMENT,\n `user_id` int NOT NULL,\n `title` varchar(200) NOT NULL COMMENT 'Post title - supports emojis \U0001F4DD✨\U0001F525\U0001F4A1\U0001F389 and Unicode characters',\n `content` longtext DEFAULT NULL COMMENT 'Post content in HTML format: <p>, <strong>, <em>, <a href=\"...\">, <img src=\"...\"/>',\n `metadata` json COMMENT 'Post metadata: {\"tags\": [\"tag1\", \"tag2\"], \"category\": \"tech\", \"featured\": true, \"views\": 0}',\n PRIMARY KEY (`id`),\n KEY `idx_user` (`user_id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Blog posts and articles - supports international content (中文, العربية, Русский, 日本語, 한국어, Français, Español, Deutsch)';\n\n--\n-- Table structure for `users`\n--\nCREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `username` varchar(50) NOT NULL COMMENT 'User''s chosen \"display name\" for the platform',\n `email` varchar(100) NOT NULL COMMENT 'Primary email address - must be \"unique\" across all users',\n `bio` text DEFAULT NULL COMMENT 'User biography text\nCan contain multiple lines\nand various formatting',\n `preferences` json COMMENT 'User settings: theme, notifications, privacy & security options (@, #, $, %, ^, &, *, +, =, |, \\\\, /, ?, <, >)',\n PRIMARY KEY (`id`),\n UNIQUE KEY `uk_email` (`email`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='User accounts - stores user''s personal information and preferences';\n\n"
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ bio TEXT,
+ preferences JSON,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content LONGTEXT,
+ metadata JSON,
+ PRIMARY KEY (id),
+ INDEX idx_user (user_id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ DROP TABLE IF EXISTS `analytics`;
+
+
+ ALTER TABLE `posts` MODIFY COLUMN `title` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `posts` MODIFY COLUMN `content` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `posts` MODIFY COLUMN `metadata` json DEFAULT NULL;
+
+ ALTER TABLE `posts` COMMENT = '';
+
+ ALTER TABLE `users` MODIFY COLUMN `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `users` MODIFY COLUMN `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `users` MODIFY COLUMN `bio` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `users` MODIFY COLUMN `preferences` json DEFAULT NULL;
+
+ ALTER TABLE `users` COMMENT = '';
+
+- description: 'Reverse: Drop tables with foreign key dependencies'
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE authors (
+ id int NOT NULL AUTO_INCREMENT,
+ name varchar(100) NOT NULL,
+ email varchar(100) DEFAULT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ CREATE TABLE books (
+ id int NOT NULL AUTO_INCREMENT,
+ title varchar(200) NOT NULL,
+ author_id int NOT NULL,
+ isbn varchar(20) DEFAULT NULL,
+ published_year int DEFAULT NULL,
+ price decimal(8,2) DEFAULT NULL,
+ PRIMARY KEY (id),
+ KEY idx_author (author_id),
+ KEY idx_year (published_year),
+ UNIQUE KEY uk_isbn (isbn),
+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors (id),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_year_valid CHECK ((published_year >= 1000) and (published_year <= 2100))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ CREATE TABLE products (
+ id int NOT NULL AUTO_INCREMENT,
+ name varchar(50) NOT NULL,
+ price decimal(8,2) NOT NULL,
+ description text DEFAULT NULL,
+ category varchar(30) DEFAULT NULL,
+ is_active tinyint(1) DEFAULT '1',
+ PRIMARY KEY (id),
+ KEY idx_category (category),
+ KEY idx_price (price)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+ expected: |+
+ CREATE TABLE IF NOT EXISTS `authors` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
+ `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_email` (`email`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ CREATE TABLE IF NOT EXISTS `books` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `title` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
+ `author_id` int NOT NULL,
+ `isbn` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
+ `published_year` int DEFAULT NULL,
+ `price` decimal(8,2) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_isbn` (`isbn`),
+ CONSTRAINT `chk_price_positive` CHECK ((`price` > 0)),
+ CONSTRAINT `chk_year_valid` CHECK (((`published_year` >= 1000) and (`published_year` <= 2100)))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+ CREATE INDEX `idx_author` ON `books` (`author_id`);
+
+ CREATE INDEX `idx_year` ON `books` (`published_year`);
+
+
+ CREATE TABLE IF NOT EXISTS `products` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
+ `price` decimal(8,2) NOT NULL,
+ `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
+ `category` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
+ `is_active` tinyint(1) DEFAULT '1',
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+ CREATE INDEX `idx_category` ON `products` (`category`);
+
+ CREATE INDEX `idx_price` ON `products` (`price`);
+
+
+ ALTER TABLE `books` ADD CONSTRAINT `fk_author` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION;
+
+- description: 'Reverse: Create tables with foreign key constraints'
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ newSchema: ""
+ expected: |+
+ DROP TABLE IF EXISTS `posts`;
+
+ DROP TABLE IF EXISTS `users`;
+
+- description: 'Reverse: Basic table operations'
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ is_active BOOLEAN DEFAULT true,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username),
+ INDEX idx_email_active (email, is_active)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+
+ CREATE TABLE comments (
+ id INT NOT NULL AUTO_INCREMENT,
+ post_id INT NOT NULL,
+ user_id INT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_post_user (post_id, user_id),
+ CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ expected: |+
+ CREATE TABLE IF NOT EXISTS `comments` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `post_id` int NOT NULL,
+ `user_id` int NOT NULL,
+ `content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+ CREATE INDEX `idx_post_user` ON `comments` (`post_id`, `user_id`);
+
+ CREATE INDEX `fk_comment_user` ON `comments` (`user_id`);
+
+
+ ALTER TABLE `comments` ADD CONSTRAINT `fk_comment_post` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE;
+
+ ALTER TABLE `comments` ADD CONSTRAINT `fk_comment_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE NO ACTION ON DELETE CASCADE;
+
+ ALTER TABLE `posts` ADD CONSTRAINT `chk_title_length` CHECK (char_length(`title`) > 0);
+
+ ALTER TABLE `users` ADD COLUMN `is_active` tinyint(1) DEFAULT '1';
+
+ CREATE INDEX `idx_email_active` ON `users` (`email`, `is_active`);
+
+- description: 'Reverse: Views and triggers'
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ ) ENGINE=InnoDB;
+
+ CREATE VIEW product_inventory AS
+ SELECT
+ p.id,
+ p.name,
+ p.price,
+ p.stock,
+ COALESCE(SUM(o.quantity), 0) AS total_ordered
+ FROM products p
+ LEFT JOIN orders o ON p.id = o.product_id
+ GROUP BY p.id, p.name, p.price, p.stock;
+
+ CREATE VIEW low_stock_products AS
+ SELECT * FROM products WHERE stock < 10;
+
+ CREATE TRIGGER update_order_total
+ BEFORE INSERT ON orders
+ FOR EACH ROW
+ BEGIN
+ DECLARE product_price DECIMAL(10, 2);
+ SELECT price INTO product_price FROM products WHERE id = NEW.product_id;
+ SET NEW.total = NEW.quantity * product_price;
+ END;
+
+ CREATE PROCEDURE GetProductInventory(IN product_name VARCHAR(100))
+ BEGIN
+ SELECT * FROM product_inventory
+ WHERE name LIKE CONCAT('%', product_name, '%');
+ END;
+ expected: |+
+ CREATE VIEW `low_stock_products` AS SELECT 1;
+
+ CREATE VIEW `product_inventory` AS SELECT 1;
+
+ CREATE TRIGGER `update_order_total` BEFORE INSERT ON `orders` FOR EACH ROW BEGIN
+ DECLARE product_price DECIMAL(10, 2);
+ SELECT price INTO product_price FROM products WHERE id = NEW.product_id;
+ SET NEW.total = NEW.quantity * product_price;
+ END;
+
+ CREATE OR REPLACE VIEW `low_stock_products` AS select `products`.`id` AS `id`,`products`.`name` AS `name`,`products`.`price` AS `price`,`products`.`stock` AS `stock` from `products` where (`products`.`stock` < 10);
+
+ CREATE OR REPLACE VIEW `product_inventory` AS select `p`.`id` AS `id`,`p`.`name` AS `name`,`p`.`price` AS `price`,`p`.`stock` AS `stock`,coalesce(sum(`o`.`quantity`),0) AS `total_ordered` from (`products` `p` left join `orders` `o` on((`p`.`id` = `o`.`product_id`))) group by `p`.`id`,`p`.`name`,`p`.`price`,`p`.`stock`;
+
+ BEGIN
+ SELECT * FROM product_inventory
+ WHERE name LIKE CONCAT('%', product_name, '%');
+ END;
+
+- description: 'Reverse: Stored functions'
+ oldSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_id, sale_date)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_id, sale_date)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE sales_summary (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ month_year VARCHAR(7) NOT NULL,
+ total_sales DECIMAL(10, 2),
+ tax_amount DECIMAL(10, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_product_month (product_id, month_year)
+ ) ENGINE=InnoDB;
+
+ CREATE FUNCTION CalculateTotalSales(p_product_id INT, p_start_date DATE, p_end_date DATE)
+ RETURNS DECIMAL(10, 2)
+ DETERMINISTIC
+ READS SQL DATA
+ BEGIN
+ DECLARE total DECIMAL(10, 2);
+
+ SELECT COALESCE(SUM(quantity * unit_price), 0) INTO total
+ FROM sales
+ WHERE product_id = p_product_id
+ AND sale_date BETWEEN p_start_date AND p_end_date;
+
+ RETURN total;
+ END;
+
+ CREATE FUNCTION GetTaxAmount(amount DECIMAL(10, 2), tax_rate DECIMAL(5, 2))
+ RETURNS DECIMAL(10, 2)
+ DETERMINISTIC
+ NO SQL
+ BEGIN
+ RETURN amount * (tax_rate / 100);
+ END;
+ expected: |+
+ CREATE TABLE IF NOT EXISTS `sales_summary` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `product_id` int NOT NULL,
+ `month_year` varchar(7) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
+ `total_sales` decimal(10,2) DEFAULT NULL,
+ `tax_amount` decimal(10,2) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_product_month` (`product_id`, `month_year`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ BEGIN
+ DECLARE total DECIMAL(10, 2);
+
+ SELECT COALESCE(SUM(quantity * unit_price), 0) INTO total
+ FROM sales
+ WHERE product_id = p_product_id
+ AND sale_date BETWEEN p_start_date AND p_end_date;
+
+ RETURN total;
+ END;
+
+ BEGIN
+ RETURN amount * (tax_rate / 100);
+ END;
+
+- description: 'Reverse: Add indexes and constraints'
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category VARCHAR(50),
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_sku (sku),
+ INDEX idx_name (name),
+ INDEX idx_category (category),
+ INDEX idx_price (price),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category VARCHAR(50),
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ expected: |+
+ ALTER TABLE `products` DROP CONSTRAINT `chk_name_length`;
+
+ ALTER TABLE `products` DROP CONSTRAINT `chk_price_positive`;
+
+ DROP INDEX `idx_category` ON `products`;
+
+ DROP INDEX `idx_name` ON `products`;
+
+ DROP INDEX `idx_price` ON `products`;
+
+ DROP INDEX `uk_sku` ON `products`;
+
+
+- description: 'Reverse: Alter table columns'
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL,
+ price DECIMAL(8, 2) NOT NULL,
+ description TEXT,
+ category VARCHAR(30),
+ is_active TINYINT(1) DEFAULT 1,
+ PRIMARY KEY (id),
+ INDEX idx_category (category),
+ INDEX idx_price (price)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ description TEXT NOT NULL,
+ category VARCHAR(50),
+ is_active TINYINT(1) DEFAULT 1,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ stock_quantity INT DEFAULT 0,
+ weight DECIMAL(5, 2),
+ PRIMARY KEY (id),
+ INDEX idx_category (category),
+ INDEX idx_price (price),
+ INDEX idx_created_at (created_at),
+ UNIQUE INDEX uk_name_category (name, category),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_stock_non_negative CHECK (stock_quantity >= 0)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+ expected: |+
+ ALTER TABLE `products` ADD COLUMN `created_at` timestamp DEFAULT CURRENT_TIMESTAMP;
+
+ ALTER TABLE `products` ADD COLUMN `updated_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
+
+ ALTER TABLE `products` ADD COLUMN `stock_quantity` int DEFAULT '0';
+
+ ALTER TABLE `products` ADD COLUMN `weight` decimal(5,2) DEFAULT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `price` decimal(10,2) NOT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;
+
+ ALTER TABLE `products` MODIFY COLUMN `category` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ CREATE INDEX `idx_created_at` ON `products` (`created_at`);
+
+ ALTER TABLE `products` ADD UNIQUE KEY `uk_name_category` (`name`, `category`);
+
+ ALTER TABLE `products` ADD CONSTRAINT `chk_price_positive` CHECK (`price` > 0);
+
+ ALTER TABLE `products` ADD CONSTRAINT `chk_stock_non_negative` CHECK (`stock_quantity` >= 0);
+
+- description: 'Reverse: Drop FULLTEXT and SPATIAL indexes'
+ oldSchema: |
+ CREATE TABLE articles (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ content TEXT NOT NULL,
+ tags VARCHAR(500),
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE locations (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ position POINT NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE articles (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ content TEXT NOT NULL,
+ tags VARCHAR(500),
+ PRIMARY KEY (id),
+ FULLTEXT idx_fulltext_content (title, content),
+ FULLTEXT idx_fulltext_tags (tags),
+ INDEX idx_title_tags (title(50), tags(50))
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE locations (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ position POINT NOT NULL,
+ PRIMARY KEY (id),
+ SPATIAL INDEX idx_spatial_position (position)
+ ) ENGINE=InnoDB;
+ expected: |+
+ CREATE FULLTEXT INDEX `idx_fulltext_content` ON `articles` (`title`, `content`);
+
+ CREATE FULLTEXT INDEX `idx_fulltext_tags` ON `articles` (`tags`);
+
+ CREATE INDEX `idx_title_tags` ON `articles` (`title`(50), `tags`(50));
+
+ CREATE SPATIAL INDEX `idx_spatial_position` ON `locations` (`position`);
+
+- description: 'Reverse: Drop generated columns'
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ tax_rate DECIMAL(5, 2) DEFAULT 8.0,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ tax_rate DECIMAL(5, 2) DEFAULT 8.0,
+ price_with_tax DECIMAL(10, 2) AS (price * (1 + tax_rate / 100)) STORED,
+ name_upper VARCHAR(100) AS (UPPER(name)) VIRTUAL,
+ PRIMARY KEY (id),
+ INDEX idx_price_with_tax (price_with_tax),
+ INDEX idx_name_upper (name_upper)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE order_summary (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ total_price DECIMAL(10, 2) AS (quantity * unit_price) STORED,
+ order_date DATE NOT NULL,
+ order_year INT AS (YEAR(order_date)) VIRTUAL,
+ order_month INT AS (MONTH(order_date)) VIRTUAL,
+ PRIMARY KEY (id),
+ INDEX idx_year_month (order_year, order_month)
+ ) ENGINE=InnoDB;
+ expected: |+
+ CREATE TABLE IF NOT EXISTS `order_summary` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `product_id` int NOT NULL,
+ `quantity` int NOT NULL,
+ `unit_price` decimal(10,2) NOT NULL,
+ `total_price` decimal(10,2) GENERATED ALWAYS AS ((`quantity` * `unit_price`)) STORED,
+ `order_date` date NOT NULL,
+ `order_year` int GENERATED ALWAYS AS (year(`order_date`)) VIRTUAL,
+ `order_month` int GENERATED ALWAYS AS (month(`order_date`)) VIRTUAL,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+ CREATE INDEX `idx_year_month` ON `order_summary` (`order_year`, `order_month`);
+
+
+ ALTER TABLE `products` ADD COLUMN `price_with_tax` decimal(10,2) GENERATED ALWAYS AS ((`price` * ((1 + (`tax_rate` / 100))))) STORED;
+
+ ALTER TABLE `products` ADD COLUMN `name_upper` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci GENERATED ALWAYS AS (upper(`name`)) VIRTUAL;
+
+ CREATE INDEX `idx_name_upper` ON `products` (`name_upper`);
+
+ CREATE INDEX `idx_price_with_tax` ON `products` (`price_with_tax`);
+
+- description: 'Reverse: Drop JSON columns and indexes'
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ preferences JSON,
+ metadata JSON,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ details JSON NOT NULL,
+ tags JSON,
+ brand VARCHAR(50) AS (details->>'$.brand') VIRTUAL,
+ PRIMARY KEY (id),
+ INDEX idx_product_brand ((CAST(details->>'$.brand' AS CHAR(50)))),
+ INDEX idx_product_price ((CAST(details->>'$.price' AS DECIMAL(10,2)))),
+ INDEX idx_brand (brand),
+ CONSTRAINT chk_details_not_empty CHECK (JSON_TYPE(details) IS NOT NULL)
+ ) ENGINE=InnoDB;
+ expected: |+
+ CREATE TABLE IF NOT EXISTS `products` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
+ `details` json NOT NULL,
+ `tags` json DEFAULT NULL,
+ `brand` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci GENERATED ALWAYS AS (json_unquote(json_extract(`details`,_utf8mb4'$.brand'))) VIRTUAL,
+ PRIMARY KEY (`id`),
+ CONSTRAINT `chk_details_not_empty` CHECK ((json_type(`details`) is not null))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+ CREATE INDEX `idx_product_brand` ON `products` (`cast(json_unquote(json_extract(`details`,_utf8mb4'$.brand')) as char(50) charset utf8mb4)`);
+
+ CREATE INDEX `idx_product_price` ON `products` (`cast(json_unquote(json_extract(`details`,_utf8mb4'$.price')) as decimal(10,2))`);
+
+ CREATE INDEX `idx_brand` ON `products` (`brand`);
+
+
+ ALTER TABLE `users` ADD COLUMN `preferences` json DEFAULT NULL;
+
+ ALTER TABLE `users` ADD COLUMN `metadata` json DEFAULT NULL;
+
+- description: 'Reverse: Drop triggers and views'
+ oldSchema: |
+ CREATE TABLE inventory (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL DEFAULT 0,
+ last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_product (product_id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE inventory_log (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ old_quantity INT,
+ new_quantity INT,
+ change_type VARCHAR(20),
+ changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE inventory (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ quantity INT NOT NULL DEFAULT 0,
+ last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_product (product_id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE inventory_log (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ old_quantity INT,
+ new_quantity INT,
+ change_type VARCHAR(20),
+ changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TRIGGER trg_inventory_insert
+ AFTER INSERT ON inventory
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (NEW.product_id, NULL, NEW.quantity, 'INSERT');
+ END;
+
+ CREATE TRIGGER trg_inventory_update
+ AFTER UPDATE ON inventory
+ FOR EACH ROW
+ BEGIN
+ IF OLD.quantity != NEW.quantity THEN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (NEW.product_id, OLD.quantity, NEW.quantity, 'UPDATE');
+ END IF;
+ END;
+
+ CREATE TRIGGER trg_inventory_delete
+ BEFORE DELETE ON inventory
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (OLD.product_id, OLD.quantity, NULL, 'DELETE');
+ END;
+
+ CREATE VIEW inventory_changes AS
+ SELECT
+ product_id,
+ COUNT(*) AS change_count,
+ MAX(changed_at) AS last_changed
+ FROM inventory_log
+ GROUP BY product_id;
+ expected: |+
+ CREATE VIEW `inventory_changes` AS SELECT 1;
+
+ CREATE TRIGGER `trg_inventory_delete` BEFORE DELETE ON `inventory` FOR EACH ROW BEGIN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (OLD.product_id, OLD.quantity, NULL, 'DELETE');
+ END;
+
+ CREATE TRIGGER `trg_inventory_insert` AFTER INSERT ON `inventory` FOR EACH ROW BEGIN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (NEW.product_id, NULL, NEW.quantity, 'INSERT');
+ END;
+
+ CREATE TRIGGER `trg_inventory_update` AFTER UPDATE ON `inventory` FOR EACH ROW BEGIN
+ IF OLD.quantity != NEW.quantity THEN
+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)
+ VALUES (NEW.product_id, OLD.quantity, NEW.quantity, 'UPDATE');
+ END IF;
+ END;
+
+ CREATE OR REPLACE VIEW `inventory_changes` AS select `inventory_log`.`product_id` AS `product_id`,count(0) AS `change_count`,max(`inventory_log`.`changed_at`) AS `last_changed` from `inventory_log` group by `inventory_log`.`product_id`;
+
+- description: 'Reverse: Drop events and advanced features'
+ oldSchema: |
+ CREATE TABLE system_stats (
+ id INT NOT NULL AUTO_INCREMENT,
+ stat_name VARCHAR(100) NOT NULL,
+ stat_value DECIMAL(10, 2),
+ recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+ newSchema: |
+ CREATE TABLE system_stats (
+ id INT NOT NULL AUTO_INCREMENT,
+ stat_name VARCHAR(100) NOT NULL,
+ stat_value DECIMAL(10, 2),
+ recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE EVENT IF NOT EXISTS evt_cleanup_old_stats
+ ON SCHEDULE EVERY 1 DAY
+ STARTS CURRENT_TIMESTAMP
+ DO
+ BEGIN
+ DELETE FROM system_stats
+ WHERE recorded_at < DATE_SUB(NOW(), INTERVAL 30 DAY);
+ END;
+
+ CREATE PROCEDURE RecordSystemStat(
+ IN p_stat_name VARCHAR(100),
+ IN p_stat_value DECIMAL(10, 2)
+ )
+ BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ INSERT INTO system_stats (stat_name, stat_value)
+ VALUES (p_stat_name, p_stat_value);
+
+ COMMIT;
+ END;
+
+ CREATE FUNCTION GetAverageStat(p_stat_name VARCHAR(100))
+ RETURNS DECIMAL(10, 2)
+ DETERMINISTIC
+ READS SQL DATA
+ BEGIN
+ DECLARE avg_value DECIMAL(10, 2);
+
+ SELECT AVG(stat_value) INTO avg_value
+ FROM system_stats
+ WHERE stat_name = p_stat_name
+ AND recorded_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);
+
+ RETURN COALESCE(avg_value, 0);
+ END;
+ expected: |+
+ BEGIN
+ DECLARE avg_value DECIMAL(10, 2);
+
+ SELECT AVG(stat_value) INTO avg_value
+ FROM system_stats
+ WHERE stat_name = p_stat_name
+ AND recorded_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);
+
+ RETURN COALESCE(avg_value, 0);
+ END;
+
+ BEGIN
+ DECLARE EXIT HANDLER FOR SQLEXCEPTION
+ BEGIN
+ ROLLBACK;
+ RESIGNAL;
+ END;
+
+ START TRANSACTION;
+
+ INSERT INTO system_stats (stat_name, stat_value)
+ VALUES (p_stat_name, p_stat_value);
+
+ COMMIT;
+ END;
+
+ CREATE DEFINER=`root`@`%` EVENT `evt_cleanup_old_stats` ON SCHEDULE EVERY 1 DAY
+ STARTS CURRENT_TIMESTAMP ON COMPLETION NOT PRESERVE ENABLE DO BEGIN
+ DELETE FROM system_stats
+ WHERE recorded_at < DATE_SUB(NOW(), INTERVAL 30 DAY);
+ END;
+
+- description: Verify no migration generated for identical schemas (tests primary key, index, check constraints, DEFAULT NULL fixes)
+ oldSchema: |+
+ --
+ -- Table structure for `some_table`
+ --
+ CREATE TABLE `some_table` (
+ `id` int NOT NULL,
+ `a` int NOT NULL,
+ PRIMARY KEY (`id`),
+ CONSTRAINT `some_table_chk_1` CHECK (`a` in (1,2,3))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` char(255) DEFAULT (NULL),
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `t1`
+ --
+ CREATE TABLE `t1` (
+ `id` int NOT NULL,
+ `a` int NOT NULL,
+ `b` int DEFAULT (NULL),
+ `c` int DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ KEY `b` (`b`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `test_table`
+ --
+ CREATE TABLE `test_table` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) DEFAULT (NULL),
+ `email` varchar(100) DEFAULT (NULL),
+ `status` varchar(20) DEFAULT ('active'),
+ `age` int DEFAULT (NULL),
+ `score` decimal(5,2) DEFAULT (NULL),
+ PRIMARY KEY (`id`),
+ KEY `idx_name` (`name`),
+ KEY `idx_status_hash` (`status`),
+ UNIQUE KEY `uk_email` (`email`),
+ CONSTRAINT `chk_age` CHECK (`age` >= 18),
+ CONSTRAINT `chk_status` CHECK (`status` in ('active','inactive','pending'))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ newSchema: |
+ -- Test that identical schemas don't generate unnecessary migrations
+ -- This tests the fixes for primary key, index type, check constraints, and DEFAULT NULL
+
+ CREATE TABLE test_table (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) DEFAULT NULL,
+ email VARCHAR(100),
+ status VARCHAR(20) DEFAULT 'active',
+ age INT DEFAULT NULL,
+ score DECIMAL(5,2),
+ PRIMARY KEY (id),
+ INDEX idx_name (name),
+ INDEX idx_status_hash (status) USING HASH,
+ UNIQUE KEY uk_email (email),
+ CONSTRAINT chk_age CHECK (age >= 18),
+ CONSTRAINT chk_status CHECK (status IN ('active', 'inactive', 'pending'))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+ -- Table with various column types and defaults
+ CREATE TABLE t (
+ id INT NOT NULL AUTO_INCREMENT,
+ name CHAR(255) DEFAULT NULL,
+ PRIMARY KEY (id)
+ ) ENGINE=InnoDB;
+
+ CREATE TABLE t1 (
+ id INT NOT NULL,
+ a INT NOT NULL,
+ b INT DEFAULT NULL,
+ c INT,
+ PRIMARY KEY (id),
+ INDEX b (b) USING HASH
+ ) ENGINE=InnoDB;
+
+ -- Table with check constraint that has spaces
+ CREATE TABLE some_table (
+ id INT PRIMARY KEY,
+ a INT NOT NULL,
+ CONSTRAINT some_table_chk_1 CHECK (a IN (1, 2, 3))
+ ) ENGINE=InnoDB;
+ expected: |+
+ ALTER TABLE `t` MODIFY COLUMN `name` char(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `t1` MODIFY COLUMN `b` int DEFAULT NULL;
+
+ ALTER TABLE `t1` MODIFY COLUMN `c` int DEFAULT NULL;
+
+ ALTER TABLE `test_table` MODIFY COLUMN `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `test_table` MODIFY COLUMN `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL;
+
+ ALTER TABLE `test_table` MODIFY COLUMN `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT 'active';
+
+ ALTER TABLE `test_table` MODIFY COLUMN `age` int DEFAULT NULL;
+
+ ALTER TABLE `test_table` MODIFY COLUMN `score` decimal(5,2) DEFAULT NULL;
+
diff --git a/backend/plugin/schema/mysql/testdata/get_database_definition.yaml b/backend/plugin/schema/mysql/testdata/get_database_definition.yaml
new file mode 100644
index 0000000000..44c1877716
--- /dev/null
+++ b/backend/plugin/schema/mysql/testdata/get_database_definition.yaml
@@ -0,0 +1,2201 @@
+- description: Basic tables with various column types
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "posts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "title",
+ "position": 3,
+ "type": "varchar(200)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "content",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "published_at",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "datetime"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_user_published",
+ "expressions": [
+ "user_id",
+ "published_at"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "posts_ibfk_1",
+ "columns": [
+ "user_id"
+ ],
+ "referenced_table": "users",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "CASCADE"
+ }
+ ]
+ },
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "username",
+ "position": 2,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "age",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "updated_at",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "on_update": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "profile",
+ "position": 7,
+ "default": "NULL",
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "is_active",
+ "position": 8,
+ "default": "'1'",
+ "nullable": true,
+ "type": "tinyint(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "username",
+ "expressions": [
+ "username"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "idx_email",
+ "expressions": [
+ "email"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_created_at",
+ "expressions": [
+ "created_at"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "check_constraints": [
+ {
+ "name": "users_chk_1",
+ "expression": "(`age` \u003e= 18)"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `posts`
+ --
+ CREATE TABLE `posts` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `user_id` int NOT NULL,
+ `title` varchar(200) NOT NULL,
+ `content` text DEFAULT NULL,
+ `published_at` datetime DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `idx_user_published` (`user_id`, `published_at`),
+ CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `users`
+ --
+ CREATE TABLE `users` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `username` varchar(50) NOT NULL,
+ `email` varchar(100) NOT NULL,
+ `age` int DEFAULT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ `updated_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ `profile` json,
+ `is_active` tinyint(1) DEFAULT '1',
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `username` (`username`),
+ KEY `idx_email` (`email`),
+ KEY `idx_created_at` (`created_at`),
+ CONSTRAINT `users_chk_1` CHECK (`age` >= 18)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Generated columns and complex indexes
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "inventory",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "product_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "warehouse",
+ "position": 3,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "quantity",
+ "position": 4,
+ "default": "'0'",
+ "type": "int"
+ },
+ {
+ "name": "last_updated",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "on_update": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "uk_product_warehouse",
+ "expressions": [
+ "product_id",
+ "warehouse"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "inventory_ibfk_1",
+ "columns": [
+ "product_id"
+ ],
+ "referenced_table": "products",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION"
+ }
+ ]
+ },
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "price",
+ "position": 3,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "tax_rate",
+ "position": 4,
+ "default": "'0.08'",
+ "type": "decimal(5,2)"
+ },
+ {
+ "name": "price_with_tax",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)",
+ "generation": {
+ "type": 2,
+ "expression": "(`price` * ((1 + `tax_rate`)))"
+ }
+ },
+ {
+ "name": "description",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "tags",
+ "position": 7,
+ "default": "NULL",
+ "nullable": true,
+ "type": "json"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_fulltext",
+ "expressions": [
+ "name",
+ "description"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "FULLTEXT",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `inventory`
+ --
+ CREATE TABLE `inventory` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `product_id` int NOT NULL,
+ `warehouse` varchar(50) NOT NULL,
+ `quantity` int NOT NULL DEFAULT '0',
+ `last_updated` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_product_warehouse` (`product_id`, `warehouse`),
+ CONSTRAINT `inventory_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `products`
+ --
+ CREATE TABLE `products` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `price` decimal(10,2) NOT NULL,
+ `tax_rate` decimal(5,2) NOT NULL DEFAULT '0.08',
+ `price_with_tax` decimal(10,2) GENERATED ALWAYS AS ((`price` * ((1 + `tax_rate`)))) STORED,
+ `description` text DEFAULT NULL,
+ `tags` json,
+ PRIMARY KEY (`id`),
+ FULLTEXT KEY `idx_fulltext` (`name`, `description`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Views and triggers
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "order_history",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "order_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "old_status",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "new_status",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "changed_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "order_id",
+ "expressions": [
+ "order_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "order_history_ibfk_1",
+ "columns": [
+ "order_id"
+ ],
+ "referenced_table": "orders",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION"
+ }
+ ]
+ },
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "order_number",
+ "position": 2,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "customer_name",
+ "position": 3,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "total_amount",
+ "position": 4,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "status",
+ "position": 5,
+ "default": "'pending'",
+ "nullable": true,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "created_at",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "order_number",
+ "expressions": [
+ "order_number"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "triggers": [
+ {
+ "name": "order_status_change",
+ "event": "UPDATE",
+ "timing": "AFTER",
+ "body": "BEGIN\n IF OLD.status != NEW.status THEN\n INSERT INTO order_history (order_id, old_status, new_status)\n VALUES (NEW.id, OLD.status, NEW.status);\n END IF;\nEND"
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "pending_orders",
+ "definition": "select `orders`.`id` AS `id`,`orders`.`order_number` AS `order_number`,`orders`.`customer_name` AS `customer_name`,`orders`.`total_amount` AS `total_amount`,`orders`.`created_at` AS `created_at` from `orders` where (`orders`.`status` = 'pending') order by `orders`.`created_at` desc"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `pending_orders`
+ --
+ -- `pending_orders` references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+
+ --
+ -- Table structure for `order_history`
+ --
+ CREATE TABLE `order_history` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `order_id` int NOT NULL,
+ `old_status` varchar(20) DEFAULT NULL,
+ `new_status` varchar(20) DEFAULT NULL,
+ `changed_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ KEY `order_id` (`order_id`),
+ CONSTRAINT `order_history_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `orders`
+ --
+ CREATE TABLE `orders` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `order_number` varchar(20) NOT NULL,
+ `customer_name` varchar(100) NOT NULL,
+ `total_amount` decimal(10,2) NOT NULL,
+ `status` varchar(20) DEFAULT 'pending',
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `order_number` (`order_number`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- View structure for `pending_orders`
+ --
+ CREATE OR REPLACE VIEW `pending_orders` AS select `orders`.`id` AS `id`,`orders`.`order_number` AS `order_number`,`orders`.`customer_name` AS `customer_name`,`orders`.`total_amount` AS `total_amount`,`orders`.`created_at` AS `created_at` from `orders` where (`orders`.`status` = 'pending') order by `orders`.`created_at` desc;
+
+ --
+ -- Trigger structure for `order_status_change`
+ --
+ SET character_set_client = ;
+ SET character_set_results = ;
+ SET collation_connection = ;
+ SET sql_mode = '';
+ DELIMITER ;;
+ CREATE TRIGGER `order_status_change`
+ AFTER UPDATE ON `orders` FOR EACH ROW
+ BEGIN
+ IF OLD.status != NEW.status THEN
+ INSERT INTO order_history (order_id, old_status, new_status)
+ VALUES (NEW.id, OLD.status, NEW.status);
+ END IF;
+ END;;
+ DELIMITER ;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Stored procedures and functions
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "accounts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "account_number",
+ "position": 2,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "balance",
+ "position": 3,
+ "default": "'0.00'",
+ "type": "decimal(15,2)"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "account_number",
+ "expressions": [
+ "account_number"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ],
+ "functions": [
+ {
+ "name": "calculate_interest",
+ "definition": "CREATE FUNCTION `calculate_interest`(principal DECIMAL(15,2), rate DECIMAL(5,4), years INT) RETURNS decimal(15,2) READS SQL DATA DETERMINISTIC\nBEGIN\n RETURN principal * POW(1 + rate, years);\nEND"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "transfer_funds",
+ "definition": "CREATE PROCEDURE `transfer_funds`(IN from_account VARCHAR(20), IN to_account VARCHAR(20), IN amount DECIMAL(15,2))\nBEGIN\n DECLARE from_balance DECIMAL(15, 2);\n\n START TRANSACTION;\n\n SELECT balance INTO from_balance\n FROM accounts\n WHERE account_number = from_account\n FOR UPDATE;\n\n IF from_balance \u003e= amount THEN\n UPDATE accounts\n SET balance = balance - amount\n WHERE account_number = from_account;\n\n UPDATE accounts\n SET balance = balance + amount\n WHERE account_number = to_account;\n\n COMMIT;\n ELSE\n ROLLBACK;\n SIGNAL SQLSTATE '45000'\n SET MESSAGE_TEXT = 'Insufficient funds';\n END IF;\nEND"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `accounts`
+ --
+ CREATE TABLE `accounts` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `account_number` varchar(20) NOT NULL,
+ `balance` decimal(15,2) NOT NULL DEFAULT '0.00',
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `account_number` (`account_number`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Function structure for `calculate_interest`
+ --
+ CREATE FUNCTION `calculate_interest`(principal DECIMAL(15,2), rate DECIMAL(5,4), years INT) RETURNS decimal(15,2) READS SQL DATA DETERMINISTIC
+ BEGIN
+ RETURN principal * POW(1 + rate, years);
+ END;;
+ DELIMITER ;
+
+ --
+ -- Procedure structure for `transfer_funds`
+ --
+ DELIMITER ;;
+ CREATE PROCEDURE `transfer_funds`(IN from_account VARCHAR(20), IN to_account VARCHAR(20), IN amount DECIMAL(15,2))
+ BEGIN
+ DECLARE from_balance DECIMAL(15, 2);
+
+ START TRANSACTION;
+
+ SELECT balance INTO from_balance
+ FROM accounts
+ WHERE account_number = from_account
+ FOR UPDATE;
+
+ IF from_balance >= amount THEN
+ UPDATE accounts
+ SET balance = balance - amount
+ WHERE account_number = from_account;
+
+ UPDATE accounts
+ SET balance = balance + amount
+ WHERE account_number = to_account;
+
+ COMMIT;
+ ELSE
+ ROLLBACK;
+ SIGNAL SQLSTATE '45000'
+ SET MESSAGE_TEXT = 'Insufficient funds';
+ END IF;
+ END;;
+ DELIMITER ;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Partitioned tables
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "customer_regions",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "customer_name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "region",
+ "position": 3,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "sales_amount",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "region"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p_north",
+ "type": 4,
+ "expression": "region",
+ "value": "'north','northeast','northwest'"
+ },
+ {
+ "name": "p_south",
+ "type": 4,
+ "expression": "region",
+ "value": "'south','southeast','southwest'"
+ },
+ {
+ "name": "p_east",
+ "type": 4,
+ "expression": "region",
+ "value": "'east'"
+ },
+ {
+ "name": "p_west",
+ "type": 4,
+ "expression": "region",
+ "value": "'west'"
+ },
+ {
+ "name": "p_central",
+ "type": 4,
+ "expression": "region",
+ "value": "'central'"
+ }
+ ]
+ },
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "department_id",
+ "position": 3,
+ "type": "int"
+ },
+ {
+ "name": "hired_date",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "date"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p0",
+ "type": 5,
+ "expression": "`id`"
+ },
+ {
+ "name": "p1",
+ "type": 5,
+ "expression": "`id`"
+ },
+ {
+ "name": "p2",
+ "type": 5,
+ "expression": "`id`"
+ },
+ {
+ "name": "p3",
+ "type": 5,
+ "expression": "`id`"
+ }
+ ]
+ },
+ {
+ "name": "order_archive",
+ "columns": [
+ {
+ "name": "order_id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "order_date",
+ "position": 2,
+ "type": "date"
+ },
+ {
+ "name": "customer_id",
+ "position": 3,
+ "type": "int"
+ },
+ {
+ "name": "status",
+ "position": 4,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "total_amount",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "order_id",
+ "order_date"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p_2022_q1",
+ "type": 2,
+ "expression": "order_date",
+ "value": "'2022-04-01'"
+ },
+ {
+ "name": "p_2022_q2",
+ "type": 2,
+ "expression": "order_date",
+ "value": "'2022-07-01'"
+ },
+ {
+ "name": "p_2022_q3",
+ "type": 2,
+ "expression": "order_date",
+ "value": "'2022-10-01'"
+ },
+ {
+ "name": "p_2022_q4",
+ "type": 2,
+ "expression": "order_date",
+ "value": "'2023-01-01'"
+ },
+ {
+ "name": "p_2023_and_later",
+ "type": 2,
+ "expression": "order_date",
+ "value": "MAXVALUE"
+ }
+ ]
+ },
+ {
+ "name": "sales",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "sale_date",
+ "position": 2,
+ "type": "date"
+ },
+ {
+ "name": "product_id",
+ "position": 3,
+ "type": "int"
+ },
+ {
+ "name": "quantity",
+ "position": 4,
+ "type": "int"
+ },
+ {
+ "name": "amount",
+ "position": 5,
+ "type": "decimal(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "sale_date"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p2022",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2023"
+ },
+ {
+ "name": "p2023",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2024"
+ },
+ {
+ "name": "p2024",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2025"
+ },
+ {
+ "name": "p_future",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "MAXVALUE"
+ }
+ ]
+ },
+ {
+ "name": "user_sessions",
+ "columns": [
+ {
+ "name": "session_id",
+ "position": 1,
+ "type": "varchar(64)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "created_at",
+ "position": 3,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "last_activity",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "on_update": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "session_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p0",
+ "type": 7,
+ "expression": "session_id"
+ },
+ {
+ "name": "p1",
+ "type": 7,
+ "expression": "session_id"
+ },
+ {
+ "name": "p2",
+ "type": 7,
+ "expression": "session_id"
+ },
+ {
+ "name": "p3",
+ "type": 7,
+ "expression": "session_id"
+ },
+ {
+ "name": "p4",
+ "type": 7,
+ "expression": "session_id"
+ },
+ {
+ "name": "p5",
+ "type": 7,
+ "expression": "session_id"
+ },
+ {
+ "name": "p6",
+ "type": 7,
+ "expression": "session_id"
+ },
+ {
+ "name": "p7",
+ "type": 7,
+ "expression": "session_id"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `customer_regions`
+ --
+ CREATE TABLE `customer_regions` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `customer_name` varchar(100) NOT NULL,
+ `region` varchar(20) NOT NULL,
+ `sales_amount` decimal(10,2) DEFAULT NULL,
+ PRIMARY KEY (`id`, `region`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
+ /*!50500 PARTITION BY LIST COLUMNS (region)
+ (PARTITION `p_north` VALUES IN ('north','northeast','northwest') ENGINE=InnoDB,
+ PARTITION `p_south` VALUES IN ('south','southeast','southwest') ENGINE=InnoDB,
+ PARTITION `p_east` VALUES IN ('east') ENGINE=InnoDB,
+ PARTITION `p_west` VALUES IN ('west') ENGINE=InnoDB,
+ PARTITION `p_central` VALUES IN ('central') ENGINE=InnoDB) */;
+
+ --
+ -- Table structure for `employees`
+ --
+ CREATE TABLE `employees` (
+ `id` int NOT NULL,
+ `name` varchar(100) NOT NULL,
+ `department_id` int NOT NULL,
+ `hired_date` date DEFAULT NULL,
+ PRIMARY KEY (`id`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
+ /*!50100 PARTITION BY HASH (`id`)
+ (PARTITION `p0` ENGINE=InnoDB,
+ PARTITION `p1` ENGINE=InnoDB,
+ PARTITION `p2` ENGINE=InnoDB,
+ PARTITION `p3` ENGINE=InnoDB) */;
+
+ --
+ -- Table structure for `order_archive`
+ --
+ CREATE TABLE `order_archive` (
+ `order_id` int NOT NULL,
+ `order_date` date NOT NULL,
+ `customer_id` int NOT NULL,
+ `status` varchar(20) NOT NULL,
+ `total_amount` decimal(10,2) DEFAULT NULL,
+ PRIMARY KEY (`order_id`, `order_date`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
+ /*!50500 PARTITION BY RANGE COLUMNS (order_date)
+ (PARTITION `p_2022_q1` VALUES LESS THAN ('2022-04-01') ENGINE=InnoDB,
+ PARTITION `p_2022_q2` VALUES LESS THAN ('2022-07-01') ENGINE=InnoDB,
+ PARTITION `p_2022_q3` VALUES LESS THAN ('2022-10-01') ENGINE=InnoDB,
+ PARTITION `p_2022_q4` VALUES LESS THAN ('2023-01-01') ENGINE=InnoDB,
+ PARTITION `p_2023_and_later` VALUES LESS THAN MAXVALUE ENGINE=InnoDB) */;
+
+ --
+ -- Table structure for `sales`
+ --
+ CREATE TABLE `sales` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `sale_date` date NOT NULL,
+ `product_id` int NOT NULL,
+ `quantity` int NOT NULL,
+ `amount` decimal(10,2) NOT NULL,
+ PRIMARY KEY (`id`, `sale_date`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
+ /*!50100 PARTITION BY RANGE (year(`sale_date`))
+ (PARTITION `p2022` VALUES LESS THAN (2023) ENGINE=InnoDB,
+ PARTITION `p2023` VALUES LESS THAN (2024) ENGINE=InnoDB,
+ PARTITION `p2024` VALUES LESS THAN (2025) ENGINE=InnoDB,
+ PARTITION `p_future` VALUES LESS THAN MAXVALUE ENGINE=InnoDB) */;
+
+ --
+ -- Table structure for `user_sessions`
+ --
+ CREATE TABLE `user_sessions` (
+ `session_id` varchar(64) NOT NULL,
+ `user_id` int NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ `last_activity` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`session_id`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
+ /*!50100 PARTITION BY KEY (session_id)
+ (PARTITION `p0` ENGINE=InnoDB,
+ PARTITION `p1` ENGINE=InnoDB,
+ PARTITION `p2` ENGINE=InnoDB,
+ PARTITION `p3` ENGINE=InnoDB,
+ PARTITION `p4` ENGINE=InnoDB,
+ PARTITION `p5` ENGINE=InnoDB,
+ PARTITION `p6` ENGINE=InnoDB,
+ PARTITION `p7` ENGINE=InnoDB) */;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Events
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "daily_stats",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "stat_date",
+ "position": 2,
+ "type": "date"
+ },
+ {
+ "name": "total_orders",
+ "position": 3,
+ "default": "'0'",
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "total_revenue",
+ "position": 4,
+ "default": "'0.00'",
+ "nullable": true,
+ "type": "decimal(15,2)"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "stat_date",
+ "expressions": [
+ "stat_date"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ],
+ "events": [
+ {
+ "name": "update_daily_stats",
+ "definition": "CREATE DEFINER=`root`@`%` EVENT `update_daily_stats` ON SCHEDULE EVERY 1 DAY\nSTARTS CURRENT_TIMESTAMP ON COMPLETION NOT PRESERVE ENABLE DO INSERT INTO daily_stats (stat_date, total_orders, total_revenue)\n VALUES (CURDATE() - INTERVAL 1 DAY, 0, 0.00)\n ON DUPLICATE KEY UPDATE\n total_orders = VALUES(total_orders),\n total_revenue = VALUES(total_revenue)"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `daily_stats`
+ --
+ CREATE TABLE `daily_stats` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `stat_date` date NOT NULL,
+ `total_orders` int DEFAULT '0',
+ `total_revenue` decimal(15,2) DEFAULT '0.00',
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `stat_date` (`stat_date`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Event structure for `update_daily_stats`
+ --
+ SET character_set_client = ;
+ SET character_set_results = ;
+ SET collation_connection = ;
+ SET sql_mode = '';
+ SET time_zone = '';
+ DELIMITER ;;
+ CREATE DEFINER=`root`@`%` EVENT `update_daily_stats` ON SCHEDULE EVERY 1 DAY
+ STARTS CURRENT_TIMESTAMP ON COMPLETION NOT PRESERVE ENABLE DO INSERT INTO daily_stats (stat_date, total_orders, total_revenue)
+ VALUES (CURDATE() - INTERVAL 1 DAY, 0, 0.00)
+ ON DUPLICATE KEY UPDATE
+ total_orders = VALUES(total_orders),
+ total_revenue = VALUES(total_revenue);;
+ DELIMITER ;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Character sets and collations
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "translations",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "language_code",
+ "position": 2,
+ "type": "varchar(5)",
+ "character_set": "ascii",
+ "collation": "ascii_general_ci"
+ },
+ {
+ "name": "content_key",
+ "position": 3,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_bin"
+ },
+ {
+ "name": "translation",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_unicode_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "uk_lang_key",
+ "expressions": [
+ "language_code",
+ "content_key"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_general_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `translations`
+ --
+ CREATE TABLE `translations` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `language_code` varchar(5) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL,
+ `content_key` varchar(100) COLLATE utf8mb4_bin NOT NULL,
+ `translation` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_lang_key` (`language_code`, `content_key`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Check constraints with string literals and function with multiline parameters
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "transactions",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "type",
+ "position": 2,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(10)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "amount",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "check_constraints": [
+ {
+ "name": "c1",
+ "expression": "((`type` = 'A') and (`amount` is not null))"
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "lookup_token",
+ "definition": "CREATE FUNCTION `lookup_token`(p_a BIGINT, p_b VARCHAR(36)) RETURNS char(36) CHARSET utf8mb4 NO SQL DETERMINISTIC\nBEGIN\n RETURN p_b;\nEND"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `transactions`
+ --
+ CREATE TABLE `transactions` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `type` varchar(10) DEFAULT NULL,
+ `amount` decimal(10,2) DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ CONSTRAINT `c1` CHECK ((`type` = 'A') and (`amount` is not null))
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Function structure for `lookup_token`
+ --
+ CREATE FUNCTION `lookup_token`(p_a BIGINT, p_b VARCHAR(36)) RETURNS char(36) CHARSET utf8mb4 NO SQL DETERMINISTIC
+ BEGIN
+ RETURN p_b;
+ END;;
+ DELIMITER ;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Connected foreign key dependencies
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "department",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "parent_id",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "parent_id",
+ "expressions": [
+ "parent_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "department_ibfk_1",
+ "columns": [
+ "parent_id"
+ ],
+ "referenced_table": "department",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "NO ACTION"
+ }
+ ]
+ },
+ {
+ "name": "employee",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "department_id",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "manager_id",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "department_id",
+ "expressions": [
+ "department_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "manager_id",
+ "expressions": [
+ "manager_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "employee_ibfk_1",
+ "columns": [
+ "department_id"
+ ],
+ "referenced_table": "department",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "NO ACTION"
+ },
+ {
+ "name": "employee_ibfk_2",
+ "columns": [
+ "manager_id"
+ ],
+ "referenced_table": "employee",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "NO ACTION"
+ }
+ ]
+ },
+ {
+ "name": "project",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "lead_id",
+ "position": 3,
+ "type": "int"
+ },
+ {
+ "name": "department_id",
+ "position": 4,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "lead_id",
+ "expressions": [
+ "lead_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "department_id",
+ "expressions": [
+ "department_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "project_ibfk_1",
+ "columns": [
+ "lead_id"
+ ],
+ "referenced_table": "employee",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION"
+ },
+ {
+ "name": "project_ibfk_2",
+ "columns": [
+ "department_id"
+ ],
+ "referenced_table": "department",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION"
+ }
+ ]
+ },
+ {
+ "name": "project_member",
+ "columns": [
+ {
+ "name": "project_id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "employee_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "role",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "project_id",
+ "employee_id"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "employee_id",
+ "expressions": [
+ "employee_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "project_member_ibfk_1",
+ "columns": [
+ "project_id"
+ ],
+ "referenced_table": "project",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "NO ACTION"
+ },
+ {
+ "name": "project_member_ibfk_2",
+ "columns": [
+ "employee_id"
+ ],
+ "referenced_table": "employee",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "NO ACTION"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `department`
+ --
+ CREATE TABLE `department` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `parent_id` int DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `parent_id` (`parent_id`),
+ CONSTRAINT `department_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `department` (`id`) ON DELETE SET NULL
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `employee`
+ --
+ CREATE TABLE `employee` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `department_id` int DEFAULT NULL,
+ `manager_id` int DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `department_id` (`department_id`),
+ KEY `manager_id` (`manager_id`),
+ CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`) ON DELETE SET NULL,
+ CONSTRAINT `employee_ibfk_2` FOREIGN KEY (`manager_id`) REFERENCES `employee` (`id`) ON DELETE SET NULL
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `project`
+ --
+ CREATE TABLE `project` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `lead_id` int NOT NULL,
+ `department_id` int NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `lead_id` (`lead_id`),
+ KEY `department_id` (`department_id`),
+ CONSTRAINT `project_ibfk_1` FOREIGN KEY (`lead_id`) REFERENCES `employee` (`id`),
+ CONSTRAINT `project_ibfk_2` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`)
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Table structure for `project_member`
+ --
+ CREATE TABLE `project_member` (
+ `project_id` int NOT NULL,
+ `employee_id` int NOT NULL,
+ `role` varchar(50) DEFAULT NULL,
+ PRIMARY KEY (`project_id`, `employee_id`),
+ KEY `employee_id` (`employee_id`),
+ CONSTRAINT `project_member_ibfk_1` FOREIGN KEY (`project_id`) REFERENCES `project` (`id`) ON DELETE CASCADE,
+ CONSTRAINT `project_member_ibfk_2` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`id`) ON DELETE CASCADE
+ ) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
diff --git a/backend/plugin/schema/mysql/testdata/get_database_metadata.yaml b/backend/plugin/schema/mysql/testdata/get_database_metadata.yaml
new file mode 100644
index 0000000000..7b41d41bd4
--- /dev/null
+++ b/backend/plugin/schema/mysql/testdata/get_database_metadata.yaml
@@ -0,0 +1,3355 @@
+- description: basic_table_creation1
+ schema: |2
+ CREATE TABLE users(
+ id INT PRIMARY KEY AUTO_INCREMENT,
+ name varchar(220)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(220)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: basic_table_creation2
+ schema: |2
+ CREATE TABLE users(
+ id INT PRIMARY KEY AUTO_INCREMENT
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: basic_tables_with_constraints
+ schema: |
+ CREATE TABLE users (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ username VARCHAR(50) NOT NULL UNIQUE,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE posts (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published BOOLEAN DEFAULT false,
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ INDEX idx_user_id (user_id),
+ INDEX idx_published (published)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "posts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "title",
+ "position": 3,
+ "type": "varchar(200)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "content",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "published",
+ "position": 5,
+ "default": "'0'",
+ "nullable": true,
+ "type": "tinyint(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_user_id",
+ "expressions": [
+ "user_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_published",
+ "expressions": [
+ "published"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "fk_user",
+ "columns": [
+ "user_id"
+ ],
+ "referenced_table": "users",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "NO ACTION"
+ }
+ ]
+ },
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "username",
+ "position": 2,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "updated_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "on_update": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "username",
+ "expressions": [
+ "username"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: table_with_various_data_types
+ schema: |
+ CREATE TABLE data_types_test (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ tiny_int_col TINYINT,
+ small_int_col SMALLINT,
+ medium_int_col MEDIUMINT,
+ int_col INT,
+ big_int_col BIGINT,
+ decimal_col DECIMAL(10, 2),
+ float_col FLOAT,
+ double_col DOUBLE,
+ bit_col BIT(8),
+ bool_col BOOLEAN,
+ char_col CHAR(10),
+ varchar_col VARCHAR(255),
+ binary_col BINARY(16),
+ varbinary_col VARBINARY(255),
+ tinyblob_col TINYBLOB,
+ blob_col BLOB,
+ mediumblob_col MEDIUMBLOB,
+ longblob_col LONGBLOB,
+ tinytext_col TINYTEXT,
+ text_col TEXT,
+ mediumtext_col MEDIUMTEXT,
+ longtext_col LONGTEXT,
+ enum_col ENUM('small', 'medium', 'large'),
+ set_col SET('red', 'green', 'blue'),
+ date_col DATE,
+ time_col TIME,
+ datetime_col DATETIME,
+ timestamp_col TIMESTAMP,
+ year_col YEAR,
+ json_col JSON
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "data_types_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "tiny_int_col",
+ "position": 2,
+ "default": "NULL",
+ "nullable": true,
+ "type": "tinyint"
+ },
+ {
+ "name": "small_int_col",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "smallint"
+ },
+ {
+ "name": "medium_int_col",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "mediumint"
+ },
+ {
+ "name": "int_col",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "big_int_col",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "bigint"
+ },
+ {
+ "name": "decimal_col",
+ "position": 7,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "float_col",
+ "position": 8,
+ "default": "NULL",
+ "nullable": true,
+ "type": "float"
+ },
+ {
+ "name": "double_col",
+ "position": 9,
+ "default": "NULL",
+ "nullable": true,
+ "type": "double"
+ },
+ {
+ "name": "bit_col",
+ "position": 10,
+ "default": "NULL",
+ "nullable": true,
+ "type": "bit(8)"
+ },
+ {
+ "name": "bool_col",
+ "position": 11,
+ "default": "NULL",
+ "nullable": true,
+ "type": "tinyint(1)"
+ },
+ {
+ "name": "char_col",
+ "position": 12,
+ "default": "NULL",
+ "nullable": true,
+ "type": "char(10)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "varchar_col",
+ "position": 13,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(255)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "binary_col",
+ "position": 14,
+ "default": "NULL",
+ "nullable": true,
+ "type": "binary(16)"
+ },
+ {
+ "name": "varbinary_col",
+ "position": 15,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varbinary(255)"
+ },
+ {
+ "name": "tinyblob_col",
+ "position": 16,
+ "default": "NULL",
+ "nullable": true,
+ "type": "tinyblob"
+ },
+ {
+ "name": "blob_col",
+ "position": 17,
+ "default": "NULL",
+ "nullable": true,
+ "type": "blob"
+ },
+ {
+ "name": "mediumblob_col",
+ "position": 18,
+ "default": "NULL",
+ "nullable": true,
+ "type": "mediumblob"
+ },
+ {
+ "name": "longblob_col",
+ "position": 19,
+ "default": "NULL",
+ "nullable": true,
+ "type": "longblob"
+ },
+ {
+ "name": "tinytext_col",
+ "position": 20,
+ "default": "NULL",
+ "nullable": true,
+ "type": "tinytext",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "text_col",
+ "position": 21,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "mediumtext_col",
+ "position": 22,
+ "default": "NULL",
+ "nullable": true,
+ "type": "mediumtext",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "longtext_col",
+ "position": 23,
+ "default": "NULL",
+ "nullable": true,
+ "type": "longtext",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "enum_col",
+ "position": 24,
+ "default": "NULL",
+ "nullable": true,
+ "type": "enum('small','medium','large')",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "set_col",
+ "position": 25,
+ "default": "NULL",
+ "nullable": true,
+ "type": "set('red','green','blue')",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "date_col",
+ "position": 26,
+ "default": "NULL",
+ "nullable": true,
+ "type": "date"
+ },
+ {
+ "name": "time_col",
+ "position": 27,
+ "default": "NULL",
+ "nullable": true,
+ "type": "time"
+ },
+ {
+ "name": "datetime_col",
+ "position": 28,
+ "default": "NULL",
+ "nullable": true,
+ "type": "datetime"
+ },
+ {
+ "name": "timestamp_col",
+ "position": 29,
+ "default": "NULL",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "year_col",
+ "position": 30,
+ "default": "NULL",
+ "nullable": true,
+ "type": "year"
+ },
+ {
+ "name": "json_col",
+ "position": 31,
+ "default": "NULL",
+ "nullable": true,
+ "type": "json"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: views_and_generated_columns
+ schema: |
+ CREATE TABLE employees (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ first_name VARCHAR(50) NOT NULL,
+ last_name VARCHAR(50) NOT NULL,
+ full_name VARCHAR(101) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) STORED,
+ email VARCHAR(100) GENERATED ALWAYS AS (CONCAT(LOWER(first_name), '.', LOWER(last_name), '@company.com')) VIRTUAL,
+ department VARCHAR(50),
+ salary DECIMAL(10, 2)
+ );
+
+ CREATE VIEW active_employees AS
+ SELECT id, first_name, last_name, full_name, department
+ FROM employees
+ WHERE department IS NOT NULL;
+
+ CREATE VIEW high_earners AS
+ SELECT id, full_name, salary
+ FROM employees
+ WHERE salary > 100000;
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "first_name",
+ "position": 2,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "last_name",
+ "position": 3,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "full_name",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(101)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "generation": {
+ "type": 2,
+ "expression": "concat(`first_name`,_utf8mb4' ',`last_name`)"
+ }
+ },
+ {
+ "name": "email",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "generation": {
+ "type": 1,
+ "expression": "concat(lower(`first_name`),_utf8mb4'.',lower(`last_name`),_utf8mb4'@company.com')"
+ }
+ },
+ {
+ "name": "department",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "salary",
+ "position": 7,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ],
+ "views": [
+ {
+ "name": "active_employees",
+ "definition": "select `employees`.`id` AS `id`,`employees`.`first_name` AS `first_name`,`employees`.`last_name` AS `last_name`,`employees`.`full_name` AS `full_name`,`employees`.`department` AS `department` from `employees` where (`employees`.`department` is not null)"
+ },
+ {
+ "name": "high_earners",
+ "definition": "select `employees`.`id` AS `id`,`employees`.`full_name` AS `full_name`,`employees`.`salary` AS `salary` from `employees` where (`employees`.`salary` \u003e 100000)"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: functions_and_procedures
+ schema: |
+ DELIMITER //
+
+ CREATE FUNCTION get_employee_count(dept VARCHAR(50))
+ RETURNS INT
+ DETERMINISTIC
+ READS SQL DATA
+ BEGIN
+ DECLARE emp_count INT;
+ SELECT COUNT(*) INTO emp_count
+ FROM employees
+ WHERE department = dept;
+ RETURN emp_count;
+ END//
+
+ CREATE PROCEDURE update_employee_salary(
+ IN emp_id INT,
+ IN new_salary DECIMAL(10, 2)
+ )
+ BEGIN
+ UPDATE employees
+ SET salary = new_salary
+ WHERE id = emp_id;
+ END//
+
+ DELIMITER ;
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "functions": [
+ {
+ "name": "get_employee_count",
+ "definition": "BEGIN\n DECLARE emp_count INT;\n SELECT COUNT(*) INTO emp_count\n FROM employees\n WHERE department = dept;\n RETURN emp_count;\nEND"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "update_employee_salary",
+ "definition": "BEGIN\n UPDATE employees\n SET salary = new_salary\n WHERE id = emp_id;\nEND"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: partitioned_tables
+ schema: |
+ CREATE TABLE sales (
+ id INT AUTO_INCREMENT,
+ sale_date DATE NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ region VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id, sale_date)
+ ) PARTITION BY RANGE (YEAR(sale_date)) (
+ PARTITION p2021 VALUES LESS THAN (2022),
+ PARTITION p2022 VALUES LESS THAN (2023),
+ PARTITION p2023 VALUES LESS THAN (2024),
+ PARTITION p2024 VALUES LESS THAN (2025)
+ );
+
+ CREATE TABLE user_logs (
+ id INT AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ log_date DATE NOT NULL,
+ action VARCHAR(100),
+ PRIMARY KEY (id, user_id)
+ ) PARTITION BY HASH(user_id) PARTITIONS 4;
+
+ CREATE TABLE regions (
+ id INT AUTO_INCREMENT,
+ region_code VARCHAR(10) NOT NULL,
+ region_name VARCHAR(100),
+ PRIMARY KEY (id, region_code)
+ ) PARTITION BY KEY(region_code) PARTITIONS 3;
+
+ CREATE TABLE products (
+ id INT AUTO_INCREMENT,
+ category VARCHAR(50) NOT NULL,
+ name VARCHAR(100),
+ price DECIMAL(10, 2),
+ PRIMARY KEY (id, category)
+ ) PARTITION BY LIST COLUMNS(category) (
+ PARTITION p_electronics VALUES IN ('laptop', 'phone', 'tablet'),
+ PARTITION p_clothing VALUES IN ('shirt', 'pants', 'shoes'),
+ PARTITION p_food VALUES IN ('fruit', 'vegetable', 'meat')
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "category",
+ "position": 2,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "name",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "price",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "category"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p_electronics",
+ "type": 4,
+ "expression": "category",
+ "value": "'laptop','phone','tablet'"
+ },
+ {
+ "name": "p_clothing",
+ "type": 4,
+ "expression": "category",
+ "value": "'shirt','pants','shoes'"
+ },
+ {
+ "name": "p_food",
+ "type": 4,
+ "expression": "category",
+ "value": "'fruit','vegetable','meat'"
+ }
+ ]
+ },
+ {
+ "name": "regions",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "region_code",
+ "position": 2,
+ "type": "varchar(10)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "region_name",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "region_code"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p0",
+ "type": 7,
+ "expression": "region_code"
+ },
+ {
+ "name": "p1",
+ "type": 7,
+ "expression": "region_code"
+ },
+ {
+ "name": "p2",
+ "type": 7,
+ "expression": "region_code"
+ }
+ ]
+ },
+ {
+ "name": "sales",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "sale_date",
+ "position": 2,
+ "type": "date"
+ },
+ {
+ "name": "amount",
+ "position": 3,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "region",
+ "position": 4,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "sale_date"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p2021",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2022"
+ },
+ {
+ "name": "p2022",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2023"
+ },
+ {
+ "name": "p2023",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2024"
+ },
+ {
+ "name": "p2024",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2025"
+ }
+ ]
+ },
+ {
+ "name": "user_logs",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "log_date",
+ "position": 3,
+ "type": "date"
+ },
+ {
+ "name": "action",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "user_id"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p0",
+ "type": 5,
+ "expression": "`user_id`"
+ },
+ {
+ "name": "p1",
+ "type": 5,
+ "expression": "`user_id`"
+ },
+ {
+ "name": "p2",
+ "type": 5,
+ "expression": "`user_id`"
+ },
+ {
+ "name": "p3",
+ "type": 5,
+ "expression": "`user_id`"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: indexes_with_various_types
+ schema: |
+ CREATE TABLE orders (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ customer_id INT NOT NULL,
+ order_date DATE NOT NULL,
+ total_amount DECIMAL(10, 2) NOT NULL,
+ status VARCHAR(20),
+ notes TEXT,
+ INDEX idx_customer (customer_id),
+ INDEX idx_date_desc (order_date DESC),
+ INDEX idx_customer_date (customer_id ASC, order_date DESC),
+ UNIQUE INDEX idx_unique_customer_status (customer_id, status),
+ FULLTEXT INDEX idx_fulltext_notes (notes)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "customer_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "order_date",
+ "position": 3,
+ "type": "date"
+ },
+ {
+ "name": "total_amount",
+ "position": 4,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "status",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "notes",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_customer",
+ "expressions": [
+ "customer_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_date_desc",
+ "expressions": [
+ "order_date"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ true
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_customer_date",
+ "expressions": [
+ "customer_id",
+ "order_date"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ true
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_unique_customer_status",
+ "expressions": [
+ "customer_id",
+ "status"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "idx_fulltext_notes",
+ "expressions": [
+ "notes"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "FULLTEXT",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: check_constraints
+ schema: |
+ CREATE TABLE products_with_checks (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ quantity INT NOT NULL,
+ category VARCHAR(50),
+ CONSTRAINT chk_price CHECK (price > 0),
+ CONSTRAINT chk_quantity CHECK (quantity >= 0),
+ CONSTRAINT chk_category CHECK (category IN ('electronics', 'clothing', 'food', 'other'))
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "products_with_checks",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "price",
+ "position": 3,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "quantity",
+ "position": 4,
+ "type": "int"
+ },
+ {
+ "name": "category",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "check_constraints": [
+ {
+ "name": "chk_price",
+ "expression": "(`price` \u003e 0)"
+ },
+ {
+ "name": "chk_quantity",
+ "expression": "(`quantity` \u003e= 0)"
+ },
+ {
+ "name": "chk_category",
+ "expression": "(`category` in ('electronics','clothing','food','other'))"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: triggers
+ schema: |
+ CREATE TABLE users (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE audit_log (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ table_name VARCHAR(100),
+ action VARCHAR(10),
+ user VARCHAR(100),
+ timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ DELIMITER //
+
+ CREATE TRIGGER users_after_insert
+ AFTER INSERT ON users
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO audit_log (table_name, action, user)
+ VALUES ('users', 'INSERT', USER());
+ END//
+
+ CREATE TRIGGER users_after_update
+ AFTER UPDATE ON users
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO audit_log (table_name, action, user)
+ VALUES ('users', 'UPDATE', USER());
+ END//
+
+ DELIMITER ;
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "audit_log",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "table_name",
+ "position": 2,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "action",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(10)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "user",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "timestamp",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ },
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "username",
+ "position": 2,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "triggers": [
+ {
+ "name": "users_after_insert",
+ "event": "INSERT",
+ "timing": "AFTER",
+ "body": "BEGIN\n INSERT INTO audit_log (table_name, action, user)\n VALUES ('users', 'INSERT', USER());\nEND"
+ },
+ {
+ "name": "users_after_update",
+ "event": "UPDATE",
+ "timing": "AFTER",
+ "body": "BEGIN\n INSERT INTO audit_log (table_name, action, user)\n VALUES ('users', 'UPDATE', USER());\nEND"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: table_with_comments
+ schema: |
+ CREATE TABLE documented_table (
+ id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
+ name VARCHAR(100) NOT NULL COMMENT 'The name of the item',
+ description TEXT COMMENT 'Detailed description',
+ price DECIMAL(10, 2) COMMENT 'Price in USD',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation timestamp',
+ INDEX idx_name (name) COMMENT 'Index on name for faster lookups'
+ ) COMMENT='This table stores documented items';
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "documented_table",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int",
+ "comment": "Unique identifier"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "comment": "The name of the item"
+ },
+ {
+ "name": "description",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "comment": "Detailed description"
+ },
+ {
+ "name": "price",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)",
+ "comment": "Price in USD"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp",
+ "comment": "Creation timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_name",
+ "expressions": [
+ "name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true,
+ "comment": "Index on name for faster lookups"
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "comment": "This table stores documented items"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: complex_foreign_keys
+ schema: |
+ CREATE TABLE departments (
+ dept_id INT PRIMARY KEY,
+ dept_name VARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE employees_fk (
+ emp_id INT PRIMARY KEY,
+ emp_name VARCHAR(100) NOT NULL,
+ dept_id INT,
+ manager_id INT,
+ CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees_fk(emp_id) ON DELETE RESTRICT ON UPDATE RESTRICT
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "departments",
+ "columns": [
+ {
+ "name": "dept_id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "dept_name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "dept_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ },
+ {
+ "name": "employees_fk",
+ "columns": [
+ {
+ "name": "emp_id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "emp_name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "dept_id",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "manager_id",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "emp_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "fk_dept",
+ "expressions": [
+ "dept_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "fk_manager",
+ "expressions": [
+ "manager_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "fk_dept",
+ "columns": [
+ "dept_id"
+ ],
+ "referenced_table": "departments",
+ "referenced_columns": [
+ "dept_id"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "CASCADE"
+ },
+ {
+ "name": "fk_manager",
+ "columns": [
+ "manager_id"
+ ],
+ "referenced_table": "employees_fk",
+ "referenced_columns": [
+ "emp_id"
+ ],
+ "on_delete": "RESTRICT",
+ "on_update": "RESTRICT"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: advanced_column_attributes
+ schema: |
+ CREATE TABLE advanced_columns (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ unsigned_int INT UNSIGNED NOT NULL,
+ zerofill_int INT(8) ZEROFILL,
+ unsigned_zerofill INT UNSIGNED ZEROFILL,
+ tiny_unsigned TINYINT UNSIGNED,
+ big_unsigned BIGINT UNSIGNED,
+ decimal_unsigned DECIMAL(10,2) UNSIGNED,
+ float_unsigned FLOAT UNSIGNED,
+ double_unsigned DOUBLE UNSIGNED,
+ bit_field BIT(16),
+ char_binary CHAR(10) BINARY,
+ varchar_binary VARCHAR(50) BINARY,
+ text_collate TEXT COLLATE utf8mb4_unicode_ci,
+ varchar_collate VARCHAR(100) COLLATE utf8mb4_bin,
+ datetime_precision DATETIME(6),
+ timestamp_precision TIMESTAMP(3),
+ time_precision TIME(2)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "advanced_columns",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "unsigned_int",
+ "position": 2,
+ "type": "int unsigned"
+ },
+ {
+ "name": "zerofill_int",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int(8) unsigned zerofill"
+ },
+ {
+ "name": "unsigned_zerofill",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int(10) unsigned zerofill"
+ },
+ {
+ "name": "tiny_unsigned",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "tinyint unsigned"
+ },
+ {
+ "name": "big_unsigned",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "bigint unsigned"
+ },
+ {
+ "name": "decimal_unsigned",
+ "position": 7,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2) unsigned"
+ },
+ {
+ "name": "float_unsigned",
+ "position": 8,
+ "default": "NULL",
+ "nullable": true,
+ "type": "float unsigned"
+ },
+ {
+ "name": "double_unsigned",
+ "position": 9,
+ "default": "NULL",
+ "nullable": true,
+ "type": "double unsigned"
+ },
+ {
+ "name": "bit_field",
+ "position": 10,
+ "default": "NULL",
+ "nullable": true,
+ "type": "bit(16)"
+ },
+ {
+ "name": "char_binary",
+ "position": 11,
+ "default": "NULL",
+ "nullable": true,
+ "type": "char(10)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_bin"
+ },
+ {
+ "name": "varchar_binary",
+ "position": 12,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_bin"
+ },
+ {
+ "name": "text_collate",
+ "position": 13,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_unicode_ci"
+ },
+ {
+ "name": "varchar_collate",
+ "position": 14,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_bin"
+ },
+ {
+ "name": "datetime_precision",
+ "position": 15,
+ "default": "NULL",
+ "nullable": true,
+ "type": "datetime(6)"
+ },
+ {
+ "name": "timestamp_precision",
+ "position": 16,
+ "default": "NULL",
+ "nullable": true,
+ "type": "timestamp(3)"
+ },
+ {
+ "name": "time_precision",
+ "position": 17,
+ "default": "NULL",
+ "nullable": true,
+ "type": "time(2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: spatial_data_types
+ schema: |
+ CREATE TABLE spatial_test (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ location GEOMETRY NOT NULL,
+ point_col POINT NOT NULL,
+ line_col LINESTRING NOT NULL,
+ polygon_col POLYGON NOT NULL,
+ multipoint_col MULTIPOINT NOT NULL,
+ multiline_col MULTILINESTRING NOT NULL,
+ multipolygon_col MULTIPOLYGON NOT NULL,
+ geocollection_col GEOMETRYCOLLECTION NOT NULL,
+ SPATIAL INDEX idx_location (location),
+ SPATIAL INDEX idx_point (point_col)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "spatial_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "location",
+ "position": 2,
+ "type": "geometry"
+ },
+ {
+ "name": "point_col",
+ "position": 3,
+ "type": "point"
+ },
+ {
+ "name": "line_col",
+ "position": 4,
+ "type": "linestring"
+ },
+ {
+ "name": "polygon_col",
+ "position": 5,
+ "type": "polygon"
+ },
+ {
+ "name": "multipoint_col",
+ "position": 6,
+ "type": "multipoint"
+ },
+ {
+ "name": "multiline_col",
+ "position": 7,
+ "type": "multilinestring"
+ },
+ {
+ "name": "multipolygon_col",
+ "position": 8,
+ "type": "multipolygon"
+ },
+ {
+ "name": "geocollection_col",
+ "position": 9,
+ "type": "geomcollection"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_location",
+ "expressions": [
+ "location"
+ ],
+ "key_length": [
+ 32
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "visible": true
+ },
+ {
+ "name": "idx_point",
+ "expressions": [
+ "point_col"
+ ],
+ "key_length": [
+ 32
+ ],
+ "descending": [
+ false
+ ],
+ "type": "SPATIAL",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: mysql8_invisible_indexes
+ schema: |
+ CREATE TABLE invisible_index_test (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100),
+ status VARCHAR(20),
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ INDEX idx_name (name),
+ INDEX idx_email (email) INVISIBLE,
+ INDEX idx_status_invisible (status) INVISIBLE,
+ INDEX idx_composite (name, email) INVISIBLE
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "invisible_index_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "status",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_name",
+ "expressions": [
+ "name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_email",
+ "expressions": [
+ "email"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE"
+ },
+ {
+ "name": "idx_status_invisible",
+ "expressions": [
+ "status"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE"
+ },
+ {
+ "name": "idx_composite",
+ "expressions": [
+ "name",
+ "email"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE"
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: advanced_indexes
+ schema: |
+ CREATE TABLE advanced_index_test (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ price DECIMAL(10,2),
+ category VARCHAR(50),
+ tags JSON,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ INDEX idx_name_prefix (name(10)),
+ INDEX idx_price_desc (price DESC),
+ INDEX idx_composite_mixed (category ASC, price DESC),
+ UNIQUE INDEX idx_unique_name_category (name, category),
+ FULLTEXT INDEX idx_fulltext_desc (description),
+ INDEX idx_expression ((YEAR(created_at)))
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "advanced_index_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "description",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "price",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "category",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "tags",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "created_at",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_name_prefix",
+ "expressions": [
+ "name"
+ ],
+ "key_length": [
+ 10
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_price_desc",
+ "expressions": [
+ "price"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ true
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_composite_mixed",
+ "expressions": [
+ "category",
+ "price"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ true
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_unique_name_category",
+ "expressions": [
+ "name",
+ "category"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "idx_fulltext_desc",
+ "expressions": [
+ "description"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "FULLTEXT",
+ "visible": true
+ },
+ {
+ "name": "idx_expression",
+ "expressions": [
+ "year(`created_at`)"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: table_level_options
+ schema: |
+ CREATE TABLE table_options_test (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ data TEXT
+ ) ENGINE=InnoDB
+ DEFAULT CHARSET=utf8mb4
+ COLLATE=utf8mb4_unicode_ci
+ ROW_FORMAT=DYNAMIC
+ AUTO_INCREMENT=1000
+ COMMENT='Table with various options';
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "table_options_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_unicode_ci"
+ },
+ {
+ "name": "data",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_unicode_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "collation": "utf8mb4_unicode_ci",
+ "charset": "utf8mb4",
+ "comment": "Table with various options"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: advanced_partitioning_maxvalue
+ schema: |
+ CREATE TABLE sales_maxvalue (
+ id INT AUTO_INCREMENT,
+ sale_date DATE NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ region VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id, sale_date)
+ ) PARTITION BY RANGE (YEAR(sale_date)) (
+ PARTITION p2021 VALUES LESS THAN (2022),
+ PARTITION p2022 VALUES LESS THAN (2023),
+ PARTITION p2023 VALUES LESS THAN (2024),
+ PARTITION p_future VALUES LESS THAN MAXVALUE
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "sales_maxvalue",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "sale_date",
+ "position": 2,
+ "type": "date"
+ },
+ {
+ "name": "amount",
+ "position": 3,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "region",
+ "position": 4,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "sale_date"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p2021",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2022"
+ },
+ {
+ "name": "p2022",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2023"
+ },
+ {
+ "name": "p2023",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "2024"
+ },
+ {
+ "name": "p_future",
+ "type": 1,
+ "expression": "year(`sale_date`)",
+ "value": "MAXVALUE"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: multi_column_partitioning
+ schema: |
+ CREATE TABLE multi_column_partition (
+ id INT AUTO_INCREMENT,
+ year_col INT NOT NULL,
+ month_col INT NOT NULL,
+ data VARCHAR(100),
+ PRIMARY KEY (id, year_col, month_col)
+ ) PARTITION BY RANGE COLUMNS(year_col, month_col) (
+ PARTITION p202101 VALUES LESS THAN (2021, 7),
+ PARTITION p202107 VALUES LESS THAN (2022, 1),
+ PARTITION p202201 VALUES LESS THAN (2022, 7),
+ PARTITION p202207 VALUES LESS THAN (2023, 1)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "multi_column_partition",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "year_col",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "month_col",
+ "position": 3,
+ "type": "int"
+ },
+ {
+ "name": "data",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id",
+ "year_col",
+ "month_col"
+ ],
+ "key_length": [
+ -1,
+ -1,
+ -1
+ ],
+ "descending": [
+ false,
+ false,
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "partitions": [
+ {
+ "name": "p202101",
+ "type": 2,
+ "expression": "year_col,month_col",
+ "value": "2021,7"
+ },
+ {
+ "name": "p202107",
+ "type": 2,
+ "expression": "year_col,month_col",
+ "value": "2022,1"
+ },
+ {
+ "name": "p202201",
+ "type": 2,
+ "expression": "year_col,month_col",
+ "value": "2022,7"
+ },
+ {
+ "name": "p202207",
+ "type": 2,
+ "expression": "year_col,month_col",
+ "value": "2023,1"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: self_referencing_foreign_keys
+ schema: |
+ CREATE TABLE hierarchical_data (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ parent_id INT,
+ manager_id INT,
+ CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES hierarchical_data(id) ON DELETE CASCADE,
+ CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES hierarchical_data(id) ON DELETE SET NULL
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "hierarchical_data",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "parent_id",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "manager_id",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "fk_parent",
+ "expressions": [
+ "parent_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "fk_manager",
+ "expressions": [
+ "manager_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "foreign_keys": [
+ {
+ "name": "fk_parent",
+ "columns": [
+ "parent_id"
+ ],
+ "referenced_table": "hierarchical_data",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "NO ACTION"
+ },
+ {
+ "name": "fk_manager",
+ "columns": [
+ "manager_id"
+ ],
+ "referenced_table": "hierarchical_data",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "NO ACTION"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: complex_generated_columns
+ schema: |
+ CREATE TABLE complex_generated (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ first_name VARCHAR(50) NOT NULL,
+ last_name VARCHAR(50) NOT NULL,
+ birth_date DATE NOT NULL,
+ salary DECIMAL(10,2),
+ full_name VARCHAR(101) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) STORED,
+ email VARCHAR(150) GENERATED ALWAYS AS (CONCAT(LOWER(first_name), '.', LOWER(last_name), '@company.com')) VIRTUAL,
+ age_years INT GENERATED ALWAYS AS (TIMESTAMPDIFF(YEAR, birth_date, '2024-01-01')) VIRTUAL,
+ salary_category VARCHAR(20) GENERATED ALWAYS AS (
+ CASE
+ WHEN salary < 50000 THEN 'junior'
+ WHEN salary < 100000 THEN 'mid'
+ ELSE 'senior'
+ END
+ ) STORED,
+ INDEX idx_full_name (full_name),
+ INDEX idx_age (age_years),
+ INDEX idx_salary_cat (salary_category)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "complex_generated",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "first_name",
+ "position": 2,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "last_name",
+ "position": 3,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "birth_date",
+ "position": 4,
+ "type": "date"
+ },
+ {
+ "name": "salary",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "full_name",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(101)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "generation": {
+ "type": 2,
+ "expression": "concat(`first_name`,_utf8mb4' ',`last_name`)"
+ }
+ },
+ {
+ "name": "email",
+ "position": 7,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(150)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "generation": {
+ "type": 1,
+ "expression": "concat(lower(`first_name`),_utf8mb4'.',lower(`last_name`),_utf8mb4'@company.com')"
+ }
+ },
+ {
+ "name": "age_years",
+ "position": 8,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int",
+ "generation": {
+ "type": 1,
+ "expression": "timestampdiff(YEAR,`birth_date`,_utf8mb4'2024-01-01')"
+ }
+ },
+ {
+ "name": "salary_category",
+ "position": 9,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(20)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "generation": {
+ "type": 2,
+ "expression": "(?)"
+ }
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_full_name",
+ "expressions": [
+ "full_name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_age",
+ "expressions": [
+ "age_years"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_salary_cat",
+ "expressions": [
+ "salary_category"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: quoted_identifiers_special_chars
+ schema: |
+ CREATE TABLE `special-table` (
+ `id-field` INT AUTO_INCREMENT PRIMARY KEY,
+ `first name` VARCHAR(50) NOT NULL,
+ `email@domain` VARCHAR(100),
+ `order` INT COMMENT 'Reserved keyword as column name',
+ `group` VARCHAR(50) COMMENT 'Another reserved keyword',
+ INDEX `idx-name` (`first name`),
+ UNIQUE INDEX `idx-email` (`email@domain`)
+ ) COMMENT='Table with special characters in identifiers';
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "special-table",
+ "columns": [
+ {
+ "name": "id-field",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "first name",
+ "position": 2,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "email@domain",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ },
+ {
+ "name": "order",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int",
+ "comment": "Reserved keyword as column name"
+ },
+ {
+ "name": "group",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(50)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "comment": "Another reserved keyword"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id-field"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx-name",
+ "expressions": [
+ "first name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx-email",
+ "expressions": [
+ "email@domain"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "comment": "Table with special characters in identifiers"
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+- description: json_and_array_features
+ schema: |
+ CREATE TABLE json_features (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ metadata JSON,
+ config JSON,
+ tags JSON,
+ name_from_json VARCHAR(100) GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(metadata, '$.name'))) STORED,
+ tag_count INT GENERATED ALWAYS AS (JSON_LENGTH(tags)) VIRTUAL,
+ CHECK (JSON_VALID(metadata)),
+ CHECK (JSON_VALID(config)),
+ INDEX idx_name_json (name_from_json),
+ INDEX idx_tag_count (tag_count)
+ );
+ metadata: |
+ {
+ "name": "tmp",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "json_features",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "metadata",
+ "position": 2,
+ "default": "NULL",
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "config",
+ "position": 3,
+ "default": "NULL",
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "tags",
+ "position": 4,
+ "default": "NULL",
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "name_from_json",
+ "position": 5,
+ "default": "NULL",
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci",
+ "generation": {
+ "type": 2,
+ "expression": "json_unquote(json_extract(`metadata`,_utf8mb4'$.name'))"
+ }
+ },
+ {
+ "name": "tag_count",
+ "position": 6,
+ "default": "NULL",
+ "nullable": true,
+ "type": "int",
+ "generation": {
+ "type": 1,
+ "expression": "json_length(`tags`)"
+ }
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_name_json",
+ "expressions": [
+ "name_from_json"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_tag_count",
+ "expressions": [
+ "tag_count"
+ ],
+ "key_length": [
+ -1
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "charset": "utf8mb4",
+ "check_constraints": [
+ {
+ "name": "json_features_chk_1",
+ "expression": "json_valid(`metadata`)"
+ },
+ {
+ "name": "json_features_chk_2",
+ "expression": "json_valid(`config`)"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
diff --git a/backend/plugin/schema/mysql/testdata/sdl/big_schema_core.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/big_schema_core.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/big_schema_core.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/big_schema_core.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/big_schema_user_sdl_core.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/big_schema_user_sdl_core.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/big_schema_user_sdl_core.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/big_schema_user_sdl_core.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/chain_s0.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/chain_s0.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/chain_s0.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/chain_s0.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/chain_s1_common.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/chain_s1_common.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/chain_s1_common.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/chain_s1_common.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/chain_s2_common.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/chain_s2_common.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/chain_s2_common.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/chain_s2_common.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/chain_s3_common.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/chain_s3_common.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/chain_s3_common.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/chain_s3_common.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/chain_s4_base.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/chain_s4_base.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/chain_s4_base.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/chain_s4_base.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/diverge_schema.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/diverge_schema.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/diverge_schema.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/diverge_schema.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/diverge_schema_with_check.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/diverge_schema_with_check.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/diverge_schema_with_check.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/diverge_schema_with_check.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/drop_heavy_base.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/drop_heavy_base.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/drop_heavy_base.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/drop_heavy_base.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/drop_heavy_target.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/drop_heavy_target.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/drop_heavy_target.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/drop_heavy_target.sql
diff --git a/backend/plugin/schema/mysql/testdata/realworld/employees.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/employees.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/realworld/employees.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/employees.sql
diff --git a/backend/plugin/schema/mysql/testdata/realworld/employees_part.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/employees_part.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/realworld/employees_part.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/employees_part.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/ent_a1_aux.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/ent_a1_aux.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/ent_a1_aux.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/ent_a1_aux.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/ent_a5c_aux.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/ent_a5c_aux.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/ent_a5c_aux.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/ent_a5c_aux.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/ent_fuzz_aux.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/ent_fuzz_aux.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/ent_fuzz_aux.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/ent_fuzz_aux.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/ent_sf_aux_80.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/ent_sf_aux_80.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/ent_sf_aux_80.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/ent_sf_aux_80.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/ent_sf_aux_common.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/ent_sf_aux_common.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/ent_sf_aux_common.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/ent_sf_aux_common.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/ent_upg_binary_default_ddl.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/ent_upg_binary_default_ddl.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/ent_upg_binary_default_ddl.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/ent_upg_binary_default_ddl.sql
diff --git a/backend/plugin/schema/mysql/testdata/realworld/mediawiki.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/mediawiki.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/realworld/mediawiki.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/mediawiki.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/multi_change_base.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/multi_change_base.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/multi_change_base.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/multi_change_base.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/multi_change_target_57.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/multi_change_target_57.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/multi_change_target_57.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/multi_change_target_57.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/multi_change_target_80.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/multi_change_target_80.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/multi_change_target_80.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/multi_change_target_80.sql
diff --git a/backend/plugin/schema/mysql/testdata/enterprise/openemr.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/openemr.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/enterprise/openemr.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/openemr.sql
diff --git a/backend/plugin/schema/mysql/testdata/enterprise/prestashop.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/prestashop.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/enterprise/prestashop.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/prestashop.sql
diff --git a/backend/plugin/schema/mysql/testdata/sdl/representative_ddl.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/representative_ddl.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/sdl/representative_ddl.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/representative_ddl.sql
diff --git a/backend/plugin/schema/mysql/testdata/realworld/roundcube.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/roundcube.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/realworld/roundcube.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/roundcube.sql
diff --git a/backend/plugin/schema/mysql/testdata/realworld/sakila.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/sakila.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/realworld/sakila.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/sakila.sql
diff --git a/backend/plugin/schema/mysql/testdata/enterprise/sys.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/sys.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/enterprise/sys.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/sys.sql
diff --git a/backend/plugin/schema/mysql/testdata/enterprise/zabbix.sql b/backend/plugin/schema/mysql/testdata/sdl_migration/zabbix.sql
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/enterprise/zabbix.sql
rename to backend/plugin/schema/mysql/testdata/sdl_migration/zabbix.sql
diff --git a/backend/plugin/schema/mysql/testutil_test.go b/backend/plugin/schema/mysql/testutil_test.go
deleted file mode 100644
index f1b258b14c..0000000000
--- a/backend/plugin/schema/mysql/testutil_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package mysql
-
-import (
- "context"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
- mysqldb "github.com/bytebase/bytebase/backend/plugin/db/mysql"
-)
-
-// createMySQLDriver creates and opens a MySQL driver for the specified database.
-// This is a shared helper function for tests.
-func createMySQLDriver(ctx context.Context, host, port, database string) (db.Driver, error) {
- driver := &mysqldb.Driver{}
- config := db.ConnectionConfig{
- DataSource: &storepb.DataSource{
- Type: storepb.DataSourceType_ADMIN,
- Username: "root",
- Host: host,
- Port: port,
- Database: database,
- },
- Password: "root-password",
- ConnectionContext: db.ConnectionContext{
- EngineVersion: "8.0",
- DatabaseName: database,
- },
- }
- return driver.Open(ctx, storepb.Engine_MYSQL, config)
-}
diff --git a/backend/plugin/schema/oracle/generate_migration_test.go b/backend/plugin/schema/oracle/generate_migration_test.go
index 2220c5f8c8..c041f4f832 100644
--- a/backend/plugin/schema/oracle/generate_migration_test.go
+++ b/backend/plugin/schema/oracle/generate_migration_test.go
@@ -1,1792 +1,74 @@
package oracle
import (
- "context"
- "encoding/json"
- "fmt"
"os"
- "path/filepath"
- "regexp"
"strings"
"testing"
- "github.com/google/go-cmp/cmp"
- "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/encoding/protojson"
- "google.golang.org/protobuf/testing/protocmp"
+
+ "gopkg.in/yaml.v3"
"github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
)
-// TestGenerateMigration runs the rollback generator over metadata Oracle itself
-// reported for each fixture: diff the post-migration schema back to the initial
-// one and compare the DDL against the recorded golden. The metadata comes from
-// testdata/generate_migration/*.json, captured by TestGenerateMigrationAgainstOracle.
-//
-// Set record to regenerate the .sql goldens; it needs no Oracle. Refreshing the
-// .json metadata does, and is TestGenerateMigrationAgainstOracle's job.
-func TestGenerateMigration(t *testing.T) {
- t.Parallel()
-
- const record = false
-
- for _, tc := range generateMigrationCases() {
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
+type generateMigrationCase struct {
+ Description string `yaml:"description"`
+ OldMetadata string `yaml:"oldMetadata"`
+ NewMetadata string `yaml:"newMetadata"`
+ Expected string `yaml:"expected"`
+}
- schemaA, schemaB := loadGenerateMigrationFixture(t, tc.name)
+// TestGenerateMigration pins the DDL that takes oldMetadata to newMetadata. The
+// metadata is what Oracle itself reported for each case, captured once; the
+// recorder that produced it is gone, so these inputs are frozen and only the
+// expected DDL re-records.
+func TestGenerateMigration(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/generate_migration.yaml"
+ )
- dbSchemaA := model.NewDatabaseMetadata(schemaA, nil, nil, storepb.Engine_ORACLE, false)
- dbSchemaB := model.NewDatabaseMetadata(schemaB, nil, nil, storepb.Engine_ORACLE, false)
+ var tests []generateMigrationCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
- // Diff B back to A: the migration under test is the rollback.
- diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_ORACLE, dbSchemaB, dbSchemaA)
- require.NoError(t, err, "failed to diff %s", tc.description)
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_ORACLE,
+ parseMetadata(t, tc.OldMetadata), parseMetadata(t, tc.NewMetadata))
+ require.NoError(t, err)
- rollbackDDL, err := schema.GenerateMigration(storepb.Engine_ORACLE, diff)
- require.NoError(t, err, "failed to generate migration for %s", tc.description)
+ migration, err := schema.GenerateMigration(storepb.Engine_ORACLE, diff)
+ require.NoError(t, err)
- goldenPath := generateMigrationGoldenPath(tc.name)
if record {
- require.NoError(t, os.WriteFile(goldenPath, []byte(rollbackDDL), 0o644))
+ tests[i].Expected = migration
return
}
-
- want, err := os.ReadFile(goldenPath)
- require.NoErrorf(t, err, "missing golden %s; set record to regenerate", goldenPath)
- require.Equal(t, string(want), rollbackDDL, "generated migration changed for %s", tc.description)
+ require.Equal(t, tc.Expected, migration)
})
}
-}
-
-const generateMigrationFixtureDir = "testdata/generate_migration"
-
-// generateMigrationFixture is one case's pair of engine-reported schemas: the
-// state after initialSchema, and the state after migrationDDL. Both are
-// protojson because storepb messages do not round-trip through encoding/json.
-type generateMigrationFixture struct {
- SchemaA json.RawMessage `json:"schemaA"`
- SchemaB json.RawMessage `json:"schemaB"`
-}
-func generateMigrationFixturePath(name string) string {
- return filepath.Join(generateMigrationFixtureDir, name+".json")
-}
-
-func generateMigrationGoldenPath(name string) string {
- return filepath.Join(generateMigrationFixtureDir, name+".sql")
+ if record {
+ yamltest.Record(t, filepath, tests)
+ }
}
-// loadGenerateMigrationFixture reads the metadata Oracle reported for a case.
-func loadGenerateMigrationFixture(t *testing.T, name string) (*storepb.DatabaseSchemaMetadata, *storepb.DatabaseSchemaMetadata) {
+func parseMetadata(t *testing.T, encoded string) *model.DatabaseMetadata {
t.Helper()
- path := generateMigrationFixturePath(name)
- raw, err := os.ReadFile(path)
- require.NoErrorf(t, err, "missing fixture %s; regenerate by setting record = true in TestGenerateMigrationAgainstOracle, then running: go test -run TestGenerateMigrationAgainstOracle ./backend/plugin/schema/oracle/", path)
-
- var fixture generateMigrationFixture
- require.NoError(t, json.Unmarshal(raw, &fixture), "failed to read %s", path)
-
- schemaA := &storepb.DatabaseSchemaMetadata{}
- require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal(fixture.SchemaA, schemaA), "failed to decode schemaA in %s", path)
- schemaB := &storepb.DatabaseSchemaMetadata{}
- require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal(fixture.SchemaB, schemaB), "failed to decode schemaB in %s", path)
-
- return schemaA, schemaB
-}
-
-// generateMigrationCase is one schema-change fixture: apply initialSchema to an
-// empty schema, then apply migrationDDL, and the generator must produce the DDL
-// that takes the second state back to the first.
-type generateMigrationCase struct {
- name string
- initialSchema string
- migrationDDL string
- description string
+ metadata := &storepb.DatabaseSchemaMetadata{}
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(encoded), metadata))
+ return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_ORACLE, false)
}
-// generateMigrationCases returns the fixtures shared by the golden test and the
-// container-backed recorder that captures their metadata.
-func generateMigrationCases() []generateMigrationCase {
- return []generateMigrationCase{
- {
- name: "create_tables_with_fk",
- initialSchema: `
-CREATE TABLE USERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USERNAME VARCHAR2(50) NOT NULL,
- EMAIL VARCHAR2(100) NOT NULL,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE UNIQUE INDEX UK_EMAIL ON USERS(EMAIL);
-CREATE INDEX IDX_USERNAME ON USERS(USERNAME);
-
-CREATE TABLE POSTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USER_ID NUMBER NOT NULL,
- TITLE VARCHAR2(200) NOT NULL,
- CONTENT CLOB,
- PUBLISHED_AT TIMESTAMP,
- CONSTRAINT FK_USER FOREIGN KEY (USER_ID) REFERENCES USERS(ID) ON DELETE CASCADE
-);
-
-CREATE INDEX IDX_USER_ID ON POSTS(USER_ID);
-`,
- migrationDDL: `
-DROP TABLE POSTS CASCADE CONSTRAINTS;
-DROP TABLE USERS CASCADE CONSTRAINTS;`,
- description: "Create tables with foreign key constraints",
- },
- {
- name: "basic_table_operations",
- initialSchema: `
-CREATE TABLE USERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USERNAME VARCHAR2(50) NOT NULL,
- EMAIL VARCHAR2(100) NOT NULL,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE POSTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USER_ID NUMBER NOT NULL,
- TITLE VARCHAR2(200) NOT NULL,
- CONTENT CLOB,
- CONSTRAINT FK_USER FOREIGN KEY (USER_ID) REFERENCES USERS(ID)
-);
-
-CREATE INDEX IDX_POSTS_USER_ID ON POSTS(USER_ID);
-`,
- migrationDDL: `
--- Add new column
-ALTER TABLE USERS ADD IS_ACTIVE NUMBER(1) DEFAULT 1;
-
--- Create new table
-CREATE TABLE COMMENTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- POST_ID NUMBER NOT NULL,
- USER_ID NUMBER NOT NULL,
- CONTENT CLOB NOT NULL,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- CONSTRAINT FK_POST FOREIGN KEY (POST_ID) REFERENCES POSTS(ID),
- CONSTRAINT FK_COMMENT_USER FOREIGN KEY (USER_ID) REFERENCES USERS(ID)
-);
-
--- Add new index
-CREATE INDEX IDX_USERS_EMAIL ON USERS(EMAIL);
-
--- Add check constraint
-ALTER TABLE POSTS ADD CONSTRAINT CHECK_TITLE_LENGTH CHECK (LENGTH(TITLE) > 0);
-`,
- description: "Basic table operations with columns, constraints, and indexes",
- },
- {
- name: "views_and_functions",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PRICE NUMBER(10, 2) NOT NULL,
- STOCK NUMBER DEFAULT 0
-);
-
-CREATE TABLE ORDERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- PRODUCT_ID NUMBER NOT NULL,
- QUANTITY NUMBER NOT NULL,
- TOTAL NUMBER(10, 2),
- CONSTRAINT FK_PRODUCT FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCTS(ID)
-);
-`,
- migrationDDL: `
--- Create view
-CREATE VIEW PRODUCT_INVENTORY AS
-SELECT
- P.ID,
- P.NAME,
- P.PRICE,
- P.STOCK,
- NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED
-FROM PRODUCTS P
-LEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID
-GROUP BY P.ID, P.NAME, P.PRICE, P.STOCK;
-
--- Create function
-CREATE OR REPLACE FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)
-RETURN NUMBER
-IS
- V_PRICE NUMBER(10, 2);
-BEGIN
- SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;
- RETURN P_QUANTITY * V_PRICE;
-EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RETURN 0;
-END;
-/
-
--- Create materialized view
-CREATE MATERIALIZED VIEW PRODUCT_STATS AS
-SELECT
- PRODUCT_ID,
- COUNT(*) AS ORDER_COUNT,
- SUM(QUANTITY) AS TOTAL_QUANTITY,
- SUM(TOTAL) AS TOTAL_REVENUE
-FROM ORDERS
-GROUP BY PRODUCT_ID;
-
--- Create index on materialized view
-CREATE INDEX IDX_PRODUCT_STATS_REVENUE ON PRODUCT_STATS(TOTAL_REVENUE DESC);
-`,
- description: "Views, functions, and materialized views",
- },
- {
- name: "sequences",
- initialSchema: `
-CREATE TABLE ITEMS (
- ID NUMBER PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL
-);
-`,
- migrationDDL: `
--- Create sequence
-CREATE SEQUENCE ORDER_SEQ START WITH 1000 INCREMENT BY 10;
-
--- Create table using sequence
-CREATE TABLE SALES_ORDERS (
- ID NUMBER DEFAULT ORDER_SEQ.NEXTVAL PRIMARY KEY,
- ITEM_ID NUMBER NOT NULL,
- QUANTITY NUMBER NOT NULL,
- CONSTRAINT FK_ITEM FOREIGN KEY (ITEM_ID) REFERENCES ITEMS(ID)
-);
-`,
- description: "Sequences and their usage in tables",
- },
- {
- name: "drop_indexes_and_constraints",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- CATEGORY VARCHAR2(50),
- PRICE NUMBER(10, 2),
- SUPPLIER_ID NUMBER
-);
-
-CREATE INDEX IDX_PRODUCTS_CATEGORY ON PRODUCTS(CATEGORY);
-CREATE INDEX IDX_PRODUCTS_PRICE ON PRODUCTS(PRICE);
-CREATE UNIQUE INDEX IDX_PRODUCTS_NAME ON PRODUCTS(NAME);
-
-ALTER TABLE PRODUCTS ADD CONSTRAINT CHECK_PRICE_POSITIVE CHECK (PRICE > 0);
-ALTER TABLE PRODUCTS ADD CONSTRAINT CHECK_NAME_LENGTH CHECK (LENGTH(NAME) >= 3);
-`,
- migrationDDL: `
--- Drop indexes and constraints
-DROP INDEX IDX_PRODUCTS_CATEGORY;
-DROP INDEX IDX_PRODUCTS_PRICE;
-DROP INDEX IDX_PRODUCTS_NAME;
-ALTER TABLE PRODUCTS DROP CONSTRAINT CHECK_PRICE_POSITIVE;
-ALTER TABLE PRODUCTS DROP CONSTRAINT CHECK_NAME_LENGTH;
-`,
- description: "Drop indexes and constraints from tables",
- },
- {
- name: "drop_views_and_functions",
- initialSchema: `
-CREATE TABLE SALES (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- PRODUCT_NAME VARCHAR2(100) NOT NULL,
- SALE_AMOUNT NUMBER(10, 2) NOT NULL,
- SALE_DATE DATE NOT NULL
-);
-
-CREATE VIEW MONTHLY_SALES AS
-SELECT
- EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,
- EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,
- SUM(SALE_AMOUNT) AS TOTAL_SALES
-FROM SALES
-GROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE);
-
-CREATE MATERIALIZED VIEW TOP_PRODUCTS AS
-SELECT
- PRODUCT_NAME,
- COUNT(*) AS SALE_COUNT,
- SUM(SALE_AMOUNT) AS TOTAL_REVENUE
-FROM SALES
-GROUP BY PRODUCT_NAME
-ORDER BY SUM(SALE_AMOUNT) DESC;
-
-CREATE OR REPLACE FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)
-RETURN NUMBER
-IS
- V_TOTAL NUMBER;
-BEGIN
- SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL
- FROM SALES
- WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM
- AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;
-
- RETURN V_TOTAL;
-END;
-/
-
-CREATE OR REPLACE FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)
-RETURN NUMBER
-IS
-BEGIN
- RETURN AMOUNT * 0.1;
-END;
-/
-`,
- migrationDDL: `
--- Drop views and functions
-DROP MATERIALIZED VIEW TOP_PRODUCTS;
-DROP VIEW MONTHLY_SALES;
-DROP FUNCTION GET_MONTHLY_TOTAL;
-DROP FUNCTION CALCULATE_DISCOUNT;
-`,
- description: "Drop views and functions that depend on tables",
- },
- {
- name: "alter_table_columns",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(50) NOT NULL,
- PRICE NUMBER(8, 2) NOT NULL,
- DESCRIPTION CLOB,
- CATEGORY VARCHAR2(30),
- IS_ACTIVE NUMBER(1) DEFAULT 1
-);
-
-CREATE INDEX IDX_PRODUCTS_CATEGORY ON PRODUCTS(CATEGORY);
-CREATE INDEX IDX_PRODUCTS_PRICE ON PRODUCTS(PRICE);
-`,
- migrationDDL: `
--- Alter table operations
-ALTER TABLE PRODUCTS ADD CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-ALTER TABLE PRODUCTS ADD STOCK_QUANTITY NUMBER DEFAULT 0;
-ALTER TABLE PRODUCTS ADD WEIGHT NUMBER(5, 2);
-
--- Change column types and constraints
-ALTER TABLE PRODUCTS MODIFY NAME VARCHAR2(100);
-ALTER TABLE PRODUCTS MODIFY PRICE NUMBER(10, 2);
-ALTER TABLE PRODUCTS MODIFY DESCRIPTION NOT NULL;
-
--- Add constraints
-ALTER TABLE PRODUCTS ADD CONSTRAINT CHECK_PRICE_POSITIVE CHECK (PRICE > 0);
-ALTER TABLE PRODUCTS ADD CONSTRAINT CHECK_STOCK_NON_NEGATIVE CHECK (STOCK_QUANTITY >= 0);
-
--- Add new index
-CREATE INDEX IDX_PRODUCTS_CREATED_AT ON PRODUCTS(CREATED_AT);
-CREATE UNIQUE INDEX IDX_PRODUCTS_NAME_CATEGORY ON PRODUCTS(NAME, CATEGORY);
-`,
- description: "Alter table with column additions, type changes, and constraints",
- },
- {
- name: "drop_and_recreate_constraints",
- initialSchema: `
-CREATE TABLE AUTHORS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- EMAIL VARCHAR2(100) UNIQUE
-);
-
-CREATE TABLE BOOKS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- TITLE VARCHAR2(200) NOT NULL,
- AUTHOR_ID NUMBER NOT NULL,
- ISBN VARCHAR2(20) UNIQUE,
- PUBLISHED_YEAR NUMBER,
- PRICE NUMBER(8, 2),
- CONSTRAINT FK_AUTHOR FOREIGN KEY (AUTHOR_ID) REFERENCES AUTHORS(ID),
- CONSTRAINT CHECK_YEAR_VALID CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2100),
- CONSTRAINT CHECK_PRICE_POSITIVE CHECK (PRICE > 0)
-);
-
-CREATE INDEX IDX_BOOKS_AUTHOR ON BOOKS(AUTHOR_ID);
-CREATE INDEX IDX_BOOKS_YEAR ON BOOKS(PUBLISHED_YEAR);
-`,
- migrationDDL: `
--- Drop and recreate foreign key with different options
-ALTER TABLE BOOKS DROP CONSTRAINT FK_AUTHOR;
-ALTER TABLE BOOKS ADD CONSTRAINT FK_AUTHOR_NEW FOREIGN KEY (AUTHOR_ID) REFERENCES AUTHORS(ID) ON DELETE CASCADE;
-
--- Drop and modify check constraints
-ALTER TABLE BOOKS DROP CONSTRAINT CHECK_YEAR_VALID;
-ALTER TABLE BOOKS ADD CONSTRAINT CHECK_YEAR_EXTENDED CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2030);
-
--- Add new constraints
-ALTER TABLE BOOKS ADD CONSTRAINT CHECK_TITLE_LENGTH CHECK (LENGTH(TITLE) >= 3);
-`,
- description: "Drop and recreate constraints with different definitions",
- },
- {
- name: "drop_sequence",
- initialSchema: `
-CREATE SEQUENCE TRANSACTION_SEQ START WITH 1000;
-
-CREATE TABLE SIMPLE_LOG (
- ID NUMBER DEFAULT TRANSACTION_SEQ.NEXTVAL PRIMARY KEY,
- MESSAGE CLOB NOT NULL
-);
-`,
- migrationDDL: `
--- Drop table and sequence
-DROP TABLE SIMPLE_LOG;
-DROP SEQUENCE TRANSACTION_SEQ;
-`,
- description: "Drop sequence and dependent table",
- },
- {
- name: "complex_view_dependencies",
- initialSchema: `
-CREATE TABLE DEPARTMENTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- MANAGER_ID NUMBER
-);
-
-CREATE TABLE EMPLOYEES (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- DEPARTMENT_ID NUMBER,
- SALARY NUMBER(10, 2),
- CONSTRAINT FK_DEPT FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENTS(ID)
-);
-
--- Self-referencing foreign key
-ALTER TABLE DEPARTMENTS ADD CONSTRAINT FK_MANAGER FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEES(ID);
-`,
- migrationDDL: `
--- Create base view
-CREATE VIEW DEPT_EMPLOYEE_COUNT AS
-SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT
-FROM DEPARTMENTS D
-LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
-GROUP BY D.ID, D.NAME;
-
--- Create dependent view
-CREATE VIEW DEPT_SUMMARY AS
-SELECT
- DEC.DEPT_ID,
- DEC.DEPT_NAME,
- DEC.EMP_COUNT,
- NVL(AVG(E.SALARY), 0) AS AVG_SALARY
-FROM DEPT_EMPLOYEE_COUNT DEC
-LEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID
-GROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT;
-
--- Create highly dependent view
-CREATE VIEW DEPT_MANAGER_SUMMARY AS
-SELECT
- DS.DEPT_ID,
- DS.DEPT_NAME,
- DS.EMP_COUNT,
- DS.AVG_SALARY,
- M.NAME AS MANAGER_NAME
-FROM DEPT_SUMMARY DS
-JOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID
-LEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID;
-
--- Create materialized view with complex dependencies
-CREATE MATERIALIZED VIEW MV_DEPT_STATS AS
-SELECT
- D.ID AS DEPT_ID,
- D.NAME AS DEPT_NAME,
- COUNT(E.ID) AS TOTAL_EMPLOYEES,
- NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,
- NVL(AVG(E.SALARY), 0) AS AVG_SALARY,
- NVL(MAX(E.SALARY), 0) AS MAX_SALARY,
- NVL(MIN(E.SALARY), 0) AS MIN_SALARY
-FROM DEPARTMENTS D
-LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
-GROUP BY D.ID, D.NAME;
-
--- Create index on materialized view
-CREATE INDEX IDX_MV_DEPT_PAYROLL ON MV_DEPT_STATS(TOTAL_PAYROLL DESC);
-`,
- description: "Complex view dependencies with multiple levels and materialized views",
- },
- {
- name: "circular_foreign_key_dependencies",
- initialSchema: `
-CREATE TABLE CUSTOMERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PREFERRED_ORDER_ID NUMBER
-);
-
-CREATE TABLE ORDERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- CUSTOMER_ID NUMBER NOT NULL,
- ORDER_DATE DATE DEFAULT SYSDATE,
- TOTAL_AMOUNT NUMBER(10, 2)
-);
-`,
- migrationDDL: `
--- Create circular foreign key dependencies
-ALTER TABLE CUSTOMERS ADD CONSTRAINT FK_PREFERRED_ORDER FOREIGN KEY (PREFERRED_ORDER_ID) REFERENCES ORDERS(ID);
-ALTER TABLE ORDERS ADD CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS(ID);
-
--- Add more tables with complex relationships
-CREATE TABLE ORDER_ITEMS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- ORDER_ID NUMBER NOT NULL,
- PRODUCT_NAME VARCHAR2(100) NOT NULL,
- QUANTITY NUMBER NOT NULL,
- UNIT_PRICE NUMBER(10, 2) NOT NULL,
- CONSTRAINT FK_ORDER_ITEM FOREIGN KEY (ORDER_ID) REFERENCES ORDERS(ID) ON DELETE CASCADE
-);
-
--- Create trigger to update order total
-CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL
-AFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS
-FOR EACH ROW
-DECLARE
- V_ORDER_ID NUMBER;
- V_TOTAL NUMBER(10, 2);
-BEGIN
- -- Get order ID
- IF INSERTING OR UPDATING THEN
- V_ORDER_ID := :NEW.ORDER_ID;
- ELSE
- V_ORDER_ID := :OLD.ORDER_ID;
- END IF;
-
- -- Calculate new total
- SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL
- FROM ORDER_ITEMS
- WHERE ORDER_ID = V_ORDER_ID;
-
- -- Update order total
- UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;
-END;
-/
-`,
- description: "Circular foreign key dependencies and triggers",
- },
- {
- name: "advanced_indexes_and_constraints",
- initialSchema: `
-CREATE TABLE SALES_DATA (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY,
- SALE_DATE DATE NOT NULL,
- CUSTOMER_ID NUMBER NOT NULL,
- PRODUCT_ID NUMBER NOT NULL,
- AMOUNT NUMBER(10, 2) NOT NULL,
- REGION VARCHAR2(50) NOT NULL
-);
-`,
- migrationDDL: `
--- Create function-based index
-CREATE INDEX IDX_SALES_MONTH_YEAR ON SALES_DATA(EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE));
-
--- Create composite index with mixed sort order
-CREATE INDEX IDX_SALES_REGION_AMOUNT ON SALES_DATA(REGION ASC, AMOUNT DESC);
-
--- Create unique constraint on composite columns
-ALTER TABLE SALES_DATA ADD CONSTRAINT UK_SALES_DATE_CUSTOMER UNIQUE (SALE_DATE, CUSTOMER_ID, PRODUCT_ID);
-
--- Create check constraint with complex expression
-ALTER TABLE SALES_DATA ADD CONSTRAINT CHK_AMOUNT_RANGE CHECK (AMOUNT > 0 AND AMOUNT <= 999999.99);
-
--- Create conditional check constraint
-ALTER TABLE SALES_DATA ADD CONSTRAINT CHK_REGION_VALID CHECK (REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL'));
-`,
- description: "Advanced Oracle-specific indexes and complex constraints",
- },
- {
- name: "stored_procedures_and_functions",
- initialSchema: `
-CREATE TABLE AUDIT_LOG (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- TABLE_NAME VARCHAR2(100) NOT NULL,
- OPERATION VARCHAR2(10) NOT NULL,
- OLD_VALUES CLOB,
- NEW_VALUES CLOB,
- TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- USER_NAME VARCHAR2(100) DEFAULT USER
-);
-`,
- migrationDDL: `
--- Create stored procedure
-CREATE OR REPLACE PROCEDURE LOG_AUDIT(
- P_TABLE_NAME VARCHAR2,
- P_OPERATION VARCHAR2,
- P_OLD_VALUES CLOB DEFAULT NULL,
- P_NEW_VALUES CLOB DEFAULT NULL
-)
-IS
-BEGIN
- INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)
- VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);
- COMMIT;
-EXCEPTION
- WHEN OTHERS THEN
- ROLLBACK;
- RAISE;
-END;
-/
-
--- Create function with complex logic
-CREATE OR REPLACE FUNCTION CALCULATE_BUSINESS_DAYS(
- P_START_DATE DATE,
- P_END_DATE DATE
-) RETURN NUMBER
-IS
- V_DAYS NUMBER := 0;
- V_CURRENT_DATE DATE := P_START_DATE;
-BEGIN
- WHILE V_CURRENT_DATE <= P_END_DATE LOOP
- -- Skip weekends (Saturday = 7, Sunday = 1)
- IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN
- V_DAYS := V_DAYS + 1;
- END IF;
- V_CURRENT_DATE := V_CURRENT_DATE + 1;
- END LOOP;
-
- RETURN V_DAYS;
-END;
-/
-
--- Create another function for testing dependencies
-CREATE OR REPLACE FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER
-IS
- V_COUNT NUMBER;
-BEGIN
- SELECT COUNT(*) INTO V_COUNT
- FROM AUDIT_LOG
- WHERE TABLE_NAME = P_TABLE_NAME;
-
- RETURN V_COUNT;
-END;
-/
-`,
- description: "Stored procedures and functions with dependencies",
- },
- {
- name: "edge_case_column_operations",
- initialSchema: `
-CREATE TABLE TEST_COLUMNS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- COL_VARCHAR VARCHAR2(50),
- COL_NUMBER NUMBER(10,2),
- COL_DATE DATE,
- COL_CLOB CLOB,
- COL_NULLABLE VARCHAR2(100),
- COL_WITH_DEFAULT VARCHAR2(50) DEFAULT 'DEFAULT_VALUE'
-);
-`,
- migrationDDL: `
--- Test various column modifications
-ALTER TABLE TEST_COLUMNS MODIFY COL_VARCHAR VARCHAR2(200);
-ALTER TABLE TEST_COLUMNS MODIFY COL_NUMBER NUMBER(15,3);
-ALTER TABLE TEST_COLUMNS MODIFY COL_NULLABLE NOT NULL;
-ALTER TABLE TEST_COLUMNS MODIFY COL_WITH_DEFAULT DEFAULT 'NEW_DEFAULT';
-
--- Add columns with various data types and constraints
-ALTER TABLE TEST_COLUMNS ADD COL_TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-ALTER TABLE TEST_COLUMNS ADD COL_BOOLEAN NUMBER(1) CHECK (COL_BOOLEAN IN (0,1));
-
--- Drop some columns
-ALTER TABLE TEST_COLUMNS DROP COLUMN COL_CLOB;
-
--- Add constraints
-ALTER TABLE TEST_COLUMNS ADD CONSTRAINT CHK_VARCHAR_LENGTH CHECK (LENGTH(COL_VARCHAR) >= 5);
-ALTER TABLE TEST_COLUMNS ADD CONSTRAINT CHK_NUMBER_POSITIVE CHECK (COL_NUMBER > 0);
-`,
- description: "Edge cases for column operations and data type modifications",
- },
- {
- name: "reverse_create_tables_with_fk",
- initialSchema: "",
- migrationDDL: `
-CREATE TABLE USERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USERNAME VARCHAR2(50) NOT NULL,
- EMAIL VARCHAR2(100) NOT NULL,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE UNIQUE INDEX UK_EMAIL ON USERS(EMAIL);
-CREATE INDEX IDX_USERNAME ON USERS(USERNAME);
-
-CREATE TABLE POSTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USER_ID NUMBER NOT NULL,
- TITLE VARCHAR2(200) NOT NULL,
- CONTENT CLOB,
- PUBLISHED_AT TIMESTAMP,
- CONSTRAINT FK_USER FOREIGN KEY (USER_ID) REFERENCES USERS(ID) ON DELETE CASCADE
-);
-
-CREATE INDEX IDX_USER_ID ON POSTS(USER_ID);
-`,
- description: "Reverse: Drop tables with foreign key constraints",
- },
- {
- name: "reverse_basic_table_operations",
- initialSchema: `
-CREATE TABLE USERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USERNAME VARCHAR2(50) NOT NULL,
- EMAIL VARCHAR2(100) NOT NULL,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- IS_ACTIVE NUMBER(1) DEFAULT 1
-);
-
-CREATE TABLE POSTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- USER_ID NUMBER NOT NULL,
- TITLE VARCHAR2(200) NOT NULL,
- CONTENT CLOB,
- CONSTRAINT FK_USER FOREIGN KEY (USER_ID) REFERENCES USERS(ID),
- CONSTRAINT CHECK_TITLE_LENGTH CHECK (LENGTH(TITLE) > 0)
-);
-
-CREATE TABLE COMMENTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- POST_ID NUMBER NOT NULL,
- USER_ID NUMBER NOT NULL,
- CONTENT CLOB NOT NULL,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- CONSTRAINT FK_POST FOREIGN KEY (POST_ID) REFERENCES POSTS(ID),
- CONSTRAINT FK_COMMENT_USER FOREIGN KEY (USER_ID) REFERENCES USERS(ID)
-);
-
-CREATE INDEX IDX_POSTS_USER_ID ON POSTS(USER_ID);
-CREATE INDEX IDX_USERS_EMAIL ON USERS(EMAIL);
-`,
- migrationDDL: `
--- Drop table
-DROP TABLE COMMENTS CASCADE CONSTRAINTS;
-
--- Drop index
-DROP INDEX IDX_USERS_EMAIL;
-
--- Drop check constraint
-ALTER TABLE POSTS DROP CONSTRAINT CHECK_TITLE_LENGTH;
-
--- Drop column
-ALTER TABLE USERS DROP COLUMN IS_ACTIVE;
-`,
- description: "Reverse: Drop tables, columns, constraints, and indexes",
- },
- {
- name: "reverse_views_and_functions",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PRICE NUMBER(10, 2) NOT NULL,
- STOCK NUMBER DEFAULT 0
-);
-
-CREATE TABLE ORDERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- PRODUCT_ID NUMBER NOT NULL,
- QUANTITY NUMBER NOT NULL,
- TOTAL NUMBER(10, 2),
- CONSTRAINT FK_PRODUCT FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCTS(ID)
-);
-
-CREATE VIEW PRODUCT_INVENTORY AS
-SELECT
- P.ID,
- P.NAME,
- P.PRICE,
- P.STOCK,
- NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED
-FROM PRODUCTS P
-LEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID
-GROUP BY P.ID, P.NAME, P.PRICE, P.STOCK;
-
-CREATE OR REPLACE FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)
-RETURN NUMBER
-IS
- V_PRICE NUMBER(10, 2);
-BEGIN
- SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;
- RETURN P_QUANTITY * V_PRICE;
-EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RETURN 0;
-END;
-/
-
-CREATE MATERIALIZED VIEW PRODUCT_STATS AS
-SELECT
- PRODUCT_ID,
- COUNT(*) AS ORDER_COUNT,
- SUM(QUANTITY) AS TOTAL_QUANTITY,
- SUM(TOTAL) AS TOTAL_REVENUE
-FROM ORDERS
-GROUP BY PRODUCT_ID;
-
-CREATE INDEX IDX_PRODUCT_STATS_REVENUE ON PRODUCT_STATS(TOTAL_REVENUE DESC);
-`,
- migrationDDL: `
--- Drop index on materialized view
-DROP INDEX IDX_PRODUCT_STATS_REVENUE;
-
--- Drop materialized view
-DROP MATERIALIZED VIEW PRODUCT_STATS;
-
--- Drop function
-DROP FUNCTION CALCULATE_ORDER_TOTAL;
-
--- Drop view
-DROP VIEW PRODUCT_INVENTORY;
-`,
- description: "Reverse: Drop views, functions, and materialized views",
- },
- {
- name: "reverse_sequences",
- initialSchema: `
-CREATE SEQUENCE ORDER_SEQ START WITH 1000 INCREMENT BY 10;
-
-CREATE TABLE ITEMS (
- ID NUMBER PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL
-);
-
-CREATE TABLE SALES_ORDERS (
- ID NUMBER DEFAULT ORDER_SEQ.NEXTVAL PRIMARY KEY,
- ITEM_ID NUMBER NOT NULL,
- QUANTITY NUMBER NOT NULL,
- CONSTRAINT FK_ITEM FOREIGN KEY (ITEM_ID) REFERENCES ITEMS(ID)
-);
-`,
- migrationDDL: `
--- Drop table using sequence
-DROP TABLE SALES_ORDERS CASCADE CONSTRAINTS;
-
--- Drop sequence
-DROP SEQUENCE ORDER_SEQ;
-`,
- description: "Reverse: Drop sequences and tables using them",
- },
- {
- name: "reverse_drop_indexes_and_constraints",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- CATEGORY VARCHAR2(50),
- PRICE NUMBER(10, 2),
- SUPPLIER_ID NUMBER
-);
-`,
- migrationDDL: `
--- Create indexes and constraints
-CREATE INDEX IDX_PRODUCTS_CATEGORY ON PRODUCTS(CATEGORY);
-CREATE INDEX IDX_PRODUCTS_PRICE ON PRODUCTS(PRICE);
-CREATE UNIQUE INDEX IDX_PRODUCTS_NAME ON PRODUCTS(NAME);
-
-ALTER TABLE PRODUCTS ADD CONSTRAINT CHECK_PRICE_POSITIVE CHECK (PRICE > 0);
-ALTER TABLE PRODUCTS ADD CONSTRAINT CHECK_NAME_LENGTH CHECK (LENGTH(NAME) >= 3);
-`,
- description: "Reverse: Create indexes and constraints on tables",
- },
- {
- name: "reverse_drop_views_and_functions",
- initialSchema: `
-CREATE TABLE SALES (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- PRODUCT_NAME VARCHAR2(100) NOT NULL,
- SALE_AMOUNT NUMBER(10, 2) NOT NULL,
- SALE_DATE DATE NOT NULL
-);
-`,
- migrationDDL: `
--- Create views and functions
-CREATE VIEW MONTHLY_SALES AS
-SELECT
- EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,
- EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,
- SUM(SALE_AMOUNT) AS TOTAL_SALES
-FROM SALES
-GROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE);
-
-CREATE MATERIALIZED VIEW TOP_PRODUCTS AS
-SELECT
- PRODUCT_NAME,
- COUNT(*) AS SALE_COUNT,
- SUM(SALE_AMOUNT) AS TOTAL_REVENUE
-FROM SALES
-GROUP BY PRODUCT_NAME
-ORDER BY SUM(SALE_AMOUNT) DESC;
-
-CREATE OR REPLACE FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)
-RETURN NUMBER
-IS
- V_TOTAL NUMBER;
-BEGIN
- SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL
- FROM SALES
- WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM
- AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;
-
- RETURN V_TOTAL;
-END;
-/
-
-CREATE OR REPLACE FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)
-RETURN NUMBER
-IS
-BEGIN
- RETURN AMOUNT * 0.1;
-END;
-/
-`,
- description: "Reverse: Create views and functions that depend on tables",
- },
- {
- name: "reverse_alter_table_columns",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PRICE NUMBER(10, 2) NOT NULL,
- DESCRIPTION CLOB NOT NULL,
- CATEGORY VARCHAR2(30),
- IS_ACTIVE NUMBER(1) DEFAULT 1,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- STOCK_QUANTITY NUMBER DEFAULT 0,
- WEIGHT NUMBER(5, 2),
- CONSTRAINT CHECK_PRICE_POSITIVE CHECK (PRICE > 0),
- CONSTRAINT CHECK_STOCK_NON_NEGATIVE CHECK (STOCK_QUANTITY >= 0)
-);
-
-CREATE INDEX IDX_PRODUCTS_CATEGORY ON PRODUCTS(CATEGORY);
-CREATE INDEX IDX_PRODUCTS_PRICE ON PRODUCTS(PRICE);
-CREATE INDEX IDX_PRODUCTS_CREATED_AT ON PRODUCTS(CREATED_AT);
-CREATE UNIQUE INDEX IDX_PRODUCTS_NAME_CATEGORY ON PRODUCTS(NAME, CATEGORY);
-`,
- migrationDDL: `
--- Drop indexes
-DROP INDEX IDX_PRODUCTS_NAME_CATEGORY;
-DROP INDEX IDX_PRODUCTS_CREATED_AT;
-
--- Drop constraints
-ALTER TABLE PRODUCTS DROP CONSTRAINT CHECK_STOCK_NON_NEGATIVE;
-ALTER TABLE PRODUCTS DROP CONSTRAINT CHECK_PRICE_POSITIVE;
-
--- Revert column changes
-ALTER TABLE PRODUCTS MODIFY DESCRIPTION NULL;
-ALTER TABLE PRODUCTS MODIFY PRICE NUMBER(8, 2);
-ALTER TABLE PRODUCTS MODIFY NAME VARCHAR2(50);
-
--- Drop columns
-ALTER TABLE PRODUCTS DROP COLUMN WEIGHT;
-ALTER TABLE PRODUCTS DROP COLUMN STOCK_QUANTITY;
-ALTER TABLE PRODUCTS DROP COLUMN CREATED_AT;
-`,
- description: "Reverse: Remove columns, constraints and revert type changes",
- },
- {
- name: "reverse_drop_and_recreate_constraints",
- initialSchema: `
-CREATE TABLE AUTHORS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- EMAIL VARCHAR2(100) UNIQUE
-);
-
-CREATE TABLE BOOKS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- TITLE VARCHAR2(200) NOT NULL,
- AUTHOR_ID NUMBER NOT NULL,
- ISBN VARCHAR2(20) UNIQUE,
- PUBLISHED_YEAR NUMBER,
- PRICE NUMBER(8, 2),
- CONSTRAINT FK_AUTHOR_NEW FOREIGN KEY (AUTHOR_ID) REFERENCES AUTHORS(ID) ON DELETE CASCADE,
- CONSTRAINT CHECK_YEAR_EXTENDED CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2030),
- CONSTRAINT CHECK_TITLE_LENGTH CHECK (LENGTH(TITLE) >= 3)
-);
-
-CREATE INDEX IDX_BOOKS_AUTHOR ON BOOKS(AUTHOR_ID);
-CREATE INDEX IDX_BOOKS_YEAR ON BOOKS(PUBLISHED_YEAR);
-`,
- migrationDDL: `
--- Drop new constraints
-ALTER TABLE BOOKS DROP CONSTRAINT CHECK_TITLE_LENGTH;
-ALTER TABLE BOOKS DROP CONSTRAINT CHECK_YEAR_EXTENDED;
-ALTER TABLE BOOKS DROP CONSTRAINT FK_AUTHOR_NEW;
-
--- Recreate original constraints
-ALTER TABLE BOOKS ADD CONSTRAINT FK_AUTHOR FOREIGN KEY (AUTHOR_ID) REFERENCES AUTHORS(ID);
-ALTER TABLE BOOKS ADD CONSTRAINT CHECK_YEAR_VALID CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2100);
-ALTER TABLE BOOKS ADD CONSTRAINT CHECK_PRICE_POSITIVE CHECK (PRICE > 0);
-`,
- description: "Reverse: Revert constraint modifications",
- },
- {
- name: "reverse_drop_sequence",
- initialSchema: "",
- migrationDDL: `
--- Create sequence and table
-CREATE SEQUENCE TRANSACTION_SEQ START WITH 1000;
-
-CREATE TABLE SIMPLE_LOG (
- ID NUMBER DEFAULT TRANSACTION_SEQ.NEXTVAL PRIMARY KEY,
- MESSAGE CLOB NOT NULL
-);
-`,
- description: "Reverse: Create sequence and dependent table",
- },
- {
- name: "reverse_complex_view_dependencies",
- initialSchema: `
-CREATE TABLE DEPARTMENTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- MANAGER_ID NUMBER
-);
-
-CREATE TABLE EMPLOYEES (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- DEPARTMENT_ID NUMBER,
- SALARY NUMBER(10, 2),
- CONSTRAINT FK_DEPT FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENTS(ID)
-);
-
-ALTER TABLE DEPARTMENTS ADD CONSTRAINT FK_MANAGER FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEES(ID);
-
-CREATE VIEW DEPT_EMPLOYEE_COUNT AS
-SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT
-FROM DEPARTMENTS D
-LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
-GROUP BY D.ID, D.NAME;
-
-CREATE VIEW DEPT_SUMMARY AS
-SELECT
- DEC.DEPT_ID,
- DEC.DEPT_NAME,
- DEC.EMP_COUNT,
- NVL(AVG(E.SALARY), 0) AS AVG_SALARY
-FROM DEPT_EMPLOYEE_COUNT DEC
-LEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID
-GROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT;
-
-CREATE VIEW DEPT_MANAGER_SUMMARY AS
-SELECT
- DS.DEPT_ID,
- DS.DEPT_NAME,
- DS.EMP_COUNT,
- DS.AVG_SALARY,
- M.NAME AS MANAGER_NAME
-FROM DEPT_SUMMARY DS
-JOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID
-LEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID;
-
-CREATE MATERIALIZED VIEW MV_DEPT_STATS AS
-SELECT
- D.ID AS DEPT_ID,
- D.NAME AS DEPT_NAME,
- COUNT(E.ID) AS TOTAL_EMPLOYEES,
- NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,
- NVL(AVG(E.SALARY), 0) AS AVG_SALARY,
- NVL(MAX(E.SALARY), 0) AS MAX_SALARY,
- NVL(MIN(E.SALARY), 0) AS MIN_SALARY
-FROM DEPARTMENTS D
-LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
-GROUP BY D.ID, D.NAME;
-
-CREATE INDEX IDX_MV_DEPT_PAYROLL ON MV_DEPT_STATS(TOTAL_PAYROLL DESC);
-`,
- migrationDDL: `
--- Drop index on materialized view
-DROP INDEX IDX_MV_DEPT_PAYROLL;
-
--- Drop materialized view
-DROP MATERIALIZED VIEW MV_DEPT_STATS;
-
--- Drop views in dependency order
-DROP VIEW DEPT_MANAGER_SUMMARY;
-DROP VIEW DEPT_SUMMARY;
-DROP VIEW DEPT_EMPLOYEE_COUNT;
-`,
- description: "Reverse: Drop complex view dependencies",
- },
- {
- name: "reverse_circular_foreign_key_dependencies",
- initialSchema: `
-CREATE TABLE CUSTOMERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PREFERRED_ORDER_ID NUMBER
-);
-
-CREATE TABLE ORDERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- CUSTOMER_ID NUMBER NOT NULL,
- ORDER_DATE DATE DEFAULT SYSDATE,
- TOTAL_AMOUNT NUMBER(10, 2)
-);
-
-ALTER TABLE CUSTOMERS ADD CONSTRAINT FK_PREFERRED_ORDER FOREIGN KEY (PREFERRED_ORDER_ID) REFERENCES ORDERS(ID);
-ALTER TABLE ORDERS ADD CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS(ID);
-
-CREATE TABLE ORDER_ITEMS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- ORDER_ID NUMBER NOT NULL,
- PRODUCT_NAME VARCHAR2(100) NOT NULL,
- QUANTITY NUMBER NOT NULL,
- UNIT_PRICE NUMBER(10, 2) NOT NULL,
- CONSTRAINT FK_ORDER_ITEM FOREIGN KEY (ORDER_ID) REFERENCES ORDERS(ID) ON DELETE CASCADE
-);
-
-CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL
-AFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS
-FOR EACH ROW
-DECLARE
- V_ORDER_ID NUMBER;
- V_TOTAL NUMBER(10, 2);
-BEGIN
- -- Get order ID
- IF INSERTING OR UPDATING THEN
- V_ORDER_ID := :NEW.ORDER_ID;
- ELSE
- V_ORDER_ID := :OLD.ORDER_ID;
- END IF;
-
- -- Calculate new total
- SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL
- FROM ORDER_ITEMS
- WHERE ORDER_ID = V_ORDER_ID;
-
- -- Update order total
- UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;
-END;
-/
-`,
- migrationDDL: `
--- Drop trigger
-DROP TRIGGER TRG_UPDATE_ORDER_TOTAL;
-
--- Drop table with foreign key
-DROP TABLE ORDER_ITEMS CASCADE CONSTRAINTS;
-
--- Drop circular foreign keys
-ALTER TABLE ORDERS DROP CONSTRAINT FK_CUSTOMER;
-ALTER TABLE CUSTOMERS DROP CONSTRAINT FK_PREFERRED_ORDER;
-`,
- description: "Reverse: Remove circular foreign key dependencies and triggers",
- },
- {
- name: "reverse_advanced_indexes_and_constraints",
- initialSchema: `
-CREATE TABLE SALES_DATA (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY,
- SALE_DATE DATE NOT NULL,
- CUSTOMER_ID NUMBER NOT NULL,
- PRODUCT_ID NUMBER NOT NULL,
- AMOUNT NUMBER(10, 2) NOT NULL,
- REGION VARCHAR2(50) NOT NULL,
- CONSTRAINT UK_SALES_DATE_CUSTOMER UNIQUE (SALE_DATE, CUSTOMER_ID, PRODUCT_ID),
- CONSTRAINT CHK_AMOUNT_RANGE CHECK (AMOUNT > 0 AND AMOUNT <= 999999.99),
- CONSTRAINT CHK_REGION_VALID CHECK (REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL'))
-);
-
-CREATE INDEX IDX_SALES_MONTH_YEAR ON SALES_DATA(EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE));
-CREATE INDEX IDX_SALES_REGION_AMOUNT ON SALES_DATA(REGION ASC, AMOUNT DESC);
-`,
- migrationDDL: `
--- Drop indexes
-DROP INDEX IDX_SALES_REGION_AMOUNT;
-DROP INDEX IDX_SALES_MONTH_YEAR;
-
--- Drop constraints
-ALTER TABLE SALES_DATA DROP CONSTRAINT CHK_REGION_VALID;
-ALTER TABLE SALES_DATA DROP CONSTRAINT CHK_AMOUNT_RANGE;
-ALTER TABLE SALES_DATA DROP CONSTRAINT UK_SALES_DATE_CUSTOMER;
-`,
- description: "Reverse: Remove advanced indexes and complex constraints",
- },
- {
- name: "reverse_stored_procedures_and_functions",
- initialSchema: `
-CREATE TABLE AUDIT_LOG (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- TABLE_NAME VARCHAR2(100) NOT NULL,
- OPERATION VARCHAR2(10) NOT NULL,
- OLD_VALUES CLOB,
- NEW_VALUES CLOB,
- TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- USER_NAME VARCHAR2(100) DEFAULT USER
-);
-
-CREATE OR REPLACE PROCEDURE LOG_AUDIT(
- P_TABLE_NAME VARCHAR2,
- P_OPERATION VARCHAR2,
- P_OLD_VALUES CLOB DEFAULT NULL,
- P_NEW_VALUES CLOB DEFAULT NULL
-)
-IS
-BEGIN
- INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)
- VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);
- COMMIT;
-EXCEPTION
- WHEN OTHERS THEN
- ROLLBACK;
- RAISE;
-END;
-/
-
-CREATE OR REPLACE FUNCTION CALCULATE_BUSINESS_DAYS(
- P_START_DATE DATE,
- P_END_DATE DATE
-) RETURN NUMBER
-IS
- V_DAYS NUMBER := 0;
- V_CURRENT_DATE DATE := P_START_DATE;
-BEGIN
- WHILE V_CURRENT_DATE <= P_END_DATE LOOP
- -- Skip weekends (Saturday = 7, Sunday = 1)
- IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN
- V_DAYS := V_DAYS + 1;
- END IF;
- V_CURRENT_DATE := V_CURRENT_DATE + 1;
- END LOOP;
-
- RETURN V_DAYS;
-END;
-/
-
-CREATE OR REPLACE FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER
-IS
- V_COUNT NUMBER;
-BEGIN
- SELECT COUNT(*) INTO V_COUNT
- FROM AUDIT_LOG
- WHERE TABLE_NAME = P_TABLE_NAME;
-
- RETURN V_COUNT;
-END;
-/
-`,
- migrationDDL: `
--- Drop functions and procedures
-DROP FUNCTION GET_AUDIT_COUNT;
-DROP FUNCTION CALCULATE_BUSINESS_DAYS;
-DROP PROCEDURE LOG_AUDIT;
-`,
- description: "Reverse: Remove stored procedures and functions",
- },
- {
- name: "reverse_edge_case_column_operations",
- initialSchema: `
-CREATE TABLE TEST_COLUMNS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- COL_VARCHAR VARCHAR2(200) NOT NULL,
- COL_NUMBER NUMBER(15,3),
- COL_DATE DATE,
- COL_NULLABLE VARCHAR2(100) NOT NULL,
- COL_WITH_DEFAULT VARCHAR2(50) DEFAULT 'NEW_DEFAULT',
- COL_TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- COL_BOOLEAN NUMBER(1) CHECK (COL_BOOLEAN IN (0,1)),
- CONSTRAINT CHK_VARCHAR_LENGTH CHECK (LENGTH(COL_VARCHAR) >= 5),
- CONSTRAINT CHK_NUMBER_POSITIVE CHECK (COL_NUMBER > 0)
-);
-`,
- migrationDDL: `
--- Drop constraints
-ALTER TABLE TEST_COLUMNS DROP CONSTRAINT CHK_NUMBER_POSITIVE;
-ALTER TABLE TEST_COLUMNS DROP CONSTRAINT CHK_VARCHAR_LENGTH;
-
--- Drop columns
-ALTER TABLE TEST_COLUMNS DROP COLUMN COL_BOOLEAN;
-ALTER TABLE TEST_COLUMNS DROP COLUMN COL_TIMESTAMP;
-
--- Add back dropped column
-ALTER TABLE TEST_COLUMNS ADD COL_CLOB CLOB;
-
--- Revert column modifications
-ALTER TABLE TEST_COLUMNS MODIFY COL_WITH_DEFAULT DEFAULT 'DEFAULT_VALUE';
-ALTER TABLE TEST_COLUMNS MODIFY COL_NULLABLE NULL;
-ALTER TABLE TEST_COLUMNS MODIFY COL_NUMBER NUMBER(10,2);
-ALTER TABLE TEST_COLUMNS MODIFY COL_VARCHAR VARCHAR2(50);
-`,
- description: "Reverse: Revert edge case column operations",
- },
- {
- name: "table_and_column_comments",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PRICE NUMBER(10, 2) NOT NULL,
- DESCRIPTION CLOB,
- CATEGORY VARCHAR2(50),
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE CUSTOMERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- EMAIL VARCHAR2(100),
- PHONE VARCHAR2(20),
- ADDRESS CLOB
-);
-
-CREATE INDEX IDX_PRODUCTS_CATEGORY ON PRODUCTS(CATEGORY);
-CREATE UNIQUE INDEX IDX_CUSTOMERS_EMAIL ON CUSTOMERS(EMAIL);
-`,
- migrationDDL: `
--- Add table comments
-COMMENT ON TABLE PRODUCTS IS 'Product catalog table containing all product information';
-COMMENT ON TABLE CUSTOMERS IS 'Customer information and contact details';
-
--- Add column comments
-COMMENT ON COLUMN PRODUCTS.ID IS 'Unique product identifier (auto-generated)';
-COMMENT ON COLUMN PRODUCTS.NAME IS 'Product name - must be unique and descriptive';
-COMMENT ON COLUMN PRODUCTS.PRICE IS 'Product price in USD with 2 decimal places';
-COMMENT ON COLUMN PRODUCTS.DESCRIPTION IS 'Detailed product description with HTML formatting support';
-COMMENT ON COLUMN PRODUCTS.CATEGORY IS 'Product category for filtering and organization';
-COMMENT ON COLUMN PRODUCTS.CREATED_AT IS 'Timestamp when the product was added to catalog';
-
-COMMENT ON COLUMN CUSTOMERS.ID IS 'Primary key for customer records';
-COMMENT ON COLUMN CUSTOMERS.NAME IS 'Full name of the customer';
-COMMENT ON COLUMN CUSTOMERS.EMAIL IS 'Customer email address (unique)';
-COMMENT ON COLUMN CUSTOMERS.PHONE IS 'Contact phone number';
-COMMENT ON COLUMN CUSTOMERS.ADDRESS IS 'Full mailing address with multiple lines';
-
--- Create new table with comments immediately
-CREATE TABLE ORDERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- CUSTOMER_ID NUMBER NOT NULL,
- PRODUCT_ID NUMBER NOT NULL,
- ORDER_DATE DATE DEFAULT SYSDATE,
- QUANTITY NUMBER NOT NULL,
- TOTAL_AMOUNT NUMBER(12, 2),
- STATUS VARCHAR2(20) DEFAULT 'PENDING',
- CONSTRAINT FK_ORDER_CUSTOMER FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS(ID),
- CONSTRAINT FK_ORDER_PRODUCT FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCTS(ID)
-);
-
--- Add comments to the new table
-COMMENT ON TABLE ORDERS IS 'Customer orders linking products and customers';
-COMMENT ON COLUMN ORDERS.ID IS 'Unique order identifier';
-COMMENT ON COLUMN ORDERS.CUSTOMER_ID IS 'Reference to customer who placed the order';
-COMMENT ON COLUMN ORDERS.PRODUCT_ID IS 'Reference to ordered product';
-COMMENT ON COLUMN ORDERS.ORDER_DATE IS 'Date when the order was placed';
-COMMENT ON COLUMN ORDERS.QUANTITY IS 'Number of items ordered';
-COMMENT ON COLUMN ORDERS.TOTAL_AMOUNT IS 'Total order amount including taxes';
-COMMENT ON COLUMN ORDERS.STATUS IS 'Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)';
-`,
- description: "Add comprehensive comments to tables and columns using Oracle COMMENT syntax",
- },
- {
- name: "modify_and_drop_comments",
- initialSchema: `
-CREATE TABLE INVENTORY (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- PRODUCT_CODE VARCHAR2(50) NOT NULL,
- STOCK_LEVEL NUMBER NOT NULL,
- MIN_STOCK NUMBER DEFAULT 10,
- MAX_STOCK NUMBER DEFAULT 1000,
- WAREHOUSE_ID NUMBER,
- LAST_UPDATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
--- Add initial comments
-COMMENT ON TABLE INVENTORY IS 'Initial inventory tracking table';
-COMMENT ON COLUMN INVENTORY.ID IS 'Primary key for inventory records';
-COMMENT ON COLUMN INVENTORY.PRODUCT_CODE IS 'Product identification code';
-COMMENT ON COLUMN INVENTORY.STOCK_LEVEL IS 'Current stock quantity';
-COMMENT ON COLUMN INVENTORY.MIN_STOCK IS 'Minimum stock threshold';
-COMMENT ON COLUMN INVENTORY.MAX_STOCK IS 'Maximum stock capacity';
-COMMENT ON COLUMN INVENTORY.WAREHOUSE_ID IS 'Warehouse location identifier';
-
-CREATE TABLE SUPPLIERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- CONTACT_EMAIL VARCHAR2(100),
- RATING NUMBER(2,1)
-);
-
-COMMENT ON TABLE SUPPLIERS IS 'Supplier information table';
-COMMENT ON COLUMN SUPPLIERS.NAME IS 'Supplier company name';
-COMMENT ON COLUMN SUPPLIERS.CONTACT_EMAIL IS 'Primary contact email';
-`,
- migrationDDL: `
--- Modify existing table comment
-COMMENT ON TABLE INVENTORY IS 'Updated inventory management system with enhanced tracking capabilities';
-
--- Modify existing column comments
-COMMENT ON COLUMN INVENTORY.PRODUCT_CODE IS 'Updated: Standardized product SKU following new naming convention';
-COMMENT ON COLUMN INVENTORY.STOCK_LEVEL IS 'Updated: Real-time stock quantity with automated updates';
-COMMENT ON COLUMN INVENTORY.MIN_STOCK IS 'Updated: Dynamic minimum threshold based on sales velocity';
-
--- Remove comments by setting to empty string
-COMMENT ON COLUMN INVENTORY.MAX_STOCK IS '';
-COMMENT ON COLUMN INVENTORY.WAREHOUSE_ID IS '';
-
--- Remove table comment
-COMMENT ON TABLE SUPPLIERS IS '';
-
--- Remove specific column comments using empty string
-COMMENT ON COLUMN SUPPLIERS.CONTACT_EMAIL IS '';
-
--- Add new comment to previously uncommented column
-COMMENT ON COLUMN INVENTORY.LAST_UPDATED IS 'Timestamp of last inventory update or modification';
-
--- Add new column with comment
-ALTER TABLE INVENTORY ADD REORDER_POINT NUMBER DEFAULT 0;
-COMMENT ON COLUMN INVENTORY.REORDER_POINT IS 'Calculated reorder point based on lead time and demand';
-
--- Modify existing column comment after it was cleared
-COMMENT ON COLUMN SUPPLIERS.RATING IS 'Supplier performance rating (1.0 to 5.0 scale)';
-`,
- description: "Modify existing comments and remove comments using empty string",
- },
- {
- name: "comments_with_special_characters",
- initialSchema: `
-CREATE TABLE SPECIAL_DATA (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- DATA_VALUE VARCHAR2(500),
- METADATA_JSON CLOB,
- UNICODE_TEXT NVARCHAR2(200),
- BINARY_DATA BLOB,
- CATEGORY VARCHAR2(100),
- STATUS VARCHAR2(50)
-);
-
-CREATE TABLE MULTILANG_CONTENT (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- TITLE_EN VARCHAR2(200),
- TITLE_ES VARCHAR2(200),
- TITLE_ZH NVARCHAR2(200),
- CONTENT_TEXT CLOB,
- TAGS VARCHAR2(1000)
-);
-`,
- migrationDDL: `
--- Comments with single quotes and escaping
-COMMENT ON TABLE SPECIAL_DATA IS 'Table containing "special" data with various formats & types';
-COMMENT ON COLUMN SPECIAL_DATA.DATA_VALUE IS 'Data value field - supports NULL, empty strings, and ''quoted'' content';
-
--- Comments with double quotes
-COMMENT ON COLUMN SPECIAL_DATA.METADATA_JSON IS 'JSON metadata: {"key": "value", "array": [1,2,3]}';
-
--- Multi-line comments with line breaks and special characters
-COMMENT ON COLUMN SPECIAL_DATA.UNICODE_TEXT IS 'Unicode text support:
-Line 1: Basic ASCII text
-Line 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?
-Line 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π
-Line 4: Currencies $ € £ ¥ ₹';
-
--- Comments with backslashes and escape sequences
-COMMENT ON COLUMN SPECIAL_DATA.BINARY_DATA IS 'Binary data storage\nSupports: images, documents, archives\tTab-separated info\r\nWindows line endings';
-
--- Comments with percent signs and wildcards
-COMMENT ON COLUMN SPECIAL_DATA.CATEGORY IS 'Category field: use % for wildcard searches, _ for single char matching';
-
--- Comments with SQL injection-like patterns (should be safely handled)
-COMMENT ON COLUMN SPECIAL_DATA.STATUS IS 'Status field - values: ''ACTIVE'', ''INACTIVE'', ''PENDING''; DROP TABLE users; --';
-
--- Unicode comments with international characters
-COMMENT ON TABLE MULTILANG_CONTENT IS 'Multilingual content: English, Español, 中文, العربية, Русский, 日本語';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_EN IS 'English title field';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_ES IS 'Título en español';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_ZH IS '中文标题字段 - 支持简体和繁体中文';
-
--- Long comment with mixed content
-COMMENT ON COLUMN MULTILANG_CONTENT.CONTENT_TEXT IS 'Content field supporting:
-1. HTML tags: <b>bold</b>, <i>italic</i>, <a href="http://example.com">links</a>
-2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick
-3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″
-4. Emojis: 😀 😃 😄 😁 🚀 ⭐ 🎉 💯
-5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2';
-
--- Comment with XML/HTML content
-COMMENT ON COLUMN MULTILANG_CONTENT.TAGS IS 'XML tags: <tag type="category" value="news"/><tag type="priority" value="high"/>End of XML';
-
--- Create additional table to test more complex scenarios
-CREATE TABLE COMPLEX_TYPES (
- ID NUMBER PRIMARY KEY,
- XML_DATA XMLTYPE,
- TIMESTAMP_TZ TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
- INTERVAL_DS INTERVAL DAY TO SECOND,
- RAW_DATA RAW(100),
- LONG_RAW_DATA LONG RAW
-);
-
--- Comments with technical specifications
-COMMENT ON TABLE COMPLEX_TYPES IS 'Advanced data types testing table
-Supports: XMLType, Timestamps with timezone, Intervals, RAW data
-Performance: Optimized for OLTP workloads @ 10K+ TPS
-Security: Row-level security enabled, audit trails maintained';
-
-COMMENT ON COLUMN COMPLEX_TYPES.XML_DATA IS 'XMLType column for structured XML storage
-Example: <?xml version="1.0" encoding="UTF-8"?>
-<root><item id="1" name="test">Content</item></root>';
-
-COMMENT ON COLUMN COMPLEX_TYPES.TIMESTAMP_TZ IS 'Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR
-Default: SYSTIMESTAMP (system timestamp with session timezone)';
-
-COMMENT ON COLUMN COMPLEX_TYPES.INTERVAL_DS IS 'Interval Day to Second: +/-DD HH:MI:SS.FFFFFF
-Range: +/-999999999 days, precision up to nanoseconds';
-`,
- description: "Test comments with special characters, quotes, Unicode, multi-line text, and complex content",
- },
- {
- name: "reverse_table_and_column_comments",
- initialSchema: `
-CREATE TABLE PRODUCTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PRICE NUMBER(10, 2) NOT NULL,
- DESCRIPTION CLOB,
- CATEGORY VARCHAR2(50),
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE CUSTOMERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- EMAIL VARCHAR2(100),
- PHONE VARCHAR2(20),
- ADDRESS CLOB
-);
-
-CREATE TABLE ORDERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- CUSTOMER_ID NUMBER NOT NULL,
- PRODUCT_ID NUMBER NOT NULL,
- ORDER_DATE DATE DEFAULT SYSDATE,
- QUANTITY NUMBER NOT NULL,
- TOTAL_AMOUNT NUMBER(12, 2),
- STATUS VARCHAR2(20) DEFAULT 'PENDING',
- CONSTRAINT FK_ORDER_CUSTOMER FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMERS(ID),
- CONSTRAINT FK_ORDER_PRODUCT FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCTS(ID)
-);
-
-CREATE INDEX IDX_PRODUCTS_CATEGORY ON PRODUCTS(CATEGORY);
-CREATE UNIQUE INDEX IDX_CUSTOMERS_EMAIL ON CUSTOMERS(EMAIL);
-
--- Add all comments
-COMMENT ON TABLE PRODUCTS IS 'Product catalog table containing all product information';
-COMMENT ON TABLE CUSTOMERS IS 'Customer information and contact details';
-COMMENT ON COLUMN PRODUCTS.ID IS 'Unique product identifier (auto-generated)';
-COMMENT ON COLUMN PRODUCTS.NAME IS 'Product name - must be unique and descriptive';
-COMMENT ON COLUMN PRODUCTS.PRICE IS 'Product price in USD with 2 decimal places';
-COMMENT ON COLUMN PRODUCTS.DESCRIPTION IS 'Detailed product description with HTML formatting support';
-COMMENT ON COLUMN PRODUCTS.CATEGORY IS 'Product category for filtering and organization';
-COMMENT ON COLUMN PRODUCTS.CREATED_AT IS 'Timestamp when the product was added to catalog';
-COMMENT ON COLUMN CUSTOMERS.ID IS 'Primary key for customer records';
-COMMENT ON COLUMN CUSTOMERS.NAME IS 'Full name of the customer';
-COMMENT ON COLUMN CUSTOMERS.EMAIL IS 'Customer email address (unique)';
-COMMENT ON COLUMN CUSTOMERS.PHONE IS 'Contact phone number';
-COMMENT ON COLUMN CUSTOMERS.ADDRESS IS 'Full mailing address with multiple lines';
-COMMENT ON TABLE ORDERS IS 'Customer orders linking products and customers';
-COMMENT ON COLUMN ORDERS.ID IS 'Unique order identifier';
-COMMENT ON COLUMN ORDERS.CUSTOMER_ID IS 'Reference to customer who placed the order';
-COMMENT ON COLUMN ORDERS.PRODUCT_ID IS 'Reference to ordered product';
-COMMENT ON COLUMN ORDERS.ORDER_DATE IS 'Date when the order was placed';
-COMMENT ON COLUMN ORDERS.QUANTITY IS 'Number of items ordered';
-COMMENT ON COLUMN ORDERS.TOTAL_AMOUNT IS 'Total order amount including taxes';
-COMMENT ON COLUMN ORDERS.STATUS IS 'Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)';
-`,
- migrationDDL: `
--- Remove all comments
-COMMENT ON COLUMN ORDERS.STATUS IS '';
-COMMENT ON COLUMN ORDERS.TOTAL_AMOUNT IS '';
-COMMENT ON COLUMN ORDERS.QUANTITY IS '';
-COMMENT ON COLUMN ORDERS.ORDER_DATE IS '';
-COMMENT ON COLUMN ORDERS.PRODUCT_ID IS '';
-COMMENT ON COLUMN ORDERS.CUSTOMER_ID IS '';
-COMMENT ON COLUMN ORDERS.ID IS '';
-COMMENT ON TABLE ORDERS IS '';
-
-COMMENT ON COLUMN CUSTOMERS.ADDRESS IS '';
-COMMENT ON COLUMN CUSTOMERS.PHONE IS '';
-COMMENT ON COLUMN CUSTOMERS.EMAIL IS '';
-COMMENT ON COLUMN CUSTOMERS.NAME IS '';
-COMMENT ON COLUMN CUSTOMERS.ID IS '';
-
-COMMENT ON COLUMN PRODUCTS.CREATED_AT IS '';
-COMMENT ON COLUMN PRODUCTS.CATEGORY IS '';
-COMMENT ON COLUMN PRODUCTS.DESCRIPTION IS '';
-COMMENT ON COLUMN PRODUCTS.PRICE IS '';
-COMMENT ON COLUMN PRODUCTS.NAME IS '';
-COMMENT ON COLUMN PRODUCTS.ID IS '';
-
-COMMENT ON TABLE CUSTOMERS IS '';
-COMMENT ON TABLE PRODUCTS IS '';
-
--- Drop the ORDERS table
-DROP TABLE ORDERS CASCADE CONSTRAINTS;
-`,
- description: "Reverse: Remove all comments and drop a table",
- },
- {
- name: "reverse_modify_and_drop_comments",
- initialSchema: `
-CREATE TABLE INVENTORY (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- PRODUCT_CODE VARCHAR2(50) NOT NULL,
- STOCK_LEVEL NUMBER NOT NULL,
- MIN_STOCK NUMBER DEFAULT 10,
- MAX_STOCK NUMBER DEFAULT 1000,
- WAREHOUSE_ID NUMBER,
- LAST_UPDATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- REORDER_POINT NUMBER DEFAULT 0
-);
-
-CREATE TABLE SUPPLIERS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- CONTACT_EMAIL VARCHAR2(100),
- RATING NUMBER(2,1)
-);
-
--- Modified comments
-COMMENT ON TABLE INVENTORY IS 'Updated inventory management system with enhanced tracking capabilities';
-COMMENT ON COLUMN INVENTORY.PRODUCT_CODE IS 'Updated: Standardized product SKU following new naming convention';
-COMMENT ON COLUMN INVENTORY.STOCK_LEVEL IS 'Updated: Real-time stock quantity with automated updates';
-COMMENT ON COLUMN INVENTORY.MIN_STOCK IS 'Updated: Dynamic minimum threshold based on sales velocity';
-COMMENT ON COLUMN INVENTORY.LAST_UPDATED IS 'Timestamp of last inventory update or modification';
-COMMENT ON COLUMN INVENTORY.REORDER_POINT IS 'Calculated reorder point based on lead time and demand';
-COMMENT ON COLUMN SUPPLIERS.RATING IS 'Supplier performance rating (1.0 to 5.0 scale)';
-`,
- migrationDDL: `
--- Drop column with comment
-ALTER TABLE INVENTORY DROP COLUMN REORDER_POINT;
-
--- Add comment to new column
-COMMENT ON COLUMN INVENTORY.WAREHOUSE_ID IS 'Warehouse location identifier';
-
--- Restore original comment
-COMMENT ON COLUMN INVENTORY.MIN_STOCK IS 'Minimum stock threshold';
-
--- Remove other updated comments
-COMMENT ON COLUMN INVENTORY.STOCK_LEVEL IS 'Current stock quantity';
-COMMENT ON COLUMN INVENTORY.PRODUCT_CODE IS 'Product identification code';
-
--- Add comments that were removed
-COMMENT ON TABLE SUPPLIERS IS 'Supplier information table';
-COMMENT ON COLUMN SUPPLIERS.CONTACT_EMAIL IS 'Primary contact email';
-
--- Restore other columns that had comments removed
-COMMENT ON COLUMN INVENTORY.MAX_STOCK IS 'Maximum stock capacity';
-
--- Change table comment
-COMMENT ON TABLE INVENTORY IS 'Initial inventory tracking table';
-
--- Remove comments
-COMMENT ON COLUMN SUPPLIERS.RATING IS '';
-COMMENT ON COLUMN INVENTORY.LAST_UPDATED IS '';
-`,
- description: "Reverse: Restore original comments and modify state",
- },
- {
- name: "reverse_comments_with_special_characters",
- initialSchema: `
-CREATE TABLE SPECIAL_DATA (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- DATA_VALUE VARCHAR2(500),
- METADATA_JSON CLOB,
- UNICODE_TEXT NVARCHAR2(200),
- BINARY_DATA BLOB,
- CATEGORY VARCHAR2(100),
- STATUS VARCHAR2(50)
-);
-
-CREATE TABLE MULTILANG_CONTENT (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- TITLE_EN VARCHAR2(200),
- TITLE_ES VARCHAR2(200),
- TITLE_ZH NVARCHAR2(200),
- CONTENT_TEXT CLOB,
- TAGS VARCHAR2(1000)
-);
-
-CREATE TABLE COMPLEX_TYPES (
- ID NUMBER PRIMARY KEY,
- XML_DATA XMLTYPE,
- TIMESTAMP_TZ TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
- INTERVAL_DS INTERVAL DAY TO SECOND,
- RAW_DATA RAW(100),
- LONG_RAW_DATA LONG RAW
-);
-
--- All comments added
-COMMENT ON TABLE SPECIAL_DATA IS 'Table containing "special" data with various formats & types';
-COMMENT ON COLUMN SPECIAL_DATA.DATA_VALUE IS 'Data value field - supports NULL, empty strings, and ''quoted'' content';
-COMMENT ON COLUMN SPECIAL_DATA.METADATA_JSON IS 'JSON metadata: {"key": "value", "array": [1,2,3]}';
-COMMENT ON COLUMN SPECIAL_DATA.UNICODE_TEXT IS 'Unicode text support:
-Line 1: Basic ASCII text
-Line 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?
-Line 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π
-Line 4: Currencies $ € £ ¥ ₹';
-COMMENT ON COLUMN SPECIAL_DATA.BINARY_DATA IS 'Binary data storage\nSupports: images, documents, archives\tTab-separated info\r\nWindows line endings';
-COMMENT ON COLUMN SPECIAL_DATA.CATEGORY IS 'Category field: use % for wildcard searches, _ for single char matching';
-COMMENT ON COLUMN SPECIAL_DATA.STATUS IS 'Status field - values: ''ACTIVE'', ''INACTIVE'', ''PENDING''; DROP TABLE users; --';
-COMMENT ON TABLE MULTILANG_CONTENT IS 'Multilingual content: English, Español, 中文, العربية, Русский, 日本語';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_EN IS 'English title field';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_ES IS 'Título en español';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_ZH IS '中文标题字段 - 支持简体和繁体中文';
-COMMENT ON COLUMN MULTILANG_CONTENT.CONTENT_TEXT IS 'Content field supporting:
-1. HTML tags: <b>bold</b>, <i>italic</i>, <a href="http://example.com">links</a>
-2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick
-3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″
-4. Emojis: 😀 😃 😄 😁 🚀 ⭐ 🎉 💯
-5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2';
-COMMENT ON COLUMN MULTILANG_CONTENT.TAGS IS 'XML tags: <tag type="category" value="news"/><tag type="priority" value="high"/>End of XML';
-COMMENT ON TABLE COMPLEX_TYPES IS 'Advanced data types testing table
-Supports: XMLType, Timestamps with timezone, Intervals, RAW data
-Performance: Optimized for OLTP workloads @ 10K+ TPS
-Security: Row-level security enabled, audit trails maintained';
-COMMENT ON COLUMN COMPLEX_TYPES.XML_DATA IS 'XMLType column for structured XML storage
-Example: <?xml version="1.0" encoding="UTF-8"?>
-<root><item id="1" name="test">Content</item></root>';
-COMMENT ON COLUMN COMPLEX_TYPES.TIMESTAMP_TZ IS 'Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR
-Default: SYSTIMESTAMP (system timestamp with session timezone)';
-COMMENT ON COLUMN COMPLEX_TYPES.INTERVAL_DS IS 'Interval Day to Second: +/-DD HH:MI:SS.FFFFFF
-Range: +/-999999999 days, precision up to nanoseconds';
-`,
- migrationDDL: `
--- Drop table with all its comments
-DROP TABLE COMPLEX_TYPES CASCADE CONSTRAINTS;
-
--- Remove all comments from remaining tables
-COMMENT ON COLUMN MULTILANG_CONTENT.TAGS IS '';
-COMMENT ON COLUMN MULTILANG_CONTENT.CONTENT_TEXT IS '';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_ZH IS '';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_ES IS '';
-COMMENT ON COLUMN MULTILANG_CONTENT.TITLE_EN IS '';
-COMMENT ON TABLE MULTILANG_CONTENT IS '';
-
-COMMENT ON COLUMN SPECIAL_DATA.STATUS IS '';
-COMMENT ON COLUMN SPECIAL_DATA.CATEGORY IS '';
-COMMENT ON COLUMN SPECIAL_DATA.BINARY_DATA IS '';
-COMMENT ON COLUMN SPECIAL_DATA.UNICODE_TEXT IS '';
-COMMENT ON COLUMN SPECIAL_DATA.METADATA_JSON IS '';
-COMMENT ON COLUMN SPECIAL_DATA.DATA_VALUE IS '';
-COMMENT ON TABLE SPECIAL_DATA IS '';
-`,
- description: "Reverse: Remove all comments with special characters",
- },
- }
-}
-
-// TestTopologicalOrderCreateObjects tests that objects are created in the correct dependency order
func TestTopologicalOrderCreateObjects(t *testing.T) {
tests := []struct {
name string
@@ -2173,173 +455,3 @@ func findStatementIndex(statements []string, stmtType, objectName string) int {
}
return -1
}
-
-// fixtureSchemaName replaces the throwaway Oracle user this recorder creates, so
-// a re-record does not churn every fixture with a new UUID-derived schema name.
-const fixtureSchemaName = "TESTSCHEMA"
-
-// oracleGeneratedName matches the identifiers Oracle allocates for itself:
-// identity-column sequences and the names it invents for unnamed constraints.
-// Both embed a database object number that depends on allocation order across
-// concurrently recording subtests, so the same schema recorded twice yields
-// different numbers.
-var oracleGeneratedName = regexp.MustCompile(`ISEQ\$\$_[0-9]+|SYS_C[0-9]+`)
-
-//nolint:tparallel
-func TestGenerateMigrationAgainstOracle(t *testing.T) {
- const record = false
-
- ctx := context.Background()
-
- container := testcontainer.SharedOracleContainer(t)
- systemDB := container.GetDB()
-
- if record {
- require.NoError(t, os.MkdirAll(generateMigrationFixtureDir, 0o755))
- }
-
- // Oracle Free slows down heavily when too many schema-heavy cases run
- // concurrently against one container.
- const maxConcurrent = 4
- gate := make(chan struct{}, maxConcurrent)
-
- for _, tc := range generateMigrationCases() {
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
- gate <- struct{}{}
- defer func() { <-gate }()
-
- testUser := fmt.Sprintf("U_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- require.NoError(t, createOracleUser(systemDB, testUser))
-
- driver, err := createOracleDriver(ctx, container.GetHost(), container.GetPort(), testUser)
- require.NoError(t, err)
- defer driver.Close(ctx)
-
- require.NoError(t, executeStatements(ctx, driver, tc.initialSchema), "failed to execute initial schema")
- schemaA, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- require.NoError(t, executeStatements(ctx, driver, tc.migrationDDL), "failed to execute migration DDL")
- schemaB, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Render the fixture before the round trip below mutates these
- // messages, but write it only once Oracle has accepted the rollback.
- var fixture generateMigrationFixture
- if record {
- fixture = renderFixture(t, schemaA, schemaB, testUser)
- }
-
- verifyRollbackAgainstOracle(ctx, t, driver, schemaA, schemaB)
-
- if record {
- out, err := json.MarshalIndent(fixture, "", " ")
- require.NoError(t, err)
- require.NoError(t, os.WriteFile(generateMigrationFixturePath(tc.name), append(out, '\n'), 0o644))
- }
- })
- }
-}
-
-// verifyRollbackAgainstOracle is the live check the offline golden test cannot
-// make: generate the rollback from B back to A, execute it, and require that the
-// engine ends up where it started.
-func verifyRollbackAgainstOracle(ctx context.Context, t *testing.T, driver db.Driver, schemaA, schemaB *storepb.DatabaseSchemaMetadata) {
- t.Helper()
-
- dbSchemaA := model.NewDatabaseMetadata(schemaA, nil, nil, storepb.Engine_ORACLE, false)
- dbSchemaB := model.NewDatabaseMetadata(schemaB, nil, nil, storepb.Engine_ORACLE, false)
-
- diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_ORACLE, dbSchemaB, dbSchemaA)
- require.NoError(t, err)
-
- rollbackDDL, err := schema.GenerateMigration(storepb.Engine_ORACLE, diff)
- require.NoError(t, err)
-
- require.NoError(t, executeStatements(ctx, driver, rollbackDDL), "Oracle rejected the generated rollback:\n%s", rollbackDDL)
-
- schemaC, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- normalizeMetadataForComparison(schemaA)
- normalizeMetadataForComparison(schemaC)
- normalizeColumnPositions(schemaA)
- normalizeColumnPositions(schemaC)
-
- if mismatch := cmp.Diff(schemaA, schemaC, protocmp.Transform()); mismatch != "" {
- t.Errorf("rollback did not restore the initial schema (-want +got):\n%s\ngenerated DDL:\n%s", mismatch, rollbackDDL)
- }
-}
-
-// renderFixture marshals the pair for storage. Both schemas go through one
-// canonicalization pass so an identifier Oracle allocated once carries the same
-// stable name on both sides.
-func renderFixture(t *testing.T, schemaA, schemaB *storepb.DatabaseSchemaMetadata, testUser string) generateMigrationFixture {
- t.Helper()
-
- rawA := marshalSchema(t, schemaA, testUser)
- rawB := marshalSchema(t, schemaB, testUser)
-
- canonical := canonicalizeGeneratedNames(rawA, rawB)
- return generateMigrationFixture{
- SchemaA: json.RawMessage(canonical[0]),
- SchemaB: json.RawMessage(canonical[1]),
- }
-}
-
-// marshalSchema renders one synced schema, substituting the throwaway user name.
-func marshalSchema(t *testing.T, metadata *storepb.DatabaseSchemaMetadata, testUser string) string {
- t.Helper()
-
- zeroVolatileStats(metadata)
-
- raw, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(metadata)
- require.NoError(t, err)
-
- // The user name reaches the metadata as the database name and inside view,
- // routine and constraint text, so substitute across the whole document.
- return strings.ReplaceAll(string(raw), strings.ToUpper(testUser), fixtureSchemaName)
-}
-
-// canonicalizeGeneratedNames renumbers Oracle-allocated identifiers by order of
-// first appearance across the documents, so re-recording an unchanged schema
-// produces an unchanged fixture. Prefixes are preserved because the generator
-// keys on them: get_database_definition.go and generate_migration.go both test
-// for "ISEQ$$_" to recognize identity-column sequences.
-func canonicalizeGeneratedNames(docs ...string) []string {
- canonical := make(map[string]string)
- seen := make(map[string]int)
-
- rename := func(match string) string {
- if replacement, ok := canonical[match]; ok {
- return replacement
- }
- prefix := "SYS_C"
- if strings.HasPrefix(match, "ISEQ") {
- prefix = "ISEQ$$_"
- }
- seen[prefix]++
- replacement := fmt.Sprintf("%s%07d", prefix, seen[prefix])
- canonical[match] = replacement
- return replacement
- }
-
- out := make([]string, 0, len(docs))
- for _, doc := range docs {
- out = append(out, oracleGeneratedName.ReplaceAllStringFunc(doc, rename))
- }
- return out
-}
-
-// zeroVolatileStats clears the row and byte counts, which differ run to run and
-// are never read by the migration generator.
-func zeroVolatileStats(metadata *storepb.DatabaseSchemaMetadata) {
- for _, schemaMetadata := range metadata.Schemas {
- for _, table := range schemaMetadata.Tables {
- table.DataSize = 0
- table.IndexSize = 0
- table.RowCount = 0
- }
- }
-}
diff --git a/backend/plugin/schema/oracle/get_database_definition_test.go b/backend/plugin/schema/oracle/get_database_definition_test.go
index b2e7b4591c..e84a403569 100644
--- a/backend/plugin/schema/oracle/get_database_definition_test.go
+++ b/backend/plugin/schema/oracle/get_database_definition_test.go
@@ -1,17 +1,16 @@
package oracle
import (
- "context"
- "fmt"
- "strings"
"testing"
- "github.com/google/go-cmp/cmp"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/testing/protocmp"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "os"
+
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/schema"
)
@@ -274,193 +273,50 @@ func TestObjectDefinitionsRegisteredForOracle(t *testing.T) {
}
}
-// TestGetDatabaseDefinitionWithTestcontainer tests the GetDatabaseDefinition function
-// by creating a schema, getting its definition, recreating it in a new database,
-// and comparing the results.
-//
-//nolint:tparallel
-func TestGetDatabaseDefinitionWithTestcontainer(t *testing.T) {
- if testing.Short() {
- t.Skip("Skipping Oracle testcontainer test in short mode")
- }
-
- ctx := context.Background()
-
- container := testcontainer.SharedOracleContainer(t)
-
- // Get SYSTEM database connection for user management
- systemDB := container.GetDB()
-
- // Test cases with various schema configurations
- testCases := []struct {
- name string
- initialSchema string
- description string
- }{
- {
- name: "basic_tables_and_constraints",
- initialSchema: `
-CREATE TABLE DEPARTMENTS (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- BUDGET NUMBER(12, 2) DEFAULT 0
-);
-
-CREATE TABLE EMPLOYEES (
- ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- EMAIL VARCHAR2(100) UNIQUE,
- DEPARTMENT_ID NUMBER,
- SALARY NUMBER(10, 2),
- HIRE_DATE DATE DEFAULT SYSDATE,
- IS_ACTIVE NUMBER(1) DEFAULT 1 CHECK (IS_ACTIVE IN (0, 1)),
- CONSTRAINT FK_DEPT FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENTS(ID)
-);
-
-CREATE INDEX IDX_EMP_DEPT ON EMPLOYEES(DEPARTMENT_ID);
-CREATE INDEX IDX_EMP_NAME ON EMPLOYEES(NAME);
-`,
- description: "Basic tables with primary keys, foreign keys, unique constraints, check constraints, and indexes",
- },
- {
- name: "view_with_instead_of_trigger",
- initialSchema: `
-CREATE TABLE EMPLOYEES (
- EMP_ID NUMBER PRIMARY KEY,
- EMAIL VARCHAR2(100)
-);
-
-CREATE VIEW EMPLOYEE_VIEW AS
-SELECT EMP_ID, EMAIL
-FROM EMPLOYEES;
-
-CREATE OR REPLACE TRIGGER EMPLOYEE_VIEW_INSERT_TRG
-INSTEAD OF INSERT ON EMPLOYEE_VIEW
-FOR EACH ROW
-BEGIN
- INSERT INTO EMPLOYEES (EMP_ID, EMAIL) VALUES (:NEW.EMP_ID, :NEW.EMAIL);
-END;
-/
-`,
- description: "A view whose INSTEAD OF trigger must survive the definition round trip",
- },
- }
-
- for _, tc := range testCases {
- tc := tc // Capture range variable
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
-
- // Create unique Oracle user for this test (Oracle users are schemas)
- // Use UUID to ensure uniqueness and avoid name collisions
- testUser := fmt.Sprintf("U_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
-
- // Create user using shared SYSTEM connection
- require.NoError(t, createOracleUser(systemDB, testUser))
-
- // Connect as the test user
- driver, err := createOracleDriver(ctx, container.GetHost(), container.GetPort(), testUser)
- require.NoError(t, err)
- defer driver.Close(ctx)
-
- // Step 1: Initialize the database schema and use SyncDBSchema to get metadata A
- err = executeStatements(ctx, driver, tc.initialSchema)
- require.NoError(t, err, "Failed to execute initial schema")
-
- // Get schema metadata A
- metadataA, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err, "Failed to get initial metadata")
-
- // Step 2: Call GetDatabaseDefinition to generate the database definition X
- definition, err := GetDatabaseDefinition(schema.GetDefinitionContext{}, metadataA)
- require.NoError(t, err, "Failed to generate database definition")
- require.NotEmpty(t, definition, "Generated definition should not be empty")
-
- // Log the generated definition for debugging
- t.Logf("Generated definition:\n%s", definition)
-
- // Step 3: Create a new user and run the database definition X
- // Create a second unique user for recreation test
- testUser2 := fmt.Sprintf("U_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
-
- // Create the second user
- require.NoError(t, createOracleUser(systemDB, testUser2))
+type getDatabaseDefinitionCase struct {
+ Description string `yaml:"description"`
+ Metadata string `yaml:"metadata"`
+ Expected string `yaml:"expected"`
+}
- // Connect as the second test user
- driver2, err := createOracleDriver(ctx, container.GetHost(), container.GetPort(), testUser2)
+// TestGetDatabaseDefinition pins the DDL generated for each metadata input, and
+// re-parses that DDL to prove it is valid Oracle syntax.
+//
+// The input is metadata rather than a schema text on purpose: deriving it by
+// parsing would cap this test's reach at whatever GetDatabaseMetadata happens to
+// extract, so any generator branch the parser cannot feed would go untested.
+func TestGetDatabaseDefinition(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/get_database_definition.yaml"
+ )
+
+ var tests []getDatabaseDefinitionCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
+
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ var metadata storepb.DatabaseSchemaMetadata
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Metadata), &metadata))
+
+ definition, err := GetDatabaseDefinition(schema.GetDefinitionContext{}, &metadata)
require.NoError(t, err)
- defer driver2.Close(ctx)
-
- // Execute the generated definition in the new user's schema
- err = executeStatements(ctx, driver2, definition)
- require.NoError(t, err, "Failed to execute generated definition")
-
- // Get metadata B after recreating from definition
- metadataB, err := driver2.SyncDBSchema(ctx)
- require.NoError(t, err, "Failed to get metadata after recreation")
+ require.NotEmpty(t, definition)
- // Step 4: Compare the database metadata A and B, should be the same
- normalizeMetadataForComparison(metadataA)
- normalizeMetadataForComparison(metadataB)
+ _, err = GetDatabaseMetadata(definition)
+ require.NoError(t, err, "generated definition should parse")
- // Normalize column positions to 0 before comparison
- normalizeColumnPositions(metadataA)
- normalizeColumnPositions(metadataB)
-
- // Additional normalization for Oracle-specific issues
- normalizeOracleMetadata(metadataA)
- normalizeOracleMetadata(metadataB)
-
- // Use cmp with protocmp for proto message comparison
- if diff := cmp.Diff(metadataA, metadataB, protocmp.Transform()); diff != "" {
- t.Errorf("Schema mismatch after recreation (-original +recreated):\n%s", diff)
+ if record {
+ tests[i].Expected = definition
+ return
}
+ require.Equal(t, tc.Expected, definition)
})
}
-}
-// normalizeOracleMetadata handles Oracle-specific normalization for metadata comparison
-func normalizeOracleMetadata(metadata *storepb.DatabaseSchemaMetadata) {
- for _, schema := range metadata.Schemas {
- // A view's dependency columns record their owning Oracle user, and this
- // test recreates the schema under a second user by construction, so the
- // two can never match.
- for _, view := range schema.Views {
- for _, dependency := range view.DependencyColumns {
- dependency.Schema = ""
- }
- }
- for _, view := range schema.MaterializedViews {
- for _, dependency := range view.DependencyColumns {
- dependency.Schema = ""
- }
- }
-
- for _, table := range schema.Tables {
- for _, column := range table.Columns {
- // Normalize system-generated sequence references in default expressions
- if column.Default != "" {
- // If it's a system-generated sequence, remove the default expression
- // since these sequences can't be manually recreated with the same name
- if strings.Contains(column.Default, "ISEQ$$_") {
- column.Default = ""
- }
- }
-
- // Clear collation information as we skip it in DDL generation
- column.Collation = ""
-
- // Normalize NVARCHAR2 type size differences
- // Oracle stores NVARCHAR2 sizes in max bytes, but DDL defines in characters
- if strings.HasPrefix(column.Type, "NVARCHAR2") {
- // Extract the size and convert to character count
- if strings.Contains(column.Type, "(") && strings.Contains(column.Type, ")") {
- // For simplicity, we'll normalize all NVARCHAR2 types to just NVARCHAR2
- // This avoids issues with byte vs character counting
- column.Type = "NVARCHAR2"
- }
- }
- }
- }
+ if record {
+ yamltest.Record(t, filepath, tests)
}
}
diff --git a/backend/plugin/schema/oracle/get_database_metadata_test.go b/backend/plugin/schema/oracle/get_database_metadata_test.go
index 09cc9f49d9..d84eab907f 100644
--- a/backend/plugin/schema/oracle/get_database_metadata_test.go
+++ b/backend/plugin/schema/oracle/get_database_metadata_test.go
@@ -1,1510 +1,62 @@
package oracle
import (
- "context"
- "fmt"
- "strings"
+ "encoding/json"
+ "os"
"testing"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/schema"
)
-type oracleMetadataTestCase struct {
- name string
- ddl string
+type getDatabaseMetadataCase struct {
+ Description string `yaml:"description"`
+ Schema string `yaml:"schema"`
+ Metadata string `yaml:"metadata"`
}
-func oracleMetadataTestCases() []oracleMetadataTestCase {
- return []oracleMetadataTestCase{
- {
- name: "basic_table",
- ddl: `
-CREATE TABLE TEST_TABLE (
- ID NUMBER PRIMARY KEY,
- NAME VARCHAR2(50) NOT NULL
-);
-`,
- },
- {
- name: "table_with_sequence",
- ddl: `
-CREATE TABLE EMPLOYEES (
- ID NUMBER PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL
-);
-
-CREATE SEQUENCE EMP_SEQ START WITH 1 INCREMENT BY 1;
-`,
- },
- {
- name: "table_with_view",
- ddl: `
-CREATE TABLE PRODUCTS (
- ID NUMBER PRIMARY KEY,
- NAME VARCHAR2(100) NOT NULL,
- PRICE NUMBER(10,2)
-);
-
-CREATE VIEW EXPENSIVE_PRODUCTS AS
-SELECT ID, NAME, PRICE
-FROM PRODUCTS
-WHERE PRICE > 100;
-`,
- },
- {
- name: "comprehensive_data_types",
- ddl: `
-CREATE TABLE DATA_TYPES_COMPREHENSIVE (
- ID NUMBER PRIMARY KEY,
- -- Numeric types
- NUMBER_COL NUMBER,
- NUMBER_PRECISION NUMBER(10),
- NUMBER_SCALE NUMBER(10,2),
- FLOAT_COL FLOAT,
- BINARY_FLOAT_COL BINARY_FLOAT,
- BINARY_DOUBLE_COL BINARY_DOUBLE,
- -- Character types
- VARCHAR2_COL VARCHAR2(4000),
- NVARCHAR2_COL NVARCHAR2(2000),
- CHAR_COL CHAR(100),
- NCHAR_COL NCHAR(100),
- -- Date and time types
- DATE_COL DATE,
- TIMESTAMP_COL TIMESTAMP,
- TIMESTAMP_TZ_COL TIMESTAMP WITH TIME ZONE,
- TIMESTAMP_LTZ_COL TIMESTAMP WITH LOCAL TIME ZONE,
- INTERVAL_YM_COL INTERVAL YEAR TO MONTH,
- INTERVAL_DS_COL INTERVAL DAY TO SECOND,
- -- Large object types
- CLOB_COL CLOB,
- NCLOB_COL NCLOB,
- BLOB_COL BLOB,
- -- Binary types
- RAW_COL RAW(2000),
- LONG_RAW_COL LONG RAW,
- -- Row identifier
- ROWID_COL ROWID,
- UROWID_COL UROWID
-);
-`,
- },
- {
- name: "complex_constraints",
- ddl: `
-CREATE TABLE ORDERS (
- ORDER_ID NUMBER PRIMARY KEY,
- CUSTOMER_ID NUMBER NOT NULL,
- ORDER_DATE DATE DEFAULT SYSDATE,
- STATUS VARCHAR2(20) DEFAULT 'PENDING',
- TOTAL_AMOUNT NUMBER(12,2) NOT NULL,
- DISCOUNT_PERCENT NUMBER(5,2) DEFAULT 0,
- SHIP_DATE DATE,
- NOTES VARCHAR2(4000),
- CREATED_BY VARCHAR2(100) DEFAULT USER,
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- UPDATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- -- Check constraints
- CONSTRAINT chk_status CHECK (STATUS IN ('PENDING', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CANCELLED')),
- CONSTRAINT chk_total_positive CHECK (TOTAL_AMOUNT > 0),
- CONSTRAINT chk_discount_range CHECK (DISCOUNT_PERCENT BETWEEN 0 AND 100),
- CONSTRAINT chk_ship_after_order CHECK (SHIP_DATE IS NULL OR SHIP_DATE >= ORDER_DATE),
- -- Unique constraints
- CONSTRAINT uk_order_customer_date UNIQUE (CUSTOMER_ID, ORDER_DATE)
-);
-`,
- },
- {
- name: "foreign_keys_and_references",
- ddl: `
-CREATE TABLE DEPARTMENTS (
- DEPT_ID NUMBER PRIMARY KEY,
- DEPT_NAME VARCHAR2(100) NOT NULL UNIQUE,
- MANAGER_ID NUMBER,
- LOCATION VARCHAR2(100),
- BUDGET NUMBER(15,2)
-);
-
-CREATE TABLE EMPLOYEES_FK (
- EMP_ID NUMBER PRIMARY KEY,
- FIRST_NAME VARCHAR2(50) NOT NULL,
- LAST_NAME VARCHAR2(50) NOT NULL,
- EMAIL VARCHAR2(100) UNIQUE,
- PHONE VARCHAR2(20),
- HIRE_DATE DATE DEFAULT SYSDATE,
- SALARY NUMBER(10,2),
- COMMISSION_PCT NUMBER(4,2),
- DEPT_ID NUMBER,
- MANAGER_ID NUMBER,
- -- Foreign key constraints
- CONSTRAINT fk_emp_dept FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENTS(DEPT_ID) ON DELETE SET NULL,
- CONSTRAINT fk_emp_manager FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEES_FK(EMP_ID) ON DELETE SET NULL,
- -- Check constraints
- CONSTRAINT chk_salary_positive CHECK (SALARY > 0),
- CONSTRAINT chk_commission_range CHECK (COMMISSION_PCT BETWEEN 0 AND 1),
- CONSTRAINT chk_email_format CHECK (EMAIL LIKE '%@%.%')
-);
-
--- Self-referencing foreign key for department manager
-ALTER TABLE DEPARTMENTS ADD CONSTRAINT fk_dept_manager
- FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEES_FK(EMP_ID) ON DELETE SET NULL;
-`,
- },
- {
- name: "indexes_comprehensive",
- ddl: `
-CREATE TABLE CUSTOMER_ORDERS (
- ORDER_ID NUMBER PRIMARY KEY,
- CUSTOMER_ID NUMBER NOT NULL,
- ORDER_DATE DATE NOT NULL,
- PRODUCT_CODE VARCHAR2(50) NOT NULL,
- QUANTITY NUMBER NOT NULL,
- UNIT_PRICE NUMBER(10,2) NOT NULL,
- TOTAL_AMOUNT NUMBER(12,2) NOT NULL,
- STATUS VARCHAR2(20) DEFAULT 'ACTIVE',
- DESCRIPTION CLOB,
- TAGS VARCHAR2(1000),
- CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
--- Various index types
-CREATE INDEX idx_customer_date ON CUSTOMER_ORDERS(CUSTOMER_ID, ORDER_DATE);
-CREATE INDEX idx_product_status ON CUSTOMER_ORDERS(PRODUCT_CODE, STATUS);
-CREATE INDEX idx_order_date_desc ON CUSTOMER_ORDERS(ORDER_DATE DESC);
-CREATE INDEX idx_total_amount ON CUSTOMER_ORDERS(TOTAL_AMOUNT);
-CREATE UNIQUE INDEX idx_customer_product_unique ON CUSTOMER_ORDERS(CUSTOMER_ID, PRODUCT_CODE, ORDER_DATE);
-CREATE BITMAP INDEX idx_status_bitmap ON CUSTOMER_ORDERS(STATUS);
-CREATE INDEX idx_upper_product ON CUSTOMER_ORDERS(UPPER(PRODUCT_CODE));
-CREATE INDEX idx_created_year ON CUSTOMER_ORDERS(EXTRACT(YEAR FROM CREATED_AT));
-`,
- },
- {
- name: "sequences_and_triggers",
- ddl: `
-CREATE TABLE AUDIT_LOG (
- LOG_ID NUMBER PRIMARY KEY,
- TABLE_NAME VARCHAR2(128) NOT NULL,
- OPERATION VARCHAR2(10) NOT NULL,
- OLD_VALUES CLOB,
- NEW_VALUES CLOB,
- USER_NAME VARCHAR2(128) DEFAULT USER,
- TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- SESSION_ID VARCHAR2(128) DEFAULT SYS_CONTEXT('USERENV', 'SESSIONID')
-);
-
-CREATE SEQUENCE audit_log_seq
- START WITH 1000
- INCREMENT BY 1
- MAXVALUE 999999999999999999
- MINVALUE 1
- NOCYCLE
- CACHE 20;
-
-CREATE OR REPLACE TRIGGER audit_log_trigger
- BEFORE INSERT ON AUDIT_LOG
- FOR EACH ROW
-BEGIN
- IF :NEW.LOG_ID IS NULL THEN
- SELECT audit_log_seq.NEXTVAL INTO :NEW.LOG_ID FROM DUAL;
- END IF;
-END;
-/
-
-CREATE TABLE INVENTORY (
- ITEM_ID NUMBER PRIMARY KEY,
- ITEM_CODE VARCHAR2(50) UNIQUE NOT NULL,
- DESCRIPTION VARCHAR2(200),
- QUANTITY_ON_HAND NUMBER DEFAULT 0,
- UNIT_COST NUMBER(10,2),
- LAST_UPDATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE SEQUENCE inventory_seq START WITH 1 INCREMENT BY 1;
-
-CREATE OR REPLACE TRIGGER inventory_audit_trigger
- AFTER INSERT OR UPDATE OR DELETE ON INVENTORY
- FOR EACH ROW
-BEGIN
- IF INSERTING THEN
- INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, NEW_VALUES)
- VALUES ('INVENTORY', 'INSERT', 'ID=' || :NEW.ITEM_ID || ',CODE=' || :NEW.ITEM_CODE);
- ELSIF UPDATING THEN
- INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)
- VALUES ('INVENTORY', 'UPDATE',
- 'ID=' || :OLD.ITEM_ID || ',QTY=' || :OLD.QUANTITY_ON_HAND,
- 'ID=' || :NEW.ITEM_ID || ',QTY=' || :NEW.QUANTITY_ON_HAND);
- ELSIF DELETING THEN
- INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES)
- VALUES ('INVENTORY', 'DELETE', 'ID=' || :OLD.ITEM_ID || ',CODE=' || :OLD.ITEM_CODE);
- END IF;
-END;
-/
-`,
- },
- {
- name: "views_complex",
- ddl: `
-CREATE TABLE SALES_TRANSACTIONS (
- TRANSACTION_ID NUMBER PRIMARY KEY,
- CUSTOMER_ID NUMBER NOT NULL,
- PRODUCT_ID NUMBER NOT NULL,
- SALE_DATE DATE NOT NULL,
- QUANTITY NUMBER NOT NULL,
- UNIT_PRICE NUMBER(10,2) NOT NULL,
- DISCOUNT_AMOUNT NUMBER(10,2) DEFAULT 0,
- TAX_AMOUNT NUMBER(10,2) DEFAULT 0,
- TOTAL_AMOUNT NUMBER(12,2) NOT NULL,
- SALES_REP_ID NUMBER,
- REGION VARCHAR2(50)
-);
-
--- Complex view with aggregations
-CREATE VIEW MONTHLY_SALES_SUMMARY AS
-SELECT
- TO_CHAR(SALE_DATE, 'YYYY-MM') AS SALES_MONTH,
- REGION,
- COUNT(*) AS TRANSACTION_COUNT,
- SUM(QUANTITY) AS TOTAL_QUANTITY,
- SUM(TOTAL_AMOUNT) AS TOTAL_REVENUE,
- AVG(TOTAL_AMOUNT) AS AVG_TRANSACTION_VALUE,
- MIN(SALE_DATE) AS FIRST_SALE_DATE,
- MAX(SALE_DATE) AS LAST_SALE_DATE
-FROM SALES_TRANSACTIONS
-WHERE SALE_DATE >= ADD_MONTHS(SYSDATE, -12)
-GROUP BY TO_CHAR(SALE_DATE, 'YYYY-MM'), REGION
-HAVING SUM(TOTAL_AMOUNT) > 1000
-ORDER BY SALES_MONTH DESC, REGION;
-
--- View with joins and complex expressions
-CREATE VIEW CUSTOMER_SALES_ANALYSIS AS
-SELECT
- st.CUSTOMER_ID,
- COUNT(DISTINCT st.TRANSACTION_ID) AS TOTAL_TRANSACTIONS,
- COUNT(DISTINCT TO_CHAR(st.SALE_DATE, 'YYYY-MM')) AS ACTIVE_MONTHS,
- SUM(st.TOTAL_AMOUNT) AS LIFETIME_VALUE,
- AVG(st.TOTAL_AMOUNT) AS AVG_TRANSACTION_VALUE,
- MAX(st.SALE_DATE) AS LAST_PURCHASE_DATE,
- CASE
- WHEN MAX(st.SALE_DATE) >= SYSDATE - 30 THEN 'ACTIVE'
- WHEN MAX(st.SALE_DATE) >= SYSDATE - 90 THEN 'RECENT'
- ELSE 'INACTIVE'
- END AS CUSTOMER_STATUS,
- ROUND(SUM(st.TOTAL_AMOUNT) / NULLIF(COUNT(DISTINCT TO_CHAR(st.SALE_DATE, 'YYYY-MM')), 0), 2) AS MONTHLY_SPEND_RATE
-FROM SALES_TRANSACTIONS st
-WHERE st.SALE_DATE >= ADD_MONTHS(SYSDATE, -24)
-GROUP BY st.CUSTOMER_ID
-HAVING COUNT(*) >= 3;
-`,
- },
- {
- name: "materialized_views",
- ddl: `
-CREATE TABLE PRODUCT_SALES_DAILY (
- SALE_DATE DATE NOT NULL,
- PRODUCT_ID NUMBER NOT NULL,
- CATEGORY VARCHAR2(50) NOT NULL,
- SALES_AMOUNT NUMBER(12,2) NOT NULL,
- UNITS_SOLD NUMBER NOT NULL,
- COST_OF_GOODS NUMBER(12,2) NOT NULL
-);
-
--- Materialized view for performance (simplified for query rewrite support)
-CREATE MATERIALIZED VIEW PRODUCT_PERFORMANCE_MV
-BUILD IMMEDIATE
-REFRESH COMPLETE ON DEMAND
-AS
-SELECT
- PRODUCT_ID,
- CATEGORY,
- COUNT(*) AS SALES_DAYS,
- SUM(SALES_AMOUNT) AS TOTAL_REVENUE,
- SUM(UNITS_SOLD) AS TOTAL_UNITS,
- SUM(COST_OF_GOODS) AS TOTAL_COST,
- SUM(SALES_AMOUNT) - SUM(COST_OF_GOODS) AS TOTAL_PROFIT,
- AVG(SALES_AMOUNT) AS AVG_DAILY_REVENUE,
- MIN(SALE_DATE) AS FIRST_SALE_DATE,
- MAX(SALE_DATE) AS LAST_SALE_DATE
-FROM PRODUCT_SALES_DAILY
-WHERE SALE_DATE >= ADD_MONTHS(SYSDATE, -12)
-GROUP BY PRODUCT_ID, CATEGORY;
-
--- Create index on materialized view
-CREATE INDEX idx_mv_category ON PRODUCT_PERFORMANCE_MV(CATEGORY);
-CREATE INDEX idx_mv_total_profit ON PRODUCT_PERFORMANCE_MV(TOTAL_PROFIT);
-`,
- },
- {
- name: "procedures_and_functions",
- ddl: `
-CREATE TABLE CUSTOMER_ACCOUNTS (
- ACCOUNT_ID NUMBER PRIMARY KEY,
- CUSTOMER_NAME VARCHAR2(100) NOT NULL,
- ACCOUNT_TYPE VARCHAR2(20) NOT NULL,
- BALANCE NUMBER(15,2) DEFAULT 0,
- CREDIT_LIMIT NUMBER(15,2) DEFAULT 0,
- STATUS VARCHAR2(20) DEFAULT 'ACTIVE',
- CREATED_DATE DATE DEFAULT SYSDATE
-);
-
--- Function to calculate available credit
-CREATE OR REPLACE FUNCTION get_available_credit(p_account_id NUMBER)
-RETURN NUMBER
-DETERMINISTIC
-IS
- v_balance NUMBER;
- v_credit_limit NUMBER;
- v_available_credit NUMBER;
-BEGIN
- SELECT BALANCE, CREDIT_LIMIT
- INTO v_balance, v_credit_limit
- FROM CUSTOMER_ACCOUNTS
- WHERE ACCOUNT_ID = p_account_id;
-
- v_available_credit := v_credit_limit - v_balance;
-
- RETURN GREATEST(v_available_credit, 0);
-EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RETURN 0;
- WHEN OTHERS THEN
- RETURN -1;
-END;
-/
-
--- Procedure to update account balance
-CREATE OR REPLACE PROCEDURE update_account_balance(
- p_account_id IN NUMBER,
- p_amount IN NUMBER,
- p_transaction_type IN VARCHAR2,
- p_result OUT VARCHAR2
-)
-IS
- v_current_balance NUMBER;
- v_new_balance NUMBER;
- v_credit_limit NUMBER;
-BEGIN
- -- Get current balance and credit limit
- SELECT BALANCE, CREDIT_LIMIT
- INTO v_current_balance, v_credit_limit
- FROM CUSTOMER_ACCOUNTS
- WHERE ACCOUNT_ID = p_account_id
- FOR UPDATE;
-
- -- Calculate new balance
- IF p_transaction_type = 'CREDIT' THEN
- v_new_balance := v_current_balance + p_amount;
- ELSIF p_transaction_type = 'DEBIT' THEN
- v_new_balance := v_current_balance - p_amount;
-
- -- Check credit limit
- IF v_new_balance < (v_credit_limit * -1) THEN
- p_result := 'ERROR: Transaction would exceed credit limit';
- ROLLBACK;
- RETURN;
- END IF;
- ELSE
- p_result := 'ERROR: Invalid transaction type';
- RETURN;
- END IF;
-
- -- Update balance
- UPDATE CUSTOMER_ACCOUNTS
- SET BALANCE = v_new_balance,
- STATUS = CASE
- WHEN v_new_balance < 0 THEN 'OVERDRAWN'
- WHEN v_new_balance >= 0 THEN 'ACTIVE'
- END
- WHERE ACCOUNT_ID = p_account_id;
-
- COMMIT;
- p_result := 'SUCCESS: Balance updated to ' || v_new_balance;
-
-EXCEPTION
- WHEN NO_DATA_FOUND THEN
- p_result := 'ERROR: Account not found';
- WHEN OTHERS THEN
- p_result := 'ERROR: ' || SQLERRM;
- ROLLBACK;
-END;
-/
-
--- Function with complex logic
-CREATE OR REPLACE FUNCTION calculate_account_risk_score(p_account_id NUMBER)
-RETURN NUMBER
-IS
- v_balance NUMBER;
- v_credit_limit NUMBER;
- v_account_age NUMBER;
- v_transaction_count NUMBER;
- v_risk_score NUMBER := 0;
-BEGIN
- SELECT
- BALANCE,
- CREDIT_LIMIT,
- SYSDATE - CREATED_DATE,
- (SELECT COUNT(*) FROM AUDIT_LOG WHERE TABLE_NAME = 'CUSTOMER_ACCOUNTS')
- INTO v_balance, v_credit_limit, v_account_age, v_transaction_count
- FROM CUSTOMER_ACCOUNTS
- WHERE ACCOUNT_ID = p_account_id;
-
- -- Calculate risk based on multiple factors
- -- Balance utilization (higher utilization = higher risk)
- IF v_credit_limit > 0 THEN
- v_risk_score := v_risk_score + (ABS(v_balance) / v_credit_limit) * 40;
- END IF;
-
- -- Account age (newer accounts = higher risk)
- IF v_account_age < 30 THEN
- v_risk_score := v_risk_score + 30;
- ELSIF v_account_age < 90 THEN
- v_risk_score := v_risk_score + 20;
- ELSIF v_account_age < 365 THEN
- v_risk_score := v_risk_score + 10;
- END IF;
-
- -- Transaction frequency (too few or too many = higher risk)
- IF v_transaction_count < 5 THEN
- v_risk_score := v_risk_score + 20;
- ELSIF v_transaction_count > 100 THEN
- v_risk_score := v_risk_score + 15;
- END IF;
-
- -- Negative balance penalty
- IF v_balance < 0 THEN
- v_risk_score := v_risk_score + 25;
- END IF;
-
- RETURN LEAST(v_risk_score, 100); -- Cap at 100
-
-EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RETURN 100; -- Max risk for non-existent accounts
- WHEN OTHERS THEN
- RETURN 50; -- Default moderate risk on errors
-END;
-/
-`,
- },
- {
- name: "packages_comprehensive",
- ddl: `
--- Package specification
-CREATE OR REPLACE PACKAGE financial_utils AS
- -- Constants
- c_max_overdraft CONSTANT NUMBER := 5000;
- c_default_interest_rate CONSTANT NUMBER := 0.05;
-
- -- Types
- TYPE account_summary_type IS RECORD (
- account_id NUMBER,
- balance NUMBER,
- available_credit NUMBER,
- risk_score NUMBER,
- status VARCHAR2(20)
- );
-
- TYPE account_list_type IS TABLE OF account_summary_type;
-
- -- Procedures
- PROCEDURE calculate_interest(
- p_account_id IN NUMBER,
- p_days IN NUMBER DEFAULT 30,
- p_interest_amount OUT NUMBER
- );
-
- PROCEDURE generate_statement(
- p_account_id IN NUMBER,
- p_statement_date IN DATE DEFAULT SYSDATE,
- p_statement_text OUT CLOB
- );
-
- -- Functions
- FUNCTION get_account_summary(p_account_id NUMBER) RETURN account_summary_type;
-
- FUNCTION get_high_risk_accounts(p_risk_threshold NUMBER DEFAULT 70)
- RETURN account_list_type PIPELINED;
-
- FUNCTION format_currency(p_amount NUMBER) RETURN VARCHAR2;
-
- FUNCTION validate_account_number(p_account_id NUMBER) RETURN BOOLEAN;
-
- -- Overloaded functions
- FUNCTION calculate_fee(p_transaction_type VARCHAR2) RETURN NUMBER;
- FUNCTION calculate_fee(p_transaction_type VARCHAR2, p_amount NUMBER) RETURN NUMBER;
-
-END financial_utils;
-/
-
--- Package body
-CREATE OR REPLACE PACKAGE BODY financial_utils AS
-
- PROCEDURE calculate_interest(
- p_account_id IN NUMBER,
- p_days IN NUMBER DEFAULT 30,
- p_interest_amount OUT NUMBER
- ) IS
- v_balance NUMBER;
- v_daily_rate NUMBER;
- BEGIN
- SELECT BALANCE INTO v_balance
- FROM CUSTOMER_ACCOUNTS
- WHERE ACCOUNT_ID = p_account_id;
-
- v_daily_rate := c_default_interest_rate / 365;
-
- IF v_balance < 0 THEN
- p_interest_amount := ABS(v_balance) * v_daily_rate * p_days;
- ELSE
- p_interest_amount := 0;
- END IF;
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- p_interest_amount := 0;
- END calculate_interest;
-
- PROCEDURE generate_statement(
- p_account_id IN NUMBER,
- p_statement_date IN DATE DEFAULT SYSDATE,
- p_statement_text OUT CLOB
- ) IS
- v_account account_summary_type;
- BEGIN
- v_account := get_account_summary(p_account_id);
-
- p_statement_text := 'ACCOUNT STATEMENT' || CHR(10) ||
- 'Account ID: ' || v_account.account_id || CHR(10) ||
- 'Statement Date: ' || TO_CHAR(p_statement_date, 'DD-MON-YYYY') || CHR(10) ||
- 'Current Balance: ' || format_currency(v_account.balance) || CHR(10) ||
- 'Available Credit: ' || format_currency(v_account.available_credit) || CHR(10) ||
- 'Account Status: ' || v_account.status || CHR(10) ||
- 'Risk Score: ' || v_account.risk_score;
- END generate_statement;
-
- FUNCTION get_account_summary(p_account_id NUMBER) RETURN account_summary_type IS
- v_summary account_summary_type;
- BEGIN
- SELECT ACCOUNT_ID, BALANCE, STATUS
- INTO v_summary.account_id, v_summary.balance, v_summary.status
- FROM CUSTOMER_ACCOUNTS
- WHERE ACCOUNT_ID = p_account_id;
-
- v_summary.available_credit := get_available_credit(p_account_id);
- v_summary.risk_score := calculate_account_risk_score(p_account_id);
-
- RETURN v_summary;
- END get_account_summary;
-
- FUNCTION get_high_risk_accounts(p_risk_threshold NUMBER DEFAULT 70)
- RETURN account_list_type PIPELINED IS
- v_summary account_summary_type;
- BEGIN
- FOR rec IN (SELECT ACCOUNT_ID FROM CUSTOMER_ACCOUNTS WHERE STATUS = 'ACTIVE') LOOP
- v_summary := get_account_summary(rec.ACCOUNT_ID);
- IF v_summary.risk_score >= p_risk_threshold THEN
- PIPE ROW(v_summary);
- END IF;
- END LOOP;
- RETURN;
- END get_high_risk_accounts;
-
- FUNCTION format_currency(p_amount NUMBER) RETURN VARCHAR2 IS
- BEGIN
- RETURN TO_CHAR(p_amount, 'FM$999,999,990.00');
- END format_currency;
-
- FUNCTION validate_account_number(p_account_id NUMBER) RETURN BOOLEAN IS
- v_count NUMBER;
- BEGIN
- SELECT COUNT(*) INTO v_count
- FROM CUSTOMER_ACCOUNTS
- WHERE ACCOUNT_ID = p_account_id;
-
- RETURN v_count > 0;
- END validate_account_number;
-
- FUNCTION calculate_fee(p_transaction_type VARCHAR2) RETURN NUMBER IS
- BEGIN
- CASE p_transaction_type
- WHEN 'TRANSFER' THEN RETURN 2.50;
- WHEN 'WITHDRAWAL' THEN RETURN 1.00;
- WHEN 'DEPOSIT' THEN RETURN 0;
- ELSE RETURN 5.00;
- END CASE;
- END calculate_fee;
-
- FUNCTION calculate_fee(p_transaction_type VARCHAR2, p_amount NUMBER) RETURN NUMBER IS
- v_base_fee NUMBER;
- v_percentage_fee NUMBER;
- BEGIN
- v_base_fee := calculate_fee(p_transaction_type);
-
- -- Add percentage-based fee for large amounts
- IF p_amount > 10000 THEN
- v_percentage_fee := p_amount * 0.001; -- 0.1%
- RETURN v_base_fee + v_percentage_fee;
- ELSE
- RETURN v_base_fee;
- END IF;
- END calculate_fee;
-
-END financial_utils;
-/
-`,
- },
- {
- name: "table_comments_and_documentation",
- ddl: `
-CREATE TABLE PRODUCT_CATALOG (
- PRODUCT_ID NUMBER PRIMARY KEY,
- SKU VARCHAR2(50) UNIQUE NOT NULL,
- PRODUCT_NAME VARCHAR2(200) NOT NULL,
- DESCRIPTION CLOB,
- CATEGORY_ID NUMBER NOT NULL,
- PRICE NUMBER(10,2) NOT NULL,
- COST NUMBER(10,2),
- WEIGHT NUMBER(8,3),
- DIMENSIONS VARCHAR2(100),
- COLOR VARCHAR2(50),
- PRODUCT_SIZE VARCHAR2(20),
- BRAND VARCHAR2(100),
- SUPPLIER_ID NUMBER,
- IS_ACTIVE NUMBER(1) DEFAULT 1,
- STOCK_QUANTITY NUMBER DEFAULT 0,
- REORDER_LEVEL NUMBER DEFAULT 10,
- CREATED_DATE DATE DEFAULT SYSDATE,
- CREATED_BY VARCHAR2(100) DEFAULT USER,
- LAST_UPDATED DATE DEFAULT SYSDATE,
- UPDATED_BY VARCHAR2(100) DEFAULT USER,
- VERSION_NUMBER NUMBER DEFAULT 1
-);
-
--- Table comments
-COMMENT ON TABLE PRODUCT_CATALOG IS 'Master catalog of all products available for sale. Contains detailed product information including pricing, inventory, and supplier details.';
-
--- Column comments
-COMMENT ON COLUMN PRODUCT_CATALOG.PRODUCT_ID IS 'Unique identifier for the product. Primary key generated from sequence.';
-COMMENT ON COLUMN PRODUCT_CATALOG.SKU IS 'Stock Keeping Unit - unique alphanumeric code for inventory tracking';
-COMMENT ON COLUMN PRODUCT_CATALOG.PRODUCT_NAME IS 'Display name of the product as shown to customers';
-COMMENT ON COLUMN PRODUCT_CATALOG.DESCRIPTION IS 'Detailed product description including features and specifications';
-COMMENT ON COLUMN PRODUCT_CATALOG.CATEGORY_ID IS 'Foreign key reference to PRODUCT_CATEGORIES table';
-COMMENT ON COLUMN PRODUCT_CATALOG.PRICE IS 'Current selling price in base currency (USD)';
-COMMENT ON COLUMN PRODUCT_CATALOG.COST IS 'Cost of goods sold - used for profit margin calculations';
-COMMENT ON COLUMN PRODUCT_CATALOG.WEIGHT IS 'Product weight in kilograms - used for shipping calculations';
-COMMENT ON COLUMN PRODUCT_CATALOG.DIMENSIONS IS 'Product dimensions in format: Length x Width x Height (cm)';
-COMMENT ON COLUMN PRODUCT_CATALOG.COLOR IS 'Primary color of the product';
-COMMENT ON COLUMN PRODUCT_CATALOG.PRODUCT_SIZE IS 'Size designation (S, M, L, XL, etc.)';
-COMMENT ON COLUMN PRODUCT_CATALOG.BRAND IS 'Brand or manufacturer name';
-COMMENT ON COLUMN PRODUCT_CATALOG.SUPPLIER_ID IS 'Reference to primary supplier in SUPPLIERS table';
-COMMENT ON COLUMN PRODUCT_CATALOG.IS_ACTIVE IS 'Flag indicating if product is active (1) or discontinued (0)';
-COMMENT ON COLUMN PRODUCT_CATALOG.STOCK_QUANTITY IS 'Current inventory quantity on hand';
-COMMENT ON COLUMN PRODUCT_CATALOG.REORDER_LEVEL IS 'Minimum stock level that triggers reorder process';
-COMMENT ON COLUMN PRODUCT_CATALOG.CREATED_DATE IS 'Date when product record was first created';
-COMMENT ON COLUMN PRODUCT_CATALOG.CREATED_BY IS 'Username of person who created the record';
-COMMENT ON COLUMN PRODUCT_CATALOG.LAST_UPDATED IS 'Date of most recent update to any field';
-COMMENT ON COLUMN PRODUCT_CATALOG.UPDATED_BY IS 'Username of person who last modified the record';
-COMMENT ON COLUMN PRODUCT_CATALOG.VERSION_NUMBER IS 'Optimistic locking version number for concurrent update control';
-
-CREATE TABLE ORDER_LINE_ITEMS (
- LINE_ITEM_ID NUMBER PRIMARY KEY,
- ORDER_ID NUMBER NOT NULL,
- PRODUCT_ID NUMBER NOT NULL,
- QUANTITY NUMBER NOT NULL,
- UNIT_PRICE NUMBER(10,2) NOT NULL,
- DISCOUNT_AMOUNT NUMBER(10,2) DEFAULT 0,
- TAX_AMOUNT NUMBER(10,2) DEFAULT 0,
- LINE_TOTAL NUMBER(12,2) NOT NULL,
- SPECIAL_INSTRUCTIONS VARCHAR2(500),
- FULFILLMENT_STATUS VARCHAR2(20) DEFAULT 'PENDING'
-);
-
-COMMENT ON TABLE ORDER_LINE_ITEMS IS 'Individual line items for customer orders. Each row represents one product within an order.';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.LINE_ITEM_ID IS 'Unique identifier for this line item';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.ORDER_ID IS 'Reference to parent order in ORDERS table';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.PRODUCT_ID IS 'Reference to product in PRODUCT_CATALOG table';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.QUANTITY IS 'Number of units ordered';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.UNIT_PRICE IS 'Price per unit at time of order (may differ from current catalog price)';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.DISCOUNT_AMOUNT IS 'Total discount applied to this line item';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.TAX_AMOUNT IS 'Total tax amount for this line item';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.LINE_TOTAL IS 'Calculated total: (quantity * unit_price) - discount + tax';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.SPECIAL_INSTRUCTIONS IS 'Customer-specific instructions for this item';
-COMMENT ON COLUMN ORDER_LINE_ITEMS.FULFILLMENT_STATUS IS 'Status: PENDING, PICKED, PACKED, SHIPPED, DELIVERED, RETURNED';
-`,
- },
- }
-}
-
-// TestGetDatabaseMetadataWithTestcontainer tests the get_database_metadata function
-// by comparing its output with the metadata retrieved from a real Oracle instance.
-//
-//nolint:tparallel
-func TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {
- ctx := context.Background()
-
- container := testcontainer.SharedOracleContainer(t)
-
- host := container.GetHost()
- port := container.GetPort()
-
- // Get SYSTEM database connection for user management
- systemDB := container.GetDB()
-
- for _, tc := range oracleMetadataTestCases() {
- tc := tc // Capture range variable
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
-
- // Create unique Oracle user for this test (Oracle users are schemas)
- testUser := fmt.Sprintf("U_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
-
- // Create user using shared SYSTEM connection
- require.NoError(t, createOracleUser(systemDB, testUser))
-
- // Create Oracle driver for metadata sync
- driver, err := createOracleDriver(ctx, host, port, testUser)
- require.NoError(t, err)
- defer driver.Close(ctx)
+// TestGetDatabaseMetadata pins what the parser extracts from each schema
+// text. The goldens describe this package's own output, not Oracle's catalog:
+// whether the parser agrees with a live server is engine conformance and belongs
+// in omni.
+func TestGetDatabaseMetadata(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/get_database_metadata.yaml"
+ )
- // Execute DDL using the driver
- _, err = driver.Execute(ctx, tc.ddl, db.ExecuteOptions{})
- require.NoError(t, err)
+ var tests []getDatabaseMetadataCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
- // Get metadata from live database using driver
- dbMetadata, err := driver.SyncDBSchema(ctx)
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ metadata, err := GetDatabaseMetadata(tc.Schema)
require.NoError(t, err)
- // Get metadata from parser
- parsedMetadata, err := GetDatabaseMetadata(tc.ddl)
+ encoded, err := json.MarshalIndent(metadata, "", " ")
require.NoError(t, err)
+ result := string(encoded) + "\n"
- // Compare metadata
- compareMetadata(t, dbMetadata, parsedMetadata, tc.name)
-
- // No need to clean up - each test has its own isolated user
- })
- }
-}
-
-// compareMetadata compares the metadata from the live database with the parsed metadata
-func compareMetadata(t *testing.T, dbMeta, parsedMeta *storepb.DatabaseSchemaMetadata, testName string) {
- // For Oracle, we have one schema per database
- require.Equal(t, 1, len(parsedMeta.Schemas), "parsed metadata should have exactly one schema")
-
- dbMetadata := dbMeta.Schemas[0]
- parsedSchema := parsedMeta.Schemas[0]
-
- t.Logf("Test case %s - DB: %d tables, %d views, %d materialized views, %d sequences, %d functions, %d procedures | Parsed: %d tables, %d views, %d materialized views, %d sequences, %d functions, %d procedures",
- testName,
- len(dbMetadata.Tables), len(dbMetadata.Views), len(dbMetadata.MaterializedViews), len(dbMetadata.Sequences), len(dbMetadata.Functions), len(dbMetadata.Procedures),
- len(parsedSchema.Tables), len(parsedSchema.Views), len(parsedSchema.MaterializedViews), len(parsedSchema.Sequences), len(parsedSchema.Functions), len(parsedSchema.Procedures))
-
- // Compare schema names (allow flexibility for Oracle default schema)
- if dbMetadata.Name != "" && parsedSchema.Name != "" {
- require.Equal(t, dbMetadata.Name, parsedSchema.Name, "schema names should match")
- } else {
- t.Logf("Schema names: DB='%s', Parsed='%s' (allowing flexibility for Oracle default schema)", dbMetadata.Name, parsedSchema.Name)
- }
-
- // Compare tables with deep content validation
- compareTables(t, dbMetadata.Tables, parsedSchema.Tables, testName)
-
- // Compare views with content validation
- compareViews(t, dbMetadata.Views, parsedSchema.Views, testName)
-
- // Compare materialized views
- compareMaterializedViews(t, dbMetadata.MaterializedViews, parsedSchema.MaterializedViews, testName)
-
- // Compare sequences with content validation
- compareSequences(t, dbMetadata.Sequences, parsedSchema.Sequences, testName)
-
- // Compare functions with content validation
- compareFunctions(t, dbMetadata.Functions, parsedSchema.Functions, testName)
-
- // Compare procedures with content validation
- compareProcedures(t, dbMetadata.Procedures, parsedSchema.Procedures, testName)
-}
-
-// compareTables does deep comparison of table metadata
-func compareTables(t *testing.T, dbTables, parsedTables []*storepb.TableMetadata, _ string) {
- // Create maps for easier lookup
- dbTableMap := make(map[string]*storepb.TableMetadata)
- for _, table := range dbTables {
- dbTableMap[table.Name] = table
- }
-
- parsedTableMap := make(map[string]*storepb.TableMetadata)
- for _, table := range parsedTables {
- parsedTableMap[table.Name] = table
- }
-
- // Validate that parsed tables exist in database and compare content
- for tableName, parsedTable := range parsedTableMap {
- dbTable, exists := dbTableMap[tableName]
- require.True(t, exists, "parsed table %s not found in database metadata", tableName)
-
- t.Logf("Comparing table %s - DB: %d columns | Parsed: %d columns",
- tableName, len(dbTable.Columns), len(parsedTable.Columns))
-
- // Compare table properties
- require.Equal(t, dbTable.Name, parsedTable.Name, "table names should match")
- if dbTable.Comment != "" || parsedTable.Comment != "" {
- require.Equal(t, dbTable.Comment, parsedTable.Comment, "table comments should match for %s", tableName)
- }
-
- // Compare columns in detail
- compareColumns(t, dbTable.Columns, parsedTable.Columns, tableName)
-
- // Compare indexes
- compareIndexes(t, dbTable.Indexes, parsedTable.Indexes, tableName)
-
- // Compare foreign keys
- compareForeignKeys(t, dbTable.ForeignKeys, parsedTable.ForeignKeys, tableName)
-
- // Compare check constraints
- compareCheckConstraints(t, dbTable.CheckConstraints, parsedTable.CheckConstraints, tableName)
- }
-
- // Log any tables found in database but not in parser (acceptable for system tables)
- for tableName := range dbTableMap {
- if _, exists := parsedTableMap[tableName]; !exists {
- t.Logf("Info: table %s found in database but not parsed (may be system table)", tableName)
- }
- }
-}
-
-// compareColumns does deep comparison of column metadata
-func compareColumns(t *testing.T, dbColumns, parsedColumns []*storepb.ColumnMetadata, tableName string) {
- // Create maps for easier lookup
- dbColumnMap := make(map[string]*storepb.ColumnMetadata)
- for _, col := range dbColumns {
- dbColumnMap[col.Name] = col
- }
-
- parsedColumnMap := make(map[string]*storepb.ColumnMetadata)
- for _, col := range parsedColumns {
- parsedColumnMap[col.Name] = col
- }
-
- // Compare each parsed column with database column
- for colName, parsedCol := range parsedColumnMap {
- dbCol, exists := dbColumnMap[colName]
- if !exists {
- t.Logf("Warning: parsed column %s.%s not found in database metadata (parser may have parsing issue)", tableName, colName)
- continue
- }
-
- // Compare all ColumnMetadata fields comprehensively
- compareColumnMetadata(t, dbCol, parsedCol, tableName, colName)
- }
-
- // Report any columns found in database but not parsed
- for colName := range dbColumnMap {
- if _, exists := parsedColumnMap[colName]; !exists {
- t.Logf("Warning: column %s.%s found in database but not parsed", tableName, colName)
- }
- }
-}
-
-// compareColumnMetadata comprehensively compares all fields in ColumnMetadata
-func compareColumnMetadata(t *testing.T, dbCol, parsedCol *storepb.ColumnMetadata, tableName, colName string) {
- // 1. Name
- require.Equal(t, dbCol.Name, parsedCol.Name,
- "column names should match for %s.%s", tableName, colName)
-
- // 2. Position
- require.Equal(t, dbCol.Position, parsedCol.Position,
- "column positions should match for %s.%s: db=%d, parsed=%d",
- tableName, colName, dbCol.Position, parsedCol.Position)
-
- // 3. Type (with Oracle-specific normalization)
- dbType := normalizeOracleDataType(dbCol.Type)
- parsedType := normalizeOracleDataType(parsedCol.Type)
- require.Equal(t, dbType, parsedType,
- "data types should match for column %s.%s: db=%s, parsed=%s",
- tableName, colName, dbCol.Type, parsedCol.Type)
-
- // 4. Nullable
- require.Equal(t, dbCol.Nullable, parsedCol.Nullable,
- "nullable property should match for column %s.%s: db=%v, parsed=%v",
- tableName, colName, dbCol.Nullable, parsedCol.Nullable)
-
- // 5. Default values (existing function)
- compareColumnDefaults(t, dbCol, parsedCol, tableName, colName)
-
- // 6. Character Set
- if dbCol.CharacterSet != "" || parsedCol.CharacterSet != "" {
- require.Equal(t, dbCol.CharacterSet, parsedCol.CharacterSet,
- "character sets should match for column %s.%s: db=%s, parsed=%s",
- tableName, colName, dbCol.CharacterSet, parsedCol.CharacterSet)
- }
-
- // 7. Collation (Oracle-specific handling)
- if dbCol.Collation != "" || parsedCol.Collation != "" {
- // Oracle automatically assigns default collations (like USING_NLS_COMP) even when
- // not explicitly specified in DDL. Only compare when both have values or when
- // the DDL explicitly specified a collation (parsed has value).
- if parsedCol.Collation != "" {
- // DDL explicitly specified collation, should match exactly
- require.Equal(t, dbCol.Collation, parsedCol.Collation,
- "explicit collations should match for column %s.%s: db=%s, parsed=%s",
- tableName, colName, dbCol.Collation, parsedCol.Collation)
- } else if dbCol.Collation != "" && parsedCol.Collation == "" {
- // Database has default collation but DDL didn't specify one - this is expected for Oracle
- t.Logf("Info: column %s.%s has database default collation '%s' (DDL didn't specify collation)",
- tableName, colName, dbCol.Collation)
- }
- }
-
- // 8. Comment
- if dbCol.Comment != "" || parsedCol.Comment != "" {
- require.Equal(t, dbCol.Comment, parsedCol.Comment,
- "column comments should match for %s.%s: db=%s, parsed=%s",
- tableName, colName, dbCol.Comment, parsedCol.Comment)
- }
-
- // 10. On Update (MySQL-specific, but include for completeness)
- if dbCol.OnUpdate != "" || parsedCol.OnUpdate != "" {
- require.Equal(t, dbCol.OnUpdate, parsedCol.OnUpdate,
- "on_update should match for column %s.%s: db=%s, parsed=%s",
- tableName, colName, dbCol.OnUpdate, parsedCol.OnUpdate)
- }
-
- // 11. Generation Metadata (for virtual/generated columns)
- compareGenerationMetadata(t, dbCol.Generation, parsedCol.Generation, tableName, colName)
-
- // 12. Identity Generation (Oracle/PostgreSQL)
- require.Equal(t, dbCol.IdentityGeneration, parsedCol.IdentityGeneration,
- "identity generation should match for column %s.%s: db=%v, parsed=%v",
- tableName, colName, dbCol.IdentityGeneration, parsedCol.IdentityGeneration)
-
- // 13. Is Identity
- require.Equal(t, dbCol.IsIdentity, parsedCol.IsIdentity,
- "is_identity should match for column %s.%s: db=%v, parsed=%v",
- tableName, colName, dbCol.IsIdentity, parsedCol.IsIdentity)
-
- // 14. Oracle-specific: Default on Null
- require.Equal(t, dbCol.DefaultOnNull, parsedCol.DefaultOnNull,
- "default_on_null should match for column %s.%s: db=%v, parsed=%v",
- tableName, colName, dbCol.DefaultOnNull, parsedCol.DefaultOnNull)
-
- // 15. Identity Seed (MSSQL-specific, but include for completeness)
- if dbCol.IdentitySeed != 0 || parsedCol.IdentitySeed != 0 {
- require.Equal(t, dbCol.IdentitySeed, parsedCol.IdentitySeed,
- "identity seed should match for column %s.%s: db=%d, parsed=%d",
- tableName, colName, dbCol.IdentitySeed, parsedCol.IdentitySeed)
- }
-
- // 16. Identity Increment (MSSQL-specific, but include for completeness)
- if dbCol.IdentityIncrement != 0 || parsedCol.IdentityIncrement != 0 {
- require.Equal(t, dbCol.IdentityIncrement, parsedCol.IdentityIncrement,
- "identity increment should match for column %s.%s: db=%d, parsed=%d",
- tableName, colName, dbCol.IdentityIncrement, parsedCol.IdentityIncrement)
- }
-
- // 17. Default Constraint Name (MSSQL-specific, but include for completeness)
- if dbCol.DefaultConstraintName != "" || parsedCol.DefaultConstraintName != "" {
- require.Equal(t, dbCol.DefaultConstraintName, parsedCol.DefaultConstraintName,
- "default constraint name should match for column %s.%s: db=%s, parsed=%s",
- tableName, colName, dbCol.DefaultConstraintName, parsedCol.DefaultConstraintName)
- }
-
- // Log successful comparison with key details
- t.Logf("✓ Column %s.%s: type=%s, nullable=%v, default=%s, pos=%d%s",
- tableName, colName, parsedType, parsedCol.Nullable,
- getColumnDefaultString(parsedCol), parsedCol.Position,
- getColumnExtraInfo(parsedCol))
-}
-
-// compareGenerationMetadata compares generation metadata for virtual/generated columns
-func compareGenerationMetadata(t *testing.T, dbGen, parsedGen *storepb.GenerationMetadata, tableName, colName string) {
- if dbGen == nil && parsedGen == nil {
- return // Both nil, match
- }
-
- if dbGen == nil || parsedGen == nil {
- require.Equal(t, dbGen, parsedGen,
- "generation metadata presence should match for column %s.%s: db=%v, parsed=%v",
- tableName, colName, dbGen != nil, parsedGen != nil)
- return
- }
-
- // Compare generation type
- require.Equal(t, dbGen.Type, parsedGen.Type,
- "generation type should match for column %s.%s: db=%v, parsed=%v",
- tableName, colName, dbGen.Type, parsedGen.Type)
-
- // Compare generation expression
- require.Equal(t, dbGen.Expression, parsedGen.Expression,
- "generation expression should match for column %s.%s: db=%s, parsed=%s",
- tableName, colName, dbGen.Expression, parsedGen.Expression)
-}
-
-// getColumnExtraInfo returns additional column information for logging
-func getColumnExtraInfo(col *storepb.ColumnMetadata) string {
- var extras []string
-
- if col.IsIdentity {
- extras = append(extras, "identity")
- }
-
- if col.Generation != nil {
- switch col.Generation.Type {
- case storepb.GenerationMetadata_TYPE_VIRTUAL:
- extras = append(extras, "virtual")
- case storepb.GenerationMetadata_TYPE_STORED:
- extras = append(extras, "stored")
- default:
- // Other generation types
- }
- }
-
- if col.CharacterSet != "" {
- extras = append(extras, fmt.Sprintf("charset=%s", col.CharacterSet))
- }
-
- if col.Collation != "" {
- extras = append(extras, fmt.Sprintf("collation=%s", col.Collation))
- }
-
- if len(extras) > 0 {
- return fmt.Sprintf(" (%s)", strings.Join(extras, ", "))
- }
- return ""
-}
-
-// compareIndexes compares index metadata
-func compareIndexes(t *testing.T, dbIndexes, parsedIndexes []*storepb.IndexMetadata, tableName string) {
- // Create maps for easier lookup
- dbIndexMap := make(map[string]*storepb.IndexMetadata)
- for _, idx := range dbIndexes {
- dbIndexMap[idx.Name] = idx
- }
-
- parsedIndexMap := make(map[string]*storepb.IndexMetadata)
- for _, idx := range parsedIndexes {
- parsedIndexMap[idx.Name] = idx
- }
-
- // Check that both directions have the same indexes
- require.Equal(t, len(dbIndexes), len(parsedIndexes), "mismatch in number of indexes for table %s", tableName)
-
- // Compare each parsed index with comprehensive IndexMetadata validation
- for idxName, parsedIdx := range parsedIndexMap {
- dbIdx, exists := dbIndexMap[idxName]
- if !exists {
- // Some indexes might be system-generated, allow some flexibility
- t.Logf("Info: parsed index %s on table %s not found in database (may be system-generated)", idxName, tableName)
- continue
- }
-
- // 1. Name - explicitly validate name consistency
- require.Equal(t, dbIdx.Name, parsedIdx.Name, "table %s, index %s: name should match", tableName, idxName)
-
- // 2. Primary - validate primary key flag
- require.Equal(t, dbIdx.Primary, parsedIdx.Primary, "table %s, index %s: primary key flag should match", tableName, idxName)
-
- // 3. Unique - validate unique constraint flag
- require.Equal(t, dbIdx.Unique, parsedIdx.Unique, "table %s, index %s: unique flag should match", tableName, idxName)
-
- // 4. Type - validate index type with Oracle-specific normalization
- if parsedIdx.Type != "" && dbIdx.Type != "" {
- require.Equal(t, normalizeIndexType(dbIdx.Type), normalizeIndexType(parsedIdx.Type),
- "table %s, index %s: index types should match", tableName, idxName)
- }
-
- // 5. Expressions - compare expressions (column list) with normalization
- require.Equal(t, len(dbIdx.Expressions), len(parsedIdx.Expressions),
- "table %s, index %s: expression count should match", tableName, idxName)
-
- // Log detailed expression information for debugging
- t.Logf("Index %s expressions - DB: %v, Parsed: %v", idxName, dbIdx.Expressions, parsedIdx.Expressions)
-
- for i, dbExpr := range dbIdx.Expressions {
- if i < len(parsedIdx.Expressions) {
- require.Equal(t, normalizeExpression(dbExpr), normalizeExpression(parsedIdx.Expressions[i]),
- "table %s, index %s: expression[%d] should match", tableName, idxName, i)
- }
- }
-
- // 6. Descending - validate descending order for each expression
- require.Equal(t, len(dbIdx.Descending), len(parsedIdx.Descending), "table %s, index %s: descending array length should match", tableName, idxName)
- for i := range dbIdx.Descending {
- if i < len(parsedIdx.Descending) {
- require.Equal(t, dbIdx.Descending[i], parsedIdx.Descending[i], "table %s, index %s: descending[%d] should match", tableName, idxName, i)
- }
- }
-
- // 7. KeyLength - validate index key lengths (Oracle specific - prefix lengths)
- if len(dbIdx.KeyLength) > 0 || len(parsedIdx.KeyLength) > 0 {
- require.Equal(t, len(dbIdx.KeyLength), len(parsedIdx.KeyLength), "table %s, index %s: key length array length should match", tableName, idxName)
- for i := range dbIdx.KeyLength {
- if i < len(parsedIdx.KeyLength) {
- require.Equal(t, dbIdx.KeyLength[i], parsedIdx.KeyLength[i], "table %s, index %s: key length[%d] should match", tableName, idxName, i)
- }
- }
- }
-
- // 8. Visible - validate index visibility (Oracle supports invisible indexes)
- require.Equal(t, dbIdx.Visible, parsedIdx.Visible, "table %s, index %s: visible should match", tableName, idxName)
-
- // 9. Comment - validate index comment
- if dbIdx.Comment != "" || parsedIdx.Comment != "" {
- require.Equal(t, dbIdx.Comment, parsedIdx.Comment, "table %s, index %s: comment should match", tableName, idxName)
- }
-
- // 10. IsConstraint - validate if index represents a constraint
- require.Equal(t, dbIdx.IsConstraint, parsedIdx.IsConstraint, "table %s, index %s: IsConstraint should match", tableName, idxName)
-
- // 11. Definition - validate full index definition for comprehensive verification
- if dbIdx.Definition != "" || parsedIdx.Definition != "" {
- // Normalize definitions for comparison since Oracle formatting may vary
- dbDef := strings.TrimSpace(strings.ToUpper(dbIdx.Definition))
- parsedDef := strings.TrimSpace(strings.ToUpper(parsedIdx.Definition))
- if dbDef != "" && parsedDef != "" {
- require.Equal(t, dbDef, parsedDef, "table %s, index %s: definition should match", tableName, idxName)
- }
- }
-
- t.Logf("✓ Validated all IndexMetadata fields for index %s: name=%s, primary=%v, unique=%v, type=%s, expressions=%v, visible=%v, comment=%s",
- idxName, parsedIdx.Name, parsedIdx.Primary, parsedIdx.Unique, parsedIdx.Type, parsedIdx.Expressions, parsedIdx.Visible, parsedIdx.Comment)
- }
-}
-
-// compareForeignKeys compares foreign key metadata
-func compareForeignKeys(t *testing.T, dbFKs, parsedFKs []*storepb.ForeignKeyMetadata, _ string) {
- // TODO: Oracle foreign key parsing needs improvement - for now we only check that parsed FKs are correct
- // Full bidirectional comparison would require fixing the Oracle parser first
- // require.Equal(t, len(dbFKs), len(parsedFKs), "mismatch in number of foreign keys for table %s", tableName)
-
- // Create maps for easier lookup
- dbFKMap := make(map[string]*storepb.ForeignKeyMetadata)
- for _, fk := range dbFKs {
- dbFKMap[fk.Name] = fk
- }
-
- parsedFKMap := make(map[string]*storepb.ForeignKeyMetadata)
- for _, fk := range parsedFKs {
- parsedFKMap[fk.Name] = fk
- }
-
- // Compare each parsed foreign key
- for fkName, parsedFK := range parsedFKMap {
- dbFK, exists := dbFKMap[fkName]
- require.True(t, exists, "parsed foreign key %s not found in database metadata", fkName)
-
- // Compare foreign key properties
- require.Equal(t, dbFK.Name, parsedFK.Name, "foreign key names should match")
- require.Equal(t, dbFK.Columns, parsedFK.Columns, "foreign key columns should match for %s", fkName)
- require.Equal(t, dbFK.ReferencedTable, parsedFK.ReferencedTable, "referenced table should match for %s", fkName)
- require.Equal(t, dbFK.ReferencedColumns, parsedFK.ReferencedColumns, "referenced columns should match for %s", fkName)
- require.Equal(t, dbFK.OnDelete, parsedFK.OnDelete, "on delete action should match for %s", fkName)
- require.Equal(t, dbFK.OnUpdate, parsedFK.OnUpdate, "on update action should match for %s", fkName)
-
- t.Logf("✓ Foreign Key %s: %v -> %s(%v), onDelete=%s, onUpdate=%s",
- fkName, parsedFK.Columns, parsedFK.ReferencedTable, parsedFK.ReferencedColumns,
- parsedFK.OnDelete, parsedFK.OnUpdate)
- }
-}
-
-// compareCheckConstraints compares check constraint metadata
-func compareCheckConstraints(t *testing.T, dbChecks, parsedChecks []*storepb.CheckConstraintMetadata, _ string) {
- // Create maps for easier lookup
- dbCheckMap := make(map[string]*storepb.CheckConstraintMetadata)
- for _, chk := range dbChecks {
- dbCheckMap[chk.Name] = chk
- }
-
- parsedCheckMap := make(map[string]*storepb.CheckConstraintMetadata)
- for _, chk := range parsedChecks {
- parsedCheckMap[chk.Name] = chk
- }
-
- // Compare each parsed check constraint
- for chkName, parsedCheck := range parsedCheckMap {
- dbCheck, exists := dbCheckMap[chkName]
- require.True(t, exists, "parsed check constraint %s not found in database metadata", chkName)
-
- // Compare check constraint properties
- require.Equal(t, dbCheck.Name, parsedCheck.Name, "check constraint names should match")
-
- // Compare expressions (normalize for comparison)
- dbExpr := normalizeCheckExpression(dbCheck.Expression)
- parsedExpr := normalizeCheckExpression(parsedCheck.Expression)
- require.Equal(t, dbExpr, parsedExpr, "check constraint expressions should match for %s", chkName)
-
- t.Logf("✓ Check Constraint %s: %s", chkName, parsedCheck.Expression)
- }
-}
-
-// compareViews compares view metadata
-func compareViews(t *testing.T, dbViews, parsedViews []*storepb.ViewMetadata, _ string) {
- // Create maps for easier lookup
- dbViewMap := make(map[string]*storepb.ViewMetadata)
- for _, view := range dbViews {
- dbViewMap[view.Name] = view
- }
-
- parsedViewMap := make(map[string]*storepb.ViewMetadata)
- for _, view := range parsedViews {
- parsedViewMap[view.Name] = view
- }
-
- // Compare each parsed view
- for viewName, parsedView := range parsedViewMap {
- dbView, exists := dbViewMap[viewName]
- require.True(t, exists, "parsed view %s not found in database metadata", viewName)
-
- // Compare view properties
- require.Equal(t, dbView.Name, parsedView.Name, "view names should match")
- require.NotEmpty(t, parsedView.Definition, "parsed view definition should not be empty")
- require.NotEmpty(t, dbView.Definition, "database view definition should not be empty")
-
- // Compare comments if present
- if dbView.Comment != "" || parsedView.Comment != "" {
- require.Equal(t, dbView.Comment, parsedView.Comment, "view comments should match for %s", viewName)
- }
-
- t.Logf("✓ View %s: definition length=%d", viewName, len(parsedView.Definition))
- }
-}
-
-// compareMaterializedViews compares materialized view metadata
-func compareMaterializedViews(t *testing.T, dbMViews, parsedMViews []*storepb.MaterializedViewMetadata, _ string) {
- // Create maps for easier lookup
- dbMViewMap := make(map[string]*storepb.MaterializedViewMetadata)
- for _, mv := range dbMViews {
- dbMViewMap[mv.Name] = mv
- }
-
- parsedMViewMap := make(map[string]*storepb.MaterializedViewMetadata)
- for _, mv := range parsedMViews {
- parsedMViewMap[mv.Name] = mv
- }
-
- // Compare each parsed materialized view
- for mvName, parsedMV := range parsedMViewMap {
- dbMV, exists := dbMViewMap[mvName]
- require.True(t, exists, "parsed materialized view %s not found in database metadata", mvName)
-
- // Compare materialized view properties
- require.Equal(t, dbMV.Name, parsedMV.Name, "materialized view names should match")
- require.NotEmpty(t, parsedMV.Definition, "parsed materialized view definition should not be empty")
- require.NotEmpty(t, dbMV.Definition, "database materialized view definition should not be empty")
- if dbMV.Comment != "" || parsedMV.Comment != "" {
- if parsedMV.Comment == "" && isOracleAutoMaterializedViewComment(dbMV.Comment) {
- t.Logf("Info: materialized view %s has Oracle-generated comment %q", mvName, dbMV.Comment)
- continue
+ if record {
+ tests[i].Metadata = result
+ return
}
- require.Equal(t, dbMV.Comment, parsedMV.Comment, "materialized view comments should match for %s", mvName)
- }
-
- t.Logf("✓ Materialized View %s: definition length=%d", mvName, len(parsedMV.Definition))
- }
-}
-
-func isOracleAutoMaterializedViewComment(comment string) bool {
- return strings.HasPrefix(comment, "snapshot table for snapshot ")
-}
-
-// compareSequences compares sequence metadata
-func compareSequences(t *testing.T, dbSequences, parsedSequences []*storepb.SequenceMetadata, _ string) {
- // Create maps for easier lookup
- dbSeqMap := make(map[string]*storepb.SequenceMetadata)
- for _, seq := range dbSequences {
- dbSeqMap[seq.Name] = seq
- }
-
- parsedSeqMap := make(map[string]*storepb.SequenceMetadata)
- for _, seq := range parsedSequences {
- parsedSeqMap[seq.Name] = seq
- }
-
- // Compare each parsed sequence
- for seqName, parsedSeq := range parsedSeqMap {
- dbSeq, exists := dbSeqMap[seqName]
- require.True(t, exists, "parsed sequence %s not found in database metadata", seqName)
-
- // Compare sequence properties
- require.Equal(t, dbSeq.Name, parsedSeq.Name, "sequence names should match")
-
- // Compare sequence properties if available
- // Oracle may not store sequence metadata consistently, so be flexible
- if parsedSeq.Start != "" && dbSeq.Start != "" {
- require.Equal(t, dbSeq.Start, parsedSeq.Start, "sequence start values should match for %s", seqName)
- } else if parsedSeq.Start != dbSeq.Start {
- // One has value, other is empty - this is acceptable for Oracle sequences
- t.Logf("Info: sequence %s has different start values - DB: '%s', Parsed: '%s' (Oracle sequence metadata can be inconsistent)",
- seqName, dbSeq.Start, parsedSeq.Start)
- }
-
- if parsedSeq.Increment != "" && dbSeq.Increment != "" {
- require.Equal(t, dbSeq.Increment, parsedSeq.Increment, "sequence increment values should match for %s", seqName)
- } else if parsedSeq.Increment != dbSeq.Increment {
- // One has value, other is empty - this is acceptable for Oracle sequences
- t.Logf("Info: sequence %s has different increment values - DB: '%s', Parsed: '%s' (Oracle sequence metadata can be inconsistent)",
- seqName, dbSeq.Increment, parsedSeq.Increment)
- }
-
- t.Logf("✓ Sequence %s: start=%s, increment=%s", seqName, parsedSeq.Start, parsedSeq.Increment)
- }
-}
-
-// compareFunctions compares function metadata
-func compareFunctions(t *testing.T, dbFunctions, parsedFunctions []*storepb.FunctionMetadata, _ string) {
- // Create maps for easier lookup
- dbFuncMap := make(map[string]*storepb.FunctionMetadata)
- for _, fn := range dbFunctions {
- dbFuncMap[fn.Name] = fn
- }
-
- parsedFuncMap := make(map[string]*storepb.FunctionMetadata)
- for _, fn := range parsedFunctions {
- parsedFuncMap[fn.Name] = fn
- }
-
- // Compare each parsed function
- for funcName, parsedFunc := range parsedFuncMap {
- dbFunc, exists := dbFuncMap[funcName]
- require.True(t, exists, "parsed function %s not found in database metadata", funcName)
-
- // Compare function properties
- require.Equal(t, dbFunc.Name, parsedFunc.Name, "function names should match")
- require.NotEmpty(t, parsedFunc.Definition, "parsed function definition should not be empty")
- require.NotEmpty(t, dbFunc.Definition, "database function definition should not be empty")
-
- t.Logf("✓ Function %s: definition length=%d", funcName, len(parsedFunc.Definition))
- }
-}
-
-// compareProcedures compares procedure metadata
-func compareProcedures(t *testing.T, dbProcedures, parsedProcedures []*storepb.ProcedureMetadata, _ string) {
- // Create maps for easier lookup
- dbProcMap := make(map[string]*storepb.ProcedureMetadata)
- for _, proc := range dbProcedures {
- dbProcMap[proc.Name] = proc
- }
-
- parsedProcMap := make(map[string]*storepb.ProcedureMetadata)
- for _, proc := range parsedProcedures {
- parsedProcMap[proc.Name] = proc
- }
-
- // Compare each parsed procedure
- for procName, parsedProc := range parsedProcMap {
- dbProc, exists := dbProcMap[procName]
- require.True(t, exists, "parsed procedure %s not found in database metadata", procName)
-
- // Compare procedure properties
- require.Equal(t, dbProc.Name, parsedProc.Name, "procedure names should match")
- require.NotEmpty(t, parsedProc.Definition, "parsed procedure definition should not be empty")
- require.NotEmpty(t, dbProc.Definition, "database procedure definition should not be empty")
-
- t.Logf("✓ Procedure %s: definition length=%d", procName, len(parsedProc.Definition))
- }
-}
-
-// Helper functions for normalization
-
-func normalizeOracleDataType(dataType string) string {
- // Normalize NUMBER types - Oracle may return NUMBER(*,0) as NUMBER
- if strings.HasPrefix(dataType, "NUMBER(") && strings.Contains(dataType, "*") {
- dataType = "NUMBER"
- }
-
- return dataType
-}
-
-func normalizeIndexType(indexType string) string {
- indexType = strings.ToUpper(strings.TrimSpace(indexType))
- if indexType == "" {
- return "NORMAL" // Oracle default
- }
- // Oracle uses "NORMAL" for standard B-tree indexes
- if indexType == "BTREE" {
- return "NORMAL"
- }
- return indexType
-}
-
-func normalizeExpression(expr string) string {
- expr = strings.ToUpper(strings.TrimSpace(expr))
- expr = strings.ReplaceAll(expr, "\"", "")
- expr = strings.ReplaceAll(expr, " ", "")
- return expr
-}
-
-func normalizeCheckExpression(expr string) string {
- expr = strings.TrimSpace(expr)
-
- // Remove outer parentheses if present
- if strings.HasPrefix(expr, "(") && strings.HasSuffix(expr, ")") {
- expr = expr[1 : len(expr)-1]
- }
-
- // Normalize spaces and quotes
- expr = strings.ReplaceAll(expr, "\"", "")
- expr = strings.ReplaceAll(expr, " ", "")
- expr = strings.ToUpper(expr)
-
- return expr
-}
-
-func compareColumnDefaults(t *testing.T, dbCol, parsedCol *storepb.ColumnMetadata, tableName, colName string) {
- // Compare default expressions
- dbDefault := getColumnDefaultString(dbCol)
- parsedDefault := getColumnDefaultString(parsedCol)
-
- // Normalize for comparison
- dbDefault = normalizeDefaultExpression(dbDefault)
- parsedDefault = normalizeDefaultExpression(parsedDefault)
-
- if dbDefault != "" || parsedDefault != "" {
- require.Equal(t, dbDefault, parsedDefault,
- "default values should match for column %s.%s: db='%s', parsed='%s'",
- tableName, colName, dbDefault, parsedDefault)
- }
-}
-
-func getColumnDefaultString(col *storepb.ColumnMetadata) string {
- if col.Default != "" {
- return col.Default
- }
- return ""
-}
-
-func normalizeDefaultExpression(expr string) string {
- expr = strings.TrimSpace(expr)
- expr = strings.ToUpper(expr)
-
- // Handle Oracle system functions
- if strings.Contains(expr, "SYSDATE") {
- return "SYSDATE"
- }
- if strings.Contains(expr, "CURRENT_TIMESTAMP") {
- return "CURRENT_TIMESTAMP"
- }
- if strings.Contains(expr, "USER") {
- return "USER"
- }
-
- // Remove quotes from simple values
- if strings.HasPrefix(expr, "'") && strings.HasSuffix(expr, "'") {
- expr = expr[1 : len(expr)-1]
+ require.Equal(t, tc.Metadata, result)
+ })
}
- // Remove parentheses from simple expressions
- if strings.HasPrefix(expr, "(") && strings.HasSuffix(expr, ")") {
- expr = expr[1 : len(expr)-1]
+ if record {
+ yamltest.Record(t, filepath, tests)
}
-
- return expr
}
-func TestGetDatabaseMetadata(t *testing.T) {
+func TestGetDatabaseMetadataObjectKinds(t *testing.T) {
tests := []struct {
name string
ddl string
@@ -1954,6 +506,10 @@ func requireMaterializedViewIndex(t *testing.T, materializedView *storepb.Materi
t.Fatalf("index %q not found in materialized view %q", name, materializedView.Name)
}
+// requireCheckConstraint matches an expression as the extractor renders it,
+// which for most nodes means with every space removed: "SALARY > 0" arrives as
+// "SALARY>0". The assertions below spell out that form rather than the readable
+// one so they describe what the package returns today.
func requireCheckConstraint(t *testing.T, table *storepb.TableMetadata, name string, expression string) {
t.Helper()
for _, check := range table.CheckConstraints {
diff --git a/backend/plugin/schema/oracle/main_test.go b/backend/plugin/schema/oracle/main_test.go
deleted file mode 100644
index e8a5706f97..0000000000
--- a/backend/plugin/schema/oracle/main_test.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package oracle
-
-import (
- "testing"
-
- "github.com/bytebase/bytebase/backend/common/testcontainer"
-)
-
-func TestMain(m *testing.M) { testcontainer.Main(m) }
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration.yaml b/backend/plugin/schema/oracle/testdata/generate_migration.yaml
new file mode 100644
index 0000000000..eaa6c652db
--- /dev/null
+++ b/backend/plugin/schema/oracle/testdata/generate_migration.yaml
@@ -0,0 +1,8249 @@
+- description: Create tables with foreign key constraints
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {}
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "POSTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 3,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PUBLISHED_AT",
+ "position": 5,
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_USER_ID",
+ "expressions": [
+ "\"USER_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ],
+ "onDelete": "CASCADE"
+ }
+ ]
+ },
+ {
+ "name": "USERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USERNAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_USERNAME",
+ "expressions": [
+ "\"USERNAME\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "UK_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE TABLE "USERS" (
+ "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000002".nextval NOT NULL,
+ "USERNAME" VARCHAR2(50 BYTE) NOT NULL,
+ "EMAIL" VARCHAR2(100 BYTE) NOT NULL,
+ "CREATED_AT" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP
+ );
+ ALTER TABLE "USERS" ADD CONSTRAINT "SYS_C0000002" PRIMARY KEY (ID);
+ CREATE INDEX "IDX_USERNAME" ON "USERS" ("USERNAME" ASC);
+ CREATE UNIQUE INDEX "UK_EMAIL" ON "USERS" ("EMAIL" ASC);
+
+ CREATE TABLE "POSTS" (
+ "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000001".nextval NOT NULL,
+ "USER_ID" NUMBER NOT NULL,
+ "TITLE" VARCHAR2(200 BYTE) NOT NULL,
+ "CONTENT" CLOB,
+ "PUBLISHED_AT" TIMESTAMP(6)
+ );
+ ALTER TABLE "POSTS" ADD CONSTRAINT "SYS_C0000001" PRIMARY KEY (ID);
+ CREATE INDEX "IDX_USER_ID" ON "POSTS" ("USER_ID" ASC);
+
+ ALTER TABLE "POSTS" ADD CONSTRAINT "FK_USER" FOREIGN KEY ("USER_ID") REFERENCES "USERS" ("ID") ON DELETE CASCADE;
+- description: Basic table operations with columns, constraints, and indexes
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "COMMENTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "POST_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_COMMENT_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ },
+ {
+ "name": "FK_POST",
+ "columns": [
+ "POST_ID"
+ ],
+ "referencedTable": "POSTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "POSTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 3,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_POSTS_USER_ID",
+ "expressions": [
+ "\"USER_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_TITLE_LENGTH",
+ "expression": "LENGTH(TITLE) > 0"
+ }
+ ]
+ },
+ {
+ "name": "USERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USERNAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 5,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_USERS_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "POSTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 3,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_POSTS_USER_ID",
+ "expressions": [
+ "\"USER_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "USERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USERNAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |+
+ ALTER TABLE "COMMENTS" DROP CONSTRAINT "FK_COMMENT_USER";
+ ALTER TABLE "COMMENTS" DROP CONSTRAINT "FK_POST";
+ DROP TABLE "COMMENTS";
+ ALTER TABLE "POSTS" DROP CONSTRAINT "CHECK_TITLE_LENGTH";
+ DROP INDEX "IDX_USERS_EMAIL";
+ ALTER TABLE "USERS" DROP COLUMN "IS_ACTIVE";
+
+- description: Views, functions, and materialized views
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_PRODUCT",
+ "columns": [
+ "PRODUCT_ID"
+ ],
+ "referencedTable": "PRODUCTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "STOCK",
+ "position": 4,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "PRODUCT_INVENTORY",
+ "definition": "SELECT\n P.ID,\n P.NAME,\n P.PRICE,\n P.STOCK,\n NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED\nFROM PRODUCTS P\nLEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID\nGROUP BY P.ID, P.NAME, P.PRICE, P.STOCK",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "ORDERS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "PRODUCTS",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "STOCK",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL_ORDERED",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "CALCULATE_ORDER_TOTAL",
+ "definition": "FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)\nRETURN NUMBER\nIS\n V_PRICE NUMBER(10, 2);\nBEGIN\n SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;\n RETURN P_QUANTITY * V_PRICE;\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN 0;\nEND;"
+ }
+ ],
+ "materializedViews": [
+ {
+ "name": "PRODUCT_STATS",
+ "definition": "SELECT\n PRODUCT_ID,\n COUNT(*) AS ORDER_COUNT,\n SUM(QUANTITY) AS TOTAL_QUANTITY,\n SUM(TOTAL) AS TOTAL_REVENUE\nFROM ORDERS\nGROUP BY PRODUCT_ID\n",
+ "comment": "snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "ORDERS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "PRODUCT_STATS",
+ "column": "*"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_PRODUCT",
+ "columns": [
+ "PRODUCT_ID"
+ ],
+ "referencedTable": "PRODUCTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "STOCK",
+ "position": 4,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ DROP FUNCTION "CALCULATE_ORDER_TOTAL";
+ DROP VIEW "PRODUCT_INVENTORY";
+ DROP MATERIALIZED VIEW "PRODUCT_STATS";
+- description: Sequences and their usage in tables
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ITEMS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "SALES_ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"ORDER_SEQ\".NEXTVAL",
+ "type": "NUMBER"
+ },
+ {
+ "name": "ITEM_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 3,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_ITEM",
+ "columns": [
+ "ITEM_ID"
+ ],
+ "referencedTable": "ITEMS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "ORDER_SEQ"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ITEMS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ DROP SEQUENCE "ORDER_SEQ";
+ ALTER TABLE "SALES_ORDERS" DROP CONSTRAINT "FK_ITEM";
+ DROP TABLE "SALES_ORDERS";
+- description: Drop indexes and constraints from tables
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SUPPLIER_ID",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SUPPLIER_ID",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_NAME",
+ "expressions": [
+ "\"NAME\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_PRICE",
+ "expressions": [
+ "\"PRICE\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_NAME_LENGTH",
+ "expression": "LENGTH(NAME) >= 3"
+ },
+ {
+ "name": "CHECK_PRICE_POSITIVE",
+ "expression": "PRICE > 0"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE INDEX "IDX_PRODUCTS_CATEGORY" ON "PRODUCTS" ("CATEGORY" ASC);
+ CREATE UNIQUE INDEX "IDX_PRODUCTS_NAME" ON "PRODUCTS" ("NAME" ASC);
+ CREATE INDEX "IDX_PRODUCTS_PRICE" ON "PRODUCTS" ("PRICE" ASC);
+ ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_NAME_LENGTH" CHECK (LENGTH(NAME) >= 3);
+ ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_PRICE_POSITIVE" CHECK (PRICE > 0);
+- description: Drop views and functions that depend on tables
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "SALE_AMOUNT",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 4,
+ "type": "DATE"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "SALE_AMOUNT",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 4,
+ "type": "DATE"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "MONTHLY_SALES",
+ "definition": "SELECT\n EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,\n EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,\n SUM(SALE_AMOUNT) AS TOTAL_SALES\nFROM SALES\nGROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE)",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "SALES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "YEAR_VAL",
+ "position": 1,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "MONTH_VAL",
+ "position": 2,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL_SALES",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "CALCULATE_DISCOUNT",
+ "definition": "FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)\nRETURN NUMBER\nIS\nBEGIN\n RETURN AMOUNT * 0.1;\nEND;"
+ },
+ {
+ "name": "GET_MONTHLY_TOTAL",
+ "definition": "FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)\nRETURN NUMBER\nIS\n V_TOTAL NUMBER;\nBEGIN\n SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL\n FROM SALES\n WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM\n AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;\n\n RETURN V_TOTAL;\nEND;"
+ }
+ ],
+ "materializedViews": [
+ {
+ "name": "TOP_PRODUCTS",
+ "definition": "SELECT\n PRODUCT_NAME,\n COUNT(*) AS SALE_COUNT,\n SUM(SALE_AMOUNT) AS TOTAL_REVENUE\nFROM SALES\nGROUP BY PRODUCT_NAME\n",
+ "comment": "snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "SALES",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "TOP_PRODUCTS",
+ "column": "*"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE OR REPLACE FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)
+ RETURN NUMBER
+ IS
+ BEGIN
+ RETURN AMOUNT * 0.1;
+ END;
+
+ CREATE OR REPLACE FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)
+ RETURN NUMBER
+ IS
+ V_TOTAL NUMBER;
+ BEGIN
+ SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL
+ FROM SALES
+ WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM
+ AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;
+
+ RETURN V_TOTAL;
+ END;
+
+ CREATE VIEW "MONTHLY_SALES" AS SELECT
+ EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,
+ EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,
+ SUM(SALE_AMOUNT) AS TOTAL_SALES
+ FROM SALES
+ GROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE);
+ CREATE MATERIALIZED VIEW "TOP_PRODUCTS" AS SELECT
+ PRODUCT_NAME,
+ COUNT(*) AS SALE_COUNT,
+ SUM(SALE_AMOUNT) AS TOTAL_REVENUE
+ FROM SALES
+ GROUP BY PRODUCT_NAME
+ ;
+ COMMENT ON MATERIALIZED VIEW "TOP_PRODUCTS" IS 'snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS';
+ COMMENT ON MATERIALIZED VIEW "TOP_PRODUCTS" IS 'snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS';
+- description: Alter table with column additions, type changes, and constraints
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(30 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 6,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "STOCK_QUANTITY",
+ "position": 8,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "WEIGHT",
+ "position": 9,
+ "nullable": true,
+ "type": "NUMBER(5,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CREATED_AT",
+ "expressions": [
+ "\"CREATED_AT\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_NAME_CATEGORY",
+ "expressions": [
+ "\"NAME\"",
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_PRICE",
+ "expressions": [
+ "\"PRICE\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_PRICE_POSITIVE",
+ "expression": "PRICE > 0"
+ },
+ {
+ "name": "CHECK_STOCK_NON_NEGATIVE",
+ "expression": "STOCK_QUANTITY >= 0"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(8,2)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(30 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 6,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_PRICE",
+ "expressions": [
+ "\"PRICE\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_PRICE_POSITIVE";
+ ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_STOCK_NON_NEGATIVE";
+ DROP INDEX "IDX_PRODUCTS_CREATED_AT";
+ DROP INDEX "IDX_PRODUCTS_NAME_CATEGORY";
+ ALTER TABLE "PRODUCTS" DROP COLUMN "CREATED_AT";
+ ALTER TABLE "PRODUCTS" DROP COLUMN "STOCK_QUANTITY";
+ ALTER TABLE "PRODUCTS" DROP COLUMN "WEIGHT";
+
+ ALTER TABLE "PRODUCTS" MODIFY "NAME" VARCHAR2(50 BYTE);
+ ALTER TABLE "PRODUCTS" MODIFY "PRICE" NUMBER(8,2);
+ ALTER TABLE "PRODUCTS" MODIFY "DESCRIPTION" NULL;
+- description: Drop and recreate constraints with different definitions
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUTHORS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "EMAIL"
+ ],
+ "unique": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "BOOKS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 2,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "AUTHOR_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ISBN",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PUBLISHED_YEAR",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRICE",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER(8,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000004",
+ "expressions": [
+ "ISBN"
+ ],
+ "unique": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_BOOKS_AUTHOR",
+ "expressions": [
+ "\"AUTHOR_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_BOOKS_YEAR",
+ "expressions": [
+ "\"PUBLISHED_YEAR\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_AUTHOR_NEW",
+ "columns": [
+ "AUTHOR_ID"
+ ],
+ "referencedTable": "AUTHORS",
+ "referencedColumns": [
+ "ID"
+ ],
+ "onDelete": "CASCADE"
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_PRICE_POSITIVE",
+ "expression": "PRICE > 0"
+ },
+ {
+ "name": "CHECK_TITLE_LENGTH",
+ "expression": "LENGTH(TITLE) >= 3"
+ },
+ {
+ "name": "CHECK_YEAR_EXTENDED",
+ "expression": "PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2030"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUTHORS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "EMAIL"
+ ],
+ "unique": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "BOOKS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 2,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "AUTHOR_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ISBN",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PUBLISHED_YEAR",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRICE",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER(8,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000004",
+ "expressions": [
+ "ISBN"
+ ],
+ "unique": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_BOOKS_AUTHOR",
+ "expressions": [
+ "\"AUTHOR_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_BOOKS_YEAR",
+ "expressions": [
+ "\"PUBLISHED_YEAR\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_AUTHOR",
+ "columns": [
+ "AUTHOR_ID"
+ ],
+ "referencedTable": "AUTHORS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_PRICE_POSITIVE",
+ "expression": "PRICE > 0"
+ },
+ {
+ "name": "CHECK_YEAR_VALID",
+ "expression": "PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2100"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "BOOKS" DROP CONSTRAINT "FK_AUTHOR_NEW";
+ ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_TITLE_LENGTH";
+ ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_YEAR_EXTENDED";
+
+ ALTER TABLE "BOOKS" ADD CONSTRAINT "CHECK_YEAR_VALID" CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2100);
+ ALTER TABLE "BOOKS" ADD CONSTRAINT "FK_AUTHOR" FOREIGN KEY ("AUTHOR_ID") REFERENCES "AUTHORS" ("ID");
+- description: Drop sequence and dependent table
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {}
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SIMPLE_LOG",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TRANSACTION_SEQ\".NEXTVAL",
+ "type": "NUMBER"
+ },
+ {
+ "name": "MESSAGE",
+ "position": 2,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "TRANSACTION_SEQ"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |+
+ CREATE SEQUENCE "TRANSACTION_SEQ";
+ CREATE TABLE "SIMPLE_LOG" (
+ "ID" NUMBER DEFAULT "TRANSACTION_SEQ".NEXTVAL NOT NULL,
+ "MESSAGE" CLOB NOT NULL
+ );
+ ALTER TABLE "SIMPLE_LOG" ADD CONSTRAINT "SYS_C0000001" PRIMARY KEY (ID);
+
+- description: Complex view dependencies with multiple levels and materialized views
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "DEPARTMENTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "MANAGER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_MANAGER",
+ "columns": [
+ "MANAGER_ID"
+ ],
+ "referencedTable": "EMPLOYEES",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "EMPLOYEES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "DEPARTMENT_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_DEPT",
+ "columns": [
+ "DEPARTMENT_ID"
+ ],
+ "referencedTable": "DEPARTMENTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "DEPT_EMPLOYEE_COUNT",
+ "definition": "SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPARTMENTS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "DEPT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "DEPT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMP_COUNT",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ },
+ {
+ "name": "DEPT_MANAGER_SUMMARY",
+ "definition": "SELECT\n DS.DEPT_ID,\n DS.DEPT_NAME,\n DS.EMP_COUNT,\n DS.AVG_SALARY,\n M.NAME AS MANAGER_NAME\nFROM DEPT_SUMMARY DS\nJOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID\nLEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPARTMENTS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPT_SUMMARY",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "DEPT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "DEPT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMP_COUNT",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AVG_SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "MANAGER_NAME",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ]
+ },
+ {
+ "name": "DEPT_SUMMARY",
+ "definition": "SELECT\n DEC.DEPT_ID,\n DEC.DEPT_NAME,\n DEC.EMP_COUNT,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY\nFROM DEPT_EMPLOYEE_COUNT DEC\nLEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID\nGROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPT_EMPLOYEE_COUNT",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "DEPT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "DEPT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMP_COUNT",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AVG_SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ }
+ ],
+ "materializedViews": [
+ {
+ "name": "MV_DEPT_STATS",
+ "definition": "SELECT\n D.ID AS DEPT_ID,\n D.NAME AS DEPT_NAME,\n COUNT(E.ID) AS TOTAL_EMPLOYEES,\n NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY,\n NVL(MAX(E.SALARY), 0) AS MAX_SALARY,\n NVL(MIN(E.SALARY), 0) AS MIN_SALARY\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME\n",
+ "comment": "snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPARTMENTS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "MV_DEPT_STATS",
+ "column": "*"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "DEPARTMENTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "MANAGER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_MANAGER",
+ "columns": [
+ "MANAGER_ID"
+ ],
+ "referencedTable": "EMPLOYEES",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "EMPLOYEES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "DEPARTMENT_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_DEPT",
+ "columns": [
+ "DEPARTMENT_ID"
+ ],
+ "referencedTable": "DEPARTMENTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ DROP VIEW "DEPT_EMPLOYEE_COUNT";
+ DROP VIEW "DEPT_MANAGER_SUMMARY";
+ DROP VIEW "DEPT_SUMMARY";
+ DROP MATERIALIZED VIEW "MV_DEPT_STATS";
+- description: Circular foreign key dependencies and triggers
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PREFERRED_ORDER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_PREFERRED_ORDER",
+ "columns": [
+ "PREFERRED_ORDER_ID"
+ ],
+ "referencedTable": "ORDERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 3,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_CUSTOMER",
+ "columns": [
+ "CUSTOMER_ID"
+ ],
+ "referencedTable": "CUSTOMERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "ORDER_ITEMS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_NAME",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 4,
+ "type": "NUMBER"
+ },
+ {
+ "name": "UNIT_PRICE",
+ "position": 5,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_ORDER_ITEM",
+ "columns": [
+ "ORDER_ID"
+ ],
+ "referencedTable": "ORDERS",
+ "referencedColumns": [
+ "ID"
+ ],
+ "onDelete": "CASCADE"
+ }
+ ],
+ "triggers": [
+ {
+ "name": "TRG_UPDATE_ORDER_TOTAL",
+ "event": "INSERT OR UPDATE OR DELETE",
+ "timing": "AFTER EACH ROW",
+ "body": "CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL\nAFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS\nFOR EACH ROW\nDECLARE\n V_ORDER_ID NUMBER;\n V_TOTAL NUMBER(10, 2);\nBEGIN\n -- Get order ID\n IF INSERTING OR UPDATING THEN\n V_ORDER_ID := :NEW.ORDER_ID;\n ELSE\n V_ORDER_ID := :OLD.ORDER_ID;\n END IF;\n\n -- Calculate new total\n SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL\n FROM ORDER_ITEMS\n WHERE ORDER_ID = V_ORDER_ID;\n\n -- Update order total\n UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;\nEND;"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PREFERRED_ORDER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 3,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |+
+ ALTER TABLE "CUSTOMERS" DROP CONSTRAINT "FK_PREFERRED_ORDER";
+ ALTER TABLE "ORDERS" DROP CONSTRAINT "FK_CUSTOMER";
+ ALTER TABLE "ORDER_ITEMS" DROP CONSTRAINT "FK_ORDER_ITEM";
+ DROP TABLE "ORDER_ITEMS";
+
+- description: Advanced Oracle-specific indexes and complex constraints
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 2,
+ "type": "DATE"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 4,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AMOUNT",
+ "position": 5,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "REGION",
+ "position": 6,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "UK_SALES_DATE_CUSTOMER",
+ "expressions": [
+ "SALE_DATE",
+ "CUSTOMER_ID",
+ "PRODUCT_ID"
+ ],
+ "unique": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_SALES_MONTH_YEAR",
+ "expressions": [
+ "EXTRACT(YEAR FROM \"SALE_DATE\")",
+ "EXTRACT(MONTH FROM \"SALE_DATE\")"
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "FUNCTION-BASED NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_SALES_REGION_AMOUNT",
+ "expressions": [
+ "\"REGION\"",
+ "\"AMOUNT\""
+ ],
+ "descending": [
+ false,
+ true
+ ],
+ "type": "FUNCTION-BASED NORMAL",
+ "visible": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHK_AMOUNT_RANGE",
+ "expression": "AMOUNT > 0 AND AMOUNT <= 999999.99"
+ },
+ {
+ "name": "CHK_REGION_VALID",
+ "expression": "REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL')"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 2,
+ "type": "DATE"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 4,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AMOUNT",
+ "position": 5,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "REGION",
+ "position": 6,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |+
+ ALTER TABLE "SALES_DATA" DROP CONSTRAINT "CHK_AMOUNT_RANGE";
+ ALTER TABLE "SALES_DATA" DROP CONSTRAINT "CHK_REGION_VALID";
+ DROP INDEX "IDX_SALES_MONTH_YEAR";
+ DROP INDEX "IDX_SALES_REGION_AMOUNT";
+ ALTER TABLE "SALES_DATA" DROP CONSTRAINT "UK_SALES_DATE_CUSTOMER";
+
+- description: Stored procedures and functions with dependencies
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUDIT_LOG",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TABLE_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OPERATION",
+ "position": 3,
+ "type": "VARCHAR2(10 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OLD_VALUES",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "NEW_VALUES",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TIMESTAMP",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "USER_NAME",
+ "position": 7,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "CALCULATE_BUSINESS_DAYS",
+ "definition": "FUNCTION CALCULATE_BUSINESS_DAYS(\n P_START_DATE DATE,\n P_END_DATE DATE\n) RETURN NUMBER\nIS\n V_DAYS NUMBER := 0;\n V_CURRENT_DATE DATE := P_START_DATE;\nBEGIN\n WHILE V_CURRENT_DATE <= P_END_DATE LOOP\n -- Skip weekends (Saturday = 7, Sunday = 1)\n IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN\n V_DAYS := V_DAYS + 1;\n END IF;\n V_CURRENT_DATE := V_CURRENT_DATE + 1;\n END LOOP;\n\n RETURN V_DAYS;\nEND;"
+ },
+ {
+ "name": "GET_AUDIT_COUNT",
+ "definition": "FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER\nIS\n V_COUNT NUMBER;\nBEGIN\n SELECT COUNT(*) INTO V_COUNT\n FROM AUDIT_LOG\n WHERE TABLE_NAME = P_TABLE_NAME;\n\n RETURN V_COUNT;\nEND;"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "LOG_AUDIT",
+ "definition": "PROCEDURE LOG_AUDIT(\n P_TABLE_NAME VARCHAR2,\n P_OPERATION VARCHAR2,\n P_OLD_VALUES CLOB DEFAULT NULL,\n P_NEW_VALUES CLOB DEFAULT NULL\n)\nIS\nBEGIN\n INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)\n VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);\n COMMIT;\nEXCEPTION\n WHEN OTHERS THEN\n ROLLBACK;\n RAISE;\nEND;"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUDIT_LOG",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TABLE_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OPERATION",
+ "position": 3,
+ "type": "VARCHAR2(10 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OLD_VALUES",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "NEW_VALUES",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TIMESTAMP",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "USER_NAME",
+ "position": 7,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ DROP FUNCTION "CALCULATE_BUSINESS_DAYS";
+ DROP FUNCTION "GET_AUDIT_COUNT";
+ DROP PROCEDURE "LOG_AUDIT";
+- description: Edge cases for column operations and data type modifications
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "TEST_COLUMNS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "COL_VARCHAR",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_NUMBER",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER(15,3)"
+ },
+ {
+ "name": "COL_DATE",
+ "position": 4,
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "COL_NULLABLE",
+ "position": 5,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_WITH_DEFAULT",
+ "position": 6,
+ "default": "'NEW_DEFAULT'",
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_TIMESTAMP",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "COL_BOOLEAN",
+ "position": 8,
+ "nullable": true,
+ "type": "NUMBER(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHK_NUMBER_POSITIVE",
+ "expression": "COL_NUMBER > 0"
+ },
+ {
+ "name": "CHK_VARCHAR_LENGTH",
+ "expression": "LENGTH(COL_VARCHAR) >= 5"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "TEST_COLUMNS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "COL_VARCHAR",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_NUMBER",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "COL_DATE",
+ "position": 4,
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "COL_CLOB",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_NULLABLE",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_WITH_DEFAULT",
+ "position": 7,
+ "default": "'DEFAULT_VALUE'",
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "TEST_COLUMNS" DROP CONSTRAINT "CHK_NUMBER_POSITIVE";
+ ALTER TABLE "TEST_COLUMNS" DROP CONSTRAINT "CHK_VARCHAR_LENGTH";
+ ALTER TABLE "TEST_COLUMNS" DROP COLUMN "COL_TIMESTAMP";
+ ALTER TABLE "TEST_COLUMNS" DROP COLUMN "COL_BOOLEAN";
+
+ ALTER TABLE "TEST_COLUMNS" ADD "COL_CLOB" CLOB;
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_VARCHAR" VARCHAR2(50 BYTE);
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NUMBER" NUMBER(10,2);
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NULLABLE" NULL;
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT NULL;
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT 'DEFAULT_VALUE';
+- description: 'Reverse: Drop tables with foreign key constraints'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "POSTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 3,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PUBLISHED_AT",
+ "position": 5,
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_USER_ID",
+ "expressions": [
+ "\"USER_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ],
+ "onDelete": "CASCADE"
+ }
+ ]
+ },
+ {
+ "name": "USERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USERNAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_USERNAME",
+ "expressions": [
+ "\"USERNAME\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "UK_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {}
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "POSTS" DROP CONSTRAINT "FK_USER";
+ DROP TABLE "POSTS";
+ DROP TABLE "USERS";
+- description: 'Reverse: Drop tables, columns, constraints, and indexes'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "POSTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 3,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_POSTS_USER_ID",
+ "expressions": [
+ "\"USER_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "USERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USERNAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "COMMENTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "POST_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_COMMENT_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ },
+ {
+ "name": "FK_POST",
+ "columns": [
+ "POST_ID"
+ ],
+ "referencedTable": "POSTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "POSTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 3,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_POSTS_USER_ID",
+ "expressions": [
+ "\"USER_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_USER",
+ "columns": [
+ "USER_ID"
+ ],
+ "referencedTable": "USERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_TITLE_LENGTH",
+ "expression": "LENGTH(TITLE) > 0"
+ }
+ ]
+ },
+ {
+ "name": "USERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "USERNAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 5,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_USERS_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "USERS" ADD "IS_ACTIVE" NUMBER(1) DEFAULT 1;
+ CREATE TABLE "COMMENTS" (
+ "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000001".nextval NOT NULL,
+ "POST_ID" NUMBER NOT NULL,
+ "USER_ID" NUMBER NOT NULL,
+ "CONTENT" CLOB NOT NULL,
+ "CREATED_AT" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP
+ );
+ ALTER TABLE "COMMENTS" ADD CONSTRAINT "SYS_C0000001" PRIMARY KEY (ID);
+
+ ALTER TABLE "COMMENTS" ADD CONSTRAINT "FK_COMMENT_USER" FOREIGN KEY ("USER_ID") REFERENCES "USERS" ("ID");
+ ALTER TABLE "COMMENTS" ADD CONSTRAINT "FK_POST" FOREIGN KEY ("POST_ID") REFERENCES "POSTS" ("ID");
+ ALTER TABLE "POSTS" ADD CONSTRAINT "CHECK_TITLE_LENGTH" CHECK (LENGTH(TITLE) > 0);
+ CREATE INDEX "IDX_USERS_EMAIL" ON "USERS" ("EMAIL" ASC);
+- description: 'Reverse: Drop views, functions, and materialized views'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_PRODUCT",
+ "columns": [
+ "PRODUCT_ID"
+ ],
+ "referencedTable": "PRODUCTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "STOCK",
+ "position": 4,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_PRODUCT",
+ "columns": [
+ "PRODUCT_ID"
+ ],
+ "referencedTable": "PRODUCTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "STOCK",
+ "position": 4,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "PRODUCT_INVENTORY",
+ "definition": "SELECT\n P.ID,\n P.NAME,\n P.PRICE,\n P.STOCK,\n NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED\nFROM PRODUCTS P\nLEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID\nGROUP BY P.ID, P.NAME, P.PRICE, P.STOCK",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "ORDERS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "PRODUCTS",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "STOCK",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL_ORDERED",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "CALCULATE_ORDER_TOTAL",
+ "definition": "FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)\nRETURN NUMBER\nIS\n V_PRICE NUMBER(10, 2);\nBEGIN\n SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;\n RETURN P_QUANTITY * V_PRICE;\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN 0;\nEND;"
+ }
+ ],
+ "materializedViews": [
+ {
+ "name": "PRODUCT_STATS",
+ "definition": "SELECT\n PRODUCT_ID,\n COUNT(*) AS ORDER_COUNT,\n SUM(QUANTITY) AS TOTAL_QUANTITY,\n SUM(TOTAL) AS TOTAL_REVENUE\nFROM ORDERS\nGROUP BY PRODUCT_ID\n",
+ "comment": "snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "ORDERS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "PRODUCT_STATS",
+ "column": "*"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE OR REPLACE FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)
+ RETURN NUMBER
+ IS
+ V_PRICE NUMBER(10, 2);
+ BEGIN
+ SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;
+ RETURN P_QUANTITY * V_PRICE;
+ EXCEPTION
+ WHEN NO_DATA_FOUND THEN
+ RETURN 0;
+ END;
+
+ CREATE VIEW "PRODUCT_INVENTORY" AS SELECT
+ P.ID,
+ P.NAME,
+ P.PRICE,
+ P.STOCK,
+ NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED
+ FROM PRODUCTS P
+ LEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID
+ GROUP BY P.ID, P.NAME, P.PRICE, P.STOCK;
+ CREATE MATERIALIZED VIEW "PRODUCT_STATS" AS SELECT
+ PRODUCT_ID,
+ COUNT(*) AS ORDER_COUNT,
+ SUM(QUANTITY) AS TOTAL_QUANTITY,
+ SUM(TOTAL) AS TOTAL_REVENUE
+ FROM ORDERS
+ GROUP BY PRODUCT_ID
+ ;
+ COMMENT ON MATERIALIZED VIEW "PRODUCT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS';
+ COMMENT ON MATERIALIZED VIEW "PRODUCT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS';
+- description: 'Reverse: Drop sequences and tables using them'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ITEMS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ITEMS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "SALES_ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"ORDER_SEQ\".NEXTVAL",
+ "type": "NUMBER"
+ },
+ {
+ "name": "ITEM_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 3,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_ITEM",
+ "columns": [
+ "ITEM_ID"
+ ],
+ "referencedTable": "ITEMS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "ORDER_SEQ"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE SEQUENCE "ORDER_SEQ";
+ CREATE TABLE "SALES_ORDERS" (
+ "ID" NUMBER DEFAULT "ORDER_SEQ".NEXTVAL NOT NULL,
+ "ITEM_ID" NUMBER NOT NULL,
+ "QUANTITY" NUMBER NOT NULL
+ );
+ ALTER TABLE "SALES_ORDERS" ADD CONSTRAINT "SYS_C0000002" PRIMARY KEY (ID);
+
+ ALTER TABLE "SALES_ORDERS" ADD CONSTRAINT "FK_ITEM" FOREIGN KEY ("ITEM_ID") REFERENCES "ITEMS" ("ID");
+- description: 'Reverse: Create indexes and constraints on tables'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SUPPLIER_ID",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_NAME",
+ "expressions": [
+ "\"NAME\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_PRICE",
+ "expressions": [
+ "\"PRICE\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_NAME_LENGTH",
+ "expression": "LENGTH(NAME) >= 3"
+ },
+ {
+ "name": "CHECK_PRICE_POSITIVE",
+ "expression": "PRICE > 0"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SUPPLIER_ID",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |+
+ ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_NAME_LENGTH";
+ ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_PRICE_POSITIVE";
+ DROP INDEX "IDX_PRODUCTS_CATEGORY";
+ DROP INDEX "IDX_PRODUCTS_NAME";
+ DROP INDEX "IDX_PRODUCTS_PRICE";
+
+- description: 'Reverse: Create views and functions that depend on tables'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "SALE_AMOUNT",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 4,
+ "type": "DATE"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "MONTHLY_SALES",
+ "definition": "SELECT\n EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,\n EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,\n SUM(SALE_AMOUNT) AS TOTAL_SALES\nFROM SALES\nGROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE)",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "SALES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "YEAR_VAL",
+ "position": 1,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "MONTH_VAL",
+ "position": 2,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TOTAL_SALES",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "CALCULATE_DISCOUNT",
+ "definition": "FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)\nRETURN NUMBER\nIS\nBEGIN\n RETURN AMOUNT * 0.1;\nEND;"
+ },
+ {
+ "name": "GET_MONTHLY_TOTAL",
+ "definition": "FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)\nRETURN NUMBER\nIS\n V_TOTAL NUMBER;\nBEGIN\n SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL\n FROM SALES\n WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM\n AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;\n\n RETURN V_TOTAL;\nEND;"
+ }
+ ],
+ "materializedViews": [
+ {
+ "name": "TOP_PRODUCTS",
+ "definition": "SELECT\n PRODUCT_NAME,\n COUNT(*) AS SALE_COUNT,\n SUM(SALE_AMOUNT) AS TOTAL_REVENUE\nFROM SALES\nGROUP BY PRODUCT_NAME\n",
+ "comment": "snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "SALES",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "TOP_PRODUCTS",
+ "column": "*"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "SALE_AMOUNT",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 4,
+ "type": "DATE"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ DROP FUNCTION "CALCULATE_DISCOUNT";
+ DROP FUNCTION "GET_MONTHLY_TOTAL";
+ DROP VIEW "MONTHLY_SALES";
+ DROP MATERIALIZED VIEW "TOP_PRODUCTS";
+- description: 'Reverse: Remove columns, constraints and revert type changes'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(8,2)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(30 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 6,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_PRICE",
+ "expressions": [
+ "\"PRICE\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(30 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 6,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "STOCK_QUANTITY",
+ "position": 8,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "WEIGHT",
+ "position": 9,
+ "nullable": true,
+ "type": "NUMBER(5,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CREATED_AT",
+ "expressions": [
+ "\"CREATED_AT\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_NAME_CATEGORY",
+ "expressions": [
+ "\"NAME\"",
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCTS_PRICE",
+ "expressions": [
+ "\"PRICE\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_PRICE_POSITIVE",
+ "expression": "PRICE > 0"
+ },
+ {
+ "name": "CHECK_STOCK_NON_NEGATIVE",
+ "expression": "STOCK_QUANTITY >= 0"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "PRODUCTS" ADD "CREATED_AT" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP;
+ ALTER TABLE "PRODUCTS" ADD "STOCK_QUANTITY" NUMBER DEFAULT 0;
+ ALTER TABLE "PRODUCTS" ADD "WEIGHT" NUMBER(5,2);
+ ALTER TABLE "PRODUCTS" MODIFY "NAME" VARCHAR2(100 BYTE);
+ ALTER TABLE "PRODUCTS" MODIFY "PRICE" NUMBER(10,2);
+ ALTER TABLE "PRODUCTS" MODIFY "DESCRIPTION" NOT NULL;
+ CREATE INDEX "IDX_PRODUCTS_CREATED_AT" ON "PRODUCTS" ("CREATED_AT" ASC);
+ CREATE UNIQUE INDEX "IDX_PRODUCTS_NAME_CATEGORY" ON "PRODUCTS" ("NAME" ASC, "CATEGORY" ASC);
+ ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_PRICE_POSITIVE" CHECK (PRICE > 0);
+ ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_STOCK_NON_NEGATIVE" CHECK (STOCK_QUANTITY >= 0);
+- description: 'Reverse: Revert constraint modifications'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUTHORS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "EMAIL"
+ ],
+ "unique": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "BOOKS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 2,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "AUTHOR_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ISBN",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PUBLISHED_YEAR",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRICE",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER(8,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000004",
+ "expressions": [
+ "ISBN"
+ ],
+ "unique": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_BOOKS_AUTHOR",
+ "expressions": [
+ "\"AUTHOR_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_BOOKS_YEAR",
+ "expressions": [
+ "\"PUBLISHED_YEAR\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_AUTHOR",
+ "columns": [
+ "AUTHOR_ID"
+ ],
+ "referencedTable": "AUTHORS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_PRICE_POSITIVE",
+ "expression": "PRICE > 0"
+ },
+ {
+ "name": "CHECK_YEAR_VALID",
+ "expression": "PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2100"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUTHORS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "EMAIL"
+ ],
+ "unique": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "BOOKS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE",
+ "position": 2,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "AUTHOR_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ISBN",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PUBLISHED_YEAR",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRICE",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER(8,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "SYS_C0000004",
+ "expressions": [
+ "ISBN"
+ ],
+ "unique": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_BOOKS_AUTHOR",
+ "expressions": [
+ "\"AUTHOR_ID\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_BOOKS_YEAR",
+ "expressions": [
+ "\"PUBLISHED_YEAR\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_AUTHOR_NEW",
+ "columns": [
+ "AUTHOR_ID"
+ ],
+ "referencedTable": "AUTHORS",
+ "referencedColumns": [
+ "ID"
+ ],
+ "onDelete": "CASCADE"
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHECK_TITLE_LENGTH",
+ "expression": "LENGTH(TITLE) >= 3"
+ },
+ {
+ "name": "CHECK_YEAR_EXTENDED",
+ "expression": "PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2030"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "BOOKS" DROP CONSTRAINT "FK_AUTHOR";
+ ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_PRICE_POSITIVE";
+ ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_YEAR_VALID";
+
+ ALTER TABLE "BOOKS" ADD CONSTRAINT "CHECK_TITLE_LENGTH" CHECK (LENGTH(TITLE) >= 3);
+ ALTER TABLE "BOOKS" ADD CONSTRAINT "CHECK_YEAR_EXTENDED" CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2030);
+ ALTER TABLE "BOOKS" ADD CONSTRAINT "FK_AUTHOR_NEW" FOREIGN KEY ("AUTHOR_ID") REFERENCES "AUTHORS" ("ID") ON DELETE CASCADE;
+- description: 'Reverse: Create sequence and dependent table'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SIMPLE_LOG",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TRANSACTION_SEQ\".NEXTVAL",
+ "type": "NUMBER"
+ },
+ {
+ "name": "MESSAGE",
+ "position": 2,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "TRANSACTION_SEQ"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {}
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ DROP TABLE "SIMPLE_LOG";
+ DROP SEQUENCE "TRANSACTION_SEQ";
+- description: 'Reverse: Drop complex view dependencies'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "DEPARTMENTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "MANAGER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_MANAGER",
+ "columns": [
+ "MANAGER_ID"
+ ],
+ "referencedTable": "EMPLOYEES",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "EMPLOYEES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "DEPARTMENT_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_DEPT",
+ "columns": [
+ "DEPARTMENT_ID"
+ ],
+ "referencedTable": "DEPARTMENTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "DEPARTMENTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "MANAGER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_MANAGER",
+ "columns": [
+ "MANAGER_ID"
+ ],
+ "referencedTable": "EMPLOYEES",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "EMPLOYEES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "DEPARTMENT_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_DEPT",
+ "columns": [
+ "DEPARTMENT_ID"
+ ],
+ "referencedTable": "DEPARTMENTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "DEPT_EMPLOYEE_COUNT",
+ "definition": "SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPARTMENTS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "DEPT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "DEPT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMP_COUNT",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ },
+ {
+ "name": "DEPT_MANAGER_SUMMARY",
+ "definition": "SELECT\n DS.DEPT_ID,\n DS.DEPT_NAME,\n DS.EMP_COUNT,\n DS.AVG_SALARY,\n M.NAME AS MANAGER_NAME\nFROM DEPT_SUMMARY DS\nJOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID\nLEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPARTMENTS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPT_SUMMARY",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "DEPT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "DEPT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMP_COUNT",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AVG_SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "MANAGER_NAME",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ]
+ },
+ {
+ "name": "DEPT_SUMMARY",
+ "definition": "SELECT\n DEC.DEPT_ID,\n DEC.DEPT_NAME,\n DEC.EMP_COUNT,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY\nFROM DEPT_EMPLOYEE_COUNT DEC\nLEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID\nGROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPT_EMPLOYEE_COUNT",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ }
+ ],
+ "columns": [
+ {
+ "name": "DEPT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "DEPT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMP_COUNT",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AVG_SALARY",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ]
+ }
+ ],
+ "materializedViews": [
+ {
+ "name": "MV_DEPT_STATS",
+ "definition": "SELECT\n D.ID AS DEPT_ID,\n D.NAME AS DEPT_NAME,\n COUNT(E.ID) AS TOTAL_EMPLOYEES,\n NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY,\n NVL(MAX(E.SALARY), 0) AS MAX_SALARY,\n NVL(MIN(E.SALARY), 0) AS MIN_SALARY\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME\n",
+ "comment": "snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS",
+ "dependencyColumns": [
+ {
+ "schema": "TESTSCHEMA",
+ "table": "DEPARTMENTS",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "EMPLOYEES",
+ "column": "*"
+ },
+ {
+ "schema": "TESTSCHEMA",
+ "table": "MV_DEPT_STATS",
+ "column": "*"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE VIEW "DEPT_EMPLOYEE_COUNT" AS SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT
+ FROM DEPARTMENTS D
+ LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
+ GROUP BY D.ID, D.NAME;
+ CREATE MATERIALIZED VIEW "MV_DEPT_STATS" AS SELECT
+ D.ID AS DEPT_ID,
+ D.NAME AS DEPT_NAME,
+ COUNT(E.ID) AS TOTAL_EMPLOYEES,
+ NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,
+ NVL(AVG(E.SALARY), 0) AS AVG_SALARY,
+ NVL(MAX(E.SALARY), 0) AS MAX_SALARY,
+ NVL(MIN(E.SALARY), 0) AS MIN_SALARY
+ FROM DEPARTMENTS D
+ LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
+ GROUP BY D.ID, D.NAME
+ ;
+ COMMENT ON MATERIALIZED VIEW "MV_DEPT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS';
+ CREATE VIEW "DEPT_SUMMARY" AS SELECT
+ DEC.DEPT_ID,
+ DEC.DEPT_NAME,
+ DEC.EMP_COUNT,
+ NVL(AVG(E.SALARY), 0) AS AVG_SALARY
+ FROM DEPT_EMPLOYEE_COUNT DEC
+ LEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID
+ GROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT;
+ CREATE VIEW "DEPT_MANAGER_SUMMARY" AS SELECT
+ DS.DEPT_ID,
+ DS.DEPT_NAME,
+ DS.EMP_COUNT,
+ DS.AVG_SALARY,
+ M.NAME AS MANAGER_NAME
+ FROM DEPT_SUMMARY DS
+ JOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID
+ LEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID;
+ COMMENT ON MATERIALIZED VIEW "MV_DEPT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS';
+- description: 'Reverse: Remove circular foreign key dependencies and triggers'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PREFERRED_ORDER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 3,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PREFERRED_ORDER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_PREFERRED_ORDER",
+ "columns": [
+ "PREFERRED_ORDER_ID"
+ ],
+ "referencedTable": "ORDERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 3,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_CUSTOMER",
+ "columns": [
+ "CUSTOMER_ID"
+ ],
+ "referencedTable": "CUSTOMERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "ORDER_ITEMS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_NAME",
+ "position": 3,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 4,
+ "type": "NUMBER"
+ },
+ {
+ "name": "UNIT_PRICE",
+ "position": 5,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_ORDER_ITEM",
+ "columns": [
+ "ORDER_ID"
+ ],
+ "referencedTable": "ORDERS",
+ "referencedColumns": [
+ "ID"
+ ],
+ "onDelete": "CASCADE"
+ }
+ ],
+ "triggers": [
+ {
+ "name": "TRG_UPDATE_ORDER_TOTAL",
+ "event": "INSERT OR UPDATE OR DELETE",
+ "timing": "AFTER EACH ROW",
+ "body": "CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL\nAFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS\nFOR EACH ROW\nDECLARE\n V_ORDER_ID NUMBER;\n V_TOTAL NUMBER(10, 2);\nBEGIN\n -- Get order ID\n IF INSERTING OR UPDATING THEN\n V_ORDER_ID := :NEW.ORDER_ID;\n ELSE\n V_ORDER_ID := :OLD.ORDER_ID;\n END IF;\n\n -- Calculate new total\n SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL\n FROM ORDER_ITEMS\n WHERE ORDER_ID = V_ORDER_ID;\n\n -- Update order total\n UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;\nEND;"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE TABLE "ORDER_ITEMS" (
+ "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000003".nextval NOT NULL,
+ "ORDER_ID" NUMBER NOT NULL,
+ "PRODUCT_NAME" VARCHAR2(100 BYTE) NOT NULL,
+ "QUANTITY" NUMBER NOT NULL,
+ "UNIT_PRICE" NUMBER(10,2) NOT NULL
+ );
+ ALTER TABLE "ORDER_ITEMS" ADD CONSTRAINT "SYS_C0000003" PRIMARY KEY (ID);
+ CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL
+ AFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS
+ FOR EACH ROW
+ DECLARE
+ V_ORDER_ID NUMBER;
+ V_TOTAL NUMBER(10, 2);
+ BEGIN
+ -- Get order ID
+ IF INSERTING OR UPDATING THEN
+ V_ORDER_ID := :NEW.ORDER_ID;
+ ELSE
+ V_ORDER_ID := :OLD.ORDER_ID;
+ END IF;
+
+ -- Calculate new total
+ SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL
+ FROM ORDER_ITEMS
+ WHERE ORDER_ID = V_ORDER_ID;
+
+ -- Update order total
+ UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;
+ END;
+
+ ALTER TABLE "ORDER_ITEMS" ADD CONSTRAINT "FK_ORDER_ITEM" FOREIGN KEY ("ORDER_ID") REFERENCES "ORDERS" ("ID") ON DELETE CASCADE;
+ ALTER TABLE "CUSTOMERS" ADD CONSTRAINT "FK_PREFERRED_ORDER" FOREIGN KEY ("PREFERRED_ORDER_ID") REFERENCES "ORDERS" ("ID");
+ ALTER TABLE "ORDERS" ADD CONSTRAINT "FK_CUSTOMER" FOREIGN KEY ("CUSTOMER_ID") REFERENCES "CUSTOMERS" ("ID");
+- description: 'Reverse: Remove advanced indexes and complex constraints'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 2,
+ "type": "DATE"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 4,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AMOUNT",
+ "position": 5,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "REGION",
+ "position": 6,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 2,
+ "type": "DATE"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 4,
+ "type": "NUMBER"
+ },
+ {
+ "name": "AMOUNT",
+ "position": 5,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "REGION",
+ "position": 6,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "UK_SALES_DATE_CUSTOMER",
+ "expressions": [
+ "SALE_DATE",
+ "CUSTOMER_ID",
+ "PRODUCT_ID"
+ ],
+ "unique": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_SALES_MONTH_YEAR",
+ "expressions": [
+ "EXTRACT(YEAR FROM \"SALE_DATE\")",
+ "EXTRACT(MONTH FROM \"SALE_DATE\")"
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "FUNCTION-BASED NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_SALES_REGION_AMOUNT",
+ "expressions": [
+ "\"REGION\"",
+ "\"AMOUNT\""
+ ],
+ "descending": [
+ false,
+ true
+ ],
+ "type": "FUNCTION-BASED NORMAL",
+ "visible": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHK_AMOUNT_RANGE",
+ "expression": "AMOUNT > 0 AND AMOUNT <= 999999.99"
+ },
+ {
+ "name": "CHK_REGION_VALID",
+ "expression": "REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL')"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE INDEX "IDX_SALES_MONTH_YEAR" ON "SALES_DATA" (EXTRACT(YEAR FROM "SALE_DATE") ASC, EXTRACT(MONTH FROM "SALE_DATE") ASC);
+ CREATE INDEX "IDX_SALES_REGION_AMOUNT" ON "SALES_DATA" ("REGION" ASC, "AMOUNT" DESC);
+ ALTER TABLE "SALES_DATA" ADD CONSTRAINT "UK_SALES_DATE_CUSTOMER" UNIQUE (SALE_DATE, CUSTOMER_ID, PRODUCT_ID);
+ ALTER TABLE "SALES_DATA" ADD CONSTRAINT "CHK_AMOUNT_RANGE" CHECK (AMOUNT > 0 AND AMOUNT <= 999999.99);
+ ALTER TABLE "SALES_DATA" ADD CONSTRAINT "CHK_REGION_VALID" CHECK (REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL'));
+- description: 'Reverse: Remove stored procedures and functions'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUDIT_LOG",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TABLE_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OPERATION",
+ "position": 3,
+ "type": "VARCHAR2(10 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OLD_VALUES",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "NEW_VALUES",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TIMESTAMP",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "USER_NAME",
+ "position": 7,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUDIT_LOG",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TABLE_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OPERATION",
+ "position": 3,
+ "type": "VARCHAR2(10 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "OLD_VALUES",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "NEW_VALUES",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TIMESTAMP",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "USER_NAME",
+ "position": 7,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "CALCULATE_BUSINESS_DAYS",
+ "definition": "FUNCTION CALCULATE_BUSINESS_DAYS(\n P_START_DATE DATE,\n P_END_DATE DATE\n) RETURN NUMBER\nIS\n V_DAYS NUMBER := 0;\n V_CURRENT_DATE DATE := P_START_DATE;\nBEGIN\n WHILE V_CURRENT_DATE <= P_END_DATE LOOP\n -- Skip weekends (Saturday = 7, Sunday = 1)\n IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN\n V_DAYS := V_DAYS + 1;\n END IF;\n V_CURRENT_DATE := V_CURRENT_DATE + 1;\n END LOOP;\n\n RETURN V_DAYS;\nEND;"
+ },
+ {
+ "name": "GET_AUDIT_COUNT",
+ "definition": "FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER\nIS\n V_COUNT NUMBER;\nBEGIN\n SELECT COUNT(*) INTO V_COUNT\n FROM AUDIT_LOG\n WHERE TABLE_NAME = P_TABLE_NAME;\n\n RETURN V_COUNT;\nEND;"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "LOG_AUDIT",
+ "definition": "PROCEDURE LOG_AUDIT(\n P_TABLE_NAME VARCHAR2,\n P_OPERATION VARCHAR2,\n P_OLD_VALUES CLOB DEFAULT NULL,\n P_NEW_VALUES CLOB DEFAULT NULL\n)\nIS\nBEGIN\n INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)\n VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);\n COMMIT;\nEXCEPTION\n WHEN OTHERS THEN\n ROLLBACK;\n RAISE;\nEND;"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |+
+ CREATE OR REPLACE FUNCTION CALCULATE_BUSINESS_DAYS(
+ P_START_DATE DATE,
+ P_END_DATE DATE
+ ) RETURN NUMBER
+ IS
+ V_DAYS NUMBER := 0;
+ V_CURRENT_DATE DATE := P_START_DATE;
+ BEGIN
+ WHILE V_CURRENT_DATE <= P_END_DATE LOOP
+ -- Skip weekends (Saturday = 7, Sunday = 1)
+ IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN
+ V_DAYS := V_DAYS + 1;
+ END IF;
+ V_CURRENT_DATE := V_CURRENT_DATE + 1;
+ END LOOP;
+
+ RETURN V_DAYS;
+ END;
+
+ CREATE OR REPLACE FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER
+ IS
+ V_COUNT NUMBER;
+ BEGIN
+ SELECT COUNT(*) INTO V_COUNT
+ FROM AUDIT_LOG
+ WHERE TABLE_NAME = P_TABLE_NAME;
+
+ RETURN V_COUNT;
+ END;
+
+ CREATE OR REPLACE PROCEDURE LOG_AUDIT(
+ P_TABLE_NAME VARCHAR2,
+ P_OPERATION VARCHAR2,
+ P_OLD_VALUES CLOB DEFAULT NULL,
+ P_NEW_VALUES CLOB DEFAULT NULL
+ )
+ IS
+ BEGIN
+ INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)
+ VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);
+ COMMIT;
+ EXCEPTION
+ WHEN OTHERS THEN
+ ROLLBACK;
+ RAISE;
+ END;
+
+- description: 'Reverse: Revert edge case column operations'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "TEST_COLUMNS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "COL_VARCHAR",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_NUMBER",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "COL_DATE",
+ "position": 4,
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "COL_NULLABLE",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_WITH_DEFAULT",
+ "position": 6,
+ "default": "'DEFAULT_VALUE'",
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_CLOB",
+ "position": 7,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "TEST_COLUMNS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "COL_VARCHAR",
+ "position": 2,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_NUMBER",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER(15,3)"
+ },
+ {
+ "name": "COL_DATE",
+ "position": 4,
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "COL_NULLABLE",
+ "position": 5,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_WITH_DEFAULT",
+ "position": 6,
+ "default": "'NEW_DEFAULT'",
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "COL_TIMESTAMP",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "COL_BOOLEAN",
+ "position": 8,
+ "nullable": true,
+ "type": "NUMBER(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CHK_NUMBER_POSITIVE",
+ "expression": "COL_NUMBER > 0"
+ },
+ {
+ "name": "CHK_VARCHAR_LENGTH",
+ "expression": "LENGTH(COL_VARCHAR) >= 5"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "TEST_COLUMNS" DROP COLUMN "COL_CLOB";
+
+ ALTER TABLE "TEST_COLUMNS" ADD "COL_TIMESTAMP" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP;
+ ALTER TABLE "TEST_COLUMNS" ADD "COL_BOOLEAN" NUMBER(1);
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_VARCHAR" VARCHAR2(200 BYTE);
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NUMBER" NUMBER(15,3);
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NULLABLE" NOT NULL;
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT NULL;
+ ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT 'NEW_DEFAULT';
+ ALTER TABLE "TEST_COLUMNS" ADD CONSTRAINT "CHK_NUMBER_POSITIVE" CHECK (COL_NUMBER > 0);
+ ALTER TABLE "TEST_COLUMNS" ADD CONSTRAINT "CHK_VARCHAR_LENGTH" CHECK (LENGTH(COL_VARCHAR) >= 5);
+- description: Add comprehensive comments to tables and columns using Oracle COMMENT syntax
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER",
+ "comment": "Primary key for customer records"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Full name of the customer"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Customer email address (unique)"
+ },
+ {
+ "name": "PHONE",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Contact phone number"
+ },
+ {
+ "name": "ADDRESS",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "Full mailing address with multiple lines"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_CUSTOMERS_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "comment": "Customer information and contact details"
+ },
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER",
+ "comment": "Unique order identifier"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER",
+ "comment": "Reference to customer who placed the order"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 3,
+ "type": "NUMBER",
+ "comment": "Reference to ordered product"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 4,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE",
+ "comment": "Date when the order was placed"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 5,
+ "type": "NUMBER",
+ "comment": "Number of items ordered"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER(12,2)",
+ "comment": "Total order amount including taxes"
+ },
+ {
+ "name": "STATUS",
+ "position": 7,
+ "default": "'PENDING'",
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Customer orders linking products and customers",
+ "foreignKeys": [
+ {
+ "name": "FK_ORDER_CUSTOMER",
+ "columns": [
+ "CUSTOMER_ID"
+ ],
+ "referencedTable": "CUSTOMERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ },
+ {
+ "name": "FK_ORDER_PRODUCT",
+ "columns": [
+ "PRODUCT_ID"
+ ],
+ "referencedTable": "PRODUCTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER",
+ "comment": "Unique product identifier (auto-generated)"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Product name - must be unique and descriptive"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)",
+ "comment": "Product price in USD with 2 decimal places"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "Detailed product description with HTML formatting support"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Product category for filtering and organization"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)",
+ "comment": "Timestamp when the product was added to catalog"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "comment": "Product catalog table containing all product information"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PHONE",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "ADDRESS",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_CUSTOMERS_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "ORDERS" DROP CONSTRAINT "FK_ORDER_CUSTOMER";
+ ALTER TABLE "ORDERS" DROP CONSTRAINT "FK_ORDER_PRODUCT";
+ DROP TABLE "ORDERS";
+
+ COMMENT ON TABLE "CUSTOMERS" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."ID" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."NAME" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."ID" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."NAME" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS '';
+ COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS '';
+ COMMENT ON TABLE "PRODUCTS" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."ID" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."NAME" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."PRICE" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."ID" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."NAME" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."PRICE" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS '';
+ COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS '';
+- description: Modify existing comments and remove comments using empty string
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "INVENTORY",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER",
+ "comment": "Primary key for inventory records"
+ },
+ {
+ "name": "PRODUCT_CODE",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Updated: Standardized product SKU following new naming convention"
+ },
+ {
+ "name": "STOCK_LEVEL",
+ "position": 3,
+ "type": "NUMBER",
+ "comment": "Updated: Real-time stock quantity with automated updates"
+ },
+ {
+ "name": "MIN_STOCK",
+ "position": 4,
+ "default": "10",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Updated: Dynamic minimum threshold based on sales velocity"
+ },
+ {
+ "name": "MAX_STOCK",
+ "position": 5,
+ "default": "1000",
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "WAREHOUSE_ID",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "LAST_UPDATED",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)",
+ "comment": "Timestamp of last inventory update or modification"
+ },
+ {
+ "name": "REORDER_POINT",
+ "position": 8,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Calculated reorder point based on lead time and demand"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Updated inventory management system with enhanced tracking capabilities"
+ },
+ {
+ "name": "SUPPLIERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Supplier company name"
+ },
+ {
+ "name": "CONTACT_EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "RATING",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(2,1)",
+ "comment": "Supplier performance rating (1.0 to 5.0 scale)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "INVENTORY",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER",
+ "comment": "Primary key for inventory records"
+ },
+ {
+ "name": "PRODUCT_CODE",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Product identification code"
+ },
+ {
+ "name": "STOCK_LEVEL",
+ "position": 3,
+ "type": "NUMBER",
+ "comment": "Current stock quantity"
+ },
+ {
+ "name": "MIN_STOCK",
+ "position": 4,
+ "default": "10",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Minimum stock threshold"
+ },
+ {
+ "name": "MAX_STOCK",
+ "position": 5,
+ "default": "1000",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Maximum stock capacity"
+ },
+ {
+ "name": "WAREHOUSE_ID",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Warehouse location identifier"
+ },
+ {
+ "name": "LAST_UPDATED",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Initial inventory tracking table"
+ },
+ {
+ "name": "SUPPLIERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Supplier company name"
+ },
+ {
+ "name": "CONTACT_EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Primary contact email"
+ },
+ {
+ "name": "RATING",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(2,1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Supplier information table"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "INVENTORY" DROP COLUMN "REORDER_POINT";
+
+ COMMENT ON TABLE "INVENTORY" IS 'Initial inventory tracking table';
+ COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Product identification code';
+ COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Current stock quantity';
+ COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Minimum stock threshold';
+ COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS 'Maximum stock capacity';
+ COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS 'Warehouse location identifier';
+ COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS '';
+ COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Product identification code';
+ COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Current stock quantity';
+ COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Minimum stock threshold';
+ COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS 'Maximum stock capacity';
+ COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS 'Warehouse location identifier';
+ COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS '';
+ COMMENT ON TABLE "SUPPLIERS" IS 'Supplier information table';
+ COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS 'Primary contact email';
+ COMMENT ON COLUMN "SUPPLIERS"."RATING" IS '';
+ COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS 'Primary contact email';
+ COMMENT ON COLUMN "SUPPLIERS"."RATING" IS '';
+- description: Test comments with special characters, quotes, Unicode, multi-line text, and complex content
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "COMPLEX_TYPES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "XML_DATA",
+ "position": 2,
+ "nullable": true,
+ "type": "XMLTYPE",
+ "comment": "XMLType column for structured XML storage\nExample: <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root><item id=\"1\" name=\"test\">Content</item></root>"
+ },
+ {
+ "name": "TIMESTAMP_TZ",
+ "position": 3,
+ "default": "SYSTIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6) WITH TIME ZONE",
+ "comment": "Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR\nDefault: SYSTIMESTAMP (system timestamp with session timezone)"
+ },
+ {
+ "name": "INTERVAL_DS",
+ "position": 4,
+ "nullable": true,
+ "type": "INTERVAL DAY(2) TO SECOND(6)",
+ "comment": "Interval Day to Second: +/-DD HH:MI:SS.FFFFFF\nRange: +/-999999999 days, precision up to nanoseconds"
+ },
+ {
+ "name": "RAW_DATA",
+ "position": 5,
+ "nullable": true,
+ "type": "RAW(100)"
+ },
+ {
+ "name": "LONG_RAW_DATA",
+ "position": 6,
+ "nullable": true,
+ "type": "LONG RAW"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Advanced data types testing table\nSupports: XMLType, Timestamps with timezone, Intervals, RAW data\nPerformance: Optimized for OLTP workloads @ 10K+ TPS\nSecurity: Row-level security enabled, audit trails maintained"
+ },
+ {
+ "name": "MULTILANG_CONTENT",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE_EN",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "English title field"
+ },
+ {
+ "name": "TITLE_ES",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "T\u00edtulo en espa\u00f1ol"
+ },
+ {
+ "name": "TITLE_ZH",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP",
+ "comment": "\u4e2d\u6587\u6807\u9898\u5b57\u6bb5 - \u652f\u6301\u7b80\u4f53\u548c\u7e41\u4f53\u4e2d\u6587"
+ },
+ {
+ "name": "CONTENT_TEXT",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "Content field supporting:\n1. HTML tags: <b>bold</b>, <i>italic</i>, <a href=\"http://example.com\">links</a>\n2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick\n3. Special symbols: \u00a9 \u00ae \u2122 \u00a7 \u00b6 \u2020 \u2021 \u2022 \u2026 \u2030 \u2032 \u2033\n4. Emojis: \ud83d\ude00 \ud83d\ude03 \ud83d\ude04 \ud83d\ude01 \ud83d\ude80 \u2b50 \ud83c\udf89 \ud83d\udcaf\n5. Mathematical: \u2200x\u2208\u211d: x\u00b2 \u2265 0, \u2211(i=1 to n) i = n(n+1)/2"
+ },
+ {
+ "name": "TAGS",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(1000 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "XML tags: <tag type=\"category\" value=\"news\"/><tag type=\"priority\" value=\"high\"/>End of XML"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Multilingual content: English, Espa\u00f1ol, \u4e2d\u6587, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u65e5\u672c\u8a9e"
+ },
+ {
+ "name": "SPECIAL_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "DATA_VALUE",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(500 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Data value field - supports NULL, empty strings, and 'quoted' content"
+ },
+ {
+ "name": "METADATA_JSON",
+ "position": 3,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "JSON metadata: {\"key\": \"value\", \"array\": [1,2,3]}"
+ },
+ {
+ "name": "UNICODE_TEXT",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Unicode text support:\nLine 1: Basic ASCII text\nLine 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?\nLine 3: Math symbols \u2264 \u2265 \u00b1 \u00d7 \u00f7 \u2211 \u220f \u2206 \u03c0\nLine 4: Currencies $ \u20ac \u00a3 \u00a5 \u20b9"
+ },
+ {
+ "name": "BINARY_DATA",
+ "position": 5,
+ "nullable": true,
+ "type": "BLOB",
+ "comment": "Binary data storage\\nSupports: images, documents, archives\\tTab-separated info\\r\\nWindows line endings"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Category field: use % for wildcard searches, _ for single char matching"
+ },
+ {
+ "name": "STATUS",
+ "position": 7,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Status field - values: 'ACTIVE', 'INACTIVE', 'PENDING'; DROP TABLE users; --"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Table containing \"special\" data with various formats & types"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "MULTILANG_CONTENT",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE_EN",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TITLE_ES",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TITLE_ZH",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT_TEXT",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TAGS",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(1000 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "SPECIAL_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "DATA_VALUE",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(500 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "METADATA_JSON",
+ "position": 3,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "UNICODE_TEXT",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "BINARY_DATA",
+ "position": 5,
+ "nullable": true,
+ "type": "BLOB"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "STATUS",
+ "position": 7,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ DROP TABLE "COMPLEX_TYPES";
+
+ COMMENT ON TABLE "MULTILANG_CONTENT" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_EN" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ES" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ZH" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."CONTENT_TEXT" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TAGS" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_EN" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ES" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ZH" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."CONTENT_TEXT" IS '';
+ COMMENT ON COLUMN "MULTILANG_CONTENT"."TAGS" IS '';
+ COMMENT ON TABLE "SPECIAL_DATA" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."DATA_VALUE" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."METADATA_JSON" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."UNICODE_TEXT" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."BINARY_DATA" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."CATEGORY" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."STATUS" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."DATA_VALUE" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."METADATA_JSON" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."UNICODE_TEXT" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."BINARY_DATA" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."CATEGORY" IS '';
+ COMMENT ON COLUMN "SPECIAL_DATA"."STATUS" IS '';
+- description: 'Reverse: Remove all comments and drop a table'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PHONE",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "ADDRESS",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_CUSTOMERS_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER",
+ "comment": "Primary key for customer records"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Full name of the customer"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Customer email address (unique)"
+ },
+ {
+ "name": "PHONE",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Contact phone number"
+ },
+ {
+ "name": "ADDRESS",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "Full mailing address with multiple lines"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_CUSTOMERS_EMAIL",
+ "expressions": [
+ "\"EMAIL\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "comment": "Customer information and contact details"
+ },
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER",
+ "comment": "Unique order identifier"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER",
+ "comment": "Reference to customer who placed the order"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 3,
+ "type": "NUMBER",
+ "comment": "Reference to ordered product"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 4,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE",
+ "comment": "Date when the order was placed"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 5,
+ "type": "NUMBER",
+ "comment": "Number of items ordered"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER(12,2)",
+ "comment": "Total order amount including taxes"
+ },
+ {
+ "name": "STATUS",
+ "position": 7,
+ "default": "'PENDING'",
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Customer orders linking products and customers",
+ "foreignKeys": [
+ {
+ "name": "FK_ORDER_CUSTOMER",
+ "columns": [
+ "CUSTOMER_ID"
+ ],
+ "referencedTable": "CUSTOMERS",
+ "referencedColumns": [
+ "ID"
+ ]
+ },
+ {
+ "name": "FK_ORDER_PRODUCT",
+ "columns": [
+ "PRODUCT_ID"
+ ],
+ "referencedTable": "PRODUCTS",
+ "referencedColumns": [
+ "ID"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
+ "type": "NUMBER",
+ "comment": "Unique product identifier (auto-generated)"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Product name - must be unique and descriptive"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "type": "NUMBER(10,2)",
+ "comment": "Product price in USD with 2 decimal places"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "Detailed product description with HTML formatting support"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Product category for filtering and organization"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)",
+ "comment": "Timestamp when the product was added to catalog"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ },
+ {
+ "name": "IDX_PRODUCTS_CATEGORY",
+ "expressions": [
+ "\"CATEGORY\""
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "comment": "Product catalog table containing all product information"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ CREATE TABLE "ORDERS" (
+ "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000002".nextval NOT NULL,
+ "CUSTOMER_ID" NUMBER NOT NULL,
+ "PRODUCT_ID" NUMBER NOT NULL,
+ "ORDER_DATE" DATE DEFAULT SYSDATE,
+ "QUANTITY" NUMBER NOT NULL,
+ "TOTAL_AMOUNT" NUMBER(12,2),
+ "STATUS" VARCHAR2(20 BYTE) DEFAULT 'PENDING'
+ );
+ ALTER TABLE "ORDERS" ADD CONSTRAINT "SYS_C0000002" PRIMARY KEY (ID);
+ COMMENT ON TABLE "ORDERS" IS 'Customer orders linking products and customers';
+ COMMENT ON COLUMN "ORDERS"."ID" IS 'Unique order identifier';
+ COMMENT ON COLUMN "ORDERS"."CUSTOMER_ID" IS 'Reference to customer who placed the order';
+ COMMENT ON COLUMN "ORDERS"."PRODUCT_ID" IS 'Reference to ordered product';
+ COMMENT ON COLUMN "ORDERS"."ORDER_DATE" IS 'Date when the order was placed';
+ COMMENT ON COLUMN "ORDERS"."QUANTITY" IS 'Number of items ordered';
+ COMMENT ON COLUMN "ORDERS"."TOTAL_AMOUNT" IS 'Total order amount including taxes';
+ COMMENT ON COLUMN "ORDERS"."STATUS" IS 'Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)';
+
+ ALTER TABLE "ORDERS" ADD CONSTRAINT "FK_ORDER_CUSTOMER" FOREIGN KEY ("CUSTOMER_ID") REFERENCES "CUSTOMERS" ("ID");
+ ALTER TABLE "ORDERS" ADD CONSTRAINT "FK_ORDER_PRODUCT" FOREIGN KEY ("PRODUCT_ID") REFERENCES "PRODUCTS" ("ID");
+ COMMENT ON TABLE "CUSTOMERS" IS 'Customer information and contact details';
+ COMMENT ON COLUMN "CUSTOMERS"."ID" IS 'Primary key for customer records';
+ COMMENT ON COLUMN "CUSTOMERS"."NAME" IS 'Full name of the customer';
+ COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS 'Customer email address (unique)';
+ COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS 'Contact phone number';
+ COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS 'Full mailing address with multiple lines';
+ COMMENT ON COLUMN "CUSTOMERS"."ID" IS 'Primary key for customer records';
+ COMMENT ON COLUMN "CUSTOMERS"."NAME" IS 'Full name of the customer';
+ COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS 'Customer email address (unique)';
+ COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS 'Contact phone number';
+ COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS 'Full mailing address with multiple lines';
+ COMMENT ON TABLE "PRODUCTS" IS 'Product catalog table containing all product information';
+ COMMENT ON COLUMN "PRODUCTS"."ID" IS 'Unique product identifier (auto-generated)';
+ COMMENT ON COLUMN "PRODUCTS"."NAME" IS 'Product name - must be unique and descriptive';
+ COMMENT ON COLUMN "PRODUCTS"."PRICE" IS 'Product price in USD with 2 decimal places';
+ COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS 'Detailed product description with HTML formatting support';
+ COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS 'Product category for filtering and organization';
+ COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS 'Timestamp when the product was added to catalog';
+ COMMENT ON COLUMN "PRODUCTS"."ID" IS 'Unique product identifier (auto-generated)';
+ COMMENT ON COLUMN "PRODUCTS"."NAME" IS 'Product name - must be unique and descriptive';
+ COMMENT ON COLUMN "PRODUCTS"."PRICE" IS 'Product price in USD with 2 decimal places';
+ COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS 'Detailed product description with HTML formatting support';
+ COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS 'Product category for filtering and organization';
+ COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS 'Timestamp when the product was added to catalog';
+- description: 'Reverse: Restore original comments and modify state'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "INVENTORY",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_CODE",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Product identification code"
+ },
+ {
+ "name": "STOCK_LEVEL",
+ "position": 3,
+ "type": "NUMBER",
+ "comment": "Current stock quantity"
+ },
+ {
+ "name": "MIN_STOCK",
+ "position": 4,
+ "default": "10",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Minimum stock threshold"
+ },
+ {
+ "name": "MAX_STOCK",
+ "position": 5,
+ "default": "1000",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Maximum stock capacity"
+ },
+ {
+ "name": "WAREHOUSE_ID",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Warehouse location identifier"
+ },
+ {
+ "name": "LAST_UPDATED",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Initial inventory tracking table"
+ },
+ {
+ "name": "SUPPLIERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTACT_EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Primary contact email"
+ },
+ {
+ "name": "RATING",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(2,1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Supplier information table"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "INVENTORY",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_CODE",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Updated: Standardized product SKU following new naming convention"
+ },
+ {
+ "name": "STOCK_LEVEL",
+ "position": 3,
+ "type": "NUMBER",
+ "comment": "Updated: Real-time stock quantity with automated updates"
+ },
+ {
+ "name": "MIN_STOCK",
+ "position": 4,
+ "default": "10",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Updated: Dynamic minimum threshold based on sales velocity"
+ },
+ {
+ "name": "MAX_STOCK",
+ "position": 5,
+ "default": "1000",
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "WAREHOUSE_ID",
+ "position": 6,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "LAST_UPDATED",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)",
+ "comment": "Timestamp of last inventory update or modification"
+ },
+ {
+ "name": "REORDER_POINT",
+ "position": 8,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Calculated reorder point based on lead time and demand"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Updated inventory management system with enhanced tracking capabilities"
+ },
+ {
+ "name": "SUPPLIERS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTACT_EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "RATING",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(2,1)",
+ "comment": "Supplier performance rating (1.0 to 5.0 scale)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: |
+ ALTER TABLE "INVENTORY" ADD "REORDER_POINT" NUMBER DEFAULT 0;
+ COMMENT ON TABLE "INVENTORY" IS 'Updated inventory management system with enhanced tracking capabilities';
+ COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Updated: Standardized product SKU following new naming convention';
+ COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Updated: Real-time stock quantity with automated updates';
+ COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Updated: Dynamic minimum threshold based on sales velocity';
+ COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS '';
+ COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS '';
+ COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS 'Timestamp of last inventory update or modification';
+ COMMENT ON COLUMN "INVENTORY"."REORDER_POINT" IS 'Calculated reorder point based on lead time and demand';
+ COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Updated: Standardized product SKU following new naming convention';
+ COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Updated: Real-time stock quantity with automated updates';
+ COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Updated: Dynamic minimum threshold based on sales velocity';
+ COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS '';
+ COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS '';
+ COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS 'Timestamp of last inventory update or modification';
+ COMMENT ON COLUMN "INVENTORY"."REORDER_POINT" IS 'Calculated reorder point based on lead time and demand';
+ COMMENT ON TABLE "SUPPLIERS" IS '';
+ COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS '';
+ COMMENT ON COLUMN "SUPPLIERS"."RATING" IS 'Supplier performance rating (1.0 to 5.0 scale)';
+ COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS '';
+ COMMENT ON COLUMN "SUPPLIERS"."RATING" IS 'Supplier performance rating (1.0 to 5.0 scale)';
+- description: 'Reverse: Remove all comments with special characters'
+ oldMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "MULTILANG_CONTENT",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE_EN",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TITLE_ES",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TITLE_ZH",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "CONTENT_TEXT",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "TAGS",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(1000 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ },
+ {
+ "name": "SPECIAL_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "DATA_VALUE",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(500 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "METADATA_JSON",
+ "position": 3,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "UNICODE_TEXT",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "BINARY_DATA",
+ "position": 5,
+ "nullable": true,
+ "type": "BLOB"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP"
+ },
+ {
+ "name": "STATUS",
+ "position": 7,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ newMetadata: |
+ {
+ "name": "TESTSCHEMA",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "COMPLEX_TYPES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "XML_DATA",
+ "position": 2,
+ "nullable": true,
+ "type": "XMLTYPE",
+ "comment": "XMLType column for structured XML storage\nExample: <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root><item id=\"1\" name=\"test\">Content</item></root>"
+ },
+ {
+ "name": "TIMESTAMP_TZ",
+ "position": 3,
+ "default": "SYSTIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6) WITH TIME ZONE",
+ "comment": "Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR\nDefault: SYSTIMESTAMP (system timestamp with session timezone)"
+ },
+ {
+ "name": "INTERVAL_DS",
+ "position": 4,
+ "nullable": true,
+ "type": "INTERVAL DAY(2) TO SECOND(6)",
+ "comment": "Interval Day to Second: +/-DD HH:MI:SS.FFFFFF\nRange: +/-999999999 days, precision up to nanoseconds"
+ },
+ {
+ "name": "RAW_DATA",
+ "position": 5,
+ "nullable": true,
+ "type": "RAW(100)"
+ },
+ {
+ "name": "LONG_RAW_DATA",
+ "position": 6,
+ "nullable": true,
+ "type": "LONG RAW"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000001",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Advanced data types testing table\nSupports: XMLType, Timestamps with timezone, Intervals, RAW data\nPerformance: Optimized for OLTP workloads @ 10K+ TPS\nSecurity: Row-level security enabled, audit trails maintained"
+ },
+ {
+ "name": "MULTILANG_CONTENT",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "TITLE_EN",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "English title field"
+ },
+ {
+ "name": "TITLE_ES",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "T\u00edtulo en espa\u00f1ol"
+ },
+ {
+ "name": "TITLE_ZH",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP",
+ "comment": "\u4e2d\u6587\u6807\u9898\u5b57\u6bb5 - \u652f\u6301\u7b80\u4f53\u548c\u7e41\u4f53\u4e2d\u6587"
+ },
+ {
+ "name": "CONTENT_TEXT",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "Content field supporting:\n1. HTML tags: <b>bold</b>, <i>italic</i>, <a href=\"http://example.com\">links</a>\n2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick\n3. Special symbols: \u00a9 \u00ae \u2122 \u00a7 \u00b6 \u2020 \u2021 \u2022 \u2026 \u2030 \u2032 \u2033\n4. Emojis: \ud83d\ude00 \ud83d\ude03 \ud83d\ude04 \ud83d\ude01 \ud83d\ude80 \u2b50 \ud83c\udf89 \ud83d\udcaf\n5. Mathematical: \u2200x\u2208\u211d: x\u00b2 \u2265 0, \u2211(i=1 to n) i = n(n+1)/2"
+ },
+ {
+ "name": "TAGS",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(1000 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "XML tags: <tag type=\"category\" value=\"news\"/><tag type=\"priority\" value=\"high\"/>End of XML"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000002",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Multilingual content: English, Espa\u00f1ol, \u4e2d\u6587, \u0627\u0644\u0639\u0631\u0628\u064a\u0629, \u0420\u0443\u0441\u0441\u043a\u0438\u0439, \u65e5\u672c\u8a9e"
+ },
+ {
+ "name": "SPECIAL_DATA",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
+ "type": "NUMBER"
+ },
+ {
+ "name": "DATA_VALUE",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(500 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Data value field - supports NULL, empty strings, and 'quoted' content"
+ },
+ {
+ "name": "METADATA_JSON",
+ "position": 3,
+ "nullable": true,
+ "type": "CLOB",
+ "collation": "USING_NLS_COMP",
+ "comment": "JSON metadata: {\"key\": \"value\", \"array\": [1,2,3]}"
+ },
+ {
+ "name": "UNICODE_TEXT",
+ "position": 4,
+ "nullable": true,
+ "type": "NVARCHAR2(400)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Unicode text support:\nLine 1: Basic ASCII text\nLine 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?\nLine 3: Math symbols \u2264 \u2265 \u00b1 \u00d7 \u00f7 \u2211 \u220f \u2206 \u03c0\nLine 4: Currencies $ \u20ac \u00a3 \u00a5 \u20b9"
+ },
+ {
+ "name": "BINARY_DATA",
+ "position": 5,
+ "nullable": true,
+ "type": "BLOB",
+ "comment": "Binary data storage\\nSupports: images, documents, archives\\tTab-separated info\\r\\nWindows line endings"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 6,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Category field: use % for wildcard searches, _ for single char matching"
+ },
+ {
+ "name": "STATUS",
+ "position": 7,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "collation": "USING_NLS_COMP",
+ "comment": "Status field - values: 'ACTIVE', 'INACTIVE', 'PENDING'; DROP TABLE users; --"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "SYS_C0000003",
+ "expressions": [
+ "ID"
+ ],
+ "unique": true,
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "comment": "Table containing \"special\" data with various formats & types"
+ }
+ ]
+ }
+ ],
+ "serviceName": "FREEPDB1"
+ }
+ expected: "CREATE TABLE \"COMPLEX_TYPES\" (\n \"ID\" NUMBER NOT NULL,\n \"XML_DATA\" XMLTYPE,\n \"TIMESTAMP_TZ\" TIMESTAMP(6) WITH TIME ZONE DEFAULT SYSTIMESTAMP,\n \"INTERVAL_DS\" INTERVAL DAY(2) TO SECOND(6),\n \"RAW_DATA\" RAW(100),\n \"LONG_RAW_DATA\" LONG RAW\n);\nALTER TABLE \"COMPLEX_TYPES\" ADD CONSTRAINT \"SYS_C0000001\" PRIMARY KEY (ID);\nCOMMENT ON TABLE \"COMPLEX_TYPES\" IS 'Advanced data types testing table\nSupports: XMLType, Timestamps with timezone, Intervals, RAW data\nPerformance: Optimized for OLTP workloads @ 10K+ TPS\nSecurity: Row-level security enabled, audit trails maintained';\nCOMMENT ON COLUMN \"COMPLEX_TYPES\".\"XML_DATA\" IS 'XMLType column for structured XML storage\nExample: <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root><item id=\"1\" name=\"test\">Content</item></root>';\nCOMMENT ON COLUMN \"COMPLEX_TYPES\".\"TIMESTAMP_TZ\" IS 'Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR\nDefault: SYSTIMESTAMP (system timestamp with session timezone)';\nCOMMENT ON COLUMN \"COMPLEX_TYPES\".\"INTERVAL_DS\" IS 'Interval Day to Second: +/-DD HH:MI:SS.FFFFFF\nRange: +/-999999999 days, precision up to nanoseconds';\n\nCOMMENT ON TABLE \"MULTILANG_CONTENT\" IS 'Multilingual content: English, Español, 中文, العربية, Русский, 日本語';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TITLE_EN\" IS 'English title field';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TITLE_ES\" IS 'Título en español';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TITLE_ZH\" IS '中文标题字段 - 支持简体和繁体中文';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"CONTENT_TEXT\" IS 'Content field supporting:\n1. HTML tags: <b>bold</b>, <i>italic</i>, <a href=\"http://example.com\">links</a>\n2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick\n3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″\n4. Emojis: \U0001F600 \U0001F603 \U0001F604 \U0001F601 \U0001F680 ⭐ \U0001F389 \U0001F4AF\n5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TAGS\" IS 'XML tags: <tag type=\"category\" value=\"news\"/><tag type=\"priority\" value=\"high\"/>End of XML';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TITLE_EN\" IS 'English title field';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TITLE_ES\" IS 'Título en español';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TITLE_ZH\" IS '中文标题字段 - 支持简体和繁体中文';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"CONTENT_TEXT\" IS 'Content field supporting:\n1. HTML tags: <b>bold</b>, <i>italic</i>, <a href=\"http://example.com\">links</a>\n2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick\n3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″\n4. Emojis: \U0001F600 \U0001F603 \U0001F604 \U0001F601 \U0001F680 ⭐ \U0001F389 \U0001F4AF\n5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2';\nCOMMENT ON COLUMN \"MULTILANG_CONTENT\".\"TAGS\" IS 'XML tags: <tag type=\"category\" value=\"news\"/><tag type=\"priority\" value=\"high\"/>End of XML';\nCOMMENT ON TABLE \"SPECIAL_DATA\" IS 'Table containing \"special\" data with various formats & types';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"DATA_VALUE\" IS 'Data value field - supports NULL, empty strings, and ''quoted'' content';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"METADATA_JSON\" IS 'JSON metadata: {\"key\": \"value\", \"array\": [1,2,3]}';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"UNICODE_TEXT\" IS 'Unicode text support:\nLine 1: Basic ASCII text\nLine 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?\nLine 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π\nLine 4: Currencies $ € £ ¥ ₹';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"BINARY_DATA\" IS 'Binary data storage\\nSupports: images, documents, archives\\tTab-separated info\\r\\nWindows line endings';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"CATEGORY\" IS 'Category field: use % for wildcard searches, _ for single char matching';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"STATUS\" IS 'Status field - values: ''ACTIVE'', ''INACTIVE'', ''PENDING''; DROP TABLE users; --';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"DATA_VALUE\" IS 'Data value field - supports NULL, empty strings, and ''quoted'' content';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"METADATA_JSON\" IS 'JSON metadata: {\"key\": \"value\", \"array\": [1,2,3]}';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"UNICODE_TEXT\" IS 'Unicode text support:\nLine 1: Basic ASCII text\nLine 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?\nLine 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π\nLine 4: Currencies $ € £ ¥ ₹';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"BINARY_DATA\" IS 'Binary data storage\\nSupports: images, documents, archives\\tTab-separated info\\r\\nWindows line endings';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"CATEGORY\" IS 'Category field: use % for wildcard searches, _ for single char matching';\nCOMMENT ON COLUMN \"SPECIAL_DATA\".\"STATUS\" IS 'Status field - values: ''ACTIVE'', ''INACTIVE'', ''PENDING''; DROP TABLE users; --';\n"
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/advanced_indexes_and_constraints.json b/backend/plugin/schema/oracle/testdata/generate_migration/advanced_indexes_and_constraints.json
deleted file mode 100644
index 153c50306e..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/advanced_indexes_and_constraints.json
+++ /dev/null
@@ -1,144 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "SALE_DATE",
- "position": 2,
- "type": "DATE"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 4,
- "type": "NUMBER"
- },
- {
- "name": "AMOUNT",
- "position": 5,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "REGION",
- "position": 6,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "SALE_DATE",
- "position": 2,
- "type": "DATE"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 4,
- "type": "NUMBER"
- },
- {
- "name": "AMOUNT",
- "position": 5,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "REGION",
- "position": 6,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "UK_SALES_DATE_CUSTOMER",
- "expressions": [
- "SALE_DATE",
- "CUSTOMER_ID",
- "PRODUCT_ID"
- ],
- "unique": true,
- "isConstraint": true
- },
- {
- "name": "IDX_SALES_MONTH_YEAR",
- "expressions": [
- "EXTRACT(YEAR FROM \"SALE_DATE\")",
- "EXTRACT(MONTH FROM \"SALE_DATE\")"
- ],
- "descending": [
- false,
- false
- ],
- "type": "FUNCTION-BASED NORMAL",
- "visible": true
- },
- {
- "name": "IDX_SALES_REGION_AMOUNT",
- "expressions": [
- "\"REGION\"",
- "\"AMOUNT\""
- ],
- "descending": [
- false,
- true
- ],
- "type": "FUNCTION-BASED NORMAL",
- "visible": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHK_AMOUNT_RANGE",
- "expression": "AMOUNT \u003e 0 AND AMOUNT \u003c= 999999.99"
- },
- {
- "name": "CHK_REGION_VALID",
- "expression": "REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL')"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/advanced_indexes_and_constraints.sql b/backend/plugin/schema/oracle/testdata/generate_migration/advanced_indexes_and_constraints.sql
deleted file mode 100644
index c89f10bdc2..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/advanced_indexes_and_constraints.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-ALTER TABLE "SALES_DATA" DROP CONSTRAINT "CHK_AMOUNT_RANGE";
-ALTER TABLE "SALES_DATA" DROP CONSTRAINT "CHK_REGION_VALID";
-DROP INDEX "IDX_SALES_MONTH_YEAR";
-DROP INDEX "IDX_SALES_REGION_AMOUNT";
-ALTER TABLE "SALES_DATA" DROP CONSTRAINT "UK_SALES_DATE_CUSTOMER";
-
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/alter_table_columns.json b/backend/plugin/schema/oracle/testdata/generate_migration/alter_table_columns.json
deleted file mode 100644
index 6389025076..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/alter_table_columns.json
+++ /dev/null
@@ -1,228 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(8,2)"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(30 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "IS_ACTIVE",
- "position": 6,
- "default": "1",
- "nullable": true,
- "type": "NUMBER(1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_PRICE",
- "expressions": [
- "\"PRICE\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(30 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "IS_ACTIVE",
- "position": 6,
- "default": "1",
- "nullable": true,
- "type": "NUMBER(1)"
- },
- {
- "name": "CREATED_AT",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "STOCK_QUANTITY",
- "position": 8,
- "default": "0",
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "WEIGHT",
- "position": 9,
- "nullable": true,
- "type": "NUMBER(5,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_CREATED_AT",
- "expressions": [
- "\"CREATED_AT\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_NAME_CATEGORY",
- "expressions": [
- "\"NAME\"",
- "\"CATEGORY\""
- ],
- "descending": [
- false,
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_PRICE",
- "expressions": [
- "\"PRICE\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_PRICE_POSITIVE",
- "expression": "PRICE \u003e 0"
- },
- {
- "name": "CHECK_STOCK_NON_NEGATIVE",
- "expression": "STOCK_QUANTITY \u003e= 0"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/alter_table_columns.sql b/backend/plugin/schema/oracle/testdata/generate_migration/alter_table_columns.sql
deleted file mode 100644
index 90f02ad161..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/alter_table_columns.sql
+++ /dev/null
@@ -1,11 +0,0 @@
-ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_PRICE_POSITIVE";
-ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_STOCK_NON_NEGATIVE";
-DROP INDEX "IDX_PRODUCTS_CREATED_AT";
-DROP INDEX "IDX_PRODUCTS_NAME_CATEGORY";
-ALTER TABLE "PRODUCTS" DROP COLUMN "CREATED_AT";
-ALTER TABLE "PRODUCTS" DROP COLUMN "STOCK_QUANTITY";
-ALTER TABLE "PRODUCTS" DROP COLUMN "WEIGHT";
-
-ALTER TABLE "PRODUCTS" MODIFY "NAME" VARCHAR2(50 BYTE);
-ALTER TABLE "PRODUCTS" MODIFY "PRICE" NUMBER(8,2);
-ALTER TABLE "PRODUCTS" MODIFY "DESCRIPTION" NULL;
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/basic_table_operations.json b/backend/plugin/schema/oracle/testdata/generate_migration/basic_table_operations.json
deleted file mode 100644
index 7531b7f60a..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/basic_table_operations.json
+++ /dev/null
@@ -1,321 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "POSTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 3,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_POSTS_USER_ID",
- "expressions": [
- "\"USER_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "USERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USERNAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 4,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "COMMENTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "POST_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 5,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_COMMENT_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ]
- },
- {
- "name": "FK_POST",
- "columns": [
- "POST_ID"
- ],
- "referencedTable": "POSTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "POSTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 3,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_POSTS_USER_ID",
- "expressions": [
- "\"USER_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_TITLE_LENGTH",
- "expression": "LENGTH(TITLE) \u003e 0"
- }
- ]
- },
- {
- "name": "USERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USERNAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 4,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "IS_ACTIVE",
- "position": 5,
- "default": "1",
- "nullable": true,
- "type": "NUMBER(1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_USERS_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/basic_table_operations.sql b/backend/plugin/schema/oracle/testdata/generate_migration/basic_table_operations.sql
deleted file mode 100644
index 86f5d03258..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/basic_table_operations.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-ALTER TABLE "COMMENTS" DROP CONSTRAINT "FK_COMMENT_USER";
-ALTER TABLE "COMMENTS" DROP CONSTRAINT "FK_POST";
-DROP TABLE "COMMENTS";
-ALTER TABLE "POSTS" DROP CONSTRAINT "CHECK_TITLE_LENGTH";
-DROP INDEX "IDX_USERS_EMAIL";
-ALTER TABLE "USERS" DROP COLUMN "IS_ACTIVE";
-
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/circular_foreign_key_dependencies.json b/backend/plugin/schema/oracle/testdata/generate_migration/circular_foreign_key_dependencies.json
deleted file mode 100644
index 0c6752d343..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/circular_foreign_key_dependencies.json
+++ /dev/null
@@ -1,258 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PREFERRED_ORDER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "ORDER_DATE",
- "position": 3,
- "default": "SYSDATE",
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "TOTAL_AMOUNT",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PREFERRED_ORDER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_PREFERRED_ORDER",
- "columns": [
- "PREFERRED_ORDER_ID"
- ],
- "referencedTable": "ORDERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "ORDER_DATE",
- "position": 3,
- "default": "SYSDATE",
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "TOTAL_AMOUNT",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_CUSTOMER",
- "columns": [
- "CUSTOMER_ID"
- ],
- "referencedTable": "CUSTOMERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "ORDER_ITEMS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "ORDER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_NAME",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "QUANTITY",
- "position": 4,
- "type": "NUMBER"
- },
- {
- "name": "UNIT_PRICE",
- "position": 5,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_ORDER_ITEM",
- "columns": [
- "ORDER_ID"
- ],
- "referencedTable": "ORDERS",
- "referencedColumns": [
- "ID"
- ],
- "onDelete": "CASCADE"
- }
- ],
- "triggers": [
- {
- "name": "TRG_UPDATE_ORDER_TOTAL",
- "event": "INSERT OR UPDATE OR DELETE",
- "timing": "AFTER EACH ROW",
- "body": "CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL\nAFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS\nFOR EACH ROW\nDECLARE\n V_ORDER_ID NUMBER;\n V_TOTAL NUMBER(10, 2);\nBEGIN\n -- Get order ID\n IF INSERTING OR UPDATING THEN\n V_ORDER_ID := :NEW.ORDER_ID;\n ELSE\n V_ORDER_ID := :OLD.ORDER_ID;\n END IF;\n \n -- Calculate new total\n SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL\n FROM ORDER_ITEMS\n WHERE ORDER_ID = V_ORDER_ID;\n \n -- Update order total\n UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;\nEND;"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/circular_foreign_key_dependencies.sql b/backend/plugin/schema/oracle/testdata/generate_migration/circular_foreign_key_dependencies.sql
deleted file mode 100644
index a850463671..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/circular_foreign_key_dependencies.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-ALTER TABLE "CUSTOMERS" DROP CONSTRAINT "FK_PREFERRED_ORDER";
-ALTER TABLE "ORDERS" DROP CONSTRAINT "FK_CUSTOMER";
-ALTER TABLE "ORDER_ITEMS" DROP CONSTRAINT "FK_ORDER_ITEM";
-DROP TABLE "ORDER_ITEMS";
-
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/comments_with_special_characters.json b/backend/plugin/schema/oracle/testdata/generate_migration/comments_with_special_characters.json
deleted file mode 100644
index ddcdf139d4..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/comments_with_special_characters.json
+++ /dev/null
@@ -1,331 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "MULTILANG_CONTENT",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE_EN",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TITLE_ES",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TITLE_ZH",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT_TEXT",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TAGS",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(1000 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "SPECIAL_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "DATA_VALUE",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(500 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "METADATA_JSON",
- "position": 3,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "UNICODE_TEXT",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "BINARY_DATA",
- "position": 5,
- "nullable": true,
- "type": "BLOB"
- },
- {
- "name": "CATEGORY",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "STATUS",
- "position": 7,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "COMPLEX_TYPES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "XML_DATA",
- "position": 2,
- "nullable": true,
- "type": "XMLTYPE",
- "comment": "XMLType column for structured XML storage\nExample: \u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003croot\u003e\u003citem id=\"1\" name=\"test\"\u003eContent\u003c/item\u003e\u003c/root\u003e"
- },
- {
- "name": "TIMESTAMP_TZ",
- "position": 3,
- "default": "SYSTIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6) WITH TIME ZONE",
- "comment": "Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR\nDefault: SYSTIMESTAMP (system timestamp with session timezone)"
- },
- {
- "name": "INTERVAL_DS",
- "position": 4,
- "nullable": true,
- "type": "INTERVAL DAY(2) TO SECOND(6)",
- "comment": "Interval Day to Second: +/-DD HH:MI:SS.FFFFFF\nRange: +/-999999999 days, precision up to nanoseconds"
- },
- {
- "name": "RAW_DATA",
- "position": 5,
- "nullable": true,
- "type": "RAW(100)"
- },
- {
- "name": "LONG_RAW_DATA",
- "position": 6,
- "nullable": true,
- "type": "LONG RAW"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Advanced data types testing table\nSupports: XMLType, Timestamps with timezone, Intervals, RAW data\nPerformance: Optimized for OLTP workloads @ 10K+ TPS\nSecurity: Row-level security enabled, audit trails maintained"
- },
- {
- "name": "MULTILANG_CONTENT",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE_EN",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "English title field"
- },
- {
- "name": "TITLE_ES",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Título en español"
- },
- {
- "name": "TITLE_ZH",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP",
- "comment": "中文标题字段 - 支持简体和繁体中文"
- },
- {
- "name": "CONTENT_TEXT",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "Content field supporting:\n1. HTML tags: \u003cb\u003ebold\u003c/b\u003e, \u003ci\u003eitalic\u003c/i\u003e, \u003ca href=\"http://example.com\"\u003elinks\u003c/a\u003e\n2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick\n3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″\n4. Emojis: 😀 😃 😄 😁 🚀 ⭐ 🎉 💯\n5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2"
- },
- {
- "name": "TAGS",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(1000 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "XML tags: \u003ctag type=\"category\" value=\"news\"/\u003e\u003ctag type=\"priority\" value=\"high\"/\u003eEnd of XML"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Multilingual content: English, Español, 中文, العربية, Русский, 日本語"
- },
- {
- "name": "SPECIAL_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "DATA_VALUE",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(500 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Data value field - supports NULL, empty strings, and 'quoted' content"
- },
- {
- "name": "METADATA_JSON",
- "position": 3,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "JSON metadata: {\"key\": \"value\", \"array\": [1,2,3]}"
- },
- {
- "name": "UNICODE_TEXT",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP",
- "comment": "Unicode text support:\nLine 1: Basic ASCII text\nLine 2: Special chars !@#$%^\u0026*()_+-={}[]|;:,.\u003c\u003e?\nLine 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π\nLine 4: Currencies $ € £ ¥ ₹"
- },
- {
- "name": "BINARY_DATA",
- "position": 5,
- "nullable": true,
- "type": "BLOB",
- "comment": "Binary data storage\\nSupports: images, documents, archives\\tTab-separated info\\r\\nWindows line endings"
- },
- {
- "name": "CATEGORY",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Category field: use % for wildcard searches, _ for single char matching"
- },
- {
- "name": "STATUS",
- "position": 7,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Status field - values: 'ACTIVE', 'INACTIVE', 'PENDING'; DROP TABLE users; --"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Table containing \"special\" data with various formats \u0026 types"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/comments_with_special_characters.sql b/backend/plugin/schema/oracle/testdata/generate_migration/comments_with_special_characters.sql
deleted file mode 100644
index 5e17705356..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/comments_with_special_characters.sql
+++ /dev/null
@@ -1,26 +0,0 @@
-DROP TABLE "COMPLEX_TYPES";
-
-COMMENT ON TABLE "MULTILANG_CONTENT" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_EN" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ES" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ZH" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."CONTENT_TEXT" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TAGS" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_EN" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ES" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ZH" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."CONTENT_TEXT" IS '';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TAGS" IS '';
-COMMENT ON TABLE "SPECIAL_DATA" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."DATA_VALUE" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."METADATA_JSON" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."UNICODE_TEXT" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."BINARY_DATA" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."CATEGORY" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."STATUS" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."DATA_VALUE" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."METADATA_JSON" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."UNICODE_TEXT" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."BINARY_DATA" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."CATEGORY" IS '';
-COMMENT ON COLUMN "SPECIAL_DATA"."STATUS" IS '';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/complex_view_dependencies.json b/backend/plugin/schema/oracle/testdata/generate_migration/complex_view_dependencies.json
deleted file mode 100644
index fc351bd62b..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/complex_view_dependencies.json
+++ /dev/null
@@ -1,373 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "DEPARTMENTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "MANAGER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_MANAGER",
- "columns": [
- "MANAGER_ID"
- ],
- "referencedTable": "EMPLOYEES",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "EMPLOYEES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "DEPARTMENT_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_DEPT",
- "columns": [
- "DEPARTMENT_ID"
- ],
- "referencedTable": "DEPARTMENTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "DEPARTMENTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "MANAGER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_MANAGER",
- "columns": [
- "MANAGER_ID"
- ],
- "referencedTable": "EMPLOYEES",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "EMPLOYEES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "DEPARTMENT_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_DEPT",
- "columns": [
- "DEPARTMENT_ID"
- ],
- "referencedTable": "DEPARTMENTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- }
- ],
- "views": [
- {
- "name": "DEPT_EMPLOYEE_COUNT",
- "definition": "SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPARTMENTS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "DEPT_ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "DEPT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMP_COUNT",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- },
- {
- "name": "DEPT_MANAGER_SUMMARY",
- "definition": "SELECT \n DS.DEPT_ID,\n DS.DEPT_NAME,\n DS.EMP_COUNT,\n DS.AVG_SALARY,\n M.NAME AS MANAGER_NAME\nFROM DEPT_SUMMARY DS\nJOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID\nLEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPARTMENTS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "DEPT_SUMMARY",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "DEPT_ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "DEPT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMP_COUNT",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "AVG_SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "MANAGER_NAME",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ]
- },
- {
- "name": "DEPT_SUMMARY",
- "definition": "SELECT \n DEC.DEPT_ID,\n DEC.DEPT_NAME,\n DEC.EMP_COUNT,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY\nFROM DEPT_EMPLOYEE_COUNT DEC\nLEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID\nGROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPT_EMPLOYEE_COUNT",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "DEPT_ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "DEPT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMP_COUNT",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "AVG_SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- }
- ],
- "materializedViews": [
- {
- "name": "MV_DEPT_STATS",
- "definition": "SELECT \n D.ID AS DEPT_ID,\n D.NAME AS DEPT_NAME,\n COUNT(E.ID) AS TOTAL_EMPLOYEES,\n NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY,\n NVL(MAX(E.SALARY), 0) AS MAX_SALARY,\n NVL(MIN(E.SALARY), 0) AS MIN_SALARY\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME\n",
- "comment": "snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPARTMENTS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "MV_DEPT_STATS",
- "column": "*"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/complex_view_dependencies.sql b/backend/plugin/schema/oracle/testdata/generate_migration/complex_view_dependencies.sql
deleted file mode 100644
index c42b25d6f4..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/complex_view_dependencies.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-DROP VIEW "DEPT_EMPLOYEE_COUNT";
-DROP VIEW "DEPT_MANAGER_SUMMARY";
-DROP VIEW "DEPT_SUMMARY";
-DROP MATERIALIZED VIEW "MV_DEPT_STATS";
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/create_tables_with_fk.json b/backend/plugin/schema/oracle/testdata/generate_migration/create_tables_with_fk.json
deleted file mode 100644
index 91bf15dfe4..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/create_tables_with_fk.json
+++ /dev/null
@@ -1,153 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "POSTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 3,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PUBLISHED_AT",
- "position": 5,
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_USER_ID",
- "expressions": [
- "\"USER_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ],
- "onDelete": "CASCADE"
- }
- ]
- },
- {
- "name": "USERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USERNAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 4,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_USERNAME",
- "expressions": [
- "\"USERNAME\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "UK_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {}
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/create_tables_with_fk.sql b/backend/plugin/schema/oracle/testdata/generate_migration/create_tables_with_fk.sql
deleted file mode 100644
index b8b4b45285..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/create_tables_with_fk.sql
+++ /dev/null
@@ -1,21 +0,0 @@
-CREATE TABLE "USERS" (
- "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000002".nextval NOT NULL,
- "USERNAME" VARCHAR2(50 BYTE) NOT NULL,
- "EMAIL" VARCHAR2(100 BYTE) NOT NULL,
- "CREATED_AT" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP
-);
-ALTER TABLE "USERS" ADD CONSTRAINT "SYS_C0000002" PRIMARY KEY (ID);
-CREATE INDEX "IDX_USERNAME" ON "USERS" ("USERNAME" ASC);
-CREATE UNIQUE INDEX "UK_EMAIL" ON "USERS" ("EMAIL" ASC);
-
-CREATE TABLE "POSTS" (
- "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000001".nextval NOT NULL,
- "USER_ID" NUMBER NOT NULL,
- "TITLE" VARCHAR2(200 BYTE) NOT NULL,
- "CONTENT" CLOB,
- "PUBLISHED_AT" TIMESTAMP(6)
-);
-ALTER TABLE "POSTS" ADD CONSTRAINT "SYS_C0000001" PRIMARY KEY (ID);
-CREATE INDEX "IDX_USER_ID" ON "POSTS" ("USER_ID" ASC);
-
-ALTER TABLE "POSTS" ADD CONSTRAINT "FK_USER" FOREIGN KEY ("USER_ID") REFERENCES "USERS" ("ID") ON DELETE CASCADE;
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_and_recreate_constraints.json b/backend/plugin/schema/oracle/testdata/generate_migration/drop_and_recreate_constraints.json
deleted file mode 100644
index d6110d1c5b..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_and_recreate_constraints.json
+++ /dev/null
@@ -1,321 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUTHORS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000002",
- "expressions": [
- "EMAIL"
- ],
- "unique": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "BOOKS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 2,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "AUTHOR_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "ISBN",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PUBLISHED_YEAR",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "PRICE",
- "position": 6,
- "nullable": true,
- "type": "NUMBER(8,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000004",
- "expressions": [
- "ISBN"
- ],
- "unique": true,
- "isConstraint": true
- },
- {
- "name": "IDX_BOOKS_AUTHOR",
- "expressions": [
- "\"AUTHOR_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_BOOKS_YEAR",
- "expressions": [
- "\"PUBLISHED_YEAR\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_AUTHOR",
- "columns": [
- "AUTHOR_ID"
- ],
- "referencedTable": "AUTHORS",
- "referencedColumns": [
- "ID"
- ]
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_PRICE_POSITIVE",
- "expression": "PRICE \u003e 0"
- },
- {
- "name": "CHECK_YEAR_VALID",
- "expression": "PUBLISHED_YEAR \u003e= 1000 AND PUBLISHED_YEAR \u003c= 2100"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUTHORS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000002",
- "expressions": [
- "EMAIL"
- ],
- "unique": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "BOOKS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 2,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "AUTHOR_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "ISBN",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PUBLISHED_YEAR",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "PRICE",
- "position": 6,
- "nullable": true,
- "type": "NUMBER(8,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000004",
- "expressions": [
- "ISBN"
- ],
- "unique": true,
- "isConstraint": true
- },
- {
- "name": "IDX_BOOKS_AUTHOR",
- "expressions": [
- "\"AUTHOR_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_BOOKS_YEAR",
- "expressions": [
- "\"PUBLISHED_YEAR\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_AUTHOR_NEW",
- "columns": [
- "AUTHOR_ID"
- ],
- "referencedTable": "AUTHORS",
- "referencedColumns": [
- "ID"
- ],
- "onDelete": "CASCADE"
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_PRICE_POSITIVE",
- "expression": "PRICE \u003e 0"
- },
- {
- "name": "CHECK_TITLE_LENGTH",
- "expression": "LENGTH(TITLE) \u003e= 3"
- },
- {
- "name": "CHECK_YEAR_EXTENDED",
- "expression": "PUBLISHED_YEAR \u003e= 1000 AND PUBLISHED_YEAR \u003c= 2030"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_and_recreate_constraints.sql b/backend/plugin/schema/oracle/testdata/generate_migration/drop_and_recreate_constraints.sql
deleted file mode 100644
index bdbf404172..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_and_recreate_constraints.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-ALTER TABLE "BOOKS" DROP CONSTRAINT "FK_AUTHOR_NEW";
-ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_TITLE_LENGTH";
-ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_YEAR_EXTENDED";
-
-ALTER TABLE "BOOKS" ADD CONSTRAINT "CHECK_YEAR_VALID" CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2100);
-ALTER TABLE "BOOKS" ADD CONSTRAINT "FK_AUTHOR" FOREIGN KEY ("AUTHOR_ID") REFERENCES "AUTHORS" ("ID");
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_indexes_and_constraints.json b/backend/plugin/schema/oracle/testdata/generate_migration/drop_indexes_and_constraints.json
deleted file mode 100644
index 28c57ff2d4..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_indexes_and_constraints.json
+++ /dev/null
@@ -1,160 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SUPPLIER_ID",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_NAME",
- "expressions": [
- "\"NAME\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_PRICE",
- "expressions": [
- "\"PRICE\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_NAME_LENGTH",
- "expression": "LENGTH(NAME) \u003e= 3"
- },
- {
- "name": "CHECK_PRICE_POSITIVE",
- "expression": "PRICE \u003e 0"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SUPPLIER_ID",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_indexes_and_constraints.sql b/backend/plugin/schema/oracle/testdata/generate_migration/drop_indexes_and_constraints.sql
deleted file mode 100644
index c71a886400..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_indexes_and_constraints.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-CREATE INDEX "IDX_PRODUCTS_CATEGORY" ON "PRODUCTS" ("CATEGORY" ASC);
-CREATE UNIQUE INDEX "IDX_PRODUCTS_NAME" ON "PRODUCTS" ("NAME" ASC);
-CREATE INDEX "IDX_PRODUCTS_PRICE" ON "PRODUCTS" ("PRICE" ASC);
-ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_NAME_LENGTH" CHECK (LENGTH(NAME) >= 3);
-ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_PRICE_POSITIVE" CHECK (PRICE > 0);
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_sequence.json b/backend/plugin/schema/oracle/testdata/generate_migration/drop_sequence.json
deleted file mode 100644
index 860f67fe3e..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_sequence.json
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SIMPLE_LOG",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TRANSACTION_SEQ\".NEXTVAL",
- "type": "NUMBER"
- },
- {
- "name": "MESSAGE",
- "position": 2,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "sequences": [
- {
- "name": "TRANSACTION_SEQ"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {}
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_sequence.sql b/backend/plugin/schema/oracle/testdata/generate_migration/drop_sequence.sql
deleted file mode 100644
index 0bf7acbc41..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_sequence.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-CREATE SEQUENCE "TRANSACTION_SEQ";
-CREATE TABLE "SIMPLE_LOG" (
- "ID" NUMBER DEFAULT "TRANSACTION_SEQ".NEXTVAL NOT NULL,
- "MESSAGE" CLOB NOT NULL
-);
-ALTER TABLE "SIMPLE_LOG" ADD CONSTRAINT "SYS_C0000001" PRIMARY KEY (ID);
-
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_views_and_functions.json b/backend/plugin/schema/oracle/testdata/generate_migration/drop_views_and_functions.json
deleted file mode 100644
index 4e1fe8e237..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_views_and_functions.json
+++ /dev/null
@@ -1,160 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "SALE_AMOUNT",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SALE_DATE",
- "position": 4,
- "type": "DATE"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "views": [
- {
- "name": "MONTHLY_SALES",
- "definition": "SELECT \n EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,\n EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,\n SUM(SALE_AMOUNT) AS TOTAL_SALES\nFROM SALES\nGROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE)",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "SALES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "YEAR_VAL",
- "position": 1,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "MONTH_VAL",
- "position": 2,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL_SALES",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- }
- ],
- "functions": [
- {
- "name": "CALCULATE_DISCOUNT",
- "definition": "FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)\nRETURN NUMBER\nIS\nBEGIN\n RETURN AMOUNT * 0.1;\nEND;"
- },
- {
- "name": "GET_MONTHLY_TOTAL",
- "definition": "FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)\nRETURN NUMBER\nIS\n V_TOTAL NUMBER;\nBEGIN\n SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL\n FROM SALES\n WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM\n AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;\n \n RETURN V_TOTAL;\nEND;"
- }
- ],
- "materializedViews": [
- {
- "name": "TOP_PRODUCTS",
- "definition": "SELECT \n PRODUCT_NAME,\n COUNT(*) AS SALE_COUNT,\n SUM(SALE_AMOUNT) AS TOTAL_REVENUE\nFROM SALES\nGROUP BY PRODUCT_NAME\n",
- "comment": "snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "SALES",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "TOP_PRODUCTS",
- "column": "*"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "SALE_AMOUNT",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SALE_DATE",
- "position": 4,
- "type": "DATE"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/drop_views_and_functions.sql b/backend/plugin/schema/oracle/testdata/generate_migration/drop_views_and_functions.sql
deleted file mode 100644
index c22e52e34e..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/drop_views_and_functions.sql
+++ /dev/null
@@ -1,35 +0,0 @@
-CREATE OR REPLACE FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)
-RETURN NUMBER
-IS
-BEGIN
- RETURN AMOUNT * 0.1;
-END;
-
-CREATE OR REPLACE FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)
-RETURN NUMBER
-IS
- V_TOTAL NUMBER;
-BEGIN
- SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL
- FROM SALES
- WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM
- AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;
-
- RETURN V_TOTAL;
-END;
-
-CREATE VIEW "MONTHLY_SALES" AS SELECT
- EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,
- EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,
- SUM(SALE_AMOUNT) AS TOTAL_SALES
-FROM SALES
-GROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE);
-CREATE MATERIALIZED VIEW "TOP_PRODUCTS" AS SELECT
- PRODUCT_NAME,
- COUNT(*) AS SALE_COUNT,
- SUM(SALE_AMOUNT) AS TOTAL_REVENUE
-FROM SALES
-GROUP BY PRODUCT_NAME
-;
-COMMENT ON MATERIALIZED VIEW "TOP_PRODUCTS" IS 'snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS';
-COMMENT ON MATERIALIZED VIEW "TOP_PRODUCTS" IS 'snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/edge_case_column_operations.json b/backend/plugin/schema/oracle/testdata/generate_migration/edge_case_column_operations.json
deleted file mode 100644
index 82f95d75f4..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/edge_case_column_operations.json
+++ /dev/null
@@ -1,163 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "TEST_COLUMNS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "COL_VARCHAR",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_NUMBER",
- "position": 3,
- "nullable": true,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "COL_DATE",
- "position": 4,
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "COL_CLOB",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_NULLABLE",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_WITH_DEFAULT",
- "position": 7,
- "default": "'DEFAULT_VALUE'",
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "TEST_COLUMNS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "COL_VARCHAR",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_NUMBER",
- "position": 3,
- "nullable": true,
- "type": "NUMBER(15,3)"
- },
- {
- "name": "COL_DATE",
- "position": 4,
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "COL_NULLABLE",
- "position": 5,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_WITH_DEFAULT",
- "position": 6,
- "default": "'NEW_DEFAULT'",
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_TIMESTAMP",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "COL_BOOLEAN",
- "position": 8,
- "nullable": true,
- "type": "NUMBER(1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHK_NUMBER_POSITIVE",
- "expression": "COL_NUMBER \u003e 0"
- },
- {
- "name": "CHK_VARCHAR_LENGTH",
- "expression": "LENGTH(COL_VARCHAR) \u003e= 5"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/edge_case_column_operations.sql b/backend/plugin/schema/oracle/testdata/generate_migration/edge_case_column_operations.sql
deleted file mode 100644
index 72032aa2d8..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/edge_case_column_operations.sql
+++ /dev/null
@@ -1,11 +0,0 @@
-ALTER TABLE "TEST_COLUMNS" DROP CONSTRAINT "CHK_NUMBER_POSITIVE";
-ALTER TABLE "TEST_COLUMNS" DROP CONSTRAINT "CHK_VARCHAR_LENGTH";
-ALTER TABLE "TEST_COLUMNS" DROP COLUMN "COL_TIMESTAMP";
-ALTER TABLE "TEST_COLUMNS" DROP COLUMN "COL_BOOLEAN";
-
-ALTER TABLE "TEST_COLUMNS" ADD "COL_CLOB" CLOB;
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_VARCHAR" VARCHAR2(50 BYTE);
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NUMBER" NUMBER(10,2);
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NULLABLE" NULL;
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT NULL;
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT 'DEFAULT_VALUE';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/modify_and_drop_comments.json b/backend/plugin/schema/oracle/testdata/generate_migration/modify_and_drop_comments.json
deleted file mode 100644
index d221d38569..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/modify_and_drop_comments.json
+++ /dev/null
@@ -1,250 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "INVENTORY",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER",
- "comment": "Primary key for inventory records"
- },
- {
- "name": "PRODUCT_CODE",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Product identification code"
- },
- {
- "name": "STOCK_LEVEL",
- "position": 3,
- "type": "NUMBER",
- "comment": "Current stock quantity"
- },
- {
- "name": "MIN_STOCK",
- "position": 4,
- "default": "10",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Minimum stock threshold"
- },
- {
- "name": "MAX_STOCK",
- "position": 5,
- "default": "1000",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Maximum stock capacity"
- },
- {
- "name": "WAREHOUSE_ID",
- "position": 6,
- "nullable": true,
- "type": "NUMBER",
- "comment": "Warehouse location identifier"
- },
- {
- "name": "LAST_UPDATED",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Initial inventory tracking table"
- },
- {
- "name": "SUPPLIERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Supplier company name"
- },
- {
- "name": "CONTACT_EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Primary contact email"
- },
- {
- "name": "RATING",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(2,1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Supplier information table"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "INVENTORY",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER",
- "comment": "Primary key for inventory records"
- },
- {
- "name": "PRODUCT_CODE",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Updated: Standardized product SKU following new naming convention"
- },
- {
- "name": "STOCK_LEVEL",
- "position": 3,
- "type": "NUMBER",
- "comment": "Updated: Real-time stock quantity with automated updates"
- },
- {
- "name": "MIN_STOCK",
- "position": 4,
- "default": "10",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Updated: Dynamic minimum threshold based on sales velocity"
- },
- {
- "name": "MAX_STOCK",
- "position": 5,
- "default": "1000",
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "WAREHOUSE_ID",
- "position": 6,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "LAST_UPDATED",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)",
- "comment": "Timestamp of last inventory update or modification"
- },
- {
- "name": "REORDER_POINT",
- "position": 8,
- "default": "0",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Calculated reorder point based on lead time and demand"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Updated inventory management system with enhanced tracking capabilities"
- },
- {
- "name": "SUPPLIERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Supplier company name"
- },
- {
- "name": "CONTACT_EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "RATING",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(2,1)",
- "comment": "Supplier performance rating (1.0 to 5.0 scale)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/modify_and_drop_comments.sql b/backend/plugin/schema/oracle/testdata/generate_migration/modify_and_drop_comments.sql
deleted file mode 100644
index f989f4ca97..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/modify_and_drop_comments.sql
+++ /dev/null
@@ -1,20 +0,0 @@
-ALTER TABLE "INVENTORY" DROP COLUMN "REORDER_POINT";
-
-COMMENT ON TABLE "INVENTORY" IS 'Initial inventory tracking table';
-COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Product identification code';
-COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Current stock quantity';
-COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Minimum stock threshold';
-COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS 'Maximum stock capacity';
-COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS 'Warehouse location identifier';
-COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS '';
-COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Product identification code';
-COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Current stock quantity';
-COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Minimum stock threshold';
-COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS 'Maximum stock capacity';
-COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS 'Warehouse location identifier';
-COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS '';
-COMMENT ON TABLE "SUPPLIERS" IS 'Supplier information table';
-COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS 'Primary contact email';
-COMMENT ON COLUMN "SUPPLIERS"."RATING" IS '';
-COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS 'Primary contact email';
-COMMENT ON COLUMN "SUPPLIERS"."RATING" IS '';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_advanced_indexes_and_constraints.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_advanced_indexes_and_constraints.json
deleted file mode 100644
index 3d7bc1a0a4..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_advanced_indexes_and_constraints.json
+++ /dev/null
@@ -1,144 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "SALE_DATE",
- "position": 2,
- "type": "DATE"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 4,
- "type": "NUMBER"
- },
- {
- "name": "AMOUNT",
- "position": 5,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "REGION",
- "position": 6,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "UK_SALES_DATE_CUSTOMER",
- "expressions": [
- "SALE_DATE",
- "CUSTOMER_ID",
- "PRODUCT_ID"
- ],
- "unique": true,
- "isConstraint": true
- },
- {
- "name": "IDX_SALES_MONTH_YEAR",
- "expressions": [
- "EXTRACT(YEAR FROM \"SALE_DATE\")",
- "EXTRACT(MONTH FROM \"SALE_DATE\")"
- ],
- "descending": [
- false,
- false
- ],
- "type": "FUNCTION-BASED NORMAL",
- "visible": true
- },
- {
- "name": "IDX_SALES_REGION_AMOUNT",
- "expressions": [
- "\"REGION\"",
- "\"AMOUNT\""
- ],
- "descending": [
- false,
- true
- ],
- "type": "FUNCTION-BASED NORMAL",
- "visible": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHK_AMOUNT_RANGE",
- "expression": "AMOUNT \u003e 0 AND AMOUNT \u003c= 999999.99"
- },
- {
- "name": "CHK_REGION_VALID",
- "expression": "REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL')"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "SALE_DATE",
- "position": 2,
- "type": "DATE"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 4,
- "type": "NUMBER"
- },
- {
- "name": "AMOUNT",
- "position": 5,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "REGION",
- "position": 6,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_advanced_indexes_and_constraints.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_advanced_indexes_and_constraints.sql
deleted file mode 100644
index d575e1aaff..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_advanced_indexes_and_constraints.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-CREATE INDEX "IDX_SALES_MONTH_YEAR" ON "SALES_DATA" (EXTRACT(YEAR FROM "SALE_DATE") ASC, EXTRACT(MONTH FROM "SALE_DATE") ASC);
-CREATE INDEX "IDX_SALES_REGION_AMOUNT" ON "SALES_DATA" ("REGION" ASC, "AMOUNT" DESC);
-ALTER TABLE "SALES_DATA" ADD CONSTRAINT "UK_SALES_DATE_CUSTOMER" UNIQUE (SALE_DATE, CUSTOMER_ID, PRODUCT_ID);
-ALTER TABLE "SALES_DATA" ADD CONSTRAINT "CHK_AMOUNT_RANGE" CHECK (AMOUNT > 0 AND AMOUNT <= 999999.99);
-ALTER TABLE "SALES_DATA" ADD CONSTRAINT "CHK_REGION_VALID" CHECK (REGION IN ('NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL'));
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_alter_table_columns.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_alter_table_columns.json
deleted file mode 100644
index 4b8ca6909c..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_alter_table_columns.json
+++ /dev/null
@@ -1,228 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(30 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "IS_ACTIVE",
- "position": 6,
- "default": "1",
- "nullable": true,
- "type": "NUMBER(1)"
- },
- {
- "name": "CREATED_AT",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "STOCK_QUANTITY",
- "position": 8,
- "default": "0",
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "WEIGHT",
- "position": 9,
- "nullable": true,
- "type": "NUMBER(5,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_CREATED_AT",
- "expressions": [
- "\"CREATED_AT\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_NAME_CATEGORY",
- "expressions": [
- "\"NAME\"",
- "\"CATEGORY\""
- ],
- "descending": [
- false,
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_PRICE",
- "expressions": [
- "\"PRICE\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_PRICE_POSITIVE",
- "expression": "PRICE \u003e 0"
- },
- {
- "name": "CHECK_STOCK_NON_NEGATIVE",
- "expression": "STOCK_QUANTITY \u003e= 0"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(8,2)"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(30 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "IS_ACTIVE",
- "position": 6,
- "default": "1",
- "nullable": true,
- "type": "NUMBER(1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_PRICE",
- "expressions": [
- "\"PRICE\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_alter_table_columns.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_alter_table_columns.sql
deleted file mode 100644
index 2ad2b39d08..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_alter_table_columns.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-ALTER TABLE "PRODUCTS" ADD "CREATED_AT" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP;
-ALTER TABLE "PRODUCTS" ADD "STOCK_QUANTITY" NUMBER DEFAULT 0;
-ALTER TABLE "PRODUCTS" ADD "WEIGHT" NUMBER(5,2);
-ALTER TABLE "PRODUCTS" MODIFY "NAME" VARCHAR2(100 BYTE);
-ALTER TABLE "PRODUCTS" MODIFY "PRICE" NUMBER(10,2);
-ALTER TABLE "PRODUCTS" MODIFY "DESCRIPTION" NOT NULL;
-CREATE INDEX "IDX_PRODUCTS_CREATED_AT" ON "PRODUCTS" ("CREATED_AT" ASC);
-CREATE UNIQUE INDEX "IDX_PRODUCTS_NAME_CATEGORY" ON "PRODUCTS" ("NAME" ASC, "CATEGORY" ASC);
-ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_PRICE_POSITIVE" CHECK (PRICE > 0);
-ALTER TABLE "PRODUCTS" ADD CONSTRAINT "CHECK_STOCK_NON_NEGATIVE" CHECK (STOCK_QUANTITY >= 0);
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_basic_table_operations.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_basic_table_operations.json
deleted file mode 100644
index 82d6c3b657..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_basic_table_operations.json
+++ /dev/null
@@ -1,321 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "COMMENTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "POST_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 5,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_COMMENT_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ]
- },
- {
- "name": "FK_POST",
- "columns": [
- "POST_ID"
- ],
- "referencedTable": "POSTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "POSTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 3,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_POSTS_USER_ID",
- "expressions": [
- "\"USER_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_TITLE_LENGTH",
- "expression": "LENGTH(TITLE) \u003e 0"
- }
- ]
- },
- {
- "name": "USERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USERNAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 4,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "IS_ACTIVE",
- "position": 5,
- "default": "1",
- "nullable": true,
- "type": "NUMBER(1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_USERS_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "POSTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 3,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_POSTS_USER_ID",
- "expressions": [
- "\"USER_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "USERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USERNAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 4,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_basic_table_operations.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_basic_table_operations.sql
deleted file mode 100644
index e50d14f95f..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_basic_table_operations.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-ALTER TABLE "USERS" ADD "IS_ACTIVE" NUMBER(1) DEFAULT 1;
-CREATE TABLE "COMMENTS" (
- "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000001".nextval NOT NULL,
- "POST_ID" NUMBER NOT NULL,
- "USER_ID" NUMBER NOT NULL,
- "CONTENT" CLOB NOT NULL,
- "CREATED_AT" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP
-);
-ALTER TABLE "COMMENTS" ADD CONSTRAINT "SYS_C0000001" PRIMARY KEY (ID);
-
-ALTER TABLE "COMMENTS" ADD CONSTRAINT "FK_COMMENT_USER" FOREIGN KEY ("USER_ID") REFERENCES "USERS" ("ID");
-ALTER TABLE "COMMENTS" ADD CONSTRAINT "FK_POST" FOREIGN KEY ("POST_ID") REFERENCES "POSTS" ("ID");
-ALTER TABLE "POSTS" ADD CONSTRAINT "CHECK_TITLE_LENGTH" CHECK (LENGTH(TITLE) > 0);
-CREATE INDEX "IDX_USERS_EMAIL" ON "USERS" ("EMAIL" ASC);
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_circular_foreign_key_dependencies.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_circular_foreign_key_dependencies.json
deleted file mode 100644
index 1006bcfb74..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_circular_foreign_key_dependencies.json
+++ /dev/null
@@ -1,258 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PREFERRED_ORDER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_PREFERRED_ORDER",
- "columns": [
- "PREFERRED_ORDER_ID"
- ],
- "referencedTable": "ORDERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "ORDER_DATE",
- "position": 3,
- "default": "SYSDATE",
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "TOTAL_AMOUNT",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_CUSTOMER",
- "columns": [
- "CUSTOMER_ID"
- ],
- "referencedTable": "CUSTOMERS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "ORDER_ITEMS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "ORDER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_NAME",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "QUANTITY",
- "position": 4,
- "type": "NUMBER"
- },
- {
- "name": "UNIT_PRICE",
- "position": 5,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_ORDER_ITEM",
- "columns": [
- "ORDER_ID"
- ],
- "referencedTable": "ORDERS",
- "referencedColumns": [
- "ID"
- ],
- "onDelete": "CASCADE"
- }
- ],
- "triggers": [
- {
- "name": "TRG_UPDATE_ORDER_TOTAL",
- "event": "INSERT OR UPDATE OR DELETE",
- "timing": "AFTER EACH ROW",
- "body": "CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL\nAFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS\nFOR EACH ROW\nDECLARE\n V_ORDER_ID NUMBER;\n V_TOTAL NUMBER(10, 2);\nBEGIN\n -- Get order ID\n IF INSERTING OR UPDATING THEN\n V_ORDER_ID := :NEW.ORDER_ID;\n ELSE\n V_ORDER_ID := :OLD.ORDER_ID;\n END IF;\n \n -- Calculate new total\n SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL\n FROM ORDER_ITEMS\n WHERE ORDER_ID = V_ORDER_ID;\n \n -- Update order total\n UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;\nEND;"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PREFERRED_ORDER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "ORDER_DATE",
- "position": 3,
- "default": "SYSDATE",
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "TOTAL_AMOUNT",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_circular_foreign_key_dependencies.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_circular_foreign_key_dependencies.sql
deleted file mode 100644
index 09dd4ecf94..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_circular_foreign_key_dependencies.sql
+++ /dev/null
@@ -1,34 +0,0 @@
-CREATE TABLE "ORDER_ITEMS" (
- "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000003".nextval NOT NULL,
- "ORDER_ID" NUMBER NOT NULL,
- "PRODUCT_NAME" VARCHAR2(100 BYTE) NOT NULL,
- "QUANTITY" NUMBER NOT NULL,
- "UNIT_PRICE" NUMBER(10,2) NOT NULL
-);
-ALTER TABLE "ORDER_ITEMS" ADD CONSTRAINT "SYS_C0000003" PRIMARY KEY (ID);
-CREATE OR REPLACE TRIGGER TRG_UPDATE_ORDER_TOTAL
-AFTER INSERT OR UPDATE OR DELETE ON ORDER_ITEMS
-FOR EACH ROW
-DECLARE
- V_ORDER_ID NUMBER;
- V_TOTAL NUMBER(10, 2);
-BEGIN
- -- Get order ID
- IF INSERTING OR UPDATING THEN
- V_ORDER_ID := :NEW.ORDER_ID;
- ELSE
- V_ORDER_ID := :OLD.ORDER_ID;
- END IF;
-
- -- Calculate new total
- SELECT NVL(SUM(QUANTITY * UNIT_PRICE), 0) INTO V_TOTAL
- FROM ORDER_ITEMS
- WHERE ORDER_ID = V_ORDER_ID;
-
- -- Update order total
- UPDATE ORDERS SET TOTAL_AMOUNT = V_TOTAL WHERE ID = V_ORDER_ID;
-END;
-
-ALTER TABLE "ORDER_ITEMS" ADD CONSTRAINT "FK_ORDER_ITEM" FOREIGN KEY ("ORDER_ID") REFERENCES "ORDERS" ("ID") ON DELETE CASCADE;
-ALTER TABLE "CUSTOMERS" ADD CONSTRAINT "FK_PREFERRED_ORDER" FOREIGN KEY ("PREFERRED_ORDER_ID") REFERENCES "ORDERS" ("ID");
-ALTER TABLE "ORDERS" ADD CONSTRAINT "FK_CUSTOMER" FOREIGN KEY ("CUSTOMER_ID") REFERENCES "CUSTOMERS" ("ID");
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_comments_with_special_characters.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_comments_with_special_characters.json
deleted file mode 100644
index 247dd07689..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_comments_with_special_characters.json
+++ /dev/null
@@ -1,331 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "COMPLEX_TYPES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "XML_DATA",
- "position": 2,
- "nullable": true,
- "type": "XMLTYPE",
- "comment": "XMLType column for structured XML storage\nExample: \u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003croot\u003e\u003citem id=\"1\" name=\"test\"\u003eContent\u003c/item\u003e\u003c/root\u003e"
- },
- {
- "name": "TIMESTAMP_TZ",
- "position": 3,
- "default": "SYSTIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6) WITH TIME ZONE",
- "comment": "Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR\nDefault: SYSTIMESTAMP (system timestamp with session timezone)"
- },
- {
- "name": "INTERVAL_DS",
- "position": 4,
- "nullable": true,
- "type": "INTERVAL DAY(2) TO SECOND(6)",
- "comment": "Interval Day to Second: +/-DD HH:MI:SS.FFFFFF\nRange: +/-999999999 days, precision up to nanoseconds"
- },
- {
- "name": "RAW_DATA",
- "position": 5,
- "nullable": true,
- "type": "RAW(100)"
- },
- {
- "name": "LONG_RAW_DATA",
- "position": 6,
- "nullable": true,
- "type": "LONG RAW"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Advanced data types testing table\nSupports: XMLType, Timestamps with timezone, Intervals, RAW data\nPerformance: Optimized for OLTP workloads @ 10K+ TPS\nSecurity: Row-level security enabled, audit trails maintained"
- },
- {
- "name": "MULTILANG_CONTENT",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE_EN",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "English title field"
- },
- {
- "name": "TITLE_ES",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Título en español"
- },
- {
- "name": "TITLE_ZH",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP",
- "comment": "中文标题字段 - 支持简体和繁体中文"
- },
- {
- "name": "CONTENT_TEXT",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "Content field supporting:\n1. HTML tags: \u003cb\u003ebold\u003c/b\u003e, \u003ci\u003eitalic\u003c/i\u003e, \u003ca href=\"http://example.com\"\u003elinks\u003c/a\u003e\n2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick\n3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″\n4. Emojis: 😀 😃 😄 😁 🚀 ⭐ 🎉 💯\n5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2"
- },
- {
- "name": "TAGS",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(1000 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "XML tags: \u003ctag type=\"category\" value=\"news\"/\u003e\u003ctag type=\"priority\" value=\"high\"/\u003eEnd of XML"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Multilingual content: English, Español, 中文, العربية, Русский, 日本語"
- },
- {
- "name": "SPECIAL_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "DATA_VALUE",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(500 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Data value field - supports NULL, empty strings, and 'quoted' content"
- },
- {
- "name": "METADATA_JSON",
- "position": 3,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "JSON metadata: {\"key\": \"value\", \"array\": [1,2,3]}"
- },
- {
- "name": "UNICODE_TEXT",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP",
- "comment": "Unicode text support:\nLine 1: Basic ASCII text\nLine 2: Special chars !@#$%^\u0026*()_+-={}[]|;:,.\u003c\u003e?\nLine 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π\nLine 4: Currencies $ € £ ¥ ₹"
- },
- {
- "name": "BINARY_DATA",
- "position": 5,
- "nullable": true,
- "type": "BLOB",
- "comment": "Binary data storage\\nSupports: images, documents, archives\\tTab-separated info\\r\\nWindows line endings"
- },
- {
- "name": "CATEGORY",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Category field: use % for wildcard searches, _ for single char matching"
- },
- {
- "name": "STATUS",
- "position": 7,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Status field - values: 'ACTIVE', 'INACTIVE', 'PENDING'; DROP TABLE users; --"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Table containing \"special\" data with various formats \u0026 types"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "MULTILANG_CONTENT",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE_EN",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TITLE_ES",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TITLE_ZH",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT_TEXT",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TAGS",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(1000 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "SPECIAL_DATA",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "DATA_VALUE",
- "position": 2,
- "nullable": true,
- "type": "VARCHAR2(500 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "METADATA_JSON",
- "position": 3,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "UNICODE_TEXT",
- "position": 4,
- "nullable": true,
- "type": "NVARCHAR2(400)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "BINARY_DATA",
- "position": 5,
- "nullable": true,
- "type": "BLOB"
- },
- {
- "name": "CATEGORY",
- "position": 6,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "STATUS",
- "position": 7,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_comments_with_special_characters.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_comments_with_special_characters.sql
deleted file mode 100644
index 8106db9c85..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_comments_with_special_characters.sql
+++ /dev/null
@@ -1,63 +0,0 @@
-CREATE TABLE "COMPLEX_TYPES" (
- "ID" NUMBER NOT NULL,
- "XML_DATA" XMLTYPE,
- "TIMESTAMP_TZ" TIMESTAMP(6) WITH TIME ZONE DEFAULT SYSTIMESTAMP,
- "INTERVAL_DS" INTERVAL DAY(2) TO SECOND(6),
- "RAW_DATA" RAW(100),
- "LONG_RAW_DATA" LONG RAW
-);
-ALTER TABLE "COMPLEX_TYPES" ADD CONSTRAINT "SYS_C0000001" PRIMARY KEY (ID);
-COMMENT ON TABLE "COMPLEX_TYPES" IS 'Advanced data types testing table
-Supports: XMLType, Timestamps with timezone, Intervals, RAW data
-Performance: Optimized for OLTP workloads @ 10K+ TPS
-Security: Row-level security enabled, audit trails maintained';
-COMMENT ON COLUMN "COMPLEX_TYPES"."XML_DATA" IS 'XMLType column for structured XML storage
-Example: <?xml version="1.0" encoding="UTF-8"?>
-<root><item id="1" name="test">Content</item></root>';
-COMMENT ON COLUMN "COMPLEX_TYPES"."TIMESTAMP_TZ" IS 'Timestamp with timezone: YYYY-MM-DD HH24:MI:SS.FF TZR
-Default: SYSTIMESTAMP (system timestamp with session timezone)';
-COMMENT ON COLUMN "COMPLEX_TYPES"."INTERVAL_DS" IS 'Interval Day to Second: +/-DD HH:MI:SS.FFFFFF
-Range: +/-999999999 days, precision up to nanoseconds';
-
-COMMENT ON TABLE "MULTILANG_CONTENT" IS 'Multilingual content: English, Español, 中文, العربية, Русский, 日本語';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_EN" IS 'English title field';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ES" IS 'Título en español';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ZH" IS '中文标题字段 - 支持简体和繁体中文';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."CONTENT_TEXT" IS 'Content field supporting:
-1. HTML tags: <b>bold</b>, <i>italic</i>, <a href="http://example.com">links</a>
-2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick
-3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″
-4. Emojis: 😀 😃 😄 😁 🚀 ⭐ 🎉 💯
-5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TAGS" IS 'XML tags: <tag type="category" value="news"/><tag type="priority" value="high"/>End of XML';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_EN" IS 'English title field';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ES" IS 'Título en español';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TITLE_ZH" IS '中文标题字段 - 支持简体和繁体中文';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."CONTENT_TEXT" IS 'Content field supporting:
-1. HTML tags: <b>bold</b>, <i>italic</i>, <a href="http://example.com">links</a>
-2. Markdown: **bold**, *italic*, [link](url), backtick-code-backtick
-3. Special symbols: © ® ™ § ¶ † ‡ • … ‰ ′ ″
-4. Emojis: 😀 😃 😄 😁 🚀 ⭐ 🎉 💯
-5. Mathematical: ∀x∈ℝ: x² ≥ 0, ∑(i=1 to n) i = n(n+1)/2';
-COMMENT ON COLUMN "MULTILANG_CONTENT"."TAGS" IS 'XML tags: <tag type="category" value="news"/><tag type="priority" value="high"/>End of XML';
-COMMENT ON TABLE "SPECIAL_DATA" IS 'Table containing "special" data with various formats & types';
-COMMENT ON COLUMN "SPECIAL_DATA"."DATA_VALUE" IS 'Data value field - supports NULL, empty strings, and ''quoted'' content';
-COMMENT ON COLUMN "SPECIAL_DATA"."METADATA_JSON" IS 'JSON metadata: {"key": "value", "array": [1,2,3]}';
-COMMENT ON COLUMN "SPECIAL_DATA"."UNICODE_TEXT" IS 'Unicode text support:
-Line 1: Basic ASCII text
-Line 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?
-Line 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π
-Line 4: Currencies $ € £ ¥ ₹';
-COMMENT ON COLUMN "SPECIAL_DATA"."BINARY_DATA" IS 'Binary data storage\nSupports: images, documents, archives\tTab-separated info\r\nWindows line endings';
-COMMENT ON COLUMN "SPECIAL_DATA"."CATEGORY" IS 'Category field: use % for wildcard searches, _ for single char matching';
-COMMENT ON COLUMN "SPECIAL_DATA"."STATUS" IS 'Status field - values: ''ACTIVE'', ''INACTIVE'', ''PENDING''; DROP TABLE users; --';
-COMMENT ON COLUMN "SPECIAL_DATA"."DATA_VALUE" IS 'Data value field - supports NULL, empty strings, and ''quoted'' content';
-COMMENT ON COLUMN "SPECIAL_DATA"."METADATA_JSON" IS 'JSON metadata: {"key": "value", "array": [1,2,3]}';
-COMMENT ON COLUMN "SPECIAL_DATA"."UNICODE_TEXT" IS 'Unicode text support:
-Line 1: Basic ASCII text
-Line 2: Special chars !@#$%^&*()_+-={}[]|;:,.<>?
-Line 3: Math symbols ≤ ≥ ± × ÷ ∑ ∏ ∆ π
-Line 4: Currencies $ € £ ¥ ₹';
-COMMENT ON COLUMN "SPECIAL_DATA"."BINARY_DATA" IS 'Binary data storage\nSupports: images, documents, archives\tTab-separated info\r\nWindows line endings';
-COMMENT ON COLUMN "SPECIAL_DATA"."CATEGORY" IS 'Category field: use % for wildcard searches, _ for single char matching';
-COMMENT ON COLUMN "SPECIAL_DATA"."STATUS" IS 'Status field - values: ''ACTIVE'', ''INACTIVE'', ''PENDING''; DROP TABLE users; --';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_complex_view_dependencies.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_complex_view_dependencies.json
deleted file mode 100644
index d7fc48fde9..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_complex_view_dependencies.json
+++ /dev/null
@@ -1,373 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "DEPARTMENTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "MANAGER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_MANAGER",
- "columns": [
- "MANAGER_ID"
- ],
- "referencedTable": "EMPLOYEES",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "EMPLOYEES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "DEPARTMENT_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_DEPT",
- "columns": [
- "DEPARTMENT_ID"
- ],
- "referencedTable": "DEPARTMENTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- }
- ],
- "views": [
- {
- "name": "DEPT_EMPLOYEE_COUNT",
- "definition": "SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPARTMENTS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "DEPT_ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "DEPT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMP_COUNT",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- },
- {
- "name": "DEPT_MANAGER_SUMMARY",
- "definition": "SELECT \n DS.DEPT_ID,\n DS.DEPT_NAME,\n DS.EMP_COUNT,\n DS.AVG_SALARY,\n M.NAME AS MANAGER_NAME\nFROM DEPT_SUMMARY DS\nJOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID\nLEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPARTMENTS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "DEPT_SUMMARY",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "DEPT_ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "DEPT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMP_COUNT",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "AVG_SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "MANAGER_NAME",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ]
- },
- {
- "name": "DEPT_SUMMARY",
- "definition": "SELECT \n DEC.DEPT_ID,\n DEC.DEPT_NAME,\n DEC.EMP_COUNT,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY\nFROM DEPT_EMPLOYEE_COUNT DEC\nLEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID\nGROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPT_EMPLOYEE_COUNT",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "DEPT_ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "DEPT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMP_COUNT",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "AVG_SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- }
- ],
- "materializedViews": [
- {
- "name": "MV_DEPT_STATS",
- "definition": "SELECT \n D.ID AS DEPT_ID,\n D.NAME AS DEPT_NAME,\n COUNT(E.ID) AS TOTAL_EMPLOYEES,\n NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,\n NVL(AVG(E.SALARY), 0) AS AVG_SALARY,\n NVL(MAX(E.SALARY), 0) AS MAX_SALARY,\n NVL(MIN(E.SALARY), 0) AS MIN_SALARY\nFROM DEPARTMENTS D\nLEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID\nGROUP BY D.ID, D.NAME\n",
- "comment": "snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "DEPARTMENTS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "EMPLOYEES",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "MV_DEPT_STATS",
- "column": "*"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "DEPARTMENTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "MANAGER_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_MANAGER",
- "columns": [
- "MANAGER_ID"
- ],
- "referencedTable": "EMPLOYEES",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "EMPLOYEES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "DEPARTMENT_ID",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "SALARY",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_DEPT",
- "columns": [
- "DEPARTMENT_ID"
- ],
- "referencedTable": "DEPARTMENTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_complex_view_dependencies.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_complex_view_dependencies.sql
deleted file mode 100644
index 5b433c3dea..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_complex_view_dependencies.sql
+++ /dev/null
@@ -1,35 +0,0 @@
-CREATE VIEW "DEPT_EMPLOYEE_COUNT" AS SELECT D.ID AS DEPT_ID, D.NAME AS DEPT_NAME, COUNT(E.ID) AS EMP_COUNT
-FROM DEPARTMENTS D
-LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
-GROUP BY D.ID, D.NAME;
-CREATE MATERIALIZED VIEW "MV_DEPT_STATS" AS SELECT
- D.ID AS DEPT_ID,
- D.NAME AS DEPT_NAME,
- COUNT(E.ID) AS TOTAL_EMPLOYEES,
- NVL(SUM(E.SALARY), 0) AS TOTAL_PAYROLL,
- NVL(AVG(E.SALARY), 0) AS AVG_SALARY,
- NVL(MAX(E.SALARY), 0) AS MAX_SALARY,
- NVL(MIN(E.SALARY), 0) AS MIN_SALARY
-FROM DEPARTMENTS D
-LEFT JOIN EMPLOYEES E ON D.ID = E.DEPARTMENT_ID
-GROUP BY D.ID, D.NAME
-;
-COMMENT ON MATERIALIZED VIEW "MV_DEPT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS';
-CREATE VIEW "DEPT_SUMMARY" AS SELECT
- DEC.DEPT_ID,
- DEC.DEPT_NAME,
- DEC.EMP_COUNT,
- NVL(AVG(E.SALARY), 0) AS AVG_SALARY
-FROM DEPT_EMPLOYEE_COUNT DEC
-LEFT JOIN EMPLOYEES E ON DEC.DEPT_ID = E.DEPARTMENT_ID
-GROUP BY DEC.DEPT_ID, DEC.DEPT_NAME, DEC.EMP_COUNT;
-CREATE VIEW "DEPT_MANAGER_SUMMARY" AS SELECT
- DS.DEPT_ID,
- DS.DEPT_NAME,
- DS.EMP_COUNT,
- DS.AVG_SALARY,
- M.NAME AS MANAGER_NAME
-FROM DEPT_SUMMARY DS
-JOIN DEPARTMENTS D ON DS.DEPT_ID = D.ID
-LEFT JOIN EMPLOYEES M ON D.MANAGER_ID = M.ID;
-COMMENT ON MATERIALIZED VIEW "MV_DEPT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.MV_DEPT_STATS';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_create_tables_with_fk.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_create_tables_with_fk.json
deleted file mode 100644
index 30ccde9b7c..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_create_tables_with_fk.json
+++ /dev/null
@@ -1,153 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {}
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "POSTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USER_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 3,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTENT",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PUBLISHED_AT",
- "position": 5,
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_USER_ID",
- "expressions": [
- "\"USER_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_USER",
- "columns": [
- "USER_ID"
- ],
- "referencedTable": "USERS",
- "referencedColumns": [
- "ID"
- ],
- "onDelete": "CASCADE"
- }
- ]
- },
- {
- "name": "USERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "USERNAME",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 4,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_USERNAME",
- "expressions": [
- "\"USERNAME\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "UK_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_create_tables_with_fk.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_create_tables_with_fk.sql
deleted file mode 100644
index e4807a7987..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_create_tables_with_fk.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-ALTER TABLE "POSTS" DROP CONSTRAINT "FK_USER";
-DROP TABLE "POSTS";
-DROP TABLE "USERS";
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_and_recreate_constraints.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_and_recreate_constraints.json
deleted file mode 100644
index 2cf84b7329..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_and_recreate_constraints.json
+++ /dev/null
@@ -1,317 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUTHORS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000002",
- "expressions": [
- "EMAIL"
- ],
- "unique": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "BOOKS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 2,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "AUTHOR_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "ISBN",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PUBLISHED_YEAR",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "PRICE",
- "position": 6,
- "nullable": true,
- "type": "NUMBER(8,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000004",
- "expressions": [
- "ISBN"
- ],
- "unique": true,
- "isConstraint": true
- },
- {
- "name": "IDX_BOOKS_AUTHOR",
- "expressions": [
- "\"AUTHOR_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_BOOKS_YEAR",
- "expressions": [
- "\"PUBLISHED_YEAR\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_AUTHOR_NEW",
- "columns": [
- "AUTHOR_ID"
- ],
- "referencedTable": "AUTHORS",
- "referencedColumns": [
- "ID"
- ],
- "onDelete": "CASCADE"
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_TITLE_LENGTH",
- "expression": "LENGTH(TITLE) \u003e= 3"
- },
- {
- "name": "CHECK_YEAR_EXTENDED",
- "expression": "PUBLISHED_YEAR \u003e= 1000 AND PUBLISHED_YEAR \u003c= 2030"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUTHORS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000002",
- "expressions": [
- "EMAIL"
- ],
- "unique": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "BOOKS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TITLE",
- "position": 2,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "AUTHOR_ID",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "ISBN",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PUBLISHED_YEAR",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "PRICE",
- "position": 6,
- "nullable": true,
- "type": "NUMBER(8,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "SYS_C0000004",
- "expressions": [
- "ISBN"
- ],
- "unique": true,
- "isConstraint": true
- },
- {
- "name": "IDX_BOOKS_AUTHOR",
- "expressions": [
- "\"AUTHOR_ID\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_BOOKS_YEAR",
- "expressions": [
- "\"PUBLISHED_YEAR\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_AUTHOR",
- "columns": [
- "AUTHOR_ID"
- ],
- "referencedTable": "AUTHORS",
- "referencedColumns": [
- "ID"
- ]
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_PRICE_POSITIVE",
- "expression": "PRICE \u003e 0"
- },
- {
- "name": "CHECK_YEAR_VALID",
- "expression": "PUBLISHED_YEAR \u003e= 1000 AND PUBLISHED_YEAR \u003c= 2100"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_and_recreate_constraints.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_and_recreate_constraints.sql
deleted file mode 100644
index 32f603894f..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_and_recreate_constraints.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-ALTER TABLE "BOOKS" DROP CONSTRAINT "FK_AUTHOR";
-ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_PRICE_POSITIVE";
-ALTER TABLE "BOOKS" DROP CONSTRAINT "CHECK_YEAR_VALID";
-
-ALTER TABLE "BOOKS" ADD CONSTRAINT "CHECK_TITLE_LENGTH" CHECK (LENGTH(TITLE) >= 3);
-ALTER TABLE "BOOKS" ADD CONSTRAINT "CHECK_YEAR_EXTENDED" CHECK (PUBLISHED_YEAR >= 1000 AND PUBLISHED_YEAR <= 2030);
-ALTER TABLE "BOOKS" ADD CONSTRAINT "FK_AUTHOR_NEW" FOREIGN KEY ("AUTHOR_ID") REFERENCES "AUTHORS" ("ID") ON DELETE CASCADE;
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_indexes_and_constraints.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_indexes_and_constraints.json
deleted file mode 100644
index d4b11dd1b1..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_indexes_and_constraints.json
+++ /dev/null
@@ -1,160 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SUPPLIER_ID",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SUPPLIER_ID",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_NAME",
- "expressions": [
- "\"NAME\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- },
- {
- "name": "IDX_PRODUCTS_PRICE",
- "expressions": [
- "\"PRICE\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHECK_NAME_LENGTH",
- "expression": "LENGTH(NAME) \u003e= 3"
- },
- {
- "name": "CHECK_PRICE_POSITIVE",
- "expression": "PRICE \u003e 0"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_indexes_and_constraints.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_indexes_and_constraints.sql
deleted file mode 100644
index 7e946d8d47..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_indexes_and_constraints.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_NAME_LENGTH";
-ALTER TABLE "PRODUCTS" DROP CONSTRAINT "CHECK_PRICE_POSITIVE";
-DROP INDEX "IDX_PRODUCTS_CATEGORY";
-DROP INDEX "IDX_PRODUCTS_NAME";
-DROP INDEX "IDX_PRODUCTS_PRICE";
-
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_sequence.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_sequence.json
deleted file mode 100644
index bc08990d30..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_sequence.json
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {}
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SIMPLE_LOG",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TRANSACTION_SEQ\".NEXTVAL",
- "type": "NUMBER"
- },
- {
- "name": "MESSAGE",
- "position": 2,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "sequences": [
- {
- "name": "TRANSACTION_SEQ"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_sequence.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_sequence.sql
deleted file mode 100644
index 4c67dd0864..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_sequence.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-DROP TABLE "SIMPLE_LOG";
-DROP SEQUENCE "TRANSACTION_SEQ";
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_views_and_functions.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_views_and_functions.json
deleted file mode 100644
index 57b20b2789..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_views_and_functions.json
+++ /dev/null
@@ -1,160 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "SALE_AMOUNT",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SALE_DATE",
- "position": 4,
- "type": "DATE"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "SALES",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "SALE_AMOUNT",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "SALE_DATE",
- "position": 4,
- "type": "DATE"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "views": [
- {
- "name": "MONTHLY_SALES",
- "definition": "SELECT \n EXTRACT(YEAR FROM SALE_DATE) AS YEAR_VAL,\n EXTRACT(MONTH FROM SALE_DATE) AS MONTH_VAL,\n SUM(SALE_AMOUNT) AS TOTAL_SALES\nFROM SALES\nGROUP BY EXTRACT(YEAR FROM SALE_DATE), EXTRACT(MONTH FROM SALE_DATE)",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "SALES",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "YEAR_VAL",
- "position": 1,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "MONTH_VAL",
- "position": 2,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL_SALES",
- "position": 3,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- }
- ],
- "functions": [
- {
- "name": "CALCULATE_DISCOUNT",
- "definition": "FUNCTION CALCULATE_DISCOUNT(AMOUNT NUMBER)\nRETURN NUMBER\nIS\nBEGIN\n RETURN AMOUNT * 0.1;\nEND;"
- },
- {
- "name": "GET_MONTHLY_TOTAL",
- "definition": "FUNCTION GET_MONTHLY_TOTAL(YEAR_PARAM NUMBER, MONTH_PARAM NUMBER)\nRETURN NUMBER\nIS\n V_TOTAL NUMBER;\nBEGIN\n SELECT NVL(SUM(SALE_AMOUNT), 0) INTO V_TOTAL\n FROM SALES\n WHERE EXTRACT(YEAR FROM SALE_DATE) = YEAR_PARAM\n AND EXTRACT(MONTH FROM SALE_DATE) = MONTH_PARAM;\n \n RETURN V_TOTAL;\nEND;"
- }
- ],
- "materializedViews": [
- {
- "name": "TOP_PRODUCTS",
- "definition": "SELECT \n PRODUCT_NAME,\n COUNT(*) AS SALE_COUNT,\n SUM(SALE_AMOUNT) AS TOTAL_REVENUE\nFROM SALES\nGROUP BY PRODUCT_NAME\n",
- "comment": "snapshot table for snapshot TESTSCHEMA.TOP_PRODUCTS",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "SALES",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "TOP_PRODUCTS",
- "column": "*"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_views_and_functions.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_views_and_functions.sql
deleted file mode 100644
index f3ad02cb5f..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_drop_views_and_functions.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-DROP FUNCTION "CALCULATE_DISCOUNT";
-DROP FUNCTION "GET_MONTHLY_TOTAL";
-DROP VIEW "MONTHLY_SALES";
-DROP MATERIALIZED VIEW "TOP_PRODUCTS";
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_edge_case_column_operations.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_edge_case_column_operations.json
deleted file mode 100644
index a71e191f17..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_edge_case_column_operations.json
+++ /dev/null
@@ -1,161 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "TEST_COLUMNS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "COL_VARCHAR",
- "position": 2,
- "type": "VARCHAR2(200 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_NUMBER",
- "position": 3,
- "nullable": true,
- "type": "NUMBER(15,3)"
- },
- {
- "name": "COL_DATE",
- "position": 4,
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "COL_NULLABLE",
- "position": 5,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_WITH_DEFAULT",
- "position": 6,
- "default": "'NEW_DEFAULT'",
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_TIMESTAMP",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "COL_BOOLEAN",
- "position": 8,
- "nullable": true,
- "type": "NUMBER(1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "checkConstraints": [
- {
- "name": "CHK_NUMBER_POSITIVE",
- "expression": "COL_NUMBER \u003e 0"
- },
- {
- "name": "CHK_VARCHAR_LENGTH",
- "expression": "LENGTH(COL_VARCHAR) \u003e= 5"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "TEST_COLUMNS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "COL_VARCHAR",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_NUMBER",
- "position": 3,
- "nullable": true,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "COL_DATE",
- "position": 4,
- "nullable": true,
- "type": "DATE"
- },
- {
- "name": "COL_NULLABLE",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_WITH_DEFAULT",
- "position": 6,
- "default": "'DEFAULT_VALUE'",
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "COL_CLOB",
- "position": 7,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_edge_case_column_operations.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_edge_case_column_operations.sql
deleted file mode 100644
index d33be2738c..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_edge_case_column_operations.sql
+++ /dev/null
@@ -1,11 +0,0 @@
-ALTER TABLE "TEST_COLUMNS" DROP COLUMN "COL_CLOB";
-
-ALTER TABLE "TEST_COLUMNS" ADD "COL_TIMESTAMP" TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP;
-ALTER TABLE "TEST_COLUMNS" ADD "COL_BOOLEAN" NUMBER(1);
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_VARCHAR" VARCHAR2(200 BYTE);
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NUMBER" NUMBER(15,3);
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_NULLABLE" NOT NULL;
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT NULL;
-ALTER TABLE "TEST_COLUMNS" MODIFY "COL_WITH_DEFAULT" DEFAULT 'NEW_DEFAULT';
-ALTER TABLE "TEST_COLUMNS" ADD CONSTRAINT "CHK_NUMBER_POSITIVE" CHECK (COL_NUMBER > 0);
-ALTER TABLE "TEST_COLUMNS" ADD CONSTRAINT "CHK_VARCHAR_LENGTH" CHECK (LENGTH(COL_VARCHAR) >= 5);
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_modify_and_drop_comments.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_modify_and_drop_comments.json
deleted file mode 100644
index e78581b3ed..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_modify_and_drop_comments.json
+++ /dev/null
@@ -1,246 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "INVENTORY",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_CODE",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Updated: Standardized product SKU following new naming convention"
- },
- {
- "name": "STOCK_LEVEL",
- "position": 3,
- "type": "NUMBER",
- "comment": "Updated: Real-time stock quantity with automated updates"
- },
- {
- "name": "MIN_STOCK",
- "position": 4,
- "default": "10",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Updated: Dynamic minimum threshold based on sales velocity"
- },
- {
- "name": "MAX_STOCK",
- "position": 5,
- "default": "1000",
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "WAREHOUSE_ID",
- "position": 6,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "LAST_UPDATED",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)",
- "comment": "Timestamp of last inventory update or modification"
- },
- {
- "name": "REORDER_POINT",
- "position": 8,
- "default": "0",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Calculated reorder point based on lead time and demand"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Updated inventory management system with enhanced tracking capabilities"
- },
- {
- "name": "SUPPLIERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTACT_EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "RATING",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(2,1)",
- "comment": "Supplier performance rating (1.0 to 5.0 scale)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "INVENTORY",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_CODE",
- "position": 2,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Product identification code"
- },
- {
- "name": "STOCK_LEVEL",
- "position": 3,
- "type": "NUMBER",
- "comment": "Current stock quantity"
- },
- {
- "name": "MIN_STOCK",
- "position": 4,
- "default": "10",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Minimum stock threshold"
- },
- {
- "name": "MAX_STOCK",
- "position": 5,
- "default": "1000",
- "nullable": true,
- "type": "NUMBER",
- "comment": "Maximum stock capacity"
- },
- {
- "name": "WAREHOUSE_ID",
- "position": 6,
- "nullable": true,
- "type": "NUMBER",
- "comment": "Warehouse location identifier"
- },
- {
- "name": "LAST_UPDATED",
- "position": 7,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Initial inventory tracking table"
- },
- {
- "name": "SUPPLIERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CONTACT_EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Primary contact email"
- },
- {
- "name": "RATING",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(2,1)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Supplier information table"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_modify_and_drop_comments.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_modify_and_drop_comments.sql
deleted file mode 100644
index e0a610d5eb..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_modify_and_drop_comments.sql
+++ /dev/null
@@ -1,21 +0,0 @@
-ALTER TABLE "INVENTORY" ADD "REORDER_POINT" NUMBER DEFAULT 0;
-COMMENT ON TABLE "INVENTORY" IS 'Updated inventory management system with enhanced tracking capabilities';
-COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Updated: Standardized product SKU following new naming convention';
-COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Updated: Real-time stock quantity with automated updates';
-COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Updated: Dynamic minimum threshold based on sales velocity';
-COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS '';
-COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS '';
-COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS 'Timestamp of last inventory update or modification';
-COMMENT ON COLUMN "INVENTORY"."REORDER_POINT" IS 'Calculated reorder point based on lead time and demand';
-COMMENT ON COLUMN "INVENTORY"."PRODUCT_CODE" IS 'Updated: Standardized product SKU following new naming convention';
-COMMENT ON COLUMN "INVENTORY"."STOCK_LEVEL" IS 'Updated: Real-time stock quantity with automated updates';
-COMMENT ON COLUMN "INVENTORY"."MIN_STOCK" IS 'Updated: Dynamic minimum threshold based on sales velocity';
-COMMENT ON COLUMN "INVENTORY"."MAX_STOCK" IS '';
-COMMENT ON COLUMN "INVENTORY"."WAREHOUSE_ID" IS '';
-COMMENT ON COLUMN "INVENTORY"."LAST_UPDATED" IS 'Timestamp of last inventory update or modification';
-COMMENT ON COLUMN "INVENTORY"."REORDER_POINT" IS 'Calculated reorder point based on lead time and demand';
-COMMENT ON TABLE "SUPPLIERS" IS '';
-COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS '';
-COMMENT ON COLUMN "SUPPLIERS"."RATING" IS 'Supplier performance rating (1.0 to 5.0 scale)';
-COMMENT ON COLUMN "SUPPLIERS"."CONTACT_EMAIL" IS '';
-COMMENT ON COLUMN "SUPPLIERS"."RATING" IS 'Supplier performance rating (1.0 to 5.0 scale)';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_sequences.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_sequences.json
deleted file mode 100644
index 595f2066cb..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_sequences.json
+++ /dev/null
@@ -1,125 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ITEMS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "SALES_ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"ORDER_SEQ\".NEXTVAL",
- "type": "NUMBER"
- },
- {
- "name": "ITEM_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "QUANTITY",
- "position": 3,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_ITEM",
- "columns": [
- "ITEM_ID"
- ],
- "referencedTable": "ITEMS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- }
- ],
- "sequences": [
- {
- "name": "ORDER_SEQ"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ITEMS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_sequences.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_sequences.sql
deleted file mode 100644
index 9004932b64..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_sequences.sql
+++ /dev/null
@@ -1,9 +0,0 @@
-CREATE SEQUENCE "ORDER_SEQ";
-CREATE TABLE "SALES_ORDERS" (
- "ID" NUMBER DEFAULT "ORDER_SEQ".NEXTVAL NOT NULL,
- "ITEM_ID" NUMBER NOT NULL,
- "QUANTITY" NUMBER NOT NULL
-);
-ALTER TABLE "SALES_ORDERS" ADD CONSTRAINT "SYS_C0000002" PRIMARY KEY (ID);
-
-ALTER TABLE "SALES_ORDERS" ADD CONSTRAINT "FK_ITEM" FOREIGN KEY ("ITEM_ID") REFERENCES "ITEMS" ("ID");
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_stored_procedures_and_functions.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_stored_procedures_and_functions.json
deleted file mode 100644
index 7cdcd51976..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_stored_procedures_and_functions.json
+++ /dev/null
@@ -1,164 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUDIT_LOG",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TABLE_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OPERATION",
- "position": 3,
- "type": "VARCHAR2(10 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OLD_VALUES",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "NEW_VALUES",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TIMESTAMP",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "USER_NAME",
- "position": 7,
- "default": "USER",
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "functions": [
- {
- "name": "CALCULATE_BUSINESS_DAYS",
- "definition": "FUNCTION CALCULATE_BUSINESS_DAYS(\n P_START_DATE DATE,\n P_END_DATE DATE\n) RETURN NUMBER\nIS\n V_DAYS NUMBER := 0;\n V_CURRENT_DATE DATE := P_START_DATE;\nBEGIN\n WHILE V_CURRENT_DATE \u003c= P_END_DATE LOOP\n -- Skip weekends (Saturday = 7, Sunday = 1)\n IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN\n V_DAYS := V_DAYS + 1;\n END IF;\n V_CURRENT_DATE := V_CURRENT_DATE + 1;\n END LOOP;\n \n RETURN V_DAYS;\nEND;"
- },
- {
- "name": "GET_AUDIT_COUNT",
- "definition": "FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER\nIS\n V_COUNT NUMBER;\nBEGIN\n SELECT COUNT(*) INTO V_COUNT\n FROM AUDIT_LOG\n WHERE TABLE_NAME = P_TABLE_NAME;\n \n RETURN V_COUNT;\nEND;"
- }
- ],
- "procedures": [
- {
- "name": "LOG_AUDIT",
- "definition": "PROCEDURE LOG_AUDIT(\n P_TABLE_NAME VARCHAR2,\n P_OPERATION VARCHAR2,\n P_OLD_VALUES CLOB DEFAULT NULL,\n P_NEW_VALUES CLOB DEFAULT NULL\n)\nIS\nBEGIN\n INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)\n VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);\n COMMIT;\nEXCEPTION\n WHEN OTHERS THEN\n ROLLBACK;\n RAISE;\nEND;"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUDIT_LOG",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TABLE_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OPERATION",
- "position": 3,
- "type": "VARCHAR2(10 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OLD_VALUES",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "NEW_VALUES",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TIMESTAMP",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "USER_NAME",
- "position": 7,
- "default": "USER",
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_stored_procedures_and_functions.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_stored_procedures_and_functions.sql
deleted file mode 100644
index 104a896c6f..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_stored_procedures_and_functions.sql
+++ /dev/null
@@ -1,47 +0,0 @@
-CREATE OR REPLACE FUNCTION CALCULATE_BUSINESS_DAYS(
- P_START_DATE DATE,
- P_END_DATE DATE
-) RETURN NUMBER
-IS
- V_DAYS NUMBER := 0;
- V_CURRENT_DATE DATE := P_START_DATE;
-BEGIN
- WHILE V_CURRENT_DATE <= P_END_DATE LOOP
- -- Skip weekends (Saturday = 7, Sunday = 1)
- IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN
- V_DAYS := V_DAYS + 1;
- END IF;
- V_CURRENT_DATE := V_CURRENT_DATE + 1;
- END LOOP;
-
- RETURN V_DAYS;
-END;
-
-CREATE OR REPLACE FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER
-IS
- V_COUNT NUMBER;
-BEGIN
- SELECT COUNT(*) INTO V_COUNT
- FROM AUDIT_LOG
- WHERE TABLE_NAME = P_TABLE_NAME;
-
- RETURN V_COUNT;
-END;
-
-CREATE OR REPLACE PROCEDURE LOG_AUDIT(
- P_TABLE_NAME VARCHAR2,
- P_OPERATION VARCHAR2,
- P_OLD_VALUES CLOB DEFAULT NULL,
- P_NEW_VALUES CLOB DEFAULT NULL
-)
-IS
-BEGIN
- INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)
- VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);
- COMMIT;
-EXCEPTION
- WHEN OTHERS THEN
- ROLLBACK;
- RAISE;
-END;
-
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_table_and_column_comments.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_table_and_column_comments.json
deleted file mode 100644
index dda769f17c..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_table_and_column_comments.json
+++ /dev/null
@@ -1,375 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER",
- "comment": "Primary key for customer records"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Full name of the customer"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Customer email address (unique)"
- },
- {
- "name": "PHONE",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Contact phone number"
- },
- {
- "name": "ADDRESS",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "Full mailing address with multiple lines"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_CUSTOMERS_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- }
- ],
- "comment": "Customer information and contact details"
- },
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER",
- "comment": "Unique order identifier"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 2,
- "type": "NUMBER",
- "comment": "Reference to customer who placed the order"
- },
- {
- "name": "PRODUCT_ID",
- "position": 3,
- "type": "NUMBER",
- "comment": "Reference to ordered product"
- },
- {
- "name": "ORDER_DATE",
- "position": 4,
- "default": "SYSDATE",
- "nullable": true,
- "type": "DATE",
- "comment": "Date when the order was placed"
- },
- {
- "name": "QUANTITY",
- "position": 5,
- "type": "NUMBER",
- "comment": "Number of items ordered"
- },
- {
- "name": "TOTAL_AMOUNT",
- "position": 6,
- "nullable": true,
- "type": "NUMBER(12,2)",
- "comment": "Total order amount including taxes"
- },
- {
- "name": "STATUS",
- "position": 7,
- "default": "'PENDING'",
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Customer orders linking products and customers",
- "foreignKeys": [
- {
- "name": "FK_ORDER_CUSTOMER",
- "columns": [
- "CUSTOMER_ID"
- ],
- "referencedTable": "CUSTOMERS",
- "referencedColumns": [
- "ID"
- ]
- },
- {
- "name": "FK_ORDER_PRODUCT",
- "columns": [
- "PRODUCT_ID"
- ],
- "referencedTable": "PRODUCTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER",
- "comment": "Unique product identifier (auto-generated)"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Product name - must be unique and descriptive"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)",
- "comment": "Product price in USD with 2 decimal places"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "Detailed product description with HTML formatting support"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Product category for filtering and organization"
- },
- {
- "name": "CREATED_AT",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)",
- "comment": "Timestamp when the product was added to catalog"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "comment": "Product catalog table containing all product information"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PHONE",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "ADDRESS",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_CUSTOMERS_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_table_and_column_comments.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_table_and_column_comments.sql
deleted file mode 100644
index 93cafc8d18..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_table_and_column_comments.sql
+++ /dev/null
@@ -1,45 +0,0 @@
-CREATE TABLE "ORDERS" (
- "ID" NUMBER DEFAULT "TESTSCHEMA"."ISEQ$$_0000002".nextval NOT NULL,
- "CUSTOMER_ID" NUMBER NOT NULL,
- "PRODUCT_ID" NUMBER NOT NULL,
- "ORDER_DATE" DATE DEFAULT SYSDATE,
- "QUANTITY" NUMBER NOT NULL,
- "TOTAL_AMOUNT" NUMBER(12,2),
- "STATUS" VARCHAR2(20 BYTE) DEFAULT 'PENDING'
-);
-ALTER TABLE "ORDERS" ADD CONSTRAINT "SYS_C0000002" PRIMARY KEY (ID);
-COMMENT ON TABLE "ORDERS" IS 'Customer orders linking products and customers';
-COMMENT ON COLUMN "ORDERS"."ID" IS 'Unique order identifier';
-COMMENT ON COLUMN "ORDERS"."CUSTOMER_ID" IS 'Reference to customer who placed the order';
-COMMENT ON COLUMN "ORDERS"."PRODUCT_ID" IS 'Reference to ordered product';
-COMMENT ON COLUMN "ORDERS"."ORDER_DATE" IS 'Date when the order was placed';
-COMMENT ON COLUMN "ORDERS"."QUANTITY" IS 'Number of items ordered';
-COMMENT ON COLUMN "ORDERS"."TOTAL_AMOUNT" IS 'Total order amount including taxes';
-COMMENT ON COLUMN "ORDERS"."STATUS" IS 'Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)';
-
-ALTER TABLE "ORDERS" ADD CONSTRAINT "FK_ORDER_CUSTOMER" FOREIGN KEY ("CUSTOMER_ID") REFERENCES "CUSTOMERS" ("ID");
-ALTER TABLE "ORDERS" ADD CONSTRAINT "FK_ORDER_PRODUCT" FOREIGN KEY ("PRODUCT_ID") REFERENCES "PRODUCTS" ("ID");
-COMMENT ON TABLE "CUSTOMERS" IS 'Customer information and contact details';
-COMMENT ON COLUMN "CUSTOMERS"."ID" IS 'Primary key for customer records';
-COMMENT ON COLUMN "CUSTOMERS"."NAME" IS 'Full name of the customer';
-COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS 'Customer email address (unique)';
-COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS 'Contact phone number';
-COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS 'Full mailing address with multiple lines';
-COMMENT ON COLUMN "CUSTOMERS"."ID" IS 'Primary key for customer records';
-COMMENT ON COLUMN "CUSTOMERS"."NAME" IS 'Full name of the customer';
-COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS 'Customer email address (unique)';
-COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS 'Contact phone number';
-COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS 'Full mailing address with multiple lines';
-COMMENT ON TABLE "PRODUCTS" IS 'Product catalog table containing all product information';
-COMMENT ON COLUMN "PRODUCTS"."ID" IS 'Unique product identifier (auto-generated)';
-COMMENT ON COLUMN "PRODUCTS"."NAME" IS 'Product name - must be unique and descriptive';
-COMMENT ON COLUMN "PRODUCTS"."PRICE" IS 'Product price in USD with 2 decimal places';
-COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS 'Detailed product description with HTML formatting support';
-COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS 'Product category for filtering and organization';
-COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS 'Timestamp when the product was added to catalog';
-COMMENT ON COLUMN "PRODUCTS"."ID" IS 'Unique product identifier (auto-generated)';
-COMMENT ON COLUMN "PRODUCTS"."NAME" IS 'Product name - must be unique and descriptive';
-COMMENT ON COLUMN "PRODUCTS"."PRICE" IS 'Product price in USD with 2 decimal places';
-COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS 'Detailed product description with HTML formatting support';
-COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS 'Product category for filtering and organization';
-COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS 'Timestamp when the product was added to catalog';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_views_and_functions.json b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_views_and_functions.json
deleted file mode 100644
index 9adedffec1..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_views_and_functions.json
+++ /dev/null
@@ -1,275 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "QUANTITY",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_PRODUCT",
- "columns": [
- "PRODUCT_ID"
- ],
- "referencedTable": "PRODUCTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "STOCK",
- "position": 4,
- "default": "0",
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "views": [
- {
- "name": "PRODUCT_INVENTORY",
- "definition": "SELECT \n P.ID,\n P.NAME,\n P.PRICE,\n P.STOCK,\n NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED\nFROM PRODUCTS P\nLEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID\nGROUP BY P.ID, P.NAME, P.PRICE, P.STOCK",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "ORDERS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "PRODUCTS",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "STOCK",
- "position": 4,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL_ORDERED",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- }
- ],
- "functions": [
- {
- "name": "CALCULATE_ORDER_TOTAL",
- "definition": "FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)\nRETURN NUMBER\nIS\n V_PRICE NUMBER(10, 2);\nBEGIN\n SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;\n RETURN P_QUANTITY * V_PRICE;\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN 0;\nEND;"
- }
- ],
- "materializedViews": [
- {
- "name": "PRODUCT_STATS",
- "definition": "SELECT \n PRODUCT_ID,\n COUNT(*) AS ORDER_COUNT,\n SUM(QUANTITY) AS TOTAL_QUANTITY,\n SUM(TOTAL) AS TOTAL_REVENUE\nFROM ORDERS\nGROUP BY PRODUCT_ID\n",
- "comment": "snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "ORDERS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "PRODUCT_STATS",
- "column": "*"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "QUANTITY",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_PRODUCT",
- "columns": [
- "PRODUCT_ID"
- ],
- "referencedTable": "PRODUCTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "STOCK",
- "position": 4,
- "default": "0",
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_views_and_functions.sql b/backend/plugin/schema/oracle/testdata/generate_migration/reverse_views_and_functions.sql
deleted file mode 100644
index 5faa18b5b8..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/reverse_views_and_functions.sql
+++ /dev/null
@@ -1,31 +0,0 @@
-CREATE OR REPLACE FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)
-RETURN NUMBER
-IS
- V_PRICE NUMBER(10, 2);
-BEGIN
- SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;
- RETURN P_QUANTITY * V_PRICE;
-EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RETURN 0;
-END;
-
-CREATE VIEW "PRODUCT_INVENTORY" AS SELECT
- P.ID,
- P.NAME,
- P.PRICE,
- P.STOCK,
- NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED
-FROM PRODUCTS P
-LEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID
-GROUP BY P.ID, P.NAME, P.PRICE, P.STOCK;
-CREATE MATERIALIZED VIEW "PRODUCT_STATS" AS SELECT
- PRODUCT_ID,
- COUNT(*) AS ORDER_COUNT,
- SUM(QUANTITY) AS TOTAL_QUANTITY,
- SUM(TOTAL) AS TOTAL_REVENUE
-FROM ORDERS
-GROUP BY PRODUCT_ID
-;
-COMMENT ON MATERIALIZED VIEW "PRODUCT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS';
-COMMENT ON MATERIALIZED VIEW "PRODUCT_STATS" IS 'snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/sequences.json b/backend/plugin/schema/oracle/testdata/generate_migration/sequences.json
deleted file mode 100644
index 57324d8b73..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/sequences.json
+++ /dev/null
@@ -1,125 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ITEMS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ITEMS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- },
- {
- "name": "SALES_ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"ORDER_SEQ\".NEXTVAL",
- "type": "NUMBER"
- },
- {
- "name": "ITEM_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "QUANTITY",
- "position": 3,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_ITEM",
- "columns": [
- "ITEM_ID"
- ],
- "referencedTable": "ITEMS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- }
- ],
- "sequences": [
- {
- "name": "ORDER_SEQ"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/sequences.sql b/backend/plugin/schema/oracle/testdata/generate_migration/sequences.sql
deleted file mode 100644
index a8cbdfcf56..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/sequences.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-DROP SEQUENCE "ORDER_SEQ";
-ALTER TABLE "SALES_ORDERS" DROP CONSTRAINT "FK_ITEM";
-DROP TABLE "SALES_ORDERS";
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/stored_procedures_and_functions.json b/backend/plugin/schema/oracle/testdata/generate_migration/stored_procedures_and_functions.json
deleted file mode 100644
index 65c0dc8a0a..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/stored_procedures_and_functions.json
+++ /dev/null
@@ -1,164 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUDIT_LOG",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TABLE_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OPERATION",
- "position": 3,
- "type": "VARCHAR2(10 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OLD_VALUES",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "NEW_VALUES",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TIMESTAMP",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "USER_NAME",
- "position": 7,
- "default": "USER",
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "AUDIT_LOG",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "TABLE_NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OPERATION",
- "position": 3,
- "type": "VARCHAR2(10 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "OLD_VALUES",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "NEW_VALUES",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "TIMESTAMP",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- },
- {
- "name": "USER_NAME",
- "position": 7,
- "default": "USER",
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "functions": [
- {
- "name": "CALCULATE_BUSINESS_DAYS",
- "definition": "FUNCTION CALCULATE_BUSINESS_DAYS(\n P_START_DATE DATE,\n P_END_DATE DATE\n) RETURN NUMBER\nIS\n V_DAYS NUMBER := 0;\n V_CURRENT_DATE DATE := P_START_DATE;\nBEGIN\n WHILE V_CURRENT_DATE \u003c= P_END_DATE LOOP\n -- Skip weekends (Saturday = 7, Sunday = 1)\n IF TO_CHAR(V_CURRENT_DATE, 'D') NOT IN ('1', '7') THEN\n V_DAYS := V_DAYS + 1;\n END IF;\n V_CURRENT_DATE := V_CURRENT_DATE + 1;\n END LOOP;\n \n RETURN V_DAYS;\nEND;"
- },
- {
- "name": "GET_AUDIT_COUNT",
- "definition": "FUNCTION GET_AUDIT_COUNT(P_TABLE_NAME VARCHAR2) RETURN NUMBER\nIS\n V_COUNT NUMBER;\nBEGIN\n SELECT COUNT(*) INTO V_COUNT\n FROM AUDIT_LOG\n WHERE TABLE_NAME = P_TABLE_NAME;\n \n RETURN V_COUNT;\nEND;"
- }
- ],
- "procedures": [
- {
- "name": "LOG_AUDIT",
- "definition": "PROCEDURE LOG_AUDIT(\n P_TABLE_NAME VARCHAR2,\n P_OPERATION VARCHAR2,\n P_OLD_VALUES CLOB DEFAULT NULL,\n P_NEW_VALUES CLOB DEFAULT NULL\n)\nIS\nBEGIN\n INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)\n VALUES (P_TABLE_NAME, P_OPERATION, P_OLD_VALUES, P_NEW_VALUES);\n COMMIT;\nEXCEPTION\n WHEN OTHERS THEN\n ROLLBACK;\n RAISE;\nEND;"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/stored_procedures_and_functions.sql b/backend/plugin/schema/oracle/testdata/generate_migration/stored_procedures_and_functions.sql
deleted file mode 100644
index 3dc103be38..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/stored_procedures_and_functions.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-DROP FUNCTION "CALCULATE_BUSINESS_DAYS";
-DROP FUNCTION "GET_AUDIT_COUNT";
-DROP PROCEDURE "LOG_AUDIT";
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/table_and_column_comments.json b/backend/plugin/schema/oracle/testdata/generate_migration/table_and_column_comments.json
deleted file mode 100644
index 1b5e4aaa68..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/table_and_column_comments.json
+++ /dev/null
@@ -1,375 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PHONE",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "ADDRESS",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_CUSTOMERS_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "CREATED_AT",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "CUSTOMERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER",
- "comment": "Primary key for customer records"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Full name of the customer"
- },
- {
- "name": "EMAIL",
- "position": 3,
- "nullable": true,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Customer email address (unique)"
- },
- {
- "name": "PHONE",
- "position": 4,
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Contact phone number"
- },
- {
- "name": "ADDRESS",
- "position": 5,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "Full mailing address with multiple lines"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_CUSTOMERS_EMAIL",
- "expressions": [
- "\"EMAIL\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "unique": true,
- "visible": true
- }
- ],
- "comment": "Customer information and contact details"
- },
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000003\".nextval",
- "type": "NUMBER",
- "comment": "Unique order identifier"
- },
- {
- "name": "CUSTOMER_ID",
- "position": 2,
- "type": "NUMBER",
- "comment": "Reference to customer who placed the order"
- },
- {
- "name": "PRODUCT_ID",
- "position": 3,
- "type": "NUMBER",
- "comment": "Reference to ordered product"
- },
- {
- "name": "ORDER_DATE",
- "position": 4,
- "default": "SYSDATE",
- "nullable": true,
- "type": "DATE",
- "comment": "Date when the order was placed"
- },
- {
- "name": "QUANTITY",
- "position": 5,
- "type": "NUMBER",
- "comment": "Number of items ordered"
- },
- {
- "name": "TOTAL_AMOUNT",
- "position": 6,
- "nullable": true,
- "type": "NUMBER(12,2)",
- "comment": "Total order amount including taxes"
- },
- {
- "name": "STATUS",
- "position": 7,
- "default": "'PENDING'",
- "nullable": true,
- "type": "VARCHAR2(20 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Current order status (PENDING, SHIPPED, DELIVERED, CANCELLED)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000003",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "comment": "Customer orders linking products and customers",
- "foreignKeys": [
- {
- "name": "FK_ORDER_CUSTOMER",
- "columns": [
- "CUSTOMER_ID"
- ],
- "referencedTable": "CUSTOMERS",
- "referencedColumns": [
- "ID"
- ]
- },
- {
- "name": "FK_ORDER_PRODUCT",
- "columns": [
- "PRODUCT_ID"
- ],
- "referencedTable": "PRODUCTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER",
- "comment": "Unique product identifier (auto-generated)"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Product name - must be unique and descriptive"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)",
- "comment": "Product price in USD with 2 decimal places"
- },
- {
- "name": "DESCRIPTION",
- "position": 4,
- "nullable": true,
- "type": "CLOB",
- "collation": "USING_NLS_COMP",
- "comment": "Detailed product description with HTML formatting support"
- },
- {
- "name": "CATEGORY",
- "position": 5,
- "nullable": true,
- "type": "VARCHAR2(50 BYTE)",
- "collation": "USING_NLS_COMP",
- "comment": "Product category for filtering and organization"
- },
- {
- "name": "CREATED_AT",
- "position": 6,
- "default": "CURRENT_TIMESTAMP",
- "nullable": true,
- "type": "TIMESTAMP(6)",
- "comment": "Timestamp when the product was added to catalog"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- },
- {
- "name": "IDX_PRODUCTS_CATEGORY",
- "expressions": [
- "\"CATEGORY\""
- ],
- "descending": [
- false
- ],
- "type": "NORMAL",
- "visible": true
- }
- ],
- "comment": "Product catalog table containing all product information"
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/table_and_column_comments.sql b/backend/plugin/schema/oracle/testdata/generate_migration/table_and_column_comments.sql
deleted file mode 100644
index bf6ac43e8d..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/table_and_column_comments.sql
+++ /dev/null
@@ -1,28 +0,0 @@
-ALTER TABLE "ORDERS" DROP CONSTRAINT "FK_ORDER_CUSTOMER";
-ALTER TABLE "ORDERS" DROP CONSTRAINT "FK_ORDER_PRODUCT";
-DROP TABLE "ORDERS";
-
-COMMENT ON TABLE "CUSTOMERS" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."ID" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."NAME" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."ID" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."NAME" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."EMAIL" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."PHONE" IS '';
-COMMENT ON COLUMN "CUSTOMERS"."ADDRESS" IS '';
-COMMENT ON TABLE "PRODUCTS" IS '';
-COMMENT ON COLUMN "PRODUCTS"."ID" IS '';
-COMMENT ON COLUMN "PRODUCTS"."NAME" IS '';
-COMMENT ON COLUMN "PRODUCTS"."PRICE" IS '';
-COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS '';
-COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS '';
-COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS '';
-COMMENT ON COLUMN "PRODUCTS"."ID" IS '';
-COMMENT ON COLUMN "PRODUCTS"."NAME" IS '';
-COMMENT ON COLUMN "PRODUCTS"."PRICE" IS '';
-COMMENT ON COLUMN "PRODUCTS"."DESCRIPTION" IS '';
-COMMENT ON COLUMN "PRODUCTS"."CATEGORY" IS '';
-COMMENT ON COLUMN "PRODUCTS"."CREATED_AT" IS '';
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/views_and_functions.json b/backend/plugin/schema/oracle/testdata/generate_migration/views_and_functions.json
deleted file mode 100644
index 959cb4d9ba..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/views_and_functions.json
+++ /dev/null
@@ -1,275 +0,0 @@
-{
- "schemaA": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "QUANTITY",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_PRODUCT",
- "columns": [
- "PRODUCT_ID"
- ],
- "referencedTable": "PRODUCTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "STOCK",
- "position": 4,
- "default": "0",
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- },
- "schemaB": {
- "name": "TESTSCHEMA",
- "schemas": [
- {
- "tables": [
- {
- "name": "ORDERS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000001\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "PRODUCT_ID",
- "position": 2,
- "type": "NUMBER"
- },
- {
- "name": "QUANTITY",
- "position": 3,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL",
- "position": 4,
- "nullable": true,
- "type": "NUMBER(10,2)"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000001",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ],
- "foreignKeys": [
- {
- "name": "FK_PRODUCT",
- "columns": [
- "PRODUCT_ID"
- ],
- "referencedTable": "PRODUCTS",
- "referencedColumns": [
- "ID"
- ]
- }
- ]
- },
- {
- "name": "PRODUCTS",
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "default": "\"TESTSCHEMA\".\"ISEQ$$_0000002\".nextval",
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "STOCK",
- "position": 4,
- "default": "0",
- "nullable": true,
- "type": "NUMBER"
- }
- ],
- "indexes": [
- {
- "name": "SYS_C0000002",
- "expressions": [
- "ID"
- ],
- "unique": true,
- "primary": true,
- "isConstraint": true
- }
- ]
- }
- ],
- "views": [
- {
- "name": "PRODUCT_INVENTORY",
- "definition": "SELECT \n P.ID,\n P.NAME,\n P.PRICE,\n P.STOCK,\n NVL(SUM(O.QUANTITY), 0) AS TOTAL_ORDERED\nFROM PRODUCTS P\nLEFT JOIN ORDERS O ON P.ID = O.PRODUCT_ID\nGROUP BY P.ID, P.NAME, P.PRICE, P.STOCK",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "ORDERS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "PRODUCTS",
- "column": "*"
- }
- ],
- "columns": [
- {
- "name": "ID",
- "position": 1,
- "type": "NUMBER"
- },
- {
- "name": "NAME",
- "position": 2,
- "type": "VARCHAR2(100 BYTE)",
- "collation": "USING_NLS_COMP"
- },
- {
- "name": "PRICE",
- "position": 3,
- "type": "NUMBER(10,2)"
- },
- {
- "name": "STOCK",
- "position": 4,
- "nullable": true,
- "type": "NUMBER"
- },
- {
- "name": "TOTAL_ORDERED",
- "position": 5,
- "nullable": true,
- "type": "NUMBER"
- }
- ]
- }
- ],
- "functions": [
- {
- "name": "CALCULATE_ORDER_TOTAL",
- "definition": "FUNCTION CALCULATE_ORDER_TOTAL(P_PRODUCT_ID NUMBER, P_QUANTITY NUMBER)\nRETURN NUMBER\nIS\n V_PRICE NUMBER(10, 2);\nBEGIN\n SELECT PRICE INTO V_PRICE FROM PRODUCTS WHERE ID = P_PRODUCT_ID;\n RETURN P_QUANTITY * V_PRICE;\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN 0;\nEND;"
- }
- ],
- "materializedViews": [
- {
- "name": "PRODUCT_STATS",
- "definition": "SELECT \n PRODUCT_ID,\n COUNT(*) AS ORDER_COUNT,\n SUM(QUANTITY) AS TOTAL_QUANTITY,\n SUM(TOTAL) AS TOTAL_REVENUE\nFROM ORDERS\nGROUP BY PRODUCT_ID\n",
- "comment": "snapshot table for snapshot TESTSCHEMA.PRODUCT_STATS",
- "dependencyColumns": [
- {
- "schema": "TESTSCHEMA",
- "table": "ORDERS",
- "column": "*"
- },
- {
- "schema": "TESTSCHEMA",
- "table": "PRODUCT_STATS",
- "column": "*"
- }
- ]
- }
- ]
- }
- ],
- "serviceName": "FREEPDB1"
- }
-}
diff --git a/backend/plugin/schema/oracle/testdata/generate_migration/views_and_functions.sql b/backend/plugin/schema/oracle/testdata/generate_migration/views_and_functions.sql
deleted file mode 100644
index dec8c01142..0000000000
--- a/backend/plugin/schema/oracle/testdata/generate_migration/views_and_functions.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-DROP FUNCTION "CALCULATE_ORDER_TOTAL";
-DROP VIEW "PRODUCT_INVENTORY";
-DROP MATERIALIZED VIEW "PRODUCT_STATS";
diff --git a/backend/plugin/schema/oracle/testdata/get_database_definition.yaml b/backend/plugin/schema/oracle/testdata/get_database_definition.yaml
new file mode 100644
index 0000000000..2ffb8b15ab
--- /dev/null
+++ b/backend/plugin/schema/oracle/testdata/get_database_definition.yaml
@@ -0,0 +1,251 @@
+- description: Basic tables with primary keys, foreign keys, unique constraints, check constraints, and indexes
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "DEPARTMENTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER",
+ "is_identity": true
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "BUDGET",
+ "position": 3,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(12, 2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_DEPARTMENTS",
+ "expressions": [
+ "ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ },
+ {
+ "name": "EMPLOYEES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER",
+ "is_identity": true
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "EMAIL",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "DEPARTMENT_ID",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALARY",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER(10, 2)"
+ },
+ {
+ "name": "HIRE_DATE",
+ "position": 6,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 7,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_EMPLOYEES",
+ "expressions": [
+ "ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UK_EMPLOYEES_EMAIL",
+ "expressions": [
+ "EMAIL"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "IDX_EMP_DEPT",
+ "expressions": [
+ "DEPARTMENT_ID"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_EMP_NAME",
+ "expressions": [
+ "NAME"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ],
+ "foreign_keys": [
+ {
+ "name": "FK_DEPT",
+ "columns": [
+ "DEPARTMENT_ID"
+ ],
+ "referenced_table": "DEPARTMENTS",
+ "referenced_columns": [
+ "ID"
+ ]
+ }
+ ],
+ "check_constraints": [
+ {
+ "name": "CHK_EMPLOYEES_IS_ACTIVE",
+ "expression": "IS_ACTIVE IN (0, 1)"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE "DEPARTMENTS" (
+ "ID" NUMBER NOT NULL,
+ "NAME" VARCHAR2(100 BYTE) NOT NULL,
+ "BUDGET" NUMBER(12, 2) DEFAULT 0,
+ CONSTRAINT "PK_DEPARTMENTS" PRIMARY KEY ("ID")
+ );
+
+ CREATE TABLE "EMPLOYEES" (
+ "ID" NUMBER NOT NULL,
+ "NAME" VARCHAR2(100 BYTE) NOT NULL,
+ "EMAIL" VARCHAR2(100 BYTE),
+ "DEPARTMENT_ID" NUMBER,
+ "SALARY" NUMBER(10, 2),
+ "HIRE_DATE" DATE DEFAULT SYSDATE,
+ "IS_ACTIVE" NUMBER(1) DEFAULT 1,
+ CONSTRAINT "PK_EMPLOYEES" PRIMARY KEY ("ID"),
+ CONSTRAINT "UK_EMPLOYEES_EMAIL" UNIQUE ("EMAIL"),
+ CONSTRAINT "CHK_EMPLOYEES_IS_ACTIVE" CHECK (IS_ACTIVE IN (0, 1)),
+ CONSTRAINT "FK_DEPT" FOREIGN KEY ("DEPARTMENT_ID") REFERENCES "DEPARTMENTS" ("ID")
+ );
+
+ CREATE INDEX "IDX_EMP_DEPT" ON "EMPLOYEES" ("DEPARTMENT_ID" ASC);
+
+ CREATE INDEX "IDX_EMP_NAME" ON "EMPLOYEES" ("NAME" ASC);
+
+- description: A view whose INSTEAD OF trigger must survive the definition round trip
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "EMPLOYEES",
+ "columns": [
+ {
+ "name": "EMP_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "EMAIL",
+ "position": 2,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_EMPLOYEES",
+ "expressions": [
+ "EMP_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "EMPLOYEE_VIEW",
+ "definition": "SELECT EMP_ID, EMAIL\nFROM EMPLOYEES",
+ "triggers": [
+ {
+ "name": "EMPLOYEE_VIEW_INSERT_TRG",
+ "body": "CREATE OR REPLACE TRIGGER EMPLOYEE_VIEW_INSERT_TRG\nINSTEAD OF INSERT ON EMPLOYEE_VIEW\nFOR EACH ROW\nBEGIN\n INSERT INTO EMPLOYEES (EMP_ID, EMAIL) VALUES (:NEW.EMP_ID, :NEW.EMAIL);\nEND;"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |+
+ CREATE TABLE "EMPLOYEES" (
+ "EMP_ID" NUMBER NOT NULL,
+ "EMAIL" VARCHAR2(100 BYTE),
+ CONSTRAINT "PK_EMPLOYEES" PRIMARY KEY ("EMP_ID")
+ );
+
+ CREATE VIEW "EMPLOYEE_VIEW" AS SELECT EMP_ID, EMAIL
+ FROM EMPLOYEES;
+
+ CREATE OR REPLACE TRIGGER EMPLOYEE_VIEW_INSERT_TRG
+ INSTEAD OF INSERT ON EMPLOYEE_VIEW
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO EMPLOYEES (EMP_ID, EMAIL) VALUES (:NEW.EMP_ID, :NEW.EMAIL);
+ END;
+
diff --git a/backend/plugin/schema/oracle/testdata/get_database_metadata.yaml b/backend/plugin/schema/oracle/testdata/get_database_metadata.yaml
new file mode 100644
index 0000000000..8c3db886aa
--- /dev/null
+++ b/backend/plugin/schema/oracle/testdata/get_database_metadata.yaml
@@ -0,0 +1,2190 @@
+- description: basic_table
+ schema: |
+ CREATE TABLE TEST_TABLE (
+ ID NUMBER PRIMARY KEY,
+ NAME VARCHAR2(50) NOT NULL
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "TEST_TABLE",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_TEST_TABLE",
+ "expressions": [
+ "ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: table_with_sequence
+ schema: |
+ CREATE TABLE EMPLOYEES (
+ ID NUMBER PRIMARY KEY,
+ NAME VARCHAR2(100) NOT NULL
+ );
+
+ CREATE SEQUENCE EMP_SEQ START WITH 1 INCREMENT BY 1;
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "EMPLOYEES",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_EMPLOYEES",
+ "expressions": [
+ "ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "EMP_SEQ",
+ "start": "1"
+ }
+ ]
+ }
+ ]
+ }
+- description: table_with_view
+ schema: |
+ CREATE TABLE PRODUCTS (
+ ID NUMBER PRIMARY KEY,
+ NAME VARCHAR2(100) NOT NULL,
+ PRICE NUMBER(10,2)
+ );
+
+ CREATE VIEW EXPENSIVE_PRODUCTS AS
+ SELECT ID, NAME, PRICE
+ FROM PRODUCTS
+ WHERE PRICE > 100;
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCTS",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "PRICE",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_PRODUCTS",
+ "expressions": [
+ "ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "EXPENSIVE_PRODUCTS",
+ "definition": "SELECT ID, NAME, PRICE\nFROM PRODUCTS\nWHERE PRICE \u003e 100"
+ }
+ ]
+ }
+ ]
+ }
+- description: comprehensive_data_types
+ schema: |
+ CREATE TABLE DATA_TYPES_COMPREHENSIVE (
+ ID NUMBER PRIMARY KEY,
+ -- Numeric types
+ NUMBER_COL NUMBER,
+ NUMBER_PRECISION NUMBER(10),
+ NUMBER_SCALE NUMBER(10,2),
+ FLOAT_COL FLOAT,
+ BINARY_FLOAT_COL BINARY_FLOAT,
+ BINARY_DOUBLE_COL BINARY_DOUBLE,
+ -- Character types
+ VARCHAR2_COL VARCHAR2(4000),
+ NVARCHAR2_COL NVARCHAR2(2000),
+ CHAR_COL CHAR(100),
+ NCHAR_COL NCHAR(100),
+ -- Date and time types
+ DATE_COL DATE,
+ TIMESTAMP_COL TIMESTAMP,
+ TIMESTAMP_TZ_COL TIMESTAMP WITH TIME ZONE,
+ TIMESTAMP_LTZ_COL TIMESTAMP WITH LOCAL TIME ZONE,
+ INTERVAL_YM_COL INTERVAL YEAR TO MONTH,
+ INTERVAL_DS_COL INTERVAL DAY TO SECOND,
+ -- Large object types
+ CLOB_COL CLOB,
+ NCLOB_COL NCLOB,
+ BLOB_COL BLOB,
+ -- Binary types
+ RAW_COL RAW(2000),
+ LONG_RAW_COL LONG RAW,
+ -- Row identifier
+ ROWID_COL ROWID,
+ UROWID_COL UROWID
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "DATA_TYPES_COMPREHENSIVE",
+ "columns": [
+ {
+ "name": "ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NUMBER_COL",
+ "position": 2,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "NUMBER_PRECISION",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER(10)"
+ },
+ {
+ "name": "NUMBER_SCALE",
+ "position": 4,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "FLOAT_COL",
+ "position": 5,
+ "nullable": true,
+ "type": "FLOAT(126)"
+ },
+ {
+ "name": "BINARY_FLOAT_COL",
+ "position": 6,
+ "nullable": true,
+ "type": "BINARY_FLOAT"
+ },
+ {
+ "name": "BINARY_DOUBLE_COL",
+ "position": 7,
+ "nullable": true,
+ "type": "BINARY_DOUBLE"
+ },
+ {
+ "name": "VARCHAR2_COL",
+ "position": 8,
+ "nullable": true,
+ "type": "VARCHAR2(4000 BYTE)"
+ },
+ {
+ "name": "NVARCHAR2_COL",
+ "position": 9,
+ "nullable": true,
+ "type": "NVARCHAR2(4000)"
+ },
+ {
+ "name": "CHAR_COL",
+ "position": 10,
+ "nullable": true,
+ "type": "CHAR(100 BYTE)"
+ },
+ {
+ "name": "NCHAR_COL",
+ "position": 11,
+ "nullable": true,
+ "type": "NCHAR(200)"
+ },
+ {
+ "name": "DATE_COL",
+ "position": 12,
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "TIMESTAMP_COL",
+ "position": 13,
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "TIMESTAMP_TZ_COL",
+ "position": 14,
+ "nullable": true,
+ "type": "TIMESTAMP(6) WITH TIME ZONE"
+ },
+ {
+ "name": "TIMESTAMP_LTZ_COL",
+ "position": 15,
+ "nullable": true,
+ "type": "TIMESTAMP(6) WITH LOCAL TIME ZONE"
+ },
+ {
+ "name": "INTERVAL_YM_COL",
+ "position": 16,
+ "nullable": true,
+ "type": "INTERVAL YEAR(2) TO MONTH"
+ },
+ {
+ "name": "INTERVAL_DS_COL",
+ "position": 17,
+ "nullable": true,
+ "type": "INTERVAL DAY(2) TO SECOND(6)"
+ },
+ {
+ "name": "CLOB_COL",
+ "position": 18,
+ "nullable": true,
+ "type": "CLOB"
+ },
+ {
+ "name": "NCLOB_COL",
+ "position": 19,
+ "nullable": true,
+ "type": "NCLOB"
+ },
+ {
+ "name": "BLOB_COL",
+ "position": 20,
+ "nullable": true,
+ "type": "BLOB"
+ },
+ {
+ "name": "RAW_COL",
+ "position": 21,
+ "nullable": true,
+ "type": "RAW(2000)"
+ },
+ {
+ "name": "LONG_RAW_COL",
+ "position": 22,
+ "nullable": true,
+ "type": "LONG RAW"
+ },
+ {
+ "name": "ROWID_COL",
+ "position": 23,
+ "nullable": true,
+ "type": "ROWID"
+ },
+ {
+ "name": "UROWID_COL",
+ "position": 24,
+ "nullable": true,
+ "type": "UROWID(4000)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_DATA_TYPES_COMPREHENSIVE",
+ "expressions": [
+ "ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: complex_constraints
+ schema: |
+ CREATE TABLE ORDERS (
+ ORDER_ID NUMBER PRIMARY KEY,
+ CUSTOMER_ID NUMBER NOT NULL,
+ ORDER_DATE DATE DEFAULT SYSDATE,
+ STATUS VARCHAR2(20) DEFAULT 'PENDING',
+ TOTAL_AMOUNT NUMBER(12,2) NOT NULL,
+ DISCOUNT_PERCENT NUMBER(5,2) DEFAULT 0,
+ SHIP_DATE DATE,
+ NOTES VARCHAR2(4000),
+ CREATED_BY VARCHAR2(100) DEFAULT USER,
+ CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ UPDATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ -- Check constraints
+ CONSTRAINT chk_status CHECK (STATUS IN ('PENDING', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'CANCELLED')),
+ CONSTRAINT chk_total_positive CHECK (TOTAL_AMOUNT > 0),
+ CONSTRAINT chk_discount_range CHECK (DISCOUNT_PERCENT BETWEEN 0 AND 100),
+ CONSTRAINT chk_ship_after_order CHECK (SHIP_DATE IS NULL OR SHIP_DATE >= ORDER_DATE),
+ -- Unique constraints
+ CONSTRAINT uk_order_customer_date UNIQUE (CUSTOMER_ID, ORDER_DATE)
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ORDERS",
+ "columns": [
+ {
+ "name": "ORDER_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 3,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "STATUS",
+ "position": 4,
+ "default": "'PENDING'",
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 5,
+ "type": "NUMBER(12,2)"
+ },
+ {
+ "name": "DISCOUNT_PERCENT",
+ "position": 6,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(5,2)"
+ },
+ {
+ "name": "SHIP_DATE",
+ "position": 7,
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "NOTES",
+ "position": 8,
+ "nullable": true,
+ "type": "VARCHAR2(4000 BYTE)"
+ },
+ {
+ "name": "CREATED_BY",
+ "position": 9,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 10,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "UPDATED_AT",
+ "position": 11,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_ORDERS",
+ "expressions": [
+ "ORDER_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UK_ORDER_CUSTOMER_DATE",
+ "expressions": [
+ "CUSTOMER_ID",
+ "ORDER_DATE"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "is_constraint": true
+ }
+ ],
+ "check_constraints": [
+ {
+ "name": "CHK_STATUS",
+ "expression": "STATUSIN('PENDING','PROCESSING','SHIPPED','DELIVERED','CANCELLED')"
+ },
+ {
+ "name": "CHK_TOTAL_POSITIVE",
+ "expression": "TOTAL_AMOUNT\u003e0"
+ },
+ {
+ "name": "CHK_DISCOUNT_RANGE",
+ "expression": "DISCOUNT_PERCENTBETWEEN0AND100"
+ },
+ {
+ "name": "CHK_SHIP_AFTER_ORDER",
+ "expression": "SHIP_DATEISNULLORSHIP_DATE\u003e=ORDER_DATE"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: foreign_keys_and_references
+ schema: |
+ CREATE TABLE DEPARTMENTS (
+ DEPT_ID NUMBER PRIMARY KEY,
+ DEPT_NAME VARCHAR2(100) NOT NULL UNIQUE,
+ MANAGER_ID NUMBER,
+ LOCATION VARCHAR2(100),
+ BUDGET NUMBER(15,2)
+ );
+
+ CREATE TABLE EMPLOYEES_FK (
+ EMP_ID NUMBER PRIMARY KEY,
+ FIRST_NAME VARCHAR2(50) NOT NULL,
+ LAST_NAME VARCHAR2(50) NOT NULL,
+ EMAIL VARCHAR2(100) UNIQUE,
+ PHONE VARCHAR2(20),
+ HIRE_DATE DATE DEFAULT SYSDATE,
+ SALARY NUMBER(10,2),
+ COMMISSION_PCT NUMBER(4,2),
+ DEPT_ID NUMBER,
+ MANAGER_ID NUMBER,
+ -- Foreign key constraints
+ CONSTRAINT fk_emp_dept FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENTS(DEPT_ID) ON DELETE SET NULL,
+ CONSTRAINT fk_emp_manager FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEES_FK(EMP_ID) ON DELETE SET NULL,
+ -- Check constraints
+ CONSTRAINT chk_salary_positive CHECK (SALARY > 0),
+ CONSTRAINT chk_commission_range CHECK (COMMISSION_PCT BETWEEN 0 AND 1),
+ CONSTRAINT chk_email_format CHECK (EMAIL LIKE '%@%.%')
+ );
+
+ -- Self-referencing foreign key for department manager
+ ALTER TABLE DEPARTMENTS ADD CONSTRAINT fk_dept_manager
+ FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEES_FK(EMP_ID) ON DELETE SET NULL;
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "DEPARTMENTS",
+ "columns": [
+ {
+ "name": "DEPT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "DEPT_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "MANAGER_ID",
+ "position": 3,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "LOCATION",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "BUDGET",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER(15,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_DEPARTMENTS",
+ "expressions": [
+ "DEPT_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UK_DEPARTMENTS_DEPT_NAME",
+ "expressions": [
+ "DEPT_NAME"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ],
+ "foreign_keys": [
+ {
+ "name": "FK_DEPT_MANAGER",
+ "columns": [
+ "MANAGER_ID"
+ ],
+ "referenced_table": "EMPLOYEES_FK",
+ "referenced_columns": [
+ "EMP_ID"
+ ],
+ "on_delete": "SET NULL"
+ }
+ ]
+ },
+ {
+ "name": "EMPLOYEES_FK",
+ "columns": [
+ {
+ "name": "EMP_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "FIRST_NAME",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)"
+ },
+ {
+ "name": "LAST_NAME",
+ "position": 3,
+ "type": "VARCHAR2(50 BYTE)"
+ },
+ {
+ "name": "EMAIL",
+ "position": 4,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "PHONE",
+ "position": 5,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)"
+ },
+ {
+ "name": "HIRE_DATE",
+ "position": 6,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ },
+ {
+ "name": "SALARY",
+ "position": 7,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "COMMISSION_PCT",
+ "position": 8,
+ "nullable": true,
+ "type": "NUMBER(4,2)"
+ },
+ {
+ "name": "DEPT_ID",
+ "position": 9,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "MANAGER_ID",
+ "position": 10,
+ "nullable": true,
+ "type": "NUMBER"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_EMPLOYEES_FK",
+ "expressions": [
+ "EMP_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UK_EMPLOYEES_FK_EMAIL",
+ "expressions": [
+ "EMAIL"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ],
+ "foreign_keys": [
+ {
+ "name": "FK_EMP_DEPT",
+ "columns": [
+ "DEPT_ID"
+ ],
+ "referenced_table": "DEPARTMENTS",
+ "referenced_columns": [
+ "DEPT_ID"
+ ],
+ "on_delete": "SET NULL"
+ },
+ {
+ "name": "FK_EMP_MANAGER",
+ "columns": [
+ "MANAGER_ID"
+ ],
+ "referenced_table": "EMPLOYEES_FK",
+ "referenced_columns": [
+ "EMP_ID"
+ ],
+ "on_delete": "SET NULL"
+ }
+ ],
+ "check_constraints": [
+ {
+ "name": "CHK_SALARY_POSITIVE",
+ "expression": "SALARY\u003e0"
+ },
+ {
+ "name": "CHK_COMMISSION_RANGE",
+ "expression": "COMMISSION_PCTBETWEEN0AND1"
+ },
+ {
+ "name": "CHK_EMAIL_FORMAT",
+ "expression": "EMAILLIKE'%@%.%'"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: indexes_comprehensive
+ schema: |
+ CREATE TABLE CUSTOMER_ORDERS (
+ ORDER_ID NUMBER PRIMARY KEY,
+ CUSTOMER_ID NUMBER NOT NULL,
+ ORDER_DATE DATE NOT NULL,
+ PRODUCT_CODE VARCHAR2(50) NOT NULL,
+ QUANTITY NUMBER NOT NULL,
+ UNIT_PRICE NUMBER(10,2) NOT NULL,
+ TOTAL_AMOUNT NUMBER(12,2) NOT NULL,
+ STATUS VARCHAR2(20) DEFAULT 'ACTIVE',
+ DESCRIPTION CLOB,
+ TAGS VARCHAR2(1000),
+ CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ -- Various index types
+ CREATE INDEX idx_customer_date ON CUSTOMER_ORDERS(CUSTOMER_ID, ORDER_DATE);
+ CREATE INDEX idx_product_status ON CUSTOMER_ORDERS(PRODUCT_CODE, STATUS);
+ CREATE INDEX idx_order_date_desc ON CUSTOMER_ORDERS(ORDER_DATE DESC);
+ CREATE INDEX idx_total_amount ON CUSTOMER_ORDERS(TOTAL_AMOUNT);
+ CREATE UNIQUE INDEX idx_customer_product_unique ON CUSTOMER_ORDERS(CUSTOMER_ID, PRODUCT_CODE, ORDER_DATE);
+ CREATE BITMAP INDEX idx_status_bitmap ON CUSTOMER_ORDERS(STATUS);
+ CREATE INDEX idx_upper_product ON CUSTOMER_ORDERS(UPPER(PRODUCT_CODE));
+ CREATE INDEX idx_created_year ON CUSTOMER_ORDERS(EXTRACT(YEAR FROM CREATED_AT));
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMER_ORDERS",
+ "columns": [
+ {
+ "name": "ORDER_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ORDER_DATE",
+ "position": 3,
+ "type": "DATE"
+ },
+ {
+ "name": "PRODUCT_CODE",
+ "position": 4,
+ "type": "VARCHAR2(50 BYTE)"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 5,
+ "type": "NUMBER"
+ },
+ {
+ "name": "UNIT_PRICE",
+ "position": 6,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 7,
+ "type": "NUMBER(12,2)"
+ },
+ {
+ "name": "STATUS",
+ "position": 8,
+ "default": "'ACTIVE'",
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 9,
+ "nullable": true,
+ "type": "CLOB"
+ },
+ {
+ "name": "TAGS",
+ "position": 10,
+ "nullable": true,
+ "type": "VARCHAR2(1000 BYTE)"
+ },
+ {
+ "name": "CREATED_AT",
+ "position": 11,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_CUSTOMER_ORDERS",
+ "expressions": [
+ "ORDER_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "IDX_CUSTOMER_DATE",
+ "expressions": [
+ "CUSTOMER_ID",
+ "ORDER_DATE"
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_PRODUCT_STATUS",
+ "expressions": [
+ "PRODUCT_CODE",
+ "STATUS"
+ ],
+ "descending": [
+ false,
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_ORDER_DATE_DESC",
+ "expressions": [
+ "ORDER_DATE"
+ ],
+ "descending": [
+ true
+ ],
+ "type": "FUNCTION-BASED NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_TOTAL_AMOUNT",
+ "expressions": [
+ "TOTAL_AMOUNT"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_CUSTOMER_PRODUCT_UNIQUE",
+ "expressions": [
+ "CUSTOMER_ID",
+ "PRODUCT_CODE",
+ "ORDER_DATE"
+ ],
+ "descending": [
+ false,
+ false,
+ false
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "IDX_STATUS_BITMAP",
+ "expressions": [
+ "STATUS"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "BITMAP",
+ "visible": true
+ },
+ {
+ "name": "IDX_UPPER_PRODUCT",
+ "expressions": [
+ "UPPER(PRODUCT_CODE)"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "FUNCTION-BASED NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_CREATED_YEAR",
+ "expressions": [
+ "EXTRACT(YEAR FROM CREATED_AT)"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "FUNCTION-BASED NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: sequences_and_triggers
+ schema: |
+ CREATE TABLE AUDIT_LOG (
+ LOG_ID NUMBER PRIMARY KEY,
+ TABLE_NAME VARCHAR2(128) NOT NULL,
+ OPERATION VARCHAR2(10) NOT NULL,
+ OLD_VALUES CLOB,
+ NEW_VALUES CLOB,
+ USER_NAME VARCHAR2(128) DEFAULT USER,
+ TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ SESSION_ID VARCHAR2(128) DEFAULT SYS_CONTEXT('USERENV', 'SESSIONID')
+ );
+
+ CREATE SEQUENCE audit_log_seq
+ START WITH 1000
+ INCREMENT BY 1
+ MAXVALUE 999999999999999999
+ MINVALUE 1
+ NOCYCLE
+ CACHE 20;
+
+ CREATE OR REPLACE TRIGGER audit_log_trigger
+ BEFORE INSERT ON AUDIT_LOG
+ FOR EACH ROW
+ BEGIN
+ IF :NEW.LOG_ID IS NULL THEN
+ SELECT audit_log_seq.NEXTVAL INTO :NEW.LOG_ID FROM DUAL;
+ END IF;
+ END;
+ /
+
+ CREATE TABLE INVENTORY (
+ ITEM_ID NUMBER PRIMARY KEY,
+ ITEM_CODE VARCHAR2(50) UNIQUE NOT NULL,
+ DESCRIPTION VARCHAR2(200),
+ QUANTITY_ON_HAND NUMBER DEFAULT 0,
+ UNIT_COST NUMBER(10,2),
+ LAST_UPDATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE SEQUENCE inventory_seq START WITH 1 INCREMENT BY 1;
+
+ CREATE OR REPLACE TRIGGER inventory_audit_trigger
+ AFTER INSERT OR UPDATE OR DELETE ON INVENTORY
+ FOR EACH ROW
+ BEGIN
+ IF INSERTING THEN
+ INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, NEW_VALUES)
+ VALUES ('INVENTORY', 'INSERT', 'ID=' || :NEW.ITEM_ID || ',CODE=' || :NEW.ITEM_CODE);
+ ELSIF UPDATING THEN
+ INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)
+ VALUES ('INVENTORY', 'UPDATE',
+ 'ID=' || :OLD.ITEM_ID || ',QTY=' || :OLD.QUANTITY_ON_HAND,
+ 'ID=' || :NEW.ITEM_ID || ',QTY=' || :NEW.QUANTITY_ON_HAND);
+ ELSIF DELETING THEN
+ INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES)
+ VALUES ('INVENTORY', 'DELETE', 'ID=' || :OLD.ITEM_ID || ',CODE=' || :OLD.ITEM_CODE);
+ END IF;
+ END;
+ /
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "AUDIT_LOG",
+ "columns": [
+ {
+ "name": "LOG_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "TABLE_NAME",
+ "position": 2,
+ "type": "VARCHAR2(128 BYTE)"
+ },
+ {
+ "name": "OPERATION",
+ "position": 3,
+ "type": "VARCHAR2(10 BYTE)"
+ },
+ {
+ "name": "OLD_VALUES",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB"
+ },
+ {
+ "name": "NEW_VALUES",
+ "position": 5,
+ "nullable": true,
+ "type": "CLOB"
+ },
+ {
+ "name": "USER_NAME",
+ "position": 6,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(128 BYTE)"
+ },
+ {
+ "name": "TIMESTAMP",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ },
+ {
+ "name": "SESSION_ID",
+ "position": 8,
+ "default": "SYS_CONTEXT('USERENV', 'SESSIONID')",
+ "nullable": true,
+ "type": "VARCHAR2(128 BYTE)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_AUDIT_LOG",
+ "expressions": [
+ "LOG_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ],
+ "triggers": [
+ {
+ "name": "AUDIT_LOG_TRIGGER",
+ "body": "CREATE OR REPLACE TRIGGER audit_log_trigger\n BEFORE INSERT ON AUDIT_LOG\n FOR EACH ROW\nBEGIN\n IF :NEW.LOG_ID IS NULL THEN\n SELECT audit_log_seq.NEXTVAL INTO :NEW.LOG_ID FROM DUAL;\n END IF;\nEND;"
+ }
+ ]
+ },
+ {
+ "name": "INVENTORY",
+ "columns": [
+ {
+ "name": "ITEM_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "ITEM_CODE",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 3,
+ "nullable": true,
+ "type": "VARCHAR2(200 BYTE)"
+ },
+ {
+ "name": "QUANTITY_ON_HAND",
+ "position": 4,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "UNIT_COST",
+ "position": 5,
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "LAST_UPDATED",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "TIMESTAMP(6)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_INVENTORY",
+ "expressions": [
+ "ITEM_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UK_INVENTORY_ITEM_CODE",
+ "expressions": [
+ "ITEM_CODE"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ],
+ "triggers": [
+ {
+ "name": "INVENTORY_AUDIT_TRIGGER",
+ "body": "CREATE OR REPLACE TRIGGER inventory_audit_trigger\n AFTER INSERT OR UPDATE OR DELETE ON INVENTORY\n FOR EACH ROW\nBEGIN\n IF INSERTING THEN\n INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, NEW_VALUES)\n VALUES ('INVENTORY', 'INSERT', 'ID=' || :NEW.ITEM_ID || ',CODE=' || :NEW.ITEM_CODE);\n ELSIF UPDATING THEN\n INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES, NEW_VALUES)\n VALUES ('INVENTORY', 'UPDATE',\n 'ID=' || :OLD.ITEM_ID || ',QTY=' || :OLD.QUANTITY_ON_HAND,\n 'ID=' || :NEW.ITEM_ID || ',QTY=' || :NEW.QUANTITY_ON_HAND);\n ELSIF DELETING THEN\n INSERT INTO AUDIT_LOG (TABLE_NAME, OPERATION, OLD_VALUES)\n VALUES ('INVENTORY', 'DELETE', 'ID=' || :OLD.ITEM_ID || ',CODE=' || :OLD.ITEM_CODE);\n END IF;\nEND;"
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "AUDIT_LOG_SEQ",
+ "start": "1000"
+ },
+ {
+ "name": "INVENTORY_SEQ",
+ "start": "1"
+ }
+ ]
+ }
+ ]
+ }
+- description: views_complex
+ schema: |
+ CREATE TABLE SALES_TRANSACTIONS (
+ TRANSACTION_ID NUMBER PRIMARY KEY,
+ CUSTOMER_ID NUMBER NOT NULL,
+ PRODUCT_ID NUMBER NOT NULL,
+ SALE_DATE DATE NOT NULL,
+ QUANTITY NUMBER NOT NULL,
+ UNIT_PRICE NUMBER(10,2) NOT NULL,
+ DISCOUNT_AMOUNT NUMBER(10,2) DEFAULT 0,
+ TAX_AMOUNT NUMBER(10,2) DEFAULT 0,
+ TOTAL_AMOUNT NUMBER(12,2) NOT NULL,
+ SALES_REP_ID NUMBER,
+ REGION VARCHAR2(50)
+ );
+
+ -- Complex view with aggregations
+ CREATE VIEW MONTHLY_SALES_SUMMARY AS
+ SELECT
+ TO_CHAR(SALE_DATE, 'YYYY-MM') AS SALES_MONTH,
+ REGION,
+ COUNT(*) AS TRANSACTION_COUNT,
+ SUM(QUANTITY) AS TOTAL_QUANTITY,
+ SUM(TOTAL_AMOUNT) AS TOTAL_REVENUE,
+ AVG(TOTAL_AMOUNT) AS AVG_TRANSACTION_VALUE,
+ MIN(SALE_DATE) AS FIRST_SALE_DATE,
+ MAX(SALE_DATE) AS LAST_SALE_DATE
+ FROM SALES_TRANSACTIONS
+ WHERE SALE_DATE >= ADD_MONTHS(SYSDATE, -12)
+ GROUP BY TO_CHAR(SALE_DATE, 'YYYY-MM'), REGION
+ HAVING SUM(TOTAL_AMOUNT) > 1000
+ ORDER BY SALES_MONTH DESC, REGION;
+
+ -- View with joins and complex expressions
+ CREATE VIEW CUSTOMER_SALES_ANALYSIS AS
+ SELECT
+ st.CUSTOMER_ID,
+ COUNT(DISTINCT st.TRANSACTION_ID) AS TOTAL_TRANSACTIONS,
+ COUNT(DISTINCT TO_CHAR(st.SALE_DATE, 'YYYY-MM')) AS ACTIVE_MONTHS,
+ SUM(st.TOTAL_AMOUNT) AS LIFETIME_VALUE,
+ AVG(st.TOTAL_AMOUNT) AS AVG_TRANSACTION_VALUE,
+ MAX(st.SALE_DATE) AS LAST_PURCHASE_DATE,
+ CASE
+ WHEN MAX(st.SALE_DATE) >= SYSDATE - 30 THEN 'ACTIVE'
+ WHEN MAX(st.SALE_DATE) >= SYSDATE - 90 THEN 'RECENT'
+ ELSE 'INACTIVE'
+ END AS CUSTOMER_STATUS,
+ ROUND(SUM(st.TOTAL_AMOUNT) / NULLIF(COUNT(DISTINCT TO_CHAR(st.SALE_DATE, 'YYYY-MM')), 0), 2) AS MONTHLY_SPEND_RATE
+ FROM SALES_TRANSACTIONS st
+ WHERE st.SALE_DATE >= ADD_MONTHS(SYSDATE, -24)
+ GROUP BY st.CUSTOMER_ID
+ HAVING COUNT(*) >= 3;
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "SALES_TRANSACTIONS",
+ "columns": [
+ {
+ "name": "TRANSACTION_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 3,
+ "type": "NUMBER"
+ },
+ {
+ "name": "SALE_DATE",
+ "position": 4,
+ "type": "DATE"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 5,
+ "type": "NUMBER"
+ },
+ {
+ "name": "UNIT_PRICE",
+ "position": 6,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "DISCOUNT_AMOUNT",
+ "position": 7,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "TAX_AMOUNT",
+ "position": 8,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(10,2)"
+ },
+ {
+ "name": "TOTAL_AMOUNT",
+ "position": 9,
+ "type": "NUMBER(12,2)"
+ },
+ {
+ "name": "SALES_REP_ID",
+ "position": 10,
+ "nullable": true,
+ "type": "NUMBER"
+ },
+ {
+ "name": "REGION",
+ "position": 11,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_SALES_TRANSACTIONS",
+ "expressions": [
+ "TRANSACTION_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "CUSTOMER_SALES_ANALYSIS",
+ "definition": "SELECT\n st.CUSTOMER_ID,\n COUNT(DISTINCT st.TRANSACTION_ID) AS TOTAL_TRANSACTIONS,\n COUNT(DISTINCT TO_CHAR(st.SALE_DATE, 'YYYY-MM')) AS ACTIVE_MONTHS,\n SUM(st.TOTAL_AMOUNT) AS LIFETIME_VALUE,\n AVG(st.TOTAL_AMOUNT) AS AVG_TRANSACTION_VALUE,\n MAX(st.SALE_DATE) AS LAST_PURCHASE_DATE,\n CASE\n WHEN MAX(st.SALE_DATE) \u003e= SYSDATE - 30 THEN 'ACTIVE'\n WHEN MAX(st.SALE_DATE) \u003e= SYSDATE - 90 THEN 'RECENT'\n ELSE 'INACTIVE'\n END AS CUSTOMER_STATUS,\n ROUND(SUM(st.TOTAL_AMOUNT) / NULLIF(COUNT(DISTINCT TO_CHAR(st.SALE_DATE, 'YYYY-MM')), 0), 2) AS MONTHLY_SPEND_RATE\nFROM SALES_TRANSACTIONS st\nWHERE st.SALE_DATE \u003e= ADD_MONTHS(SYSDATE, -24)\nGROUP BY st.CUSTOMER_ID\nHAVING COUNT(*) \u003e= 3"
+ },
+ {
+ "name": "MONTHLY_SALES_SUMMARY",
+ "definition": "SELECT\n TO_CHAR(SALE_DATE, 'YYYY-MM') AS SALES_MONTH,\n REGION,\n COUNT(*) AS TRANSACTION_COUNT,\n SUM(QUANTITY) AS TOTAL_QUANTITY,\n SUM(TOTAL_AMOUNT) AS TOTAL_REVENUE,\n AVG(TOTAL_AMOUNT) AS AVG_TRANSACTION_VALUE,\n MIN(SALE_DATE) AS FIRST_SALE_DATE,\n MAX(SALE_DATE) AS LAST_SALE_DATE\nFROM SALES_TRANSACTIONS\nWHERE SALE_DATE \u003e= ADD_MONTHS(SYSDATE, -12)\nGROUP BY TO_CHAR(SALE_DATE, 'YYYY-MM'), REGION\nHAVING SUM(TOTAL_AMOUNT) \u003e 1000\nORDER BY SALES_MONTH DESC, REGION"
+ }
+ ]
+ }
+ ]
+ }
+- description: materialized_views
+ schema: |
+ CREATE TABLE PRODUCT_SALES_DAILY (
+ SALE_DATE DATE NOT NULL,
+ PRODUCT_ID NUMBER NOT NULL,
+ CATEGORY VARCHAR2(50) NOT NULL,
+ SALES_AMOUNT NUMBER(12,2) NOT NULL,
+ UNITS_SOLD NUMBER NOT NULL,
+ COST_OF_GOODS NUMBER(12,2) NOT NULL
+ );
+
+ -- Materialized view for performance (simplified for query rewrite support)
+ CREATE MATERIALIZED VIEW PRODUCT_PERFORMANCE_MV
+ BUILD IMMEDIATE
+ REFRESH COMPLETE ON DEMAND
+ AS
+ SELECT
+ PRODUCT_ID,
+ CATEGORY,
+ COUNT(*) AS SALES_DAYS,
+ SUM(SALES_AMOUNT) AS TOTAL_REVENUE,
+ SUM(UNITS_SOLD) AS TOTAL_UNITS,
+ SUM(COST_OF_GOODS) AS TOTAL_COST,
+ SUM(SALES_AMOUNT) - SUM(COST_OF_GOODS) AS TOTAL_PROFIT,
+ AVG(SALES_AMOUNT) AS AVG_DAILY_REVENUE,
+ MIN(SALE_DATE) AS FIRST_SALE_DATE,
+ MAX(SALE_DATE) AS LAST_SALE_DATE
+ FROM PRODUCT_SALES_DAILY
+ WHERE SALE_DATE >= ADD_MONTHS(SYSDATE, -12)
+ GROUP BY PRODUCT_ID, CATEGORY;
+
+ -- Create index on materialized view
+ CREATE INDEX idx_mv_category ON PRODUCT_PERFORMANCE_MV(CATEGORY);
+ CREATE INDEX idx_mv_total_profit ON PRODUCT_PERFORMANCE_MV(TOTAL_PROFIT);
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "PRODUCT_SALES_DAILY",
+ "columns": [
+ {
+ "name": "SALE_DATE",
+ "position": 1,
+ "type": "DATE"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 2,
+ "type": "NUMBER"
+ },
+ {
+ "name": "CATEGORY",
+ "position": 3,
+ "type": "VARCHAR2(50 BYTE)"
+ },
+ {
+ "name": "SALES_AMOUNT",
+ "position": 4,
+ "type": "NUMBER(12,2)"
+ },
+ {
+ "name": "UNITS_SOLD",
+ "position": 5,
+ "type": "NUMBER"
+ },
+ {
+ "name": "COST_OF_GOODS",
+ "position": 6,
+ "type": "NUMBER(12,2)"
+ }
+ ]
+ }
+ ],
+ "materialized_views": [
+ {
+ "name": "PRODUCT_PERFORMANCE_MV",
+ "definition": "SELECT\n PRODUCT_ID,\n CATEGORY,\n COUNT(*) AS SALES_DAYS,\n SUM(SALES_AMOUNT) AS TOTAL_REVENUE,\n SUM(UNITS_SOLD) AS TOTAL_UNITS,\n SUM(COST_OF_GOODS) AS TOTAL_COST,\n SUM(SALES_AMOUNT) - SUM(COST_OF_GOODS) AS TOTAL_PROFIT,\n AVG(SALES_AMOUNT) AS AVG_DAILY_REVENUE,\n MIN(SALE_DATE) AS FIRST_SALE_DATE,\n MAX(SALE_DATE) AS LAST_SALE_DATE\nFROM PRODUCT_SALES_DAILY\nWHERE SALE_DATE \u003e= ADD_MONTHS(SYSDATE, -12)\nGROUP BY PRODUCT_ID, CATEGORY\n",
+ "indexes": [
+ {
+ "name": "IDX_MV_CATEGORY",
+ "expressions": [
+ "CATEGORY"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ },
+ {
+ "name": "IDX_MV_TOTAL_PROFIT",
+ "expressions": [
+ "TOTAL_PROFIT"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "NORMAL",
+ "visible": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: procedures_and_functions
+ schema: |
+ CREATE TABLE CUSTOMER_ACCOUNTS (
+ ACCOUNT_ID NUMBER PRIMARY KEY,
+ CUSTOMER_NAME VARCHAR2(100) NOT NULL,
+ ACCOUNT_TYPE VARCHAR2(20) NOT NULL,
+ BALANCE NUMBER(15,2) DEFAULT 0,
+ CREDIT_LIMIT NUMBER(15,2) DEFAULT 0,
+ STATUS VARCHAR2(20) DEFAULT 'ACTIVE',
+ CREATED_DATE DATE DEFAULT SYSDATE
+ );
+
+ -- Function to calculate available credit
+ CREATE OR REPLACE FUNCTION get_available_credit(p_account_id NUMBER)
+ RETURN NUMBER
+ DETERMINISTIC
+ IS
+ v_balance NUMBER;
+ v_credit_limit NUMBER;
+ v_available_credit NUMBER;
+ BEGIN
+ SELECT BALANCE, CREDIT_LIMIT
+ INTO v_balance, v_credit_limit
+ FROM CUSTOMER_ACCOUNTS
+ WHERE ACCOUNT_ID = p_account_id;
+
+ v_available_credit := v_credit_limit - v_balance;
+
+ RETURN GREATEST(v_available_credit, 0);
+ EXCEPTION
+ WHEN NO_DATA_FOUND THEN
+ RETURN 0;
+ WHEN OTHERS THEN
+ RETURN -1;
+ END;
+ /
+
+ -- Procedure to update account balance
+ CREATE OR REPLACE PROCEDURE update_account_balance(
+ p_account_id IN NUMBER,
+ p_amount IN NUMBER,
+ p_transaction_type IN VARCHAR2,
+ p_result OUT VARCHAR2
+ )
+ IS
+ v_current_balance NUMBER;
+ v_new_balance NUMBER;
+ v_credit_limit NUMBER;
+ BEGIN
+ -- Get current balance and credit limit
+ SELECT BALANCE, CREDIT_LIMIT
+ INTO v_current_balance, v_credit_limit
+ FROM CUSTOMER_ACCOUNTS
+ WHERE ACCOUNT_ID = p_account_id
+ FOR UPDATE;
+
+ -- Calculate new balance
+ IF p_transaction_type = 'CREDIT' THEN
+ v_new_balance := v_current_balance + p_amount;
+ ELSIF p_transaction_type = 'DEBIT' THEN
+ v_new_balance := v_current_balance - p_amount;
+
+ -- Check credit limit
+ IF v_new_balance < (v_credit_limit * -1) THEN
+ p_result := 'ERROR: Transaction would exceed credit limit';
+ ROLLBACK;
+ RETURN;
+ END IF;
+ ELSE
+ p_result := 'ERROR: Invalid transaction type';
+ RETURN;
+ END IF;
+
+ -- Update balance
+ UPDATE CUSTOMER_ACCOUNTS
+ SET BALANCE = v_new_balance,
+ STATUS = CASE
+ WHEN v_new_balance < 0 THEN 'OVERDRAWN'
+ WHEN v_new_balance >= 0 THEN 'ACTIVE'
+ END
+ WHERE ACCOUNT_ID = p_account_id;
+
+ COMMIT;
+ p_result := 'SUCCESS: Balance updated to ' || v_new_balance;
+
+ EXCEPTION
+ WHEN NO_DATA_FOUND THEN
+ p_result := 'ERROR: Account not found';
+ WHEN OTHERS THEN
+ p_result := 'ERROR: ' || SQLERRM;
+ ROLLBACK;
+ END;
+ /
+
+ -- Function with complex logic
+ CREATE OR REPLACE FUNCTION calculate_account_risk_score(p_account_id NUMBER)
+ RETURN NUMBER
+ IS
+ v_balance NUMBER;
+ v_credit_limit NUMBER;
+ v_account_age NUMBER;
+ v_transaction_count NUMBER;
+ v_risk_score NUMBER := 0;
+ BEGIN
+ SELECT
+ BALANCE,
+ CREDIT_LIMIT,
+ SYSDATE - CREATED_DATE,
+ (SELECT COUNT(*) FROM AUDIT_LOG WHERE TABLE_NAME = 'CUSTOMER_ACCOUNTS')
+ INTO v_balance, v_credit_limit, v_account_age, v_transaction_count
+ FROM CUSTOMER_ACCOUNTS
+ WHERE ACCOUNT_ID = p_account_id;
+
+ -- Calculate risk based on multiple factors
+ -- Balance utilization (higher utilization = higher risk)
+ IF v_credit_limit > 0 THEN
+ v_risk_score := v_risk_score + (ABS(v_balance) / v_credit_limit) * 40;
+ END IF;
+
+ -- Account age (newer accounts = higher risk)
+ IF v_account_age < 30 THEN
+ v_risk_score := v_risk_score + 30;
+ ELSIF v_account_age < 90 THEN
+ v_risk_score := v_risk_score + 20;
+ ELSIF v_account_age < 365 THEN
+ v_risk_score := v_risk_score + 10;
+ END IF;
+
+ -- Transaction frequency (too few or too many = higher risk)
+ IF v_transaction_count < 5 THEN
+ v_risk_score := v_risk_score + 20;
+ ELSIF v_transaction_count > 100 THEN
+ v_risk_score := v_risk_score + 15;
+ END IF;
+
+ -- Negative balance penalty
+ IF v_balance < 0 THEN
+ v_risk_score := v_risk_score + 25;
+ END IF;
+
+ RETURN LEAST(v_risk_score, 100); -- Cap at 100
+
+ EXCEPTION
+ WHEN NO_DATA_FOUND THEN
+ RETURN 100; -- Max risk for non-existent accounts
+ WHEN OTHERS THEN
+ RETURN 50; -- Default moderate risk on errors
+ END;
+ /
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "CUSTOMER_ACCOUNTS",
+ "columns": [
+ {
+ "name": "ACCOUNT_ID",
+ "position": 1,
+ "type": "NUMBER"
+ },
+ {
+ "name": "CUSTOMER_NAME",
+ "position": 2,
+ "type": "VARCHAR2(100 BYTE)"
+ },
+ {
+ "name": "ACCOUNT_TYPE",
+ "position": 3,
+ "type": "VARCHAR2(20 BYTE)"
+ },
+ {
+ "name": "BALANCE",
+ "position": 4,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(15,2)"
+ },
+ {
+ "name": "CREDIT_LIMIT",
+ "position": 5,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(15,2)"
+ },
+ {
+ "name": "STATUS",
+ "position": 6,
+ "default": "'ACTIVE'",
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)"
+ },
+ {
+ "name": "CREATED_DATE",
+ "position": 7,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_CUSTOMER_ACCOUNTS",
+ "expressions": [
+ "ACCOUNT_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "CALCULATE_ACCOUNT_RISK_SCORE",
+ "definition": "FUNCTION calculate_account_risk_score(p_account_id NUMBER)\nRETURN NUMBER\nIS\n v_balance NUMBER;\n v_credit_limit NUMBER;\n v_account_age NUMBER;\n v_transaction_count NUMBER;\n v_risk_score NUMBER := 0;\nBEGIN\n SELECT\n BALANCE,\n CREDIT_LIMIT,\n SYSDATE - CREATED_DATE,\n (SELECT COUNT(*) FROM AUDIT_LOG WHERE TABLE_NAME = 'CUSTOMER_ACCOUNTS')\n INTO v_balance, v_credit_limit, v_account_age, v_transaction_count\n FROM CUSTOMER_ACCOUNTS\n WHERE ACCOUNT_ID = p_account_id;\n\n -- Calculate risk based on multiple factors\n -- Balance utilization (higher utilization = higher risk)\n IF v_credit_limit \u003e 0 THEN\n v_risk_score := v_risk_score + (ABS(v_balance) / v_credit_limit) * 40;\n END IF;\n\n -- Account age (newer accounts = higher risk)\n IF v_account_age \u003c 30 THEN\n v_risk_score := v_risk_score + 30;\n ELSIF v_account_age \u003c 90 THEN\n v_risk_score := v_risk_score + 20;\n ELSIF v_account_age \u003c 365 THEN\n v_risk_score := v_risk_score + 10;\n END IF;\n\n -- Transaction frequency (too few or too many = higher risk)\n IF v_transaction_count \u003c 5 THEN\n v_risk_score := v_risk_score + 20;\n ELSIF v_transaction_count \u003e 100 THEN\n v_risk_score := v_risk_score + 15;\n END IF;\n\n -- Negative balance penalty\n IF v_balance \u003c 0 THEN\n v_risk_score := v_risk_score + 25;\n END IF;\n\n RETURN LEAST(v_risk_score, 100); -- Cap at 100\n\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN 100; -- Max risk for non-existent accounts\n WHEN OTHERS THEN\n RETURN 50; -- Default moderate risk on errors\nEND;"
+ },
+ {
+ "name": "GET_AVAILABLE_CREDIT",
+ "definition": "FUNCTION get_available_credit(p_account_id NUMBER)\nRETURN NUMBER\nDETERMINISTIC\nIS\n v_balance NUMBER;\n v_credit_limit NUMBER;\n v_available_credit NUMBER;\nBEGIN\n SELECT BALANCE, CREDIT_LIMIT\n INTO v_balance, v_credit_limit\n FROM CUSTOMER_ACCOUNTS\n WHERE ACCOUNT_ID = p_account_id;\n\n v_available_credit := v_credit_limit - v_balance;\n\n RETURN GREATEST(v_available_credit, 0);\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN 0;\n WHEN OTHERS THEN\n RETURN -1;\nEND;"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "UPDATE_ACCOUNT_BALANCE",
+ "definition": "CREATE OR REPLACE PROCEDURE update_account_balance(\n p_account_id IN NUMBER,\n p_amount IN NUMBER,\n p_transaction_type IN VARCHAR2,\n p_result OUT VARCHAR2\n)\nIS\n v_current_balance NUMBER;\n v_new_balance NUMBER;\n v_credit_limit NUMBER;\nBEGIN\n -- Get current balance and credit limit\n SELECT BALANCE, CREDIT_LIMIT\n INTO v_current_balance, v_credit_limit\n FROM CUSTOMER_ACCOUNTS\n WHERE ACCOUNT_ID = p_account_id\n FOR UPDATE;\n\n -- Calculate new balance\n IF p_transaction_type = 'CREDIT' THEN\n v_new_balance := v_current_balance + p_amount;\n ELSIF p_transaction_type = 'DEBIT' THEN\n v_new_balance := v_current_balance - p_amount;\n\n -- Check credit limit\n IF v_new_balance \u003c (v_credit_limit * -1) THEN\n p_result := 'ERROR: Transaction would exceed credit limit';\n ROLLBACK;\n RETURN;\n END IF;\n ELSE\n p_result := 'ERROR: Invalid transaction type';\n RETURN;\n END IF;\n\n -- Update balance\n UPDATE CUSTOMER_ACCOUNTS\n SET BALANCE = v_new_balance,\n STATUS = CASE\n WHEN v_new_balance \u003c 0 THEN 'OVERDRAWN'\n WHEN v_new_balance \u003e= 0 THEN 'ACTIVE'\n END\n WHERE ACCOUNT_ID = p_account_id;\n\n COMMIT;\n p_result := 'SUCCESS: Balance updated to ' || v_new_balance;\n\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n p_result := 'ERROR: Account not found';\n WHEN OTHERS THEN\n p_result := 'ERROR: ' || SQLERRM;\n ROLLBACK;\nEND;"
+ }
+ ]
+ }
+ ]
+ }
+- description: packages_comprehensive
+ schema: |
+ -- Package specification
+ CREATE OR REPLACE PACKAGE financial_utils AS
+ -- Constants
+ c_max_overdraft CONSTANT NUMBER := 5000;
+ c_default_interest_rate CONSTANT NUMBER := 0.05;
+
+ -- Types
+ TYPE account_summary_type IS RECORD (
+ account_id NUMBER,
+ balance NUMBER,
+ available_credit NUMBER,
+ risk_score NUMBER,
+ status VARCHAR2(20)
+ );
+
+ TYPE account_list_type IS TABLE OF account_summary_type;
+
+ -- Procedures
+ PROCEDURE calculate_interest(
+ p_account_id IN NUMBER,
+ p_days IN NUMBER DEFAULT 30,
+ p_interest_amount OUT NUMBER
+ );
+
+ PROCEDURE generate_statement(
+ p_account_id IN NUMBER,
+ p_statement_date IN DATE DEFAULT SYSDATE,
+ p_statement_text OUT CLOB
+ );
+
+ -- Functions
+ FUNCTION get_account_summary(p_account_id NUMBER) RETURN account_summary_type;
+
+ FUNCTION get_high_risk_accounts(p_risk_threshold NUMBER DEFAULT 70)
+ RETURN account_list_type PIPELINED;
+
+ FUNCTION format_currency(p_amount NUMBER) RETURN VARCHAR2;
+
+ FUNCTION validate_account_number(p_account_id NUMBER) RETURN BOOLEAN;
+
+ -- Overloaded functions
+ FUNCTION calculate_fee(p_transaction_type VARCHAR2) RETURN NUMBER;
+ FUNCTION calculate_fee(p_transaction_type VARCHAR2, p_amount NUMBER) RETURN NUMBER;
+
+ END financial_utils;
+ /
+
+ -- Package body
+ CREATE OR REPLACE PACKAGE BODY financial_utils AS
+
+ PROCEDURE calculate_interest(
+ p_account_id IN NUMBER,
+ p_days IN NUMBER DEFAULT 30,
+ p_interest_amount OUT NUMBER
+ ) IS
+ v_balance NUMBER;
+ v_daily_rate NUMBER;
+ BEGIN
+ SELECT BALANCE INTO v_balance
+ FROM CUSTOMER_ACCOUNTS
+ WHERE ACCOUNT_ID = p_account_id;
+
+ v_daily_rate := c_default_interest_rate / 365;
+
+ IF v_balance < 0 THEN
+ p_interest_amount := ABS(v_balance) * v_daily_rate * p_days;
+ ELSE
+ p_interest_amount := 0;
+ END IF;
+ EXCEPTION
+ WHEN NO_DATA_FOUND THEN
+ p_interest_amount := 0;
+ END calculate_interest;
+
+ PROCEDURE generate_statement(
+ p_account_id IN NUMBER,
+ p_statement_date IN DATE DEFAULT SYSDATE,
+ p_statement_text OUT CLOB
+ ) IS
+ v_account account_summary_type;
+ BEGIN
+ v_account := get_account_summary(p_account_id);
+
+ p_statement_text := 'ACCOUNT STATEMENT' || CHR(10) ||
+ 'Account ID: ' || v_account.account_id || CHR(10) ||
+ 'Statement Date: ' || TO_CHAR(p_statement_date, 'DD-MON-YYYY') || CHR(10) ||
+ 'Current Balance: ' || format_currency(v_account.balance) || CHR(10) ||
+ 'Available Credit: ' || format_currency(v_account.available_credit) || CHR(10) ||
+ 'Account Status: ' || v_account.status || CHR(10) ||
+ 'Risk Score: ' || v_account.risk_score;
+ END generate_statement;
+
+ FUNCTION get_account_summary(p_account_id NUMBER) RETURN account_summary_type IS
+ v_summary account_summary_type;
+ BEGIN
+ SELECT ACCOUNT_ID, BALANCE, STATUS
+ INTO v_summary.account_id, v_summary.balance, v_summary.status
+ FROM CUSTOMER_ACCOUNTS
+ WHERE ACCOUNT_ID = p_account_id;
+
+ v_summary.available_credit := get_available_credit(p_account_id);
+ v_summary.risk_score := calculate_account_risk_score(p_account_id);
+
+ RETURN v_summary;
+ END get_account_summary;
+
+ FUNCTION get_high_risk_accounts(p_risk_threshold NUMBER DEFAULT 70)
+ RETURN account_list_type PIPELINED IS
+ v_summary account_summary_type;
+ BEGIN
+ FOR rec IN (SELECT ACCOUNT_ID FROM CUSTOMER_ACCOUNTS WHERE STATUS = 'ACTIVE') LOOP
+ v_summary := get_account_summary(rec.ACCOUNT_ID);
+ IF v_summary.risk_score >= p_risk_threshold THEN
+ PIPE ROW(v_summary);
+ END IF;
+ END LOOP;
+ RETURN;
+ END get_high_risk_accounts;
+
+ FUNCTION format_currency(p_amount NUMBER) RETURN VARCHAR2 IS
+ BEGIN
+ RETURN TO_CHAR(p_amount, 'FM$999,999,990.00');
+ END format_currency;
+
+ FUNCTION validate_account_number(p_account_id NUMBER) RETURN BOOLEAN IS
+ v_count NUMBER;
+ BEGIN
+ SELECT COUNT(*) INTO v_count
+ FROM CUSTOMER_ACCOUNTS
+ WHERE ACCOUNT_ID = p_account_id;
+
+ RETURN v_count > 0;
+ END validate_account_number;
+
+ FUNCTION calculate_fee(p_transaction_type VARCHAR2) RETURN NUMBER IS
+ BEGIN
+ CASE p_transaction_type
+ WHEN 'TRANSFER' THEN RETURN 2.50;
+ WHEN 'WITHDRAWAL' THEN RETURN 1.00;
+ WHEN 'DEPOSIT' THEN RETURN 0;
+ ELSE RETURN 5.00;
+ END CASE;
+ END calculate_fee;
+
+ FUNCTION calculate_fee(p_transaction_type VARCHAR2, p_amount NUMBER) RETURN NUMBER IS
+ v_base_fee NUMBER;
+ v_percentage_fee NUMBER;
+ BEGIN
+ v_base_fee := calculate_fee(p_transaction_type);
+
+ -- Add percentage-based fee for large amounts
+ IF p_amount > 10000 THEN
+ v_percentage_fee := p_amount * 0.001; -- 0.1%
+ RETURN v_base_fee + v_percentage_fee;
+ ELSE
+ RETURN v_base_fee;
+ END IF;
+ END calculate_fee;
+
+ END financial_utils;
+ /
+ metadata: |
+ {
+ "schemas": [
+ {
+ "packages": [
+ {
+ "name": "FINANCIAL_UTILS",
+ "definition": "CREATE OR REPLACE PACKAGE financial_utils AS\n -- Constants\n c_max_overdraft CONSTANT NUMBER := 5000;\n c_default_interest_rate CONSTANT NUMBER := 0.05;\n\n -- Types\n TYPE account_summary_type IS RECORD (\n account_id NUMBER,\n balance NUMBER,\n available_credit NUMBER,\n risk_score NUMBER,\n status VARCHAR2(20)\n );\n\n TYPE account_list_type IS TABLE OF account_summary_type;\n\n -- Procedures\n PROCEDURE calculate_interest(\n p_account_id IN NUMBER,\n p_days IN NUMBER DEFAULT 30,\n p_interest_amount OUT NUMBER\n );\n\n PROCEDURE generate_statement(\n p_account_id IN NUMBER,\n p_statement_date IN DATE DEFAULT SYSDATE,\n p_statement_text OUT CLOB\n );\n\n -- Functions\n FUNCTION get_account_summary(p_account_id NUMBER) RETURN account_summary_type;\n\n FUNCTION get_high_risk_accounts(p_risk_threshold NUMBER DEFAULT 70)\n RETURN account_list_type PIPELINED;\n\n FUNCTION format_currency(p_amount NUMBER) RETURN VARCHAR2;\n\n FUNCTION validate_account_number(p_account_id NUMBER) RETURN BOOLEAN;\n\n -- Overloaded functions\n FUNCTION calculate_fee(p_transaction_type VARCHAR2) RETURN NUMBER;\n FUNCTION calculate_fee(p_transaction_type VARCHAR2, p_amount NUMBER) RETURN NUMBER;\n\nEND financial_utils;\n\nCREATE OR REPLACE PACKAGE BODY financial_utils AS\n\n PROCEDURE calculate_interest(\n p_account_id IN NUMBER,\n p_days IN NUMBER DEFAULT 30,\n p_interest_amount OUT NUMBER\n ) IS\n v_balance NUMBER;\n v_daily_rate NUMBER;\n BEGIN\n SELECT BALANCE INTO v_balance\n FROM CUSTOMER_ACCOUNTS\n WHERE ACCOUNT_ID = p_account_id;\n\n v_daily_rate := c_default_interest_rate / 365;\n\n IF v_balance \u003c 0 THEN\n p_interest_amount := ABS(v_balance) * v_daily_rate * p_days;\n ELSE\n p_interest_amount := 0;\n END IF;\n EXCEPTION\n WHEN NO_DATA_FOUND THEN\n p_interest_amount := 0;\n END calculate_interest;\n\n PROCEDURE generate_statement(\n p_account_id IN NUMBER,\n p_statement_date IN DATE DEFAULT SYSDATE,\n p_statement_text OUT CLOB\n ) IS\n v_account account_summary_type;\n BEGIN\n v_account := get_account_summary(p_account_id);\n\n p_statement_text := 'ACCOUNT STATEMENT' || CHR(10) ||\n 'Account ID: ' || v_account.account_id || CHR(10) ||\n 'Statement Date: ' || TO_CHAR(p_statement_date, 'DD-MON-YYYY') || CHR(10) ||\n 'Current Balance: ' || format_currency(v_account.balance) || CHR(10) ||\n 'Available Credit: ' || format_currency(v_account.available_credit) || CHR(10) ||\n 'Account Status: ' || v_account.status || CHR(10) ||\n 'Risk Score: ' || v_account.risk_score;\n END generate_statement;\n\n FUNCTION get_account_summary(p_account_id NUMBER) RETURN account_summary_type IS\n v_summary account_summary_type;\n BEGIN\n SELECT ACCOUNT_ID, BALANCE, STATUS\n INTO v_summary.account_id, v_summary.balance, v_summary.status\n FROM CUSTOMER_ACCOUNTS\n WHERE ACCOUNT_ID = p_account_id;\n\n v_summary.available_credit := get_available_credit(p_account_id);\n v_summary.risk_score := calculate_account_risk_score(p_account_id);\n\n RETURN v_summary;\n END get_account_summary;\n\n FUNCTION get_high_risk_accounts(p_risk_threshold NUMBER DEFAULT 70)\n RETURN account_list_type PIPELINED IS\n v_summary account_summary_type;\n BEGIN\n FOR rec IN (SELECT ACCOUNT_ID FROM CUSTOMER_ACCOUNTS WHERE STATUS = 'ACTIVE') LOOP\n v_summary := get_account_summary(rec.ACCOUNT_ID);\n IF v_summary.risk_score \u003e= p_risk_threshold THEN\n PIPE ROW(v_summary);\n END IF;\n END LOOP;\n RETURN;\n END get_high_risk_accounts;\n\n FUNCTION format_currency(p_amount NUMBER) RETURN VARCHAR2 IS\n BEGIN\n RETURN TO_CHAR(p_amount, 'FM$999,999,990.00');\n END format_currency;\n\n FUNCTION validate_account_number(p_account_id NUMBER) RETURN BOOLEAN IS\n v_count NUMBER;\n BEGIN\n SELECT COUNT(*) INTO v_count\n FROM CUSTOMER_ACCOUNTS\n WHERE ACCOUNT_ID = p_account_id;\n\n RETURN v_count \u003e 0;\n END validate_account_number;\n\n FUNCTION calculate_fee(p_transaction_type VARCHAR2) RETURN NUMBER IS\n BEGIN\n CASE p_transaction_type\n WHEN 'TRANSFER' THEN RETURN 2.50;\n WHEN 'WITHDRAWAL' THEN RETURN 1.00;\n WHEN 'DEPOSIT' THEN RETURN 0;\n ELSE RETURN 5.00;\n END CASE;\n END calculate_fee;\n\n FUNCTION calculate_fee(p_transaction_type VARCHAR2, p_amount NUMBER) RETURN NUMBER IS\n v_base_fee NUMBER;\n v_percentage_fee NUMBER;\n BEGIN\n v_base_fee := calculate_fee(p_transaction_type);\n\n -- Add percentage-based fee for large amounts\n IF p_amount \u003e 10000 THEN\n v_percentage_fee := p_amount * 0.001; -- 0.1%\n RETURN v_base_fee + v_percentage_fee;\n ELSE\n RETURN v_base_fee;\n END IF;\n END calculate_fee;\n\nEND financial_utils;"
+ }
+ ]
+ }
+ ]
+ }
+- description: table_comments_and_documentation
+ schema: |
+ CREATE TABLE PRODUCT_CATALOG (
+ PRODUCT_ID NUMBER PRIMARY KEY,
+ SKU VARCHAR2(50) UNIQUE NOT NULL,
+ PRODUCT_NAME VARCHAR2(200) NOT NULL,
+ DESCRIPTION CLOB,
+ CATEGORY_ID NUMBER NOT NULL,
+ PRICE NUMBER(10,2) NOT NULL,
+ COST NUMBER(10,2),
+ WEIGHT NUMBER(8,3),
+ DIMENSIONS VARCHAR2(100),
+ COLOR VARCHAR2(50),
+ PRODUCT_SIZE VARCHAR2(20),
+ BRAND VARCHAR2(100),
+ SUPPLIER_ID NUMBER,
+ IS_ACTIVE NUMBER(1) DEFAULT 1,
+ STOCK_QUANTITY NUMBER DEFAULT 0,
+ REORDER_LEVEL NUMBER DEFAULT 10,
+ CREATED_DATE DATE DEFAULT SYSDATE,
+ CREATED_BY VARCHAR2(100) DEFAULT USER,
+ LAST_UPDATED DATE DEFAULT SYSDATE,
+ UPDATED_BY VARCHAR2(100) DEFAULT USER,
+ VERSION_NUMBER NUMBER DEFAULT 1
+ );
+
+ -- Table comments
+ COMMENT ON TABLE PRODUCT_CATALOG IS 'Master catalog of all products available for sale. Contains detailed product information including pricing, inventory, and supplier details.';
+
+ -- Column comments
+ COMMENT ON COLUMN PRODUCT_CATALOG.PRODUCT_ID IS 'Unique identifier for the product. Primary key generated from sequence.';
+ COMMENT ON COLUMN PRODUCT_CATALOG.SKU IS 'Stock Keeping Unit - unique alphanumeric code for inventory tracking';
+ COMMENT ON COLUMN PRODUCT_CATALOG.PRODUCT_NAME IS 'Display name of the product as shown to customers';
+ COMMENT ON COLUMN PRODUCT_CATALOG.DESCRIPTION IS 'Detailed product description including features and specifications';
+ COMMENT ON COLUMN PRODUCT_CATALOG.CATEGORY_ID IS 'Foreign key reference to PRODUCT_CATEGORIES table';
+ COMMENT ON COLUMN PRODUCT_CATALOG.PRICE IS 'Current selling price in base currency (USD)';
+ COMMENT ON COLUMN PRODUCT_CATALOG.COST IS 'Cost of goods sold - used for profit margin calculations';
+ COMMENT ON COLUMN PRODUCT_CATALOG.WEIGHT IS 'Product weight in kilograms - used for shipping calculations';
+ COMMENT ON COLUMN PRODUCT_CATALOG.DIMENSIONS IS 'Product dimensions in format: Length x Width x Height (cm)';
+ COMMENT ON COLUMN PRODUCT_CATALOG.COLOR IS 'Primary color of the product';
+ COMMENT ON COLUMN PRODUCT_CATALOG.PRODUCT_SIZE IS 'Size designation (S, M, L, XL, etc.)';
+ COMMENT ON COLUMN PRODUCT_CATALOG.BRAND IS 'Brand or manufacturer name';
+ COMMENT ON COLUMN PRODUCT_CATALOG.SUPPLIER_ID IS 'Reference to primary supplier in SUPPLIERS table';
+ COMMENT ON COLUMN PRODUCT_CATALOG.IS_ACTIVE IS 'Flag indicating if product is active (1) or discontinued (0)';
+ COMMENT ON COLUMN PRODUCT_CATALOG.STOCK_QUANTITY IS 'Current inventory quantity on hand';
+ COMMENT ON COLUMN PRODUCT_CATALOG.REORDER_LEVEL IS 'Minimum stock level that triggers reorder process';
+ COMMENT ON COLUMN PRODUCT_CATALOG.CREATED_DATE IS 'Date when product record was first created';
+ COMMENT ON COLUMN PRODUCT_CATALOG.CREATED_BY IS 'Username of person who created the record';
+ COMMENT ON COLUMN PRODUCT_CATALOG.LAST_UPDATED IS 'Date of most recent update to any field';
+ COMMENT ON COLUMN PRODUCT_CATALOG.UPDATED_BY IS 'Username of person who last modified the record';
+ COMMENT ON COLUMN PRODUCT_CATALOG.VERSION_NUMBER IS 'Optimistic locking version number for concurrent update control';
+
+ CREATE TABLE ORDER_LINE_ITEMS (
+ LINE_ITEM_ID NUMBER PRIMARY KEY,
+ ORDER_ID NUMBER NOT NULL,
+ PRODUCT_ID NUMBER NOT NULL,
+ QUANTITY NUMBER NOT NULL,
+ UNIT_PRICE NUMBER(10,2) NOT NULL,
+ DISCOUNT_AMOUNT NUMBER(10,2) DEFAULT 0,
+ TAX_AMOUNT NUMBER(10,2) DEFAULT 0,
+ LINE_TOTAL NUMBER(12,2) NOT NULL,
+ SPECIAL_INSTRUCTIONS VARCHAR2(500),
+ FULFILLMENT_STATUS VARCHAR2(20) DEFAULT 'PENDING'
+ );
+
+ COMMENT ON TABLE ORDER_LINE_ITEMS IS 'Individual line items for customer orders. Each row represents one product within an order.';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.LINE_ITEM_ID IS 'Unique identifier for this line item';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.ORDER_ID IS 'Reference to parent order in ORDERS table';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.PRODUCT_ID IS 'Reference to product in PRODUCT_CATALOG table';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.QUANTITY IS 'Number of units ordered';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.UNIT_PRICE IS 'Price per unit at time of order (may differ from current catalog price)';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.DISCOUNT_AMOUNT IS 'Total discount applied to this line item';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.TAX_AMOUNT IS 'Total tax amount for this line item';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.LINE_TOTAL IS 'Calculated total: (quantity * unit_price) - discount + tax';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.SPECIAL_INSTRUCTIONS IS 'Customer-specific instructions for this item';
+ COMMENT ON COLUMN ORDER_LINE_ITEMS.FULFILLMENT_STATUS IS 'Status: PENDING, PICKED, PACKED, SHIPPED, DELIVERED, RETURNED';
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "ORDER_LINE_ITEMS",
+ "columns": [
+ {
+ "name": "LINE_ITEM_ID",
+ "position": 1,
+ "type": "NUMBER",
+ "comment": "Unique identifier for this line item"
+ },
+ {
+ "name": "ORDER_ID",
+ "position": 2,
+ "type": "NUMBER",
+ "comment": "Reference to parent order in ORDERS table"
+ },
+ {
+ "name": "PRODUCT_ID",
+ "position": 3,
+ "type": "NUMBER",
+ "comment": "Reference to product in PRODUCT_CATALOG table"
+ },
+ {
+ "name": "QUANTITY",
+ "position": 4,
+ "type": "NUMBER",
+ "comment": "Number of units ordered"
+ },
+ {
+ "name": "UNIT_PRICE",
+ "position": 5,
+ "type": "NUMBER(10,2)",
+ "comment": "Price per unit at time of order (may differ from current catalog price)"
+ },
+ {
+ "name": "DISCOUNT_AMOUNT",
+ "position": 6,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(10,2)",
+ "comment": "Total discount applied to this line item"
+ },
+ {
+ "name": "TAX_AMOUNT",
+ "position": 7,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER(10,2)",
+ "comment": "Total tax amount for this line item"
+ },
+ {
+ "name": "LINE_TOTAL",
+ "position": 8,
+ "type": "NUMBER(12,2)",
+ "comment": "Calculated total: (quantity * unit_price) - discount + tax"
+ },
+ {
+ "name": "SPECIAL_INSTRUCTIONS",
+ "position": 9,
+ "nullable": true,
+ "type": "VARCHAR2(500 BYTE)",
+ "comment": "Customer-specific instructions for this item"
+ },
+ {
+ "name": "FULFILLMENT_STATUS",
+ "position": 10,
+ "default": "'PENDING'",
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "comment": "Status: PENDING, PICKED, PACKED, SHIPPED, DELIVERED, RETURNED"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_ORDER_LINE_ITEMS",
+ "expressions": [
+ "LINE_ITEM_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ],
+ "comment": "Individual line items for customer orders. Each row represents one product within an order."
+ },
+ {
+ "name": "PRODUCT_CATALOG",
+ "columns": [
+ {
+ "name": "PRODUCT_ID",
+ "position": 1,
+ "type": "NUMBER",
+ "comment": "Unique identifier for the product. Primary key generated from sequence."
+ },
+ {
+ "name": "SKU",
+ "position": 2,
+ "type": "VARCHAR2(50 BYTE)",
+ "comment": "Stock Keeping Unit - unique alphanumeric code for inventory tracking"
+ },
+ {
+ "name": "PRODUCT_NAME",
+ "position": 3,
+ "type": "VARCHAR2(200 BYTE)",
+ "comment": "Display name of the product as shown to customers"
+ },
+ {
+ "name": "DESCRIPTION",
+ "position": 4,
+ "nullable": true,
+ "type": "CLOB",
+ "comment": "Detailed product description including features and specifications"
+ },
+ {
+ "name": "CATEGORY_ID",
+ "position": 5,
+ "type": "NUMBER",
+ "comment": "Foreign key reference to PRODUCT_CATEGORIES table"
+ },
+ {
+ "name": "PRICE",
+ "position": 6,
+ "type": "NUMBER(10,2)",
+ "comment": "Current selling price in base currency (USD)"
+ },
+ {
+ "name": "COST",
+ "position": 7,
+ "nullable": true,
+ "type": "NUMBER(10,2)",
+ "comment": "Cost of goods sold - used for profit margin calculations"
+ },
+ {
+ "name": "WEIGHT",
+ "position": 8,
+ "nullable": true,
+ "type": "NUMBER(8,3)",
+ "comment": "Product weight in kilograms - used for shipping calculations"
+ },
+ {
+ "name": "DIMENSIONS",
+ "position": 9,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "comment": "Product dimensions in format: Length x Width x Height (cm)"
+ },
+ {
+ "name": "COLOR",
+ "position": 10,
+ "nullable": true,
+ "type": "VARCHAR2(50 BYTE)",
+ "comment": "Primary color of the product"
+ },
+ {
+ "name": "PRODUCT_SIZE",
+ "position": 11,
+ "nullable": true,
+ "type": "VARCHAR2(20 BYTE)",
+ "comment": "Size designation (S, M, L, XL, etc.)"
+ },
+ {
+ "name": "BRAND",
+ "position": 12,
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "comment": "Brand or manufacturer name"
+ },
+ {
+ "name": "SUPPLIER_ID",
+ "position": 13,
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Reference to primary supplier in SUPPLIERS table"
+ },
+ {
+ "name": "IS_ACTIVE",
+ "position": 14,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER(1)",
+ "comment": "Flag indicating if product is active (1) or discontinued (0)"
+ },
+ {
+ "name": "STOCK_QUANTITY",
+ "position": 15,
+ "default": "0",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Current inventory quantity on hand"
+ },
+ {
+ "name": "REORDER_LEVEL",
+ "position": 16,
+ "default": "10",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Minimum stock level that triggers reorder process"
+ },
+ {
+ "name": "CREATED_DATE",
+ "position": 17,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE",
+ "comment": "Date when product record was first created"
+ },
+ {
+ "name": "CREATED_BY",
+ "position": 18,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "comment": "Username of person who created the record"
+ },
+ {
+ "name": "LAST_UPDATED",
+ "position": 19,
+ "default": "SYSDATE",
+ "nullable": true,
+ "type": "DATE",
+ "comment": "Date of most recent update to any field"
+ },
+ {
+ "name": "UPDATED_BY",
+ "position": 20,
+ "default": "USER",
+ "nullable": true,
+ "type": "VARCHAR2(100 BYTE)",
+ "comment": "Username of person who last modified the record"
+ },
+ {
+ "name": "VERSION_NUMBER",
+ "position": 21,
+ "default": "1",
+ "nullable": true,
+ "type": "NUMBER",
+ "comment": "Optimistic locking version number for concurrent update control"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_PRODUCT_CATALOG",
+ "expressions": [
+ "PRODUCT_ID"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "primary": true,
+ "visible": true,
+ "is_constraint": true
+ },
+ {
+ "name": "UK_PRODUCT_CATALOG_SKU",
+ "expressions": [
+ "SKU"
+ ],
+ "type": "NORMAL",
+ "unique": true,
+ "visible": true,
+ "is_constraint": true
+ }
+ ],
+ "comment": "Master catalog of all products available for sale. Contains detailed product information including pricing, inventory, and supplier details."
+ }
+ ]
+ }
+ ]
+ }
diff --git a/backend/plugin/schema/oracle/testutil_test.go b/backend/plugin/schema/oracle/testutil_test.go
deleted file mode 100644
index 0da8c37adf..0000000000
--- a/backend/plugin/schema/oracle/testutil_test.go
+++ /dev/null
@@ -1,249 +0,0 @@
-package oracle
-
-import (
- "context"
- "database/sql"
- "fmt"
- "slices"
- "strings"
-
- "github.com/pkg/errors"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
- oracledb "github.com/bytebase/bytebase/backend/plugin/db/oracle"
- plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql"
-)
-
-// createOracleUser creates an Oracle user (schema) with necessary privileges
-func createOracleUser(systemDB *sql.DB, username string) error {
- // Use same password as container for test simplicity
- for _, stmt := range []string{
- fmt.Sprintf("CREATE USER %s IDENTIFIED BY test123", username),
- fmt.Sprintf("GRANT CONNECT, RESOURCE, CREATE VIEW, CREATE MATERIALIZED VIEW, CREATE PROCEDURE, CREATE SEQUENCE, CREATE TRIGGER TO %s", username),
- fmt.Sprintf("GRANT UNLIMITED TABLESPACE TO %s", username),
- } {
- if _, err := systemDB.Exec(stmt); err != nil {
- return err
- }
- }
- return nil
-}
-
-// createOracleDriver creates and opens an Oracle driver connection
-func createOracleDriver(ctx context.Context, host, port, username string) (db.Driver, error) {
- driver := &oracledb.Driver{}
- config := db.ConnectionConfig{
- DataSource: &storepb.DataSource{
- Type: storepb.DataSourceType_ADMIN,
- Username: username,
- Host: host,
- Port: port,
- Database: "",
- ServiceName: "FREEPDB1",
- },
- Password: "test123", // Use same password as container for test simplicity
- ConnectionContext: db.ConnectionContext{
- EngineVersion: "23.0",
- DatabaseName: strings.ToUpper(username),
- },
- }
- return driver.Open(ctx, storepb.Engine_ORACLE, config)
-}
-
-// executeStatements executes multiple SQL statements, handling both regular DDL and PL/SQL blocks
-func executeStatements(ctx context.Context, driver db.Driver, statements string) error {
- // Use plsql.SplitSQL to properly split Oracle SQL statements
- stmts, err := plsqlparser.SplitSQL(statements)
- if err != nil {
- return errors.Wrapf(err, "failed to split SQL statements")
- }
-
- // Execute each statement
- for _, singleSQL := range stmts {
- stmt := strings.TrimSpace(singleSQL.Text)
- if stmt == "" {
- continue
- }
-
- // Skip statements that contain only comments
- // Strip all comment lines and check if there's actual SQL
- lines := strings.Split(stmt, "\n")
- hasSQL := false
- for _, line := range lines {
- trimmed := strings.TrimSpace(line)
- if trimmed != "" && !strings.HasPrefix(trimmed, "--") {
- hasSQL = true
- break
- }
- }
- if !hasSQL {
- continue
- }
-
- // Execute the statement
- if _, err := driver.Execute(ctx, stmt, db.ExecuteOptions{}); err != nil {
- // Handle Oracle-specific issues where materialized views are misclassified as tables
- if strings.Contains(err.Error(), "must use DROP MATERIALIZED VIEW") {
- // Try to fix the statement by replacing DROP TABLE with DROP MATERIALIZED VIEW
- if strings.HasPrefix(strings.ToUpper(stmt), "DROP TABLE") {
- fixedStmt := strings.Replace(stmt, "DROP TABLE", "DROP MATERIALIZED VIEW", 1)
- if _, retryErr := driver.Execute(ctx, fixedStmt, db.ExecuteOptions{}); retryErr == nil {
- continue // Successfully executed with corrected statement
- }
- }
- }
- // Handle system-generated virtual column indexes that cannot be manually created
- if strings.Contains(err.Error(), "invalid identifier") && strings.Contains(stmt, "SYS_NC") {
- // Skip statements that reference system-generated virtual columns
- continue
- }
- return errors.Wrapf(err, "failed to execute statement: %s", stmt)
- }
- }
-
- return nil
-}
-func normalizeMetadataForComparison(metadata *storepb.DatabaseSchemaMetadata) {
- // Clear database name as it might differ
- metadata.Name = ""
-
- // Normalize schemas
- for _, schema := range metadata.Schemas {
- // Normalize tables
- for _, table := range schema.Tables {
- table.DataSize = 0
- table.IndexSize = 0
- table.RowCount = 0
-
- // Filter out system-generated indexes that reference virtual columns
- var filteredIndexes []*storepb.IndexMetadata
- for _, idx := range table.Indexes {
- // Skip indexes that reference system-generated virtual columns
- hasVirtualColumn := false
- for _, expr := range idx.Expressions {
- if strings.HasPrefix(expr, "SYS_NC") {
- hasVirtualColumn = true
- break
- }
- }
- if !hasVirtualColumn {
- filteredIndexes = append(filteredIndexes, idx)
- }
- }
- table.Indexes = filteredIndexes
-
- // Sort columns by name for consistent comparison
- sortColumnsByName(table.Columns)
-
- // Sort indexes by name
- sortIndexesByName(table.Indexes)
-
- // Sort foreign keys by name
- sortForeignKeysByName(table.ForeignKeys)
-
- // Sort check constraints by name
- sortCheckConstraintsByName(table.CheckConstraints)
- }
-
- // Filter out system-generated sequences
- var filteredSequences []*storepb.SequenceMetadata
- for _, seq := range schema.Sequences {
- if !strings.HasPrefix(seq.Name, "ISEQ$$_") {
- filteredSequences = append(filteredSequences, seq)
- }
- }
- schema.Sequences = filteredSequences
-
- // Sort all collections for consistent comparison
- sortTablesByName(schema.Tables)
- sortViewsByName(schema.Views)
- sortMaterializedViewsByName(schema.MaterializedViews)
- sortFunctionsByName(schema.Functions)
- sortSequencesByName(schema.Sequences)
- }
-
- // Sort schemas by name
- sortSchemasByName(metadata.Schemas)
-
- // Sort extensions by name
- sortExtensionsByName(metadata.Extensions)
-}
-
-// Sorting helper functions
-func sortSchemasByName(schemas []*storepb.SchemaMetadata) {
- slices.SortFunc(schemas, func(a, b *storepb.SchemaMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortTablesByName(tables []*storepb.TableMetadata) {
- slices.SortFunc(tables, func(a, b *storepb.TableMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortColumnsByName(columns []*storepb.ColumnMetadata) {
- slices.SortFunc(columns, func(a, b *storepb.ColumnMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortIndexesByName(indexes []*storepb.IndexMetadata) {
- slices.SortFunc(indexes, func(a, b *storepb.IndexMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortForeignKeysByName(fks []*storepb.ForeignKeyMetadata) {
- slices.SortFunc(fks, func(a, b *storepb.ForeignKeyMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortCheckConstraintsByName(checks []*storepb.CheckConstraintMetadata) {
- slices.SortFunc(checks, func(a, b *storepb.CheckConstraintMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-// normalizeColumnPositions sets all column positions to 0 to ignore position differences during comparison
-func normalizeColumnPositions(metadata *storepb.DatabaseSchemaMetadata) {
- for _, schema := range metadata.Schemas {
- for _, table := range schema.Tables {
- for _, column := range table.Columns {
- column.Position = 0
- }
- }
- }
-}
-
-func sortViewsByName(views []*storepb.ViewMetadata) {
- slices.SortFunc(views, func(a, b *storepb.ViewMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortMaterializedViewsByName(mvs []*storepb.MaterializedViewMetadata) {
- slices.SortFunc(mvs, func(a, b *storepb.MaterializedViewMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortFunctionsByName(functions []*storepb.FunctionMetadata) {
- slices.SortFunc(functions, func(a, b *storepb.FunctionMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortSequencesByName(sequences []*storepb.SequenceMetadata) {
- slices.SortFunc(sequences, func(a, b *storepb.SequenceMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortExtensionsByName(extensions []*storepb.ExtensionMetadata) {
- slices.SortFunc(extensions, func(a, b *storepb.ExtensionMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
diff --git a/backend/plugin/schema/pg/get_database_definition_test.go b/backend/plugin/schema/pg/get_database_definition_test.go
index 02e5d4057d..1a7d3abb3c 100644
--- a/backend/plugin/schema/pg/get_database_definition_test.go
+++ b/backend/plugin/schema/pg/get_database_definition_test.go
@@ -1,18 +1,20 @@
package pg
import (
- "context"
- "fmt"
"strings"
"testing"
omnipg "github.com/bytebase/omni/pg"
"github.com/bytebase/omni/pg/catalog"
- "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "os"
+
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
@@ -2534,940 +2536,58 @@ func TestGetDatabaseDefinition_TableNameContainingDot(t *testing.T) {
}
}
-// TestGetDatabaseDefinitionWithTestcontainer tests the get_database_definition function
-// by comparing metadata from a database created using the original DDL versus
-// metadata from a database created using the generated DDL.
-//
-//nolint:tparallel
-func TestGetDatabaseDefinitionWithTestcontainer(t *testing.T) {
- ctx := context.Background()
-
- // Get PostgreSQL container from testcontainer.go
- pgContainer := testcontainer.SharedPgContainer(t)
-
- // Test cases with various PostgreSQL features
- testCases := []struct {
- name string
- ddl string
- }{
- {
- name: "basic_tables_with_constraints",
- ddl: `
-CREATE TABLE users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(50) NOT NULL UNIQUE,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP
-);
-
-CREATE TABLE posts (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published BOOLEAN DEFAULT false,
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE INDEX idx_posts_user_id ON posts(user_id);
-CREATE INDEX idx_posts_published ON posts(published) WHERE published = true;
-`,
- },
- {
- name: "sequences_and_custom_types",
- ddl: `
-CREATE TYPE status_enum AS ENUM ('pending', 'active', 'inactive', 'deleted');
-CREATE TYPE mood AS ENUM ('happy', 'sad', 'neutral');
-
-CREATE SEQUENCE custom_id_seq START WITH 1000 INCREMENT BY 10;
-
-CREATE TABLE items (
- id INTEGER DEFAULT nextval('custom_id_seq') PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- status status_enum DEFAULT 'pending',
- user_mood mood
-);
-`,
- },
- {
- name: "composite_types",
- ddl: `
--- zz_base sorts after its dependent aa_nested alphabetically, so a correct
--- dump proves dependency ordering rather than name ordering.
-CREATE TYPE zz_base AS (street text COLLATE "C", city varchar(50));
-COMMENT ON TYPE zz_base IS 'base address type';
-COMMENT ON COLUMN zz_base.street IS 'street line';
-
-CREATE TYPE aa_nested AS (home zz_base, homes zz_base[], tags text[]);
-
-CREATE TYPE order_status AS ENUM ('pending', 'shipped');
-CREATE TYPE order_info AS (status order_status, note text);
-
-CREATE SCHEMA geo;
-CREATE TYPE geo.point2 AS (lat numeric(9,6), lng numeric(9,6));
-CREATE TYPE wrapper AS (p geo.point2);
-
-CREATE TYPE empty_type AS ();
-
-CREATE TABLE orders (
- id SERIAL PRIMARY KEY,
- info order_info,
- addresses aa_nested,
- location geo.point2
-);
-`,
- },
- {
- name: "owned_sequence_dependency_order",
- ddl: `
--- This reproduces the customer's reported issue
--- Create a sequence that will be owned by a column
-CREATE SEQUENCE history_cost_changes_id_seq
- AS bigint
- START WITH 1
- INCREMENT BY 1
- MINVALUE 1
- MAXVALUE 9223372036854775807
- NO CYCLE;
-
--- Create table using the sequence in DEFAULT clause
-CREATE TABLE history_cost_changes (
- id bigint DEFAULT nextval('history_cost_changes_id_seq'::regclass) NOT NULL PRIMARY KEY,
- amount numeric(10,2),
- description text,
- created_at timestamp DEFAULT CURRENT_TIMESTAMP
-);
-
--- Make the sequence owned by the column (critical for reproducing the bug!)
-ALTER SEQUENCE history_cost_changes_id_seq OWNED BY history_cost_changes.id;
-
--- Create another table that also references the same sequence (edge case)
-CREATE TABLE history_audit (
- audit_id bigint DEFAULT nextval('history_cost_changes_id_seq'::regclass) NOT NULL,
- change_type varchar(50)
-);
-`,
- },
- {
- name: "views_and_functions",
- ddl: `
-CREATE TABLE employees (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- department VARCHAR(50),
- salary DECIMAL(10, 2)
-);
-
-CREATE VIEW active_employees AS
-SELECT id, name, department
-FROM employees
-WHERE department IS NOT NULL;
-
-CREATE FUNCTION get_employee_count(dept VARCHAR) RETURNS INTEGER AS $$
-BEGIN
- RETURN (SELECT COUNT(*) FROM employees WHERE department = dept);
-END;
-$$ LANGUAGE plpgsql;
-
-CREATE FUNCTION calculate_bonus(emp_id INTEGER) RETURNS DECIMAL AS $$
-DECLARE
- emp_salary DECIMAL;
-BEGIN
- SELECT salary INTO emp_salary FROM employees WHERE id = emp_id;
- RETURN emp_salary * 0.1;
-END;
-$$ LANGUAGE plpgsql;
-`,
- },
- {
- name: "partitioned_tables",
- ddl: `
-CREATE TABLE sales (
- id SERIAL,
- sale_date DATE NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- region VARCHAR(50) NOT NULL
-) PARTITION BY RANGE (sale_date);
-
-CREATE TABLE sales_2023_q1 PARTITION OF sales
-FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');
-
-CREATE TABLE sales_2023_q2 PARTITION OF sales
-FOR VALUES FROM ('2023-04-01') TO ('2023-07-01');
-
-CREATE TABLE sales_2023_q3 PARTITION OF sales
-FOR VALUES FROM ('2023-07-01') TO ('2023-10-01');
-
-CREATE TABLE sales_2023_q4 PARTITION OF sales
-FOR VALUES FROM ('2023-10-01') TO ('2024-01-01');
-`,
- },
- {
- name: "extensions_and_advanced_features",
- ddl: `
-CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-
-CREATE TABLE documents (
- id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- tags TEXT[],
- metadata JSONB,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE INDEX idx_documents_metadata ON documents USING GIN (metadata);
-CREATE INDEX idx_documents_tags ON documents USING GIN (tags);
-`,
- },
- {
- name: "check_constraints_and_comments",
- ddl: `
-CREATE TABLE products (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- quantity INTEGER NOT NULL,
- CONSTRAINT chk_price CHECK (price > 0),
- CONSTRAINT chk_quantity CHECK (quantity >= 0)
-);
-
-COMMENT ON TABLE products IS 'Product catalog table';
-COMMENT ON COLUMN products.name IS 'Product name';
-COMMENT ON COLUMN products.price IS 'Product price in USD';
-`,
- },
- {
- name: "materialized_views",
- ddl: `
-CREATE TABLE raw_data (
- id SERIAL PRIMARY KEY,
- data_value NUMERIC NOT NULL,
- category VARCHAR(50) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE MATERIALIZED VIEW data_summary AS
-SELECT category,
- COUNT(*) as count,
- AVG(data_value) as avg_value,
- MAX(data_value) as max_value,
- MIN(data_value) as min_value
-FROM raw_data
-GROUP BY category
-WITH NO DATA;
-
-CREATE INDEX idx_data_summary_category ON data_summary(category);
-`,
- },
- {
- name: "comprehensive_views",
- ddl: `
-CREATE TABLE customers (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100) UNIQUE,
- active BOOLEAN DEFAULT true,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE orders (
- id SERIAL PRIMARY KEY,
- customer_id INTEGER REFERENCES customers(id),
- total_amount DECIMAL(10, 2) NOT NULL,
- order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- status VARCHAR(20) DEFAULT 'pending'
-);
-
--- View with public schema references and various formatting
-CREATE VIEW public.active_customer_orders AS
- SELECT
- c.id AS customer_id,
- c.name,
- c.email,
- o.id AS order_id,
- o.total_amount,
- o.order_date
- FROM
- public.customers c
- INNER JOIN public.orders o ON c.id = o.customer_id
- WHERE
- c.active = TRUE
- AND o.status = 'completed';
-
--- Simple view without schema qualification
-CREATE VIEW customer_summary AS
-SELECT
- id,
- name,
- email,
- (SELECT COUNT(*) FROM orders WHERE customer_id = customers.id) as order_count
-FROM customers
-WHERE active = true;
-
--- Materialized view with complex aggregation
-CREATE MATERIALIZED VIEW monthly_sales_summary AS
-SELECT
- DATE_TRUNC('month', order_date) as month,
- COUNT(*) as order_count,
- SUM(total_amount) as total_revenue,
- AVG(total_amount) as avg_order_value,
- COUNT(DISTINCT customer_id) as unique_customers
-FROM public.orders
-WHERE status = 'completed'
-GROUP BY DATE_TRUNC('month', order_date)
-ORDER BY month
-WITH NO DATA;
-
-CREATE UNIQUE INDEX idx_monthly_sales_month ON monthly_sales_summary(month);
-`,
- },
- {
- name: "triggers",
- ddl: `
-CREATE TABLE audit_log (
- id SERIAL PRIMARY KEY,
- table_name VARCHAR(50) NOT NULL,
- operation VARCHAR(10) NOT NULL,
- user_name VARCHAR(50),
- timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE accounts (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- balance DECIMAL(10, 2) DEFAULT 0,
- last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE OR REPLACE FUNCTION update_last_modified()
-RETURNS TRIGGER AS $$
-BEGIN
- NEW.last_modified = CURRENT_TIMESTAMP;
- RETURN NEW;
-END;
-$$ LANGUAGE plpgsql;
-
-CREATE TRIGGER trg_update_last_modified
-BEFORE UPDATE ON accounts
-FOR EACH ROW
-EXECUTE FUNCTION update_last_modified();
-
-CREATE OR REPLACE FUNCTION log_account_changes()
-RETURNS TRIGGER AS $$
-BEGIN
- INSERT INTO audit_log (table_name, operation, user_name)
- VALUES ('accounts', TG_OP, current_user);
- RETURN NEW;
-END;
-$$ LANGUAGE plpgsql;
-
-CREATE TRIGGER trg_audit_accounts
-AFTER INSERT OR UPDATE OR DELETE ON accounts
-FOR EACH ROW
-EXECUTE FUNCTION log_account_changes();
-`,
- },
- {
- name: "foreign_key_on_delete_cascade",
- ddl: `
-CREATE TABLE categories (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL
-);
-
-CREATE TABLE products (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- category_id INTEGER,
- CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE
-);
-
-CREATE TABLE orders (
- id SERIAL PRIMARY KEY,
- product_id INTEGER,
- quantity INTEGER DEFAULT 1,
- CONSTRAINT fk_product_cascade FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE SET NULL
-);
-`,
- },
- {
- name: "foreign_key_on_update_actions",
- ddl: `
-CREATE TABLE departments (
- code VARCHAR(10) PRIMARY KEY,
- name VARCHAR(100) NOT NULL
-);
-
-CREATE TABLE employees (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- dept_code VARCHAR(10),
- manager_id INTEGER,
- CONSTRAINT fk_dept_restrict FOREIGN KEY (dept_code) REFERENCES departments(code) ON UPDATE RESTRICT ON DELETE SET NULL,
- CONSTRAINT fk_manager_cascade FOREIGN KEY (manager_id) REFERENCES employees(id) ON UPDATE CASCADE ON DELETE CASCADE
-);
-
-CREATE TABLE projects (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- lead_emp_id INTEGER,
- dept_code VARCHAR(10),
- CONSTRAINT fk_lead_setnull FOREIGN KEY (lead_emp_id) REFERENCES employees(id) ON DELETE SET NULL ON UPDATE SET NULL,
- CONSTRAINT fk_proj_dept FOREIGN KEY (dept_code) REFERENCES departments(code) ON DELETE RESTRICT ON UPDATE RESTRICT
-);
-`,
- },
- {
- name: "foreign_key_no_action",
- ddl: `
-CREATE TABLE countries (
- id SERIAL PRIMARY KEY,
- code VARCHAR(3) UNIQUE NOT NULL,
- name VARCHAR(100) NOT NULL
-);
-
-CREATE TABLE states (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- country_id INTEGER,
- -- Explicit NO ACTION
- CONSTRAINT fk_country_explicit FOREIGN KEY (country_id) REFERENCES countries(id) ON DELETE NO ACTION ON UPDATE NO ACTION
-);
-
-CREATE TABLE cities (
- id SERIAL PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- state_id INTEGER,
- -- Implicit NO ACTION (default behavior)
- CONSTRAINT fk_state_implicit FOREIGN KEY (state_id) REFERENCES states(id)
-);
-`,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
-
- // Create first database with original DDL using unique name
- dbNameA := fmt.Sprintf("test_a_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err := pgContainer.GetDB().Exec(fmt.Sprintf("CREATE DATABASE %s", dbNameA))
- require.NoError(t, err)
-
- // Create driver for database A
- driverA, err := createPgDriver(ctx, pgContainer.GetHost(), pgContainer.GetPort(), dbNameA)
- require.NoError(t, err)
- defer driverA.Close(ctx)
-
- // Execute the original DDL
- _, err = driverA.GetDB().ExecContext(ctx, tc.ddl)
- require.NoError(t, err)
-
- // Get metadata A using Driver.SyncDBSchema
- metadataA, err := driverA.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Generate database definition using GetDatabaseDefinition
- generatedDDL, err := GetDatabaseDefinition(schema.GetDefinitionContext{PrintHeader: true}, metadataA)
- require.NoError(t, err)
- require.NotEmpty(t, generatedDDL, "generated DDL should not be empty")
-
- // Create second database and apply generated DDL using unique name
- dbNameB := fmt.Sprintf("test_b_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err = pgContainer.GetDB().Exec(fmt.Sprintf("CREATE DATABASE %s", dbNameB))
- require.NoError(t, err)
-
- // Create driver for database B
- driverB, err := createPgDriver(ctx, pgContainer.GetHost(), pgContainer.GetPort(), dbNameB)
- require.NoError(t, err)
- defer driverB.Close(ctx)
-
- // Execute the generated DDL
- _, err = driverB.GetDB().ExecContext(ctx, generatedDDL)
- require.NoError(t, err, "failed to execute generated DDL: %s", generatedDDL)
-
- // Get metadata B using Driver.SyncDBSchema
- metadataB, err := driverB.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Compare metadata A and B
- compareFullMetadata(t, metadataA, metadataB)
- })
- }
+type getDatabaseDefinitionCase struct {
+ Description string `yaml:"description"`
+ Metadata string `yaml:"metadata"`
+ Expected string `yaml:"expected"`
}
-// compareFullMetadata compares all aspects of database metadata
-func compareFullMetadata(t *testing.T, metaA, metaB *storepb.DatabaseSchemaMetadata) {
- // Compare extensions
- compareExtensionsDef(t, metaA.Extensions, metaB.Extensions)
-
- // Compare schemas
- require.Equal(t, len(metaA.Schemas), len(metaB.Schemas), "number of schemas should match")
-
- // Find the public schema in both
- var schemaA, schemaB *storepb.SchemaMetadata
- for _, schema := range metaA.Schemas {
- if schema.Name == "public" {
- schemaA = schema
- break
- }
- }
- for _, schema := range metaB.Schemas {
- if schema.Name == "public" {
- schemaB = schema
- break
- }
- }
-
- require.NotNil(t, schemaA, "metadata A should have public schema")
- require.NotNil(t, schemaB, "metadata B should have public schema")
-
- // Compare schema contents
- compareSchemaContents(t, schemaA, schemaB)
-}
-
-// compareSchemaContents compares the contents of two schemas
-func compareSchemaContents(t *testing.T, schemaA, schemaB *storepb.SchemaMetadata) {
- // Compare enums
- compareEnumsDef(t, schemaA.EnumTypes, schemaB.EnumTypes)
-
- // Compare composite types
- compareCompositeTypesDef(t, schemaA.CompositeTypes, schemaB.CompositeTypes)
-
- // Compare sequences (excluding implicit sequences from SERIAL columns)
- compareExplicitSequences(t, schemaA.Sequences, schemaB.Sequences)
-
- // Compare tables
- compareTablesDef(t, schemaA.Tables, schemaB.Tables)
-
- // Compare views
- compareViewsDef(t, schemaA.Views, schemaB.Views)
-
- // Compare materialized views
- compareMaterializedViewsDef(t, schemaA.MaterializedViews, schemaB.MaterializedViews)
-
- // Compare functions
- compareFunctionsDef(t, schemaA.Functions, schemaB.Functions)
-}
-
-// compareExplicitSequences compares only explicitly created sequences
-func compareExplicitSequences(t *testing.T, seqsA, seqsB []*storepb.SequenceMetadata) {
- // Filter out implicit sequences (those owned by columns)
- explicitA := filterExplicitSequences(seqsA)
- explicitB := filterExplicitSequences(seqsB)
-
- require.Equal(t, len(explicitA), len(explicitB), "number of explicit sequences should match")
-
- // Create maps for comparison
- mapA := make(map[string]*storepb.SequenceMetadata)
- for _, seq := range explicitA {
- mapA[seq.Name] = seq
- }
-
- for _, seqB := range explicitB {
- seqA, exists := mapA[seqB.Name]
- require.True(t, exists, "sequence %s should exist in metadata A", seqB.Name)
-
- // Compare sequence properties
- require.Equal(t, seqA.Start, seqB.Start, "sequence %s: start value should match", seqB.Name)
- require.Equal(t, seqA.Increment, seqB.Increment, "sequence %s: increment should match", seqB.Name)
- require.Equal(t, seqA.MinValue, seqB.MinValue, "sequence %s: min value should match", seqB.Name)
- require.Equal(t, seqA.MaxValue, seqB.MaxValue, "sequence %s: max value should match", seqB.Name)
- require.Equal(t, seqA.Cycle, seqB.Cycle, "sequence %s: cycle should match", seqB.Name)
- require.Equal(t, seqA.Comment, seqB.Comment, "sequence %s: comment should match", seqB.Name)
- }
-}
-
-// filterExplicitSequences returns only sequences that are not owned by columns
-func filterExplicitSequences(sequences []*storepb.SequenceMetadata) []*storepb.SequenceMetadata {
- var result []*storepb.SequenceMetadata
- for _, seq := range sequences {
- if seq.OwnerTable == "" || seq.OwnerColumn == "" {
- result = append(result, seq)
- }
- }
- return result
-}
-
-// compareMaterializedViewsDef compares materialized views between two schemas using PostgreSQL view comparer
-func compareMaterializedViewsDef(t *testing.T, viewsA, viewsB []*storepb.MaterializedViewMetadata) {
- require.Equal(t, len(viewsA), len(viewsB), "number of materialized views should match")
-
- // Create maps for comparison
- mapA := make(map[string]*storepb.MaterializedViewMetadata)
- for _, view := range viewsA {
- mapA[view.Name] = view
- }
-
- for _, viewB := range viewsB {
- viewA, exists := mapA[viewB.Name]
- require.True(t, exists, "materialized view %s should exist in metadata A", viewB.Name)
-
- // Compare view definitions using normalized string comparison
- defA := normalizeSQLDef(viewA.Definition)
- defB := normalizeSQLDef(viewB.Definition)
- definitionsEqual := defA == defB
-
- // Assert that materialized view definitions must be equal after sophisticated PostgreSQL parsing
- require.True(t, definitionsEqual,
- "materialized view %s: definitions must be equal using PostgreSQL view comparer (A: %q, B: %q)",
- viewB.Name, viewA.Definition, viewB.Definition)
-
- require.Equal(t, viewA.Comment, viewB.Comment,
- "materialized view %s: comment should match", viewB.Name)
-
- // Compare indexes on materialized views
- compareIndexesDef(t, viewB.Name, viewA.Indexes, viewB.Indexes)
- }
-}
-
-// normalizeSQLDef normalizes SQL for comparison
-func normalizeSQLDef(sql string) string {
- // Convert to lowercase
- sql = strings.ToLower(sql)
-
- // Replace multiple spaces/newlines with single space
- sql = strings.Join(strings.Fields(sql), " ")
-
- // Remove trailing semicolons
- sql = strings.TrimSuffix(sql, ";")
-
- // Remove schema qualifiers for public schema
- sql = strings.ReplaceAll(sql, "public.", "")
-
- // Final trim
- sql = strings.TrimSpace(sql)
-
- return sql
-}
-
-// normalizeExprDef normalizes an expression for comparison
-func normalizeExprDef(expr string) string {
- // Convert to lowercase
- expr = strings.ToLower(expr)
-
- // Replace multiple spaces with single space
- expr = strings.Join(strings.Fields(expr), " ")
-
- // Remove spaces around parentheses
- expr = strings.ReplaceAll(expr, " (", "(")
- expr = strings.ReplaceAll(expr, "( ", "(")
- expr = strings.ReplaceAll(expr, " )", ")")
- expr = strings.ReplaceAll(expr, ") ", ")")
-
- // Normalize quotes around identifiers
- expr = strings.ReplaceAll(expr, "'", "")
-
- return expr
-}
-
-// compareTablesDef compares tables between two schemas
-func compareTablesDef(t *testing.T, tablesA, tablesB []*storepb.TableMetadata) {
- require.Equal(t, len(tablesA), len(tablesB), "number of tables should match")
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.TableMetadata)
- for _, table := range tablesA {
- mapA[table.Name] = table
- }
-
- mapB := make(map[string]*storepb.TableMetadata)
- for _, table := range tablesB {
- mapB[table.Name] = table
- }
-
- // Compare each table
- for name, tableA := range mapA {
- tableB, exists := mapB[name]
- require.True(t, exists, "table %s should exist in metadata B", name)
-
- // Compare columns
- compareColumnsDef(t, name, tableA.Columns, tableB.Columns)
-
- // Compare indexes
- compareIndexesDef(t, name, tableA.Indexes, tableB.Indexes)
-
- // Compare foreign keys
- compareForeignKeysDef(t, name, tableA.ForeignKeys, tableB.ForeignKeys)
-
- // Compare check constraints
- compareCheckConstraintsDef(t, name, tableA.CheckConstraints, tableB.CheckConstraints)
-
- // Compare partitions
- comparePartitionsDef(t, name, tableA.Partitions, tableB.Partitions)
-
- // Compare triggers
- compareTriggersDef(t, name, tableA.Triggers, tableB.Triggers)
-
- // Compare comments
- require.Equal(t, tableA.Comment, tableB.Comment, "table %s: comment should match", name)
- }
-}
-
-// compareColumnsDef compares columns between two tables
-func compareColumnsDef(t *testing.T, tableName string, colsA, colsB []*storepb.ColumnMetadata) {
- require.Equal(t, len(colsA), len(colsB), "table %s: number of columns should match", tableName)
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.ColumnMetadata)
- for _, col := range colsA {
- mapA[col.Name] = col
- }
+// TestGetDatabaseDefinition pins the DDL generated for each metadata input,
+// and reloads that DDL into an omni catalog to prove it is valid PostgreSQL.
+//
+// The input is metadata rather than a schema text on purpose: deriving it by
+// parsing would cap this test's reach at whatever the loader happens to extract,
+// so any generator branch nothing feeds would go untested.
+func TestGetDatabaseDefinition(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/get_database_definition.yaml"
+ )
- for _, colB := range colsB {
- colA, exists := mapA[colB.Name]
- require.True(t, exists, "table %s: column %s should exist in metadata A", tableName, colB.Name)
-
- // Compare column properties
- require.Equal(t, colA.Type, colB.Type, "table %s, column %s: type should match", tableName, colB.Name)
- require.Equal(t, colA.Nullable, colB.Nullable, "table %s, column %s: nullable should match", tableName, colB.Name)
- require.Equal(t, colA.Comment, colB.Comment, "table %s, column %s: comment should match", tableName, colB.Name)
-
- // Compare default values if both exist
- hasDefaultA := colA.Default != ""
- hasDefaultB := colB.Default != ""
- if hasDefaultA && hasDefaultB {
- // Default values might be represented differently, so we just check they exist
- t.Logf("table %s, column %s: default values exist in both", tableName, colB.Name)
- }
- }
-}
+ var tests []getDatabaseDefinitionCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
-// compareIndexesDef compares indexes between two tables
-func compareIndexesDef(t *testing.T, tableName string, indexesA, indexesB []*storepb.IndexMetadata) {
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.IndexMetadata)
- for _, idx := range indexesA {
- mapA[idx.Name] = idx
- }
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ var metadata storepb.DatabaseSchemaMetadata
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Metadata), &metadata))
- mapB := make(map[string]*storepb.IndexMetadata)
- for _, idx := range indexesB {
- mapB[idx.Name] = idx
- }
+ definition, err := GetDatabaseDefinition(schema.GetDefinitionContext{PrintHeader: true}, &metadata)
+ require.NoError(t, err)
+ require.NotEmpty(t, definition)
- // Compare common indexes
- for name, idxB := range mapB {
- idxA, exists := mapA[name]
- if !exists {
- // Some indexes might be system-generated
- t.Logf("table %s: index %s exists in B but not in A (might be implicit)", tableName, name)
- continue
- }
+ _, err = catalog.New().Exec(definition, &catalog.ExecOptions{ContinueOnError: true})
+ require.NoError(t, err, "generated definition should load into the omni catalog")
- require.Equal(t, idxA.Primary, idxB.Primary, "table %s, index %s: primary should match", tableName, name)
- require.Equal(t, idxA.Unique, idxB.Unique, "table %s, index %s: unique should match", tableName, name)
+ // A YAML block scalar cannot carry a leading newline, so the blank
+ // line this header opens with is trimmed rather than pinned.
+ definition = strings.TrimPrefix(definition, "\n")
- // Compare expressions
- if len(idxA.Expressions) == len(idxB.Expressions) {
- for i := range idxA.Expressions {
- exprA := normalizeExprDef(idxA.Expressions[i])
- exprB := normalizeExprDef(idxB.Expressions[i])
- require.Equal(t, exprA, exprB, "table %s, index %s: expression[%d] should match", tableName, name, i)
+ if record {
+ tests[i].Expected = definition
+ return
}
- }
-
- // Compare IsConstraint field
- require.Equal(t, idxA.IsConstraint, idxB.IsConstraint, "table %s, index %s: IsConstraint should match", tableName, name)
-
- // Compare comment
- require.Equal(t, idxA.Comment, idxB.Comment, "table %s, index %s: comment should match", tableName, name)
- }
-}
-
-// compareForeignKeysDef compares foreign keys between two tables
-func compareForeignKeysDef(t *testing.T, tableName string, fksA, fksB []*storepb.ForeignKeyMetadata) {
- require.Equal(t, len(fksA), len(fksB), "table %s: number of foreign keys should match", tableName)
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.ForeignKeyMetadata)
- for _, fk := range fksA {
- mapA[fk.Name] = fk
- }
-
- for _, fkB := range fksB {
- fkA, exists := mapA[fkB.Name]
- require.True(t, exists, "table %s: foreign key %s should exist in metadata A", tableName, fkB.Name)
-
- require.ElementsMatch(t, fkA.Columns, fkB.Columns, "table %s, FK %s: columns should match", tableName, fkB.Name)
- require.Equal(t, fkA.ReferencedTable, fkB.ReferencedTable, "table %s, FK %s: referenced table should match", tableName, fkB.Name)
- require.ElementsMatch(t, fkA.ReferencedColumns, fkB.ReferencedColumns, "table %s, FK %s: referenced columns should match", tableName, fkB.Name)
-
- // Compare ON DELETE and ON UPDATE actions
- require.Equal(t, fkA.OnDelete, fkB.OnDelete, "table %s, FK %s: ON DELETE action should match", tableName, fkB.Name)
- require.Equal(t, fkA.OnUpdate, fkB.OnUpdate, "table %s, FK %s: ON UPDATE action should match", tableName, fkB.Name)
- }
-}
-
-// compareCheckConstraintsDef compares check constraints between two tables
-func compareCheckConstraintsDef(t *testing.T, tableName string, checksA, checksB []*storepb.CheckConstraintMetadata) {
- require.Equal(t, len(checksA), len(checksB), "table %s: number of check constraints should match", tableName)
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.CheckConstraintMetadata)
- for _, check := range checksA {
- mapA[check.Name] = check
- }
-
- for _, checkB := range checksB {
- checkA, exists := mapA[checkB.Name]
- require.True(t, exists, "table %s: check constraint %s should exist in metadata A", tableName, checkB.Name)
-
- // Normalize and compare expressions
- exprA := normalizeExprDef(checkA.Expression)
- exprB := normalizeExprDef(checkB.Expression)
- require.Equal(t, exprA, exprB, "table %s, check %s: expression should match", tableName, checkB.Name)
- }
-}
-
-// comparePartitionsDef compares partitions between two tables
-func comparePartitionsDef(t *testing.T, tableName string, partsA, partsB []*storepb.TablePartitionMetadata) {
- require.Equal(t, len(partsA), len(partsB), "table %s: number of partitions should match", tableName)
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.TablePartitionMetadata)
- for _, part := range partsA {
- mapA[part.Name] = part
- }
-
- for _, partB := range partsB {
- partA, exists := mapA[partB.Name]
- require.True(t, exists, "table %s: partition %s should exist in metadata A", tableName, partB.Name)
- require.Equal(t, partA.Expression, partB.Expression, "table %s, partition %s: expression should match", tableName, partB.Name)
- require.Equal(t, partA.Value, partB.Value, "table %s, partition %s: value should match", tableName, partB.Name)
- }
-}
-
-// compareTriggersDef compares triggers between two tables
-func compareTriggersDef(t *testing.T, tableName string, triggersA, triggersB []*storepb.TriggerMetadata) {
- require.Equal(t, len(triggersA), len(triggersB), "table %s: number of triggers should match", tableName)
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.TriggerMetadata)
- for _, trigger := range triggersA {
- mapA[trigger.Name] = trigger
- }
-
- for _, triggerB := range triggersB {
- triggerA, exists := mapA[triggerB.Name]
- require.True(t, exists, "table %s: trigger %s should exist in metadata A", tableName, triggerB.Name)
-
- // Compare trigger properties
- require.Equal(t, normalizeSQLDef(triggerA.Body), normalizeSQLDef(triggerB.Body),
- "table %s, trigger %s: body should match", tableName, triggerB.Name)
- require.Equal(t, triggerA.Comment, triggerB.Comment,
- "table %s, trigger %s: comment should match", tableName, triggerB.Name)
- }
-}
-
-// compareViewsDef compares views between two schemas using PostgreSQL view comparer
-func compareViewsDef(t *testing.T, viewsA, viewsB []*storepb.ViewMetadata) {
- require.Equal(t, len(viewsA), len(viewsB), "number of views should match")
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.ViewMetadata)
- for _, view := range viewsA {
- mapA[view.Name] = view
- }
-
- for _, viewB := range viewsB {
- viewA, exists := mapA[viewB.Name]
- require.True(t, exists, "view %s should exist in metadata A", viewB.Name)
-
- // Compare view definitions using normalized string comparison
- require.Equal(t, normalizeSQLDef(viewA.Definition), normalizeSQLDef(viewB.Definition),
- "view %s: definitions should match", viewB.Name)
-
- // Compare comment
- require.Equal(t, viewA.Comment, viewB.Comment, "view %s: comment should match", viewB.Name)
- }
-}
-
-// compareFunctionsDef compares functions between two schemas
-func compareFunctionsDef(t *testing.T, funcsA, funcsB []*storepb.FunctionMetadata) {
- require.Equal(t, len(funcsA), len(funcsB), "number of functions should match")
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.FunctionMetadata)
- for _, fn := range funcsA {
- mapA[fn.Name] = fn
- }
-
- for _, fnB := range funcsB {
- fnA, exists := mapA[fnB.Name]
- require.True(t, exists, "function %s should exist in metadata A", fnB.Name)
-
- // Compare function definitions
- defA := normalizeSQLDef(fnA.Definition)
- defB := normalizeSQLDef(fnB.Definition)
- require.Equal(t, defA, defB, "function %s: definition should match", fnB.Name)
-
- // Compare comment
- require.Equal(t, fnA.Comment, fnB.Comment, "function %s: comment should match", fnB.Name)
- }
-}
-
-// compareEnumsDef compares enum types between two schemas
-func compareEnumsDef(t *testing.T, enumsA, enumsB []*storepb.EnumTypeMetadata) {
- require.Equal(t, len(enumsA), len(enumsB), "number of enums should match")
-
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.EnumTypeMetadata)
- for _, enum := range enumsA {
- mapA[enum.Name] = enum
- }
-
- for _, enumB := range enumsB {
- enumA, exists := mapA[enumB.Name]
- require.True(t, exists, "enum %s should exist in metadata A", enumB.Name)
- require.ElementsMatch(t, enumA.Values, enumB.Values, "enum %s: values should match", enumB.Name)
- require.Equal(t, enumA.Comment, enumB.Comment, "enum %s: comment should match", enumB.Name)
- }
-}
-
-func compareCompositeTypesDef(t *testing.T, compositesA, compositesB []*storepb.CompositeTypeMetadata) {
- require.Equal(t, len(compositesA), len(compositesB), "number of composite types should match")
-
- mapA := make(map[string]*storepb.CompositeTypeMetadata)
- for _, composite := range compositesA {
- mapA[composite.Name] = composite
- }
-
- for _, compositeB := range compositesB {
- compositeA, exists := mapA[compositeB.Name]
- require.True(t, exists, "composite type %s should exist in metadata A", compositeB.Name)
- require.Equal(t, compositeA.Comment, compositeB.Comment, "composite type %s: comment should match", compositeB.Name)
- require.Equal(t, len(compositeA.Attributes), len(compositeB.Attributes), "composite type %s: attribute count should match", compositeB.Name)
- for i, attributeA := range compositeA.Attributes {
- attributeB := compositeB.Attributes[i]
- require.Equal(t, attributeA.Name, attributeB.Name, "composite type %s: attribute %d name should match", compositeB.Name, i)
- require.Equal(t, attributeA.Type, attributeB.Type, "composite type %s: attribute %s type should match", compositeB.Name, attributeA.Name)
- require.Equal(t, attributeA.Collation, attributeB.Collation, "composite type %s: attribute %s collation should match", compositeB.Name, attributeA.Name)
- require.Equal(t, attributeA.Comment, attributeB.Comment, "composite type %s: attribute %s comment should match", compositeB.Name, attributeA.Name)
- }
- }
-}
-
-// compareExtensionsDef compares extensions between two databases
-func compareExtensionsDef(t *testing.T, extsA, extsB []*storepb.ExtensionMetadata) {
- // Create maps for easier comparison
- mapA := make(map[string]*storepb.ExtensionMetadata)
- for _, ext := range extsA {
- mapA[ext.Name] = ext
+ require.Equal(t, tc.Expected, definition)
+ })
}
- for _, extB := range extsB {
- extA, exists := mapA[extB.Name]
- require.True(t, exists, "extension %s should exist in metadata A", extB.Name)
- require.Equal(t, extA.Schema, extB.Schema, "extension %s: schema should match", extB.Name)
- require.Equal(t, extA.Version, extB.Version, "extension %s: version should match", extB.Name)
+ if record {
+ yamltest.Record(t, filepath, tests)
}
}
-// TestCheckConstraintOrderStability tests that CHECK constraints maintain consistent order
-// when generating SDL multiple times from the same metadata
func TestCheckConstraintOrderStability(t *testing.T) {
// Simulate database metadata with multiple CHECK constraints
// (similar to the packages_debian_group_distributions table shown in the screenshot)
diff --git a/backend/plugin/schema/pg/main_test.go b/backend/plugin/schema/pg/main_test.go
deleted file mode 100644
index 12b1b9272c..0000000000
--- a/backend/plugin/schema/pg/main_test.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package pg
-
-import (
- "testing"
-
- "github.com/bytebase/bytebase/backend/common/testcontainer"
-)
-
-func TestMain(m *testing.M) { testcontainer.Main(m) }
diff --git a/backend/plugin/schema/pg/testdata/get_database_definition.yaml b/backend/plugin/schema/pg/testdata/get_database_definition.yaml
new file mode 100644
index 0000000000..f08db6ebd7
--- /dev/null
+++ b/backend/plugin/schema/pg/testdata/get_database_definition.yaml
@@ -0,0 +1,3173 @@
+- description: basic_tables_with_constraints
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "posts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.posts_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "integer"
+ },
+ {
+ "name": "title",
+ "position": 3,
+ "type": "character varying(200)"
+ },
+ {
+ "name": "content",
+ "position": 4,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "published",
+ "position": 5,
+ "default": "false",
+ "nullable": true,
+ "type": "boolean"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "idx_posts_published",
+ "expressions": [
+ "published"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "definition": "CREATE INDEX idx_posts_published ON public.posts USING btree (published) WHERE (published = true);",
+ "opclass_names": [
+ "bool_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ },
+ {
+ "name": "idx_posts_user_id",
+ "expressions": [
+ "user_id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "definition": "CREATE INDEX idx_posts_user_id ON public.posts USING btree (user_id);",
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ },
+ {
+ "name": "posts_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX posts_pkey ON public.posts USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "data_size": 8192,
+ "index_size": 24576,
+ "foreign_keys": [
+ {
+ "name": "fk_user",
+ "columns": [
+ "user_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "users",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "NO ACTION",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ },
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.users_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "username",
+ "position": 2,
+ "type": "character varying(50)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ },
+ {
+ "name": "updated_at",
+ "position": 5,
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "users_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX users_pkey ON public.users USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ },
+ {
+ "name": "users_username_key",
+ "expressions": [
+ "username"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "definition": "CREATE UNIQUE INDEX users_username_key ON public.users USING btree (username);",
+ "is_constraint": true,
+ "opclass_names": [
+ "text_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 16384,
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "posts_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "posts",
+ "owner_column": "id"
+ },
+ {
+ "name": "users_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "users",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."posts_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ CREATE SEQUENCE "public"."users_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."posts" (
+ "id" integer DEFAULT nextval('public.posts_id_seq'::regclass) NOT NULL,
+ "user_id" integer NOT NULL,
+ "title" character varying(200) NOT NULL,
+ "content" text,
+ "published" boolean DEFAULT false
+ );
+
+ ALTER SEQUENCE "public"."posts_id_seq" OWNED BY "public"."posts"."id";
+
+ ALTER TABLE ONLY "public"."posts" ADD CONSTRAINT "posts_pkey" PRIMARY KEY (id);
+
+ CREATE INDEX "idx_posts_published" ON "public"."posts" (published) WHERE published = true;
+
+ CREATE INDEX "idx_posts_user_id" ON "public"."posts" (user_id);
+
+ CREATE TABLE "public"."users" (
+ "id" integer DEFAULT nextval('public.users_id_seq'::regclass) NOT NULL,
+ "username" character varying(50) NOT NULL,
+ "email" character varying(100) NOT NULL,
+ "created_at" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" timestamp(6) without time zone
+ );
+
+ ALTER SEQUENCE "public"."users_id_seq" OWNED BY "public"."users"."id";
+
+ ALTER TABLE ONLY "public"."users" ADD CONSTRAINT "users_pkey" PRIMARY KEY (id);
+
+ ALTER TABLE ONLY "public"."users" ADD CONSTRAINT "users_username_key" UNIQUE (username);
+
+ ALTER TABLE "public"."posts"
+ ADD CONSTRAINT "fk_user" FOREIGN KEY ("user_id")
+ REFERENCES "public"."users" ("id")
+ ON DELETE CASCADE;
+
+- description: sequences_and_custom_types
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "items",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.custom_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "status",
+ "position": 3,
+ "default": "'pending'::public.status_enum",
+ "nullable": true,
+ "type": "public.status_enum"
+ },
+ {
+ "name": "user_mood",
+ "position": 4,
+ "nullable": true,
+ "type": "public.mood"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "items_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX items_pkey ON public.items USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "custom_id_seq",
+ "data_type": "bigint",
+ "start": "1000",
+ "min_value": "1",
+ "max_value": "9223372036854775807",
+ "increment": "10",
+ "cache_size": "1"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema",
+ "enum_types": [
+ {
+ "name": "mood",
+ "values": [
+ "happy",
+ "sad",
+ "neutral"
+ ]
+ },
+ {
+ "name": "status_enum",
+ "values": [
+ "pending",
+ "active",
+ "inactive",
+ "deleted"
+ ]
+ }
+ ]
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE TYPE "public"."mood" AS ENUM (
+ 'happy',
+ 'sad',
+ 'neutral'
+ );
+
+ CREATE TYPE "public"."status_enum" AS ENUM (
+ 'pending',
+ 'active',
+ 'inactive',
+ 'deleted'
+ );
+
+ CREATE SEQUENCE "public"."custom_id_seq"
+ AS bigint
+ START WITH 1000
+ INCREMENT BY 10
+ MINVALUE 1
+ MAXVALUE 9223372036854775807
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."items" (
+ "id" integer DEFAULT nextval('public.custom_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "status" public.status_enum DEFAULT 'pending'::public.status_enum,
+ "user_mood" public.mood
+ );
+
+ ALTER TABLE ONLY "public"."items" ADD CONSTRAINT "items_pkey" PRIMARY KEY (id);
+
+- description: composite_types
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "geo",
+ "owner": "postgres",
+ "composite_types": [
+ {
+ "name": "point2",
+ "attributes": [
+ {
+ "name": "lat",
+ "type": "numeric(9,6)"
+ },
+ {
+ "name": "lng",
+ "type": "numeric(9,6)"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.orders_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "info",
+ "position": 2,
+ "nullable": true,
+ "type": "public.order_info"
+ },
+ {
+ "name": "addresses",
+ "position": 3,
+ "nullable": true,
+ "type": "public.aa_nested"
+ },
+ {
+ "name": "location",
+ "position": 4,
+ "nullable": true,
+ "type": "geo.point2"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "orders_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX orders_pkey ON public.orders USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "data_size": 8192,
+ "index_size": 8192,
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "orders_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "orders",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema",
+ "enum_types": [
+ {
+ "name": "order_status",
+ "values": [
+ "pending",
+ "shipped"
+ ]
+ }
+ ],
+ "composite_types": [
+ {
+ "name": "aa_nested",
+ "attributes": [
+ {
+ "name": "home",
+ "type": "public.zz_base"
+ },
+ {
+ "name": "homes",
+ "type": "public.zz_base[]"
+ },
+ {
+ "name": "tags",
+ "type": "text[]"
+ }
+ ]
+ },
+ {
+ "name": "empty_type"
+ },
+ {
+ "name": "order_info",
+ "attributes": [
+ {
+ "name": "status",
+ "type": "public.order_status"
+ },
+ {
+ "name": "note",
+ "type": "text"
+ }
+ ]
+ },
+ {
+ "name": "wrapper",
+ "attributes": [
+ {
+ "name": "p",
+ "type": "geo.point2"
+ }
+ ]
+ },
+ {
+ "name": "zz_base",
+ "attributes": [
+ {
+ "name": "street",
+ "type": "text",
+ "collation": "\"C\"",
+ "comment": "street line"
+ },
+ {
+ "name": "city",
+ "type": "character varying(50)"
+ }
+ ],
+ "comment": "base address type"
+ }
+ ]
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SCHEMA IF NOT EXISTS "geo";
+
+ CREATE TYPE "public"."order_status" AS ENUM (
+ 'pending',
+ 'shipped'
+ );
+
+ CREATE TYPE "geo"."point2" AS (
+ "lat" numeric(9,6),
+ "lng" numeric(9,6)
+ );
+
+ CREATE TYPE "public"."empty_type" AS (
+
+ );
+
+ CREATE TYPE "public"."order_info" AS (
+ "status" public.order_status,
+ "note" text
+ );
+
+ CREATE TYPE "public"."wrapper" AS (
+ "p" geo.point2
+ );
+
+ CREATE TYPE "public"."zz_base" AS (
+ "street" text COLLATE "C",
+ "city" character varying(50)
+ );
+
+ COMMENT ON TYPE "public"."zz_base" IS 'base address type';
+
+ COMMENT ON COLUMN "public"."zz_base"."street" IS 'street line';
+
+ CREATE TYPE "public"."aa_nested" AS (
+ "home" public.zz_base,
+ "homes" public.zz_base[],
+ "tags" text[]
+ );
+
+ CREATE SEQUENCE "public"."orders_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."orders" (
+ "id" integer DEFAULT nextval('public.orders_id_seq'::regclass) NOT NULL,
+ "info" public.order_info,
+ "addresses" public.aa_nested,
+ "location" geo.point2
+ );
+
+ ALTER SEQUENCE "public"."orders_id_seq" OWNED BY "public"."orders"."id";
+
+ ALTER TABLE ONLY "public"."orders" ADD CONSTRAINT "orders_pkey" PRIMARY KEY (id);
+
+- description: owned_sequence_dependency_order
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "history_audit",
+ "columns": [
+ {
+ "name": "audit_id",
+ "position": 1,
+ "default": "nextval('public.history_cost_changes_id_seq'::regclass)",
+ "type": "bigint"
+ },
+ {
+ "name": "change_type",
+ "position": 2,
+ "nullable": true,
+ "type": "character varying(50)"
+ }
+ ],
+ "owner": "postgres"
+ },
+ {
+ "name": "history_cost_changes",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.history_cost_changes_id_seq'::regclass)",
+ "type": "bigint"
+ },
+ {
+ "name": "amount",
+ "position": 2,
+ "nullable": true,
+ "type": "numeric(10,2)"
+ },
+ {
+ "name": "description",
+ "position": 3,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "history_cost_changes_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX history_cost_changes_pkey ON public.history_cost_changes USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int8_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "data_size": 8192,
+ "index_size": 8192,
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "history_cost_changes_id_seq",
+ "data_type": "bigint",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "9223372036854775807",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "history_cost_changes",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."history_cost_changes_id_seq"
+ AS bigint
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 9223372036854775807
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."history_audit" (
+ "audit_id" bigint DEFAULT nextval('public.history_cost_changes_id_seq'::regclass) NOT NULL,
+ "change_type" character varying(50)
+ );
+
+ CREATE TABLE "public"."history_cost_changes" (
+ "id" bigint DEFAULT nextval('public.history_cost_changes_id_seq'::regclass) NOT NULL,
+ "amount" numeric(10,2),
+ "description" text,
+ "created_at" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP
+ );
+
+ ALTER SEQUENCE "public"."history_cost_changes_id_seq" OWNED BY "public"."history_cost_changes"."id";
+
+ ALTER TABLE ONLY "public"."history_cost_changes" ADD CONSTRAINT "history_cost_changes_pkey" PRIMARY KEY (id);
+
+- description: views_and_functions
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.employees_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "department",
+ "position": 3,
+ "nullable": true,
+ "type": "character varying(50)"
+ },
+ {
+ "name": "salary",
+ "position": 4,
+ "nullable": true,
+ "type": "numeric(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "employees_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX employees_pkey ON public.employees USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "owner": "postgres"
+ }
+ ],
+ "views": [
+ {
+ "name": "active_employees",
+ "definition": " SELECT id,\n name,\n department\n FROM public.employees\n WHERE (department IS NOT NULL);",
+ "dependency_columns": [
+ {
+ "schema": "public",
+ "table": "employees",
+ "column": "department"
+ },
+ {
+ "schema": "public",
+ "table": "employees",
+ "column": "id"
+ },
+ {
+ "schema": "public",
+ "table": "employees",
+ "column": "name"
+ }
+ ],
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "nullable": true,
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "nullable": true,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "department",
+ "position": 3,
+ "nullable": true,
+ "type": "character varying(50)"
+ }
+ ]
+ }
+ ],
+ "functions": [
+ {
+ "name": "calculate_bonus",
+ "definition": "CREATE OR REPLACE FUNCTION public.calculate_bonus(emp_id integer)\n RETURNS numeric\n LANGUAGE plpgsql\nAS $function$\nDECLARE\n emp_salary DECIMAL;\nBEGIN\n SELECT salary INTO emp_salary FROM employees WHERE id = emp_id;\n RETURN emp_salary * 0.1;\nEND;\n$function$\n",
+ "signature": "calculate_bonus(emp_id integer)"
+ },
+ {
+ "name": "get_employee_count",
+ "definition": "CREATE OR REPLACE FUNCTION public.get_employee_count(dept character varying)\n RETURNS integer\n LANGUAGE plpgsql\nAS $function$\nBEGIN\n RETURN (SELECT COUNT(*) FROM employees WHERE department = dept);\nEND;\n$function$\n",
+ "signature": "get_employee_count(dept character varying)"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "employees_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "employees",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: "SET statement_timeout = 0;\nSET lock_timeout = 0;\nSET idle_in_transaction_session_timeout = 0;\nSET client_encoding = 'UTF8';\nSET standard_conforming_strings = on;\nSELECT pg_catalog.set_config('search_path', '', false);\nSET check_function_bodies = false;\nSET xmloption = content;\nSET client_min_messages = warning;\nSET row_security = off;\n\nCREATE SEQUENCE \"public\".\"employees_id_seq\"\n AS integer\n\tSTART WITH 1\n\tINCREMENT BY 1\n\tMINVALUE 1\n\tMAXVALUE 2147483647\n\tNO CYCLE;\n\nSET default_tablespace = '';\n\nCREATE OR REPLACE FUNCTION public.calculate_bonus(emp_id integer)\n RETURNS numeric\n LANGUAGE plpgsql\nAS $function$\nDECLARE\n emp_salary DECIMAL;\nBEGIN\n SELECT salary INTO emp_salary FROM employees WHERE id = emp_id;\n RETURN emp_salary * 0.1;\nEND;\n$function$\n;\n\nCREATE TABLE \"public\".\"employees\" (\n \"id\" integer DEFAULT nextval('public.employees_id_seq'::regclass) NOT NULL,\n \"name\" character varying(100) NOT NULL,\n \"department\" character varying(50),\n \"salary\" numeric(10,2)\n);\n\nALTER SEQUENCE \"public\".\"employees_id_seq\" OWNED BY \"public\".\"employees\".\"id\";\n\nALTER TABLE ONLY \"public\".\"employees\" ADD CONSTRAINT \"employees_pkey\" PRIMARY KEY (id);\n\nCREATE OR REPLACE FUNCTION public.get_employee_count(dept character varying)\n RETURNS integer\n LANGUAGE plpgsql\nAS $function$\nBEGIN\n RETURN (SELECT COUNT(*) FROM employees WHERE department = dept);\nEND;\n$function$\n;\n\nCREATE VIEW \"public\".\"active_employees\" AS \n SELECT id,\n name,\n department\n FROM public.employees\n WHERE (department IS NOT NULL);\n\n"
+- description: partitioned_tables
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "sales",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.sales_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "sale_date",
+ "position": 2,
+ "type": "date"
+ },
+ {
+ "name": "amount",
+ "position": 3,
+ "type": "numeric(10,2)"
+ },
+ {
+ "name": "region",
+ "position": 4,
+ "type": "character varying(50)"
+ }
+ ],
+ "partitions": [
+ {
+ "name": "sales_2023_q1",
+ "type": 1,
+ "expression": "RANGE (sale_date)",
+ "value": "FOR VALUES FROM ('2023-01-01') TO ('2023-04-01')"
+ },
+ {
+ "name": "sales_2023_q2",
+ "type": 1,
+ "expression": "RANGE (sale_date)",
+ "value": "FOR VALUES FROM ('2023-04-01') TO ('2023-07-01')"
+ },
+ {
+ "name": "sales_2023_q3",
+ "type": 1,
+ "expression": "RANGE (sale_date)",
+ "value": "FOR VALUES FROM ('2023-07-01') TO ('2023-10-01')"
+ },
+ {
+ "name": "sales_2023_q4",
+ "type": 1,
+ "expression": "RANGE (sale_date)",
+ "value": "FOR VALUES FROM ('2023-10-01') TO ('2024-01-01')"
+ }
+ ],
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "sales_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "sales",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."sales_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."sales" (
+ "id" integer DEFAULT nextval('public.sales_id_seq'::regclass) NOT NULL,
+ "sale_date" date NOT NULL,
+ "amount" numeric(10,2) NOT NULL,
+ "region" character varying(50) NOT NULL
+ ) PARTITION BY RANGE (sale_date);
+
+ ALTER SEQUENCE "public"."sales_id_seq" OWNED BY "public"."sales"."id";
+
+ CREATE TABLE "public"."sales_2023_q1" (
+ "id" integer DEFAULT nextval('public.sales_id_seq'::regclass) NOT NULL,
+ "sale_date" date NOT NULL,
+ "amount" numeric(10,2) NOT NULL,
+ "region" character varying(50) NOT NULL
+ );
+
+ CREATE TABLE "public"."sales_2023_q2" (
+ "id" integer DEFAULT nextval('public.sales_id_seq'::regclass) NOT NULL,
+ "sale_date" date NOT NULL,
+ "amount" numeric(10,2) NOT NULL,
+ "region" character varying(50) NOT NULL
+ );
+
+ CREATE TABLE "public"."sales_2023_q3" (
+ "id" integer DEFAULT nextval('public.sales_id_seq'::regclass) NOT NULL,
+ "sale_date" date NOT NULL,
+ "amount" numeric(10,2) NOT NULL,
+ "region" character varying(50) NOT NULL
+ );
+
+ CREATE TABLE "public"."sales_2023_q4" (
+ "id" integer DEFAULT nextval('public.sales_id_seq'::regclass) NOT NULL,
+ "sale_date" date NOT NULL,
+ "amount" numeric(10,2) NOT NULL,
+ "region" character varying(50) NOT NULL
+ );
+
+ ALTER TABLE ONLY "public"."sales" ATTACH PARTITION "public"."sales_2023_q1" FOR VALUES FROM ('2023-01-01') TO ('2023-04-01');
+
+ ALTER TABLE ONLY "public"."sales" ATTACH PARTITION "public"."sales_2023_q2" FOR VALUES FROM ('2023-04-01') TO ('2023-07-01');
+
+ ALTER TABLE ONLY "public"."sales" ATTACH PARTITION "public"."sales_2023_q3" FOR VALUES FROM ('2023-07-01') TO ('2023-10-01');
+
+ ALTER TABLE ONLY "public"."sales" ATTACH PARTITION "public"."sales_2023_q4" FOR VALUES FROM ('2023-10-01') TO ('2024-01-01');
+
+- description: extensions_and_advanced_features
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "documents",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "public.uuid_generate_v4()",
+ "type": "uuid"
+ },
+ {
+ "name": "title",
+ "position": 2,
+ "type": "character varying(200)"
+ },
+ {
+ "name": "content",
+ "position": 3,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "tags",
+ "position": 4,
+ "nullable": true,
+ "type": "_text"
+ },
+ {
+ "name": "metadata",
+ "position": 5,
+ "nullable": true,
+ "type": "jsonb"
+ },
+ {
+ "name": "created_at",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) with time zone"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "documents_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX documents_pkey ON public.documents USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "uuid_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ },
+ {
+ "name": "idx_documents_metadata",
+ "expressions": [
+ "metadata"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "gin",
+ "definition": "CREATE INDEX idx_documents_metadata ON public.documents USING gin (metadata);",
+ "opclass_names": [
+ "jsonb_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ },
+ {
+ "name": "idx_documents_tags",
+ "expressions": [
+ "tags"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "gin",
+ "definition": "CREATE INDEX idx_documents_tags ON public.documents USING gin (tags);",
+ "opclass_names": [
+ "array_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "data_size": 8192,
+ "index_size": 40960,
+ "owner": "postgres"
+ }
+ ],
+ "functions": [
+ {
+ "name": "uuid_generate_v1",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_generate_v1()\n RETURNS uuid\n LANGUAGE c\n PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_generate_v1$function$\n",
+ "signature": "uuid_generate_v1()",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_generate_v1mc",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_generate_v1mc()\n RETURNS uuid\n LANGUAGE c\n PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_generate_v1mc$function$\n",
+ "signature": "uuid_generate_v1mc()",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_generate_v3",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_generate_v3(namespace uuid, name text)\n RETURNS uuid\n LANGUAGE c\n IMMUTABLE PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_generate_v3$function$\n",
+ "signature": "uuid_generate_v3(namespace uuid, name text)",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_generate_v4",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_generate_v4()\n RETURNS uuid\n LANGUAGE c\n PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_generate_v4$function$\n",
+ "signature": "uuid_generate_v4()",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_generate_v5",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_generate_v5(namespace uuid, name text)\n RETURNS uuid\n LANGUAGE c\n IMMUTABLE PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_generate_v5$function$\n",
+ "signature": "uuid_generate_v5(namespace uuid, name text)",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_nil",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_nil()\n RETURNS uuid\n LANGUAGE c\n IMMUTABLE PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_nil$function$\n",
+ "signature": "uuid_nil()",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_ns_dns",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_ns_dns()\n RETURNS uuid\n LANGUAGE c\n IMMUTABLE PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_ns_dns$function$\n",
+ "signature": "uuid_ns_dns()",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_ns_oid",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_ns_oid()\n RETURNS uuid\n LANGUAGE c\n IMMUTABLE PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_ns_oid$function$\n",
+ "signature": "uuid_ns_oid()",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_ns_url",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_ns_url()\n RETURNS uuid\n LANGUAGE c\n IMMUTABLE PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_ns_url$function$\n",
+ "signature": "uuid_ns_url()",
+ "skip_dump": true
+ },
+ {
+ "name": "uuid_ns_x500",
+ "definition": "CREATE OR REPLACE FUNCTION public.uuid_ns_x500()\n RETURNS uuid\n LANGUAGE c\n IMMUTABLE PARALLEL SAFE STRICT\nAS '$libdir/uuid-ossp', $function$uuid_ns_x500$function$\n",
+ "signature": "uuid_ns_x500()",
+ "skip_dump": true
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "extensions": [
+ {
+ "name": "uuid-ossp",
+ "schema": "public",
+ "version": "1.1",
+ "description": "generate universally unique identifiers (UUIDs)"
+ }
+ ],
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA "public" VERSION '1.1';
+
+ COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."documents" (
+ "id" uuid DEFAULT public.uuid_generate_v4() NOT NULL,
+ "title" character varying(200) NOT NULL,
+ "content" text,
+ "tags" _text,
+ "metadata" jsonb,
+ "created_at" timestamp(6) with time zone DEFAULT CURRENT_TIMESTAMP
+ );
+
+ ALTER TABLE ONLY "public"."documents" ADD CONSTRAINT "documents_pkey" PRIMARY KEY (id);
+
+ CREATE INDEX "idx_documents_metadata" ON "public"."documents" USING GIN (metadata);
+
+ CREATE INDEX "idx_documents_tags" ON "public"."documents" USING GIN (tags);
+
+- description: check_constraints_and_comments
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.products_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)",
+ "comment": "Product name"
+ },
+ {
+ "name": "price",
+ "position": 3,
+ "type": "numeric(10,2)",
+ "comment": "Product price in USD"
+ },
+ {
+ "name": "quantity",
+ "position": 4,
+ "type": "integer"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "products_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX products_pkey ON public.products USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "comment": "Product catalog table",
+ "check_constraints": [
+ {
+ "name": "chk_price",
+ "expression": "(price \u003e 0::numeric)"
+ },
+ {
+ "name": "chk_quantity",
+ "expression": "(quantity \u003e= 0)"
+ }
+ ],
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "products_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "products",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."products_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."products" (
+ "id" integer DEFAULT nextval('public.products_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "price" numeric(10,2) NOT NULL,
+ "quantity" integer NOT NULL,
+ CONSTRAINT "chk_price" CHECK (price > 0::numeric),
+ CONSTRAINT "chk_quantity" CHECK (quantity >= 0)
+ );
+
+ ALTER SEQUENCE "public"."products_id_seq" OWNED BY "public"."products"."id";
+
+ COMMENT ON TABLE "public"."products" IS 'Product catalog table';
+
+ COMMENT ON COLUMN "public"."products"."name" IS 'Product name';
+
+ COMMENT ON COLUMN "public"."products"."price" IS 'Product price in USD';
+
+ ALTER TABLE ONLY "public"."products" ADD CONSTRAINT "products_pkey" PRIMARY KEY (id);
+
+- description: materialized_views
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "raw_data",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.raw_data_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "data_value",
+ "position": 2,
+ "type": "numeric"
+ },
+ {
+ "name": "category",
+ "position": 3,
+ "type": "character varying(50)"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "raw_data_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX raw_data_pkey ON public.raw_data USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "data_size": 8192,
+ "index_size": 8192,
+ "owner": "postgres"
+ }
+ ],
+ "materialized_views": [
+ {
+ "name": "data_summary",
+ "definition": " SELECT category,\n count(*) AS count,\n avg(data_value) AS avg_value,\n max(data_value) AS max_value,\n min(data_value) AS min_value\n FROM public.raw_data\n GROUP BY category;",
+ "dependency_columns": [
+ {
+ "schema": "public",
+ "table": "raw_data",
+ "column": "category"
+ },
+ {
+ "schema": "public",
+ "table": "raw_data",
+ "column": "data_value"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "idx_data_summary_category",
+ "expressions": [
+ "category"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "definition": "CREATE INDEX idx_data_summary_category ON public.data_summary USING btree (category);",
+ "opclass_names": [
+ "text_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "raw_data_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "raw_data",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: "SET statement_timeout = 0;\nSET lock_timeout = 0;\nSET idle_in_transaction_session_timeout = 0;\nSET client_encoding = 'UTF8';\nSET standard_conforming_strings = on;\nSELECT pg_catalog.set_config('search_path', '', false);\nSET check_function_bodies = false;\nSET xmloption = content;\nSET client_min_messages = warning;\nSET row_security = off;\n\nCREATE SEQUENCE \"public\".\"raw_data_id_seq\"\n AS integer\n\tSTART WITH 1\n\tINCREMENT BY 1\n\tMINVALUE 1\n\tMAXVALUE 2147483647\n\tNO CYCLE;\n\nSET default_tablespace = '';\n\nCREATE TABLE \"public\".\"raw_data\" (\n \"id\" integer DEFAULT nextval('public.raw_data_id_seq'::regclass) NOT NULL,\n \"data_value\" numeric NOT NULL,\n \"category\" character varying(50) NOT NULL,\n \"created_at\" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP\n);\n\nALTER SEQUENCE \"public\".\"raw_data_id_seq\" OWNED BY \"public\".\"raw_data\".\"id\";\n\nALTER TABLE ONLY \"public\".\"raw_data\" ADD CONSTRAINT \"raw_data_pkey\" PRIMARY KEY (id);\n\nCREATE MATERIALIZED VIEW \"public\".\"data_summary\" AS \n SELECT category,\n count(*) AS count,\n avg(data_value) AS avg_value,\n max(data_value) AS max_value,\n min(data_value) AS min_value\n FROM public.raw_data\n GROUP BY category\n WITH NO DATA;\n\nCREATE INDEX \"idx_data_summary_category\" ON \"public\".\"data_summary\" (category);\n\n"
+- description: comprehensive_views
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "customers",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.customers_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "nullable": true,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "active",
+ "position": 4,
+ "default": "true",
+ "nullable": true,
+ "type": "boolean"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "customers_email_key",
+ "expressions": [
+ "email"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "definition": "CREATE UNIQUE INDEX customers_email_key ON public.customers USING btree (email);",
+ "is_constraint": true,
+ "opclass_names": [
+ "text_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ },
+ {
+ "name": "customers_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX customers_pkey ON public.customers USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 16384,
+ "owner": "postgres"
+ },
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.orders_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "customer_id",
+ "position": 2,
+ "nullable": true,
+ "type": "integer"
+ },
+ {
+ "name": "total_amount",
+ "position": 3,
+ "type": "numeric(10,2)"
+ },
+ {
+ "name": "order_date",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ },
+ {
+ "name": "status",
+ "position": 5,
+ "default": "'pending'::character varying",
+ "nullable": true,
+ "type": "character varying(20)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "orders_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX orders_pkey ON public.orders USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "foreign_keys": [
+ {
+ "name": "orders_customer_id_fkey",
+ "columns": [
+ "customer_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "customers",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ }
+ ],
+ "views": [
+ {
+ "name": "active_customer_orders",
+ "definition": " SELECT c.id AS customer_id,\n c.name,\n c.email,\n o.id AS order_id,\n o.total_amount,\n o.order_date\n FROM (public.customers c\n JOIN public.orders o ON ((c.id = o.customer_id)))\n WHERE ((c.active = true) AND ((o.status)::text = 'completed'::text));",
+ "dependency_columns": [
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "active"
+ },
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "email"
+ },
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "id"
+ },
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "name"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "customer_id"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "id"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "order_date"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "status"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "total_amount"
+ }
+ ],
+ "columns": [
+ {
+ "name": "customer_id",
+ "position": 1,
+ "nullable": true,
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "nullable": true,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "nullable": true,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "order_id",
+ "position": 4,
+ "nullable": true,
+ "type": "integer"
+ },
+ {
+ "name": "total_amount",
+ "position": 5,
+ "nullable": true,
+ "type": "numeric(10,2)"
+ },
+ {
+ "name": "order_date",
+ "position": 6,
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ }
+ ]
+ },
+ {
+ "name": "customer_summary",
+ "definition": " SELECT id,\n name,\n email,\n ( SELECT count(*) AS count\n FROM public.orders\n WHERE (orders.customer_id = customers.id)) AS order_count\n FROM public.customers\n WHERE (active = true);",
+ "dependency_columns": [
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "active"
+ },
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "email"
+ },
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "id"
+ },
+ {
+ "schema": "public",
+ "table": "customers",
+ "column": "name"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "customer_id"
+ }
+ ],
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "nullable": true,
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "nullable": true,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "nullable": true,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "order_count",
+ "position": 4,
+ "nullable": true,
+ "type": "bigint"
+ }
+ ]
+ }
+ ],
+ "materialized_views": [
+ {
+ "name": "monthly_sales_summary",
+ "definition": " SELECT date_trunc('month'::text, order_date) AS month,\n count(*) AS order_count,\n sum(total_amount) AS total_revenue,\n avg(total_amount) AS avg_order_value,\n count(DISTINCT customer_id) AS unique_customers\n FROM public.orders\n WHERE ((status)::text = 'completed'::text)\n GROUP BY (date_trunc('month'::text, order_date))\n ORDER BY (date_trunc('month'::text, order_date));",
+ "dependency_columns": [
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "customer_id"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "order_date"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "status"
+ },
+ {
+ "schema": "public",
+ "table": "orders",
+ "column": "total_amount"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "idx_monthly_sales_month",
+ "expressions": [
+ "month"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "definition": "CREATE UNIQUE INDEX idx_monthly_sales_month ON public.monthly_sales_summary USING btree (month);",
+ "opclass_names": [
+ "timestamp_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ]
+ }
+ ],
+ "sequences": [
+ {
+ "name": "customers_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "customers",
+ "owner_column": "id"
+ },
+ {
+ "name": "orders_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "orders",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: "SET statement_timeout = 0;\nSET lock_timeout = 0;\nSET idle_in_transaction_session_timeout = 0;\nSET client_encoding = 'UTF8';\nSET standard_conforming_strings = on;\nSELECT pg_catalog.set_config('search_path', '', false);\nSET check_function_bodies = false;\nSET xmloption = content;\nSET client_min_messages = warning;\nSET row_security = off;\n\nCREATE SEQUENCE \"public\".\"customers_id_seq\"\n AS integer\n\tSTART WITH 1\n\tINCREMENT BY 1\n\tMINVALUE 1\n\tMAXVALUE 2147483647\n\tNO CYCLE;\n\nCREATE SEQUENCE \"public\".\"orders_id_seq\"\n AS integer\n\tSTART WITH 1\n\tINCREMENT BY 1\n\tMINVALUE 1\n\tMAXVALUE 2147483647\n\tNO CYCLE;\n\nSET default_tablespace = '';\n\nCREATE TABLE \"public\".\"customers\" (\n \"id\" integer DEFAULT nextval('public.customers_id_seq'::regclass) NOT NULL,\n \"name\" character varying(100) NOT NULL,\n \"email\" character varying(100),\n \"active\" boolean DEFAULT true,\n \"created_at\" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP\n);\n\nALTER SEQUENCE \"public\".\"customers_id_seq\" OWNED BY \"public\".\"customers\".\"id\";\n\nALTER TABLE ONLY \"public\".\"customers\" ADD CONSTRAINT \"customers_pkey\" PRIMARY KEY (id);\n\nALTER TABLE ONLY \"public\".\"customers\" ADD CONSTRAINT \"customers_email_key\" UNIQUE (email);\n\nCREATE TABLE \"public\".\"orders\" (\n \"id\" integer DEFAULT nextval('public.orders_id_seq'::regclass) NOT NULL,\n \"customer_id\" integer,\n \"total_amount\" numeric(10,2) NOT NULL,\n \"order_date\" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP,\n \"status\" character varying(20) DEFAULT 'pending'::character varying\n);\n\nALTER SEQUENCE \"public\".\"orders_id_seq\" OWNED BY \"public\".\"orders\".\"id\";\n\nALTER TABLE ONLY \"public\".\"orders\" ADD CONSTRAINT \"orders_pkey\" PRIMARY KEY (id);\n\nCREATE VIEW \"public\".\"active_customer_orders\" AS \n SELECT c.id AS customer_id,\n c.name,\n c.email,\n o.id AS order_id,\n o.total_amount,\n o.order_date\n FROM (public.customers c\n JOIN public.orders o ON ((c.id = o.customer_id)))\n WHERE ((c.active = true) AND ((o.status)::text = 'completed'::text));\n\nCREATE VIEW \"public\".\"customer_summary\" AS \n SELECT id,\n name,\n email,\n ( SELECT count(*) AS count\n FROM public.orders\n WHERE (orders.customer_id = customers.id)) AS order_count\n FROM public.customers\n WHERE (active = true);\n\nCREATE MATERIALIZED VIEW \"public\".\"monthly_sales_summary\" AS \n SELECT date_trunc('month'::text, order_date) AS month,\n count(*) AS order_count,\n sum(total_amount) AS total_revenue,\n avg(total_amount) AS avg_order_value,\n count(DISTINCT customer_id) AS unique_customers\n FROM public.orders\n WHERE ((status)::text = 'completed'::text)\n GROUP BY (date_trunc('month'::text, order_date))\n ORDER BY (date_trunc('month'::text, order_date))\n WITH NO DATA;\n\nCREATE UNIQUE INDEX \"idx_monthly_sales_month\" ON \"public\".\"monthly_sales_summary\" (month);\n\nALTER TABLE \"public\".\"orders\"\n ADD CONSTRAINT \"orders_customer_id_fkey\" FOREIGN KEY (\"customer_id\")\n REFERENCES \"public\".\"customers\" (\"id\");\n\n"
+- description: triggers
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "accounts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.accounts_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "balance",
+ "position": 3,
+ "default": "0",
+ "nullable": true,
+ "type": "numeric(10,2)"
+ },
+ {
+ "name": "last_modified",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "accounts_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX accounts_pkey ON public.accounts USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "owner": "postgres",
+ "triggers": [
+ {
+ "name": "trg_audit_accounts",
+ "body": "CREATE TRIGGER trg_audit_accounts AFTER INSERT OR DELETE OR UPDATE ON public.accounts FOR EACH ROW EXECUTE FUNCTION public.log_account_changes()"
+ },
+ {
+ "name": "trg_update_last_modified",
+ "body": "CREATE TRIGGER trg_update_last_modified BEFORE UPDATE ON public.accounts FOR EACH ROW EXECUTE FUNCTION public.update_last_modified()"
+ }
+ ]
+ },
+ {
+ "name": "audit_log",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.audit_log_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "table_name",
+ "position": 2,
+ "type": "character varying(50)"
+ },
+ {
+ "name": "operation",
+ "position": 3,
+ "type": "character varying(10)"
+ },
+ {
+ "name": "user_name",
+ "position": 4,
+ "nullable": true,
+ "type": "character varying(50)"
+ },
+ {
+ "name": "timestamp",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp(6) without time zone"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "audit_log_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX audit_log_pkey ON public.audit_log USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "owner": "postgres"
+ }
+ ],
+ "functions": [
+ {
+ "name": "log_account_changes",
+ "definition": "CREATE OR REPLACE FUNCTION public.log_account_changes()\n RETURNS trigger\n LANGUAGE plpgsql\nAS $function$\nBEGIN\n INSERT INTO audit_log (table_name, operation, user_name)\n VALUES ('accounts', TG_OP, current_user);\n RETURN NEW;\nEND;\n$function$\n",
+ "signature": "log_account_changes()"
+ },
+ {
+ "name": "update_last_modified",
+ "definition": "CREATE OR REPLACE FUNCTION public.update_last_modified()\n RETURNS trigger\n LANGUAGE plpgsql\nAS $function$\nBEGIN\n NEW.last_modified = CURRENT_TIMESTAMP;\n RETURN NEW;\nEND;\n$function$\n",
+ "signature": "update_last_modified()"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "accounts_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "accounts",
+ "owner_column": "id"
+ },
+ {
+ "name": "audit_log_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "audit_log",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."accounts_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ CREATE SEQUENCE "public"."audit_log_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."accounts" (
+ "id" integer DEFAULT nextval('public.accounts_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "balance" numeric(10,2) DEFAULT 0,
+ "last_modified" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP
+ );
+
+ ALTER SEQUENCE "public"."accounts_id_seq" OWNED BY "public"."accounts"."id";
+
+ ALTER TABLE ONLY "public"."accounts" ADD CONSTRAINT "accounts_pkey" PRIMARY KEY (id);
+
+ CREATE TABLE "public"."audit_log" (
+ "id" integer DEFAULT nextval('public.audit_log_id_seq'::regclass) NOT NULL,
+ "table_name" character varying(50) NOT NULL,
+ "operation" character varying(10) NOT NULL,
+ "user_name" character varying(50),
+ "timestamp" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP
+ );
+
+ ALTER SEQUENCE "public"."audit_log_id_seq" OWNED BY "public"."audit_log"."id";
+
+ ALTER TABLE ONLY "public"."audit_log" ADD CONSTRAINT "audit_log_pkey" PRIMARY KEY (id);
+
+ CREATE OR REPLACE FUNCTION public.log_account_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ AS $function$
+ BEGIN
+ INSERT INTO audit_log (table_name, operation, user_name)
+ VALUES ('accounts', TG_OP, current_user);
+ RETURN NEW;
+ END;
+ $function$
+ ;
+
+ CREATE OR REPLACE FUNCTION public.update_last_modified()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ AS $function$
+ BEGIN
+ NEW.last_modified = CURRENT_TIMESTAMP;
+ RETURN NEW;
+ END;
+ $function$
+ ;
+
+ CREATE TRIGGER trg_audit_accounts AFTER INSERT OR DELETE OR UPDATE ON public.accounts FOR EACH ROW EXECUTE FUNCTION public.log_account_changes();
+
+ CREATE TRIGGER trg_update_last_modified BEFORE UPDATE ON public.accounts FOR EACH ROW EXECUTE FUNCTION public.update_last_modified();
+
+- description: foreign_key_on_delete_cascade
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "categories",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.categories_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "categories_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX categories_pkey ON public.categories USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "owner": "postgres"
+ },
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.orders_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "product_id",
+ "position": 2,
+ "nullable": true,
+ "type": "integer"
+ },
+ {
+ "name": "quantity",
+ "position": 3,
+ "default": "1",
+ "nullable": true,
+ "type": "integer"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "orders_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX orders_pkey ON public.orders USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "foreign_keys": [
+ {
+ "name": "fk_product_cascade",
+ "columns": [
+ "product_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "products",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "NO ACTION",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ },
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.products_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "category_id",
+ "position": 3,
+ "nullable": true,
+ "type": "integer"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "products_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX products_pkey ON public.products USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "foreign_keys": [
+ {
+ "name": "fk_category",
+ "columns": [
+ "category_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "categories",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "NO ACTION",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "categories_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "categories",
+ "owner_column": "id"
+ },
+ {
+ "name": "orders_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "orders",
+ "owner_column": "id"
+ },
+ {
+ "name": "products_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "products",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."categories_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ CREATE SEQUENCE "public"."orders_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ CREATE SEQUENCE "public"."products_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."categories" (
+ "id" integer DEFAULT nextval('public.categories_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL
+ );
+
+ ALTER SEQUENCE "public"."categories_id_seq" OWNED BY "public"."categories"."id";
+
+ ALTER TABLE ONLY "public"."categories" ADD CONSTRAINT "categories_pkey" PRIMARY KEY (id);
+
+ CREATE TABLE "public"."orders" (
+ "id" integer DEFAULT nextval('public.orders_id_seq'::regclass) NOT NULL,
+ "product_id" integer,
+ "quantity" integer DEFAULT 1
+ );
+
+ ALTER SEQUENCE "public"."orders_id_seq" OWNED BY "public"."orders"."id";
+
+ ALTER TABLE ONLY "public"."orders" ADD CONSTRAINT "orders_pkey" PRIMARY KEY (id);
+
+ CREATE TABLE "public"."products" (
+ "id" integer DEFAULT nextval('public.products_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "category_id" integer
+ );
+
+ ALTER SEQUENCE "public"."products_id_seq" OWNED BY "public"."products"."id";
+
+ ALTER TABLE ONLY "public"."products" ADD CONSTRAINT "products_pkey" PRIMARY KEY (id);
+
+ ALTER TABLE "public"."orders"
+ ADD CONSTRAINT "fk_product_cascade" FOREIGN KEY ("product_id")
+ REFERENCES "public"."products" ("id")
+ ON DELETE SET NULL;
+
+ ALTER TABLE "public"."products"
+ ADD CONSTRAINT "fk_category" FOREIGN KEY ("category_id")
+ REFERENCES "public"."categories" ("id")
+ ON DELETE CASCADE;
+
+- description: foreign_key_on_update_actions
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "departments",
+ "columns": [
+ {
+ "name": "code",
+ "position": 1,
+ "type": "character varying(10)"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "departments_pkey",
+ "expressions": [
+ "code"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX departments_pkey ON public.departments USING btree (code);",
+ "is_constraint": true,
+ "opclass_names": [
+ "text_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "owner": "postgres"
+ },
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.employees_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "dept_code",
+ "position": 3,
+ "nullable": true,
+ "type": "character varying(10)"
+ },
+ {
+ "name": "manager_id",
+ "position": 4,
+ "nullable": true,
+ "type": "integer"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "employees_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX employees_pkey ON public.employees USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "foreign_keys": [
+ {
+ "name": "fk_dept_restrict",
+ "columns": [
+ "dept_code"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "departments",
+ "referenced_columns": [
+ "code"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "RESTRICT",
+ "match_type": "SIMPLE"
+ },
+ {
+ "name": "fk_manager_cascade",
+ "columns": [
+ "manager_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "employees",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "CASCADE",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ },
+ {
+ "name": "projects",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.projects_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "lead_emp_id",
+ "position": 3,
+ "nullable": true,
+ "type": "integer"
+ },
+ {
+ "name": "dept_code",
+ "position": 4,
+ "nullable": true,
+ "type": "character varying(10)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "projects_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX projects_pkey ON public.projects USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "foreign_keys": [
+ {
+ "name": "fk_lead_setnull",
+ "columns": [
+ "lead_emp_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "employees",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL",
+ "on_update": "SET NULL",
+ "match_type": "SIMPLE"
+ },
+ {
+ "name": "fk_proj_dept",
+ "columns": [
+ "dept_code"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "departments",
+ "referenced_columns": [
+ "code"
+ ],
+ "on_delete": "RESTRICT",
+ "on_update": "RESTRICT",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "employees_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "employees",
+ "owner_column": "id"
+ },
+ {
+ "name": "projects_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "projects",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."employees_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ CREATE SEQUENCE "public"."projects_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."departments" (
+ "code" character varying(10) NOT NULL,
+ "name" character varying(100) NOT NULL
+ );
+
+ ALTER TABLE ONLY "public"."departments" ADD CONSTRAINT "departments_pkey" PRIMARY KEY (code);
+
+ CREATE TABLE "public"."employees" (
+ "id" integer DEFAULT nextval('public.employees_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "dept_code" character varying(10),
+ "manager_id" integer
+ );
+
+ ALTER SEQUENCE "public"."employees_id_seq" OWNED BY "public"."employees"."id";
+
+ ALTER TABLE ONLY "public"."employees" ADD CONSTRAINT "employees_pkey" PRIMARY KEY (id);
+
+ CREATE TABLE "public"."projects" (
+ "id" integer DEFAULT nextval('public.projects_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "lead_emp_id" integer,
+ "dept_code" character varying(10)
+ );
+
+ ALTER SEQUENCE "public"."projects_id_seq" OWNED BY "public"."projects"."id";
+
+ ALTER TABLE ONLY "public"."projects" ADD CONSTRAINT "projects_pkey" PRIMARY KEY (id);
+
+ ALTER TABLE "public"."employees"
+ ADD CONSTRAINT "fk_dept_restrict" FOREIGN KEY ("dept_code")
+ REFERENCES "public"."departments" ("code")
+ ON DELETE SET NULL
+ ON UPDATE RESTRICT;
+
+ ALTER TABLE "public"."employees"
+ ADD CONSTRAINT "fk_manager_cascade" FOREIGN KEY ("manager_id")
+ REFERENCES "public"."employees" ("id")
+ ON DELETE CASCADE
+ ON UPDATE CASCADE;
+
+ ALTER TABLE "public"."projects"
+ ADD CONSTRAINT "fk_lead_setnull" FOREIGN KEY ("lead_emp_id")
+ REFERENCES "public"."employees" ("id")
+ ON DELETE SET NULL
+ ON UPDATE SET NULL;
+
+ ALTER TABLE "public"."projects"
+ ADD CONSTRAINT "fk_proj_dept" FOREIGN KEY ("dept_code")
+ REFERENCES "public"."departments" ("code")
+ ON DELETE RESTRICT
+ ON UPDATE RESTRICT;
+
+- description: foreign_key_no_action
+ metadata: |
+ {
+ "schemas": [
+ {
+ "name": "public",
+ "tables": [
+ {
+ "name": "cities",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.cities_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "state_id",
+ "position": 3,
+ "nullable": true,
+ "type": "integer"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "cities_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX cities_pkey ON public.cities USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "foreign_keys": [
+ {
+ "name": "fk_state_implicit",
+ "columns": [
+ "state_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "states",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ },
+ {
+ "name": "countries",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.countries_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "code",
+ "position": 2,
+ "type": "character varying(3)"
+ },
+ {
+ "name": "name",
+ "position": 3,
+ "type": "character varying(100)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "countries_code_key",
+ "expressions": [
+ "code"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "definition": "CREATE UNIQUE INDEX countries_code_key ON public.countries USING btree (code);",
+ "is_constraint": true,
+ "opclass_names": [
+ "text_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ },
+ {
+ "name": "countries_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX countries_pkey ON public.countries USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 16384,
+ "owner": "postgres"
+ },
+ {
+ "name": "states",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "nextval('public.states_id_seq'::regclass)",
+ "type": "integer"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "character varying(100)"
+ },
+ {
+ "name": "country_id",
+ "position": 3,
+ "nullable": true,
+ "type": "integer"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "states_pkey",
+ "expressions": [
+ "id"
+ ],
+ "descending": [
+ false
+ ],
+ "type": "btree",
+ "unique": true,
+ "primary": true,
+ "definition": "CREATE UNIQUE INDEX states_pkey ON public.states USING btree (id);",
+ "is_constraint": true,
+ "opclass_names": [
+ "int4_ops"
+ ],
+ "opclass_defaults": [
+ true
+ ]
+ }
+ ],
+ "index_size": 8192,
+ "foreign_keys": [
+ {
+ "name": "fk_country_explicit",
+ "columns": [
+ "country_id"
+ ],
+ "referenced_schema": "public",
+ "referenced_table": "countries",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "NO ACTION",
+ "on_update": "NO ACTION",
+ "match_type": "SIMPLE"
+ }
+ ],
+ "owner": "postgres"
+ }
+ ],
+ "sequences": [
+ {
+ "name": "cities_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "cities",
+ "owner_column": "id"
+ },
+ {
+ "name": "countries_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "countries",
+ "owner_column": "id"
+ },
+ {
+ "name": "states_id_seq",
+ "data_type": "integer",
+ "start": "1",
+ "min_value": "1",
+ "max_value": "2147483647",
+ "increment": "1",
+ "cache_size": "1",
+ "owner_table": "states",
+ "owner_column": "id"
+ }
+ ],
+ "owner": "pg_database_owner",
+ "comment": "standard public schema"
+ }
+ ],
+ "character_set": "UTF8",
+ "collation": "en_US.UTF-8",
+ "owner": "postgres",
+ "search_path": "\"$user\", public"
+ }
+ expected: |+
+ SET statement_timeout = 0;
+ SET lock_timeout = 0;
+ SET idle_in_transaction_session_timeout = 0;
+ SET client_encoding = 'UTF8';
+ SET standard_conforming_strings = on;
+ SELECT pg_catalog.set_config('search_path', '', false);
+ SET check_function_bodies = false;
+ SET xmloption = content;
+ SET client_min_messages = warning;
+ SET row_security = off;
+
+ CREATE SEQUENCE "public"."cities_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ CREATE SEQUENCE "public"."countries_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ CREATE SEQUENCE "public"."states_id_seq"
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ NO CYCLE;
+
+ SET default_tablespace = '';
+
+ CREATE TABLE "public"."cities" (
+ "id" integer DEFAULT nextval('public.cities_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "state_id" integer
+ );
+
+ ALTER SEQUENCE "public"."cities_id_seq" OWNED BY "public"."cities"."id";
+
+ ALTER TABLE ONLY "public"."cities" ADD CONSTRAINT "cities_pkey" PRIMARY KEY (id);
+
+ CREATE TABLE "public"."countries" (
+ "id" integer DEFAULT nextval('public.countries_id_seq'::regclass) NOT NULL,
+ "code" character varying(3) NOT NULL,
+ "name" character varying(100) NOT NULL
+ );
+
+ ALTER SEQUENCE "public"."countries_id_seq" OWNED BY "public"."countries"."id";
+
+ ALTER TABLE ONLY "public"."countries" ADD CONSTRAINT "countries_pkey" PRIMARY KEY (id);
+
+ ALTER TABLE ONLY "public"."countries" ADD CONSTRAINT "countries_code_key" UNIQUE (code);
+
+ CREATE TABLE "public"."states" (
+ "id" integer DEFAULT nextval('public.states_id_seq'::regclass) NOT NULL,
+ "name" character varying(100) NOT NULL,
+ "country_id" integer
+ );
+
+ ALTER SEQUENCE "public"."states_id_seq" OWNED BY "public"."states"."id";
+
+ ALTER TABLE ONLY "public"."states" ADD CONSTRAINT "states_pkey" PRIMARY KEY (id);
+
+ ALTER TABLE "public"."cities"
+ ADD CONSTRAINT "fk_state_implicit" FOREIGN KEY ("state_id")
+ REFERENCES "public"."states" ("id");
+
+ ALTER TABLE "public"."states"
+ ADD CONSTRAINT "fk_country_explicit" FOREIGN KEY ("country_id")
+ REFERENCES "public"."countries" ("id");
+
diff --git a/backend/plugin/schema/pg/testutil_test.go b/backend/plugin/schema/pg/testutil_test.go
deleted file mode 100644
index 1f793bde49..0000000000
--- a/backend/plugin/schema/pg/testutil_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package pg
-
-import (
- "context"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
- pgdb "github.com/bytebase/bytebase/backend/plugin/db/pg"
-)
-
-// createPgDriver creates and opens a PostgreSQL driver for the specified database.
-// This is a shared helper function for tests.
-func createPgDriver(ctx context.Context, host, port, database string) (*pgdb.Driver, error) {
- driver := &pgdb.Driver{}
- config := db.ConnectionConfig{
- DataSource: &storepb.DataSource{
- Type: storepb.DataSourceType_ADMIN,
- Username: "postgres",
- Host: host,
- Port: port,
- Database: database,
- },
- Password: "root-password",
- ConnectionContext: db.ConnectionContext{
- EngineVersion: "16.0",
- DatabaseName: database,
- },
- }
- _, err := driver.Open(ctx, storepb.Engine_POSTGRES, config)
- if err != nil {
- return nil, err
- }
- return driver, nil
-}
diff --git a/backend/plugin/schema/pg/walk_through_test.go b/backend/plugin/schema/pg/walk_through_test.go
index 76dfa13bd5..aa728096f7 100644
--- a/backend/plugin/schema/pg/walk_through_test.go
+++ b/backend/plugin/schema/pg/walk_through_test.go
@@ -16,6 +16,10 @@ import (
"github.com/bytebase/bytebase/backend/component/sheet"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
+
+ // Registers the PostgreSQL ParseStatements func these tests reach through
+ // base. Nothing in this package's own imports pulls it in.
+ _ "github.com/bytebase/bytebase/backend/plugin/parser/pg"
"github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
)
diff --git a/backend/plugin/schema/tidb/generate_migration_test.go b/backend/plugin/schema/tidb/generate_migration_test.go
index 775993d21a..5039a8c624 100644
--- a/backend/plugin/schema/tidb/generate_migration_test.go
+++ b/backend/plugin/schema/tidb/generate_migration_test.go
@@ -1,1540 +1,107 @@
package tidb
import (
- "context"
- "fmt"
- "slices"
- "strings"
+ "os"
"testing"
- // Import MySQL driver (TiDB is compatible with MySQL protocol)
- _ "github.com/go-sql-driver/mysql"
- "github.com/google/go-cmp/cmp"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/testing/protocmp"
+ "gopkg.in/yaml.v3"
+
+ "strings"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/pingcap/tidb/pkg/parser"
+ "github.com/pingcap/tidb/pkg/parser/mysql"
+ _ "github.com/pingcap/tidb/pkg/types/parser_driver"
+
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
)
-// TestGenerateMigrationWithTestcontainer tests the generate migration function
-// by applying migrations and rollback to verify the schema can be restored.
-func TestGenerateMigrationWithTestcontainer(t *testing.T) {
- t.Parallel()
-
- if testing.Short() {
- t.Skip("Skipping TiDB testcontainer test in short mode")
- }
-
- ctx := context.Background()
- container := testcontainer.SharedTiDBContainer(t)
-
- // Test cases with various schema changes
- testCases := []struct {
- name string
- initialSchema string
- migrationDDL string
- description string
- }{
- {
- name: "basic_table_operations",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username)
-);
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-`,
- migrationDDL: `
--- Add new column
-ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT true;
-
--- Create new table
-CREATE TABLE comments (
- id INT NOT NULL AUTO_INCREMENT,
- post_id INT NOT NULL,
- user_id INT NOT NULL,
- content TEXT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_post_user (post_id, user_id),
- CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
- CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
--- Add new index
-CREATE INDEX idx_email_active ON users(email, is_active);
-
--- Add check constraint
-ALTER TABLE posts ADD CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0);
-`,
- description: "Basic table operations with columns, constraints, and indexes",
- },
- {
- name: "reverse_basic_table_operations",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- is_active BOOLEAN DEFAULT true,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username),
- INDEX idx_email_active (email, is_active)
-);
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
- CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
-);
-
-CREATE TABLE comments (
- id INT NOT NULL AUTO_INCREMENT,
- post_id INT NOT NULL,
- user_id INT NOT NULL,
- content TEXT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_post_user (post_id, user_id),
- CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
- CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-`,
- migrationDDL: `
--- Drop check constraint
-ALTER TABLE posts DROP CHECK chk_title_length;
-
--- Drop index
-DROP INDEX idx_email_active ON users;
-
--- Drop table
-DROP TABLE comments;
-
--- Drop column
-ALTER TABLE users DROP COLUMN is_active;
-`,
- description: "Reverse of basic table operations - dropping columns, constraints, and indexes",
- },
- {
- name: "tidb_specific_features",
- initialSchema: `
-CREATE TABLE products (
- id BIGINT NOT NULL AUTO_RANDOM,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- stock INT DEFAULT 0,
- PRIMARY KEY (id),
- INDEX idx_name (name)
-);
-
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT,
- product_id BIGINT NOT NULL,
- quantity INT NOT NULL,
- total DECIMAL(10, 2),
- order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
-);
-`,
- migrationDDL: `
--- Create view
-CREATE VIEW product_inventory AS
-SELECT
- p.id,
- p.name,
- p.price,
- p.stock,
- COALESCE(SUM(o.quantity), 0) AS total_ordered
-FROM products p
-LEFT JOIN orders o ON p.id = o.product_id
-GROUP BY p.id, p.name, p.price, p.stock;
-
--- Add column with TiDB specific features
-ALTER TABLE products ADD COLUMN category VARCHAR(50) DEFAULT 'general';
-`,
- description: "TiDB specific features like AUTO_RANDOM and clustered index",
- },
- {
- name: "reverse_tidb_specific_features",
- initialSchema: `
-CREATE TABLE products (
- id BIGINT NOT NULL AUTO_RANDOM,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- stock INT DEFAULT 0,
- category VARCHAR(50) DEFAULT 'general',
- PRIMARY KEY (id),
- INDEX idx_name (name)
-);
-
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT,
- product_id BIGINT NOT NULL,
- quantity INT NOT NULL,
- total DECIMAL(10, 2),
- order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
-);
-
-CREATE VIEW product_inventory AS
-SELECT
- p.id,
- p.name,
- p.price,
- p.stock,
- COALESCE(SUM(o.quantity), 0) AS total_ordered
-FROM products p
-LEFT JOIN orders o ON p.id = o.product_id
-GROUP BY p.id, p.name, p.price, p.stock;
-`,
- migrationDDL: `
--- Drop column
-ALTER TABLE products DROP COLUMN category;
-
--- Drop view
-DROP VIEW product_inventory;
-`,
- description: "Reverse of TiDB specific features - dropping views and columns",
- },
- {
- name: "views_and_procedures",
- initialSchema: `
-CREATE TABLE sales (
- id INT NOT NULL AUTO_INCREMENT,
- product_name VARCHAR(100) NOT NULL,
- sale_amount DECIMAL(10, 2) NOT NULL,
- sale_date DATE NOT NULL,
- PRIMARY KEY (id),
- INDEX idx_product_date (product_name, sale_date)
-);
-`,
- migrationDDL: `
--- Create views
-CREATE VIEW monthly_sales AS
-SELECT
- YEAR(sale_date) AS year,
- MONTH(sale_date) AS month,
- SUM(sale_amount) AS total_sales
-FROM sales
-GROUP BY YEAR(sale_date), MONTH(sale_date);
-
-CREATE VIEW top_products AS
-SELECT
- product_name,
- COUNT(*) AS sale_count,
- SUM(sale_amount) AS total_revenue
-FROM sales
-GROUP BY product_name
-ORDER BY SUM(sale_amount) DESC;
-
--- Create additional table instead of stored routines
-CREATE TABLE sales_reports (
- id INT NOT NULL AUTO_INCREMENT,
- report_type VARCHAR(50) NOT NULL,
- report_data JSON,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_type (report_type)
-);
-`,
- description: "Views and stored routines",
- },
- {
- name: "reverse_views_and_procedures",
- initialSchema: `
-CREATE TABLE sales (
- id INT NOT NULL AUTO_INCREMENT,
- product_name VARCHAR(100) NOT NULL,
- sale_amount DECIMAL(10, 2) NOT NULL,
- sale_date DATE NOT NULL,
- PRIMARY KEY (id),
- INDEX idx_product_date (product_name, sale_date)
-);
-
-CREATE VIEW monthly_sales AS
-SELECT
- YEAR(sale_date) AS year,
- MONTH(sale_date) AS month,
- SUM(sale_amount) AS total_sales
-FROM sales
-GROUP BY YEAR(sale_date), MONTH(sale_date);
-
-CREATE VIEW top_products AS
-SELECT
- product_name,
- COUNT(*) AS sale_count,
- SUM(sale_amount) AS total_revenue
-FROM sales
-GROUP BY product_name
-ORDER BY SUM(sale_amount) DESC;
-
-CREATE TABLE sales_reports (
- id INT NOT NULL AUTO_INCREMENT,
- report_type VARCHAR(50) NOT NULL,
- report_data JSON,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_type (report_type)
-);
-`,
- migrationDDL: `
--- Drop table
-DROP TABLE sales_reports;
-
--- Drop views
-DROP VIEW top_products;
-DROP VIEW monthly_sales;
-`,
- description: "Reverse of views and procedures - dropping views and tables",
- },
- {
- name: "drop_operations",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- category VARCHAR(50),
- price DECIMAL(10, 2),
- sku VARCHAR(50) NOT NULL,
- PRIMARY KEY (id),
- UNIQUE KEY uk_sku (sku),
- INDEX idx_name (name),
- INDEX idx_category (category),
- INDEX idx_price (price),
- CONSTRAINT chk_price_positive CHECK (price > 0),
- CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
-);
-
-CREATE VIEW product_summary AS
-SELECT category, COUNT(*) as count, AVG(price) as avg_price
-FROM products
-GROUP BY category;
-
-CREATE TABLE product_stats (
- id INT NOT NULL AUTO_INCREMENT,
- category VARCHAR(50) NOT NULL,
- product_count INT DEFAULT 0,
- avg_price DECIMAL(10, 2),
- PRIMARY KEY (id),
- UNIQUE KEY uk_category (category)
-);
-`,
- migrationDDL: `
--- Drop various objects
-DROP VIEW product_summary;
-DROP TABLE product_stats;
-DROP INDEX idx_category ON products;
-DROP INDEX idx_price ON products;
-ALTER TABLE products DROP CHECK chk_price_positive;
-ALTER TABLE products DROP COLUMN category;
-`,
- description: "Drop operations for views, functions, indexes, and constraints",
- },
- {
- name: "reverse_drop_operations",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2),
- sku VARCHAR(50) NOT NULL,
- PRIMARY KEY (id),
- UNIQUE KEY uk_sku (sku),
- INDEX idx_name (name),
- CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
-);
-`,
- migrationDDL: `
--- Add column
-ALTER TABLE products ADD COLUMN category VARCHAR(50);
-
--- Add check constraint
-ALTER TABLE products ADD CONSTRAINT chk_price_positive CHECK (price > 0);
-
--- Add indexes
-CREATE INDEX idx_price ON products(price);
-CREATE INDEX idx_category ON products(category);
-
--- Create table
-CREATE TABLE product_stats (
- id INT NOT NULL AUTO_INCREMENT,
- category VARCHAR(50) NOT NULL,
- product_count INT DEFAULT 0,
- avg_price DECIMAL(10, 2),
- PRIMARY KEY (id),
- UNIQUE KEY uk_category (category)
-);
-
--- Create view
-CREATE VIEW product_summary AS
-SELECT category, COUNT(*) as count, AVG(price) as avg_price
-FROM products
-GROUP BY category;
-`,
- description: "Reverse of drop operations - creating views, indexes, and constraints",
- },
- {
- name: "alter_table_operations",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(50) NOT NULL,
- email VARCHAR(100),
- age INT,
- PRIMARY KEY (id),
- INDEX idx_email (email)
-);
-`,
- migrationDDL: `
--- Add columns
-ALTER TABLE users ADD COLUMN phone VARCHAR(20);
-ALTER TABLE users ADD COLUMN address TEXT;
-ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-
--- Modify existing columns
-ALTER TABLE users MODIFY COLUMN name VARCHAR(100) NOT NULL;
-ALTER TABLE users MODIFY COLUMN email VARCHAR(150) NOT NULL;
-
--- Add constraints
-ALTER TABLE users ADD CONSTRAINT chk_age_positive CHECK (age > 0);
-ALTER TABLE users ADD CONSTRAINT uk_phone UNIQUE (phone);
-
--- Add indexes
-CREATE INDEX idx_name ON users(name);
-CREATE INDEX idx_age ON users(age);
-`,
- description: "Various ALTER TABLE operations",
- },
- {
- name: "reverse_alter_table_operations",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(150) NOT NULL,
- age INT,
- phone VARCHAR(20),
- address TEXT,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_email (email),
- INDEX idx_name (name),
- INDEX idx_age (age),
- CONSTRAINT chk_age_positive CHECK (age > 0),
- CONSTRAINT uk_phone UNIQUE (phone)
-);
-`,
- migrationDDL: `
--- Drop indexes
-DROP INDEX idx_age ON users;
-DROP INDEX idx_name ON users;
-
--- Drop constraints
-ALTER TABLE users DROP CONSTRAINT uk_phone;
-ALTER TABLE users DROP CHECK chk_age_positive;
-
--- Modify columns back
-ALTER TABLE users MODIFY COLUMN email VARCHAR(100);
-ALTER TABLE users MODIFY COLUMN name VARCHAR(50) NOT NULL;
-
--- Drop columns
-ALTER TABLE users DROP COLUMN created_at;
-ALTER TABLE users DROP COLUMN address;
-ALTER TABLE users DROP COLUMN phone;
-`,
- description: "Reverse of ALTER TABLE operations - dropping columns and constraints",
- },
- {
- name: "complex_relationships",
- initialSchema: `
-CREATE TABLE categories (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- parent_id INT,
- PRIMARY KEY (id),
- INDEX idx_parent (parent_id)
-);
-
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- category_id INT,
- price DECIMAL(10, 2),
- PRIMARY KEY (id),
- INDEX idx_category (category_id)
-);
-
--- Add foreign keys
-ALTER TABLE categories ADD CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id);
-ALTER TABLE products ADD CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id);
-`,
- migrationDDL: `
--- Add more simple relationships without complex foreign key chains
-ALTER TABLE categories ADD COLUMN description TEXT;
-ALTER TABLE products ADD COLUMN weight DECIMAL(8, 3);
-
--- Create simple lookup table
-CREATE TABLE product_attributes (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- attribute_name VARCHAR(100) NOT NULL,
- attribute_value VARCHAR(200),
- PRIMARY KEY (id),
- INDEX idx_product_attr (product_id, attribute_name),
- CONSTRAINT fk_product_attr FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
-);
-`,
- description: "Complex table relationships with triggers",
- },
- {
- name: "reverse_complex_relationships",
- initialSchema: `
-CREATE TABLE categories (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- parent_id INT,
- description TEXT,
- PRIMARY KEY (id),
- INDEX idx_parent (parent_id),
- CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id)
-);
-
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- category_id INT,
- price DECIMAL(10, 2),
- weight DECIMAL(8, 3),
- PRIMARY KEY (id),
- INDEX idx_category (category_id),
- CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id)
-);
-
-CREATE TABLE product_attributes (
- id INT NOT NULL AUTO_INCREMENT,
- product_id INT NOT NULL,
- attribute_name VARCHAR(100) NOT NULL,
- attribute_value VARCHAR(200),
- PRIMARY KEY (id),
- INDEX idx_product_attr (product_id, attribute_name),
- CONSTRAINT fk_product_attr FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
-);
-`,
- migrationDDL: `
--- Drop lookup table
-DROP TABLE product_attributes;
-
--- Drop columns
-ALTER TABLE products DROP COLUMN weight;
-ALTER TABLE categories DROP COLUMN description;
-`,
- description: "Reverse of complex relationships - dropping tables and columns",
- },
- {
- name: "partitioned_tables",
- initialSchema: `
-CREATE TABLE sales_data (
- id INT NOT NULL AUTO_INCREMENT,
- sale_date DATE NOT NULL,
- customer_id INT NOT NULL,
- product_id INT NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- region VARCHAR(50) NOT NULL,
- PRIMARY KEY (id, sale_date)
-);
-`,
- migrationDDL: `
--- Add indexes to partitioned table
-CREATE INDEX idx_customer ON sales_data(customer_id);
-CREATE INDEX idx_product ON sales_data(product_id);
-CREATE INDEX idx_region_date ON sales_data(region, sale_date);
-
--- Create view on partitioned table
-CREATE VIEW regional_sales AS
-SELECT
- region,
- YEAR(sale_date) AS year,
- MONTH(sale_date) AS month,
- SUM(amount) AS total_sales,
- COUNT(DISTINCT customer_id) AS unique_customers
-FROM sales_data
-GROUP BY region, YEAR(sale_date), MONTH(sale_date);
-
--- Add constraint
-ALTER TABLE sales_data ADD CONSTRAINT chk_amount_positive CHECK (amount > 0);
-`,
- description: "Operations on partitioned tables",
- },
- {
- name: "reverse_partitioned_tables",
- initialSchema: `
-CREATE TABLE sales_data (
- id INT NOT NULL AUTO_INCREMENT,
- sale_date DATE NOT NULL,
- customer_id INT NOT NULL,
- product_id INT NOT NULL,
- amount DECIMAL(10, 2) NOT NULL,
- region VARCHAR(50) NOT NULL,
- PRIMARY KEY (id, sale_date),
- INDEX idx_customer (customer_id),
- INDEX idx_product (product_id),
- INDEX idx_region_date (region, sale_date),
- CONSTRAINT chk_amount_positive CHECK (amount > 0)
-);
-
-CREATE VIEW regional_sales AS
-SELECT
- region,
- YEAR(sale_date) AS year,
- MONTH(sale_date) AS month,
- SUM(amount) AS total_sales,
- COUNT(DISTINCT customer_id) AS unique_customers
-FROM sales_data
-GROUP BY region, YEAR(sale_date), MONTH(sale_date);
-`,
- migrationDDL: `
--- Drop constraint
-ALTER TABLE sales_data DROP CHECK chk_amount_positive;
-
--- Drop view
-DROP VIEW regional_sales;
-
--- Drop indexes
-DROP INDEX idx_region_date ON sales_data;
-DROP INDEX idx_product ON sales_data;
-DROP INDEX idx_customer ON sales_data;
-`,
- description: "Reverse of partitioned table operations - dropping indexes and views",
- },
- // Note: TiDB added foreign key support in v6.6.0 (experimental) and v7.5.0 (GA)
- // These tests verify that our migration generation handles foreign keys correctly
- {
- name: "create_tables_with_fk",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username)
-);
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-`,
- migrationDDL: `
-DROP TABLE IF EXISTS posts;
-DROP TABLE IF EXISTS users;`,
- description: "Create tables with foreign key constraints",
- },
- {
- name: "reverse_create_tables_with_fk",
- initialSchema: ``,
- migrationDDL: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username)
-);
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-`,
- description: "Reverse of create tables with foreign key constraints - creating from empty",
- },
- {
- name: "multiple_foreign_keys",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username)
-);
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-`,
- migrationDDL: `
--- Add new column
-ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT true;
-
--- Create new table with multiple foreign keys
-CREATE TABLE comments (
- id INT NOT NULL AUTO_INCREMENT,
- post_id INT NOT NULL,
- user_id INT NOT NULL,
- content TEXT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_post_user (post_id, user_id),
- CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
- CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
--- Add new index
-CREATE INDEX idx_email_active ON users(email, is_active);
-
--- Add check constraint (TiDB supports check constraints)
-ALTER TABLE posts ADD CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0);
-`,
- description: "Tables with multiple foreign key constraints",
- },
- {
- name: "reverse_multiple_foreign_keys",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- is_active BOOLEAN DEFAULT true,
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email),
- INDEX idx_username (username),
- INDEX idx_email_active (email, is_active)
-);
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
- CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
-);
-
-CREATE TABLE comments (
- id INT NOT NULL AUTO_INCREMENT,
- post_id INT NOT NULL,
- user_id INT NOT NULL,
- content TEXT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_post_user (post_id, user_id),
- CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
- CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-`,
- migrationDDL: `
--- Drop check constraint
-ALTER TABLE posts DROP CHECK chk_title_length;
-
--- Drop index
-DROP INDEX idx_email_active ON users;
-
--- Drop table with foreign keys
-DROP TABLE comments;
-
--- Drop column
-ALTER TABLE users DROP COLUMN is_active;
-`,
- description: "Reverse of multiple foreign keys - dropping tables and constraints",
- },
- {
- name: "drop_and_recreate_fk_constraints",
- initialSchema: `
-CREATE TABLE authors (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100),
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email)
-);
-
-CREATE TABLE books (
- id INT NOT NULL AUTO_INCREMENT,
- title VARCHAR(200) NOT NULL,
- author_id INT NOT NULL,
- isbn VARCHAR(20),
- published_year INT,
- price DECIMAL(8, 2),
- PRIMARY KEY (id),
- UNIQUE KEY uk_isbn (isbn),
- INDEX idx_author (author_id),
- INDEX idx_year (published_year),
- CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),
- CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),
- CONSTRAINT chk_price_positive CHECK (price > 0)
-);
-`,
- migrationDDL: `
--- Drop and recreate foreign key with different options
-ALTER TABLE books DROP FOREIGN KEY fk_author;
-ALTER TABLE books ADD CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE;
-
--- Drop and modify check constraints
-ALTER TABLE books DROP CHECK chk_year_valid;
-ALTER TABLE books ADD CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030);
-
--- Add new constraints
-ALTER TABLE books ADD CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) >= 3);
-`,
- description: "Drop and recreate foreign key constraints with different options",
- },
- {
- name: "reverse_drop_and_recreate_fk_constraints",
- initialSchema: `
-CREATE TABLE authors (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100),
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (email)
-);
-
-CREATE TABLE books (
- id INT NOT NULL AUTO_INCREMENT,
- title VARCHAR(200) NOT NULL,
- author_id INT NOT NULL,
- isbn VARCHAR(20),
- published_year INT,
- price DECIMAL(8, 2),
- PRIMARY KEY (id),
- UNIQUE KEY uk_isbn (isbn),
- INDEX idx_author (author_id),
- INDEX idx_year (published_year),
- CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030),
- CONSTRAINT chk_price_positive CHECK (price > 0),
- CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) >= 3)
-);
-`,
- migrationDDL: `
--- Drop new constraints
-ALTER TABLE books DROP CHECK chk_title_length;
-
--- Restore original check constraint
-ALTER TABLE books DROP CHECK chk_year_extended;
-ALTER TABLE books ADD CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100);
-
--- Restore original foreign key
-ALTER TABLE books DROP FOREIGN KEY fk_author_new;
-ALTER TABLE books ADD CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id);
-`,
- description: "Reverse of drop and recreate foreign key constraints - restoring original constraints",
- },
- {
- name: "circular_foreign_key_dependencies",
- initialSchema: `
-CREATE TABLE customers (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- preferred_order_id INT,
- PRIMARY KEY (id)
-);
-
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT,
- customer_id INT NOT NULL,
- order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
- total_amount DECIMAL(10, 2),
- PRIMARY KEY (id)
-);
-`,
- migrationDDL: `
--- Create circular foreign key dependencies
--- Note: Circular FKs might have limitations in TiDB
-ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;
-ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE;
-
--- Add more tables with complex relationships
-CREATE TABLE order_items (
- id INT NOT NULL AUTO_INCREMENT,
- order_id INT NOT NULL,
- product_name VARCHAR(100) NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- PRIMARY KEY (id),
- INDEX idx_order (order_id),
- CONSTRAINT fk_order_item FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
-);
-`,
- description: "Circular foreign key dependencies",
- },
- {
- name: "reverse_circular_foreign_key_dependencies",
- initialSchema: `
-CREATE TABLE customers (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- preferred_order_id INT,
- PRIMARY KEY (id)
-);
-
-CREATE TABLE orders (
- id INT NOT NULL AUTO_INCREMENT,
- customer_id INT NOT NULL,
- order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
- total_amount DECIMAL(10, 2),
- PRIMARY KEY (id)
-);
-
-ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;
-ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE;
-
-CREATE TABLE order_items (
- id INT NOT NULL AUTO_INCREMENT,
- order_id INT NOT NULL,
- product_name VARCHAR(100) NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- PRIMARY KEY (id),
- INDEX idx_order (order_id),
- CONSTRAINT fk_order_item FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
-);
-`,
- migrationDDL: `
--- Drop dependent table
-DROP TABLE order_items;
-
--- Drop circular foreign keys
-ALTER TABLE orders DROP FOREIGN KEY fk_customer;
-ALTER TABLE customers DROP FOREIGN KEY fk_preferred_order;
-`,
- description: "Reverse of circular foreign key dependencies - dropping tables and foreign keys",
- },
- {
- name: "table_and_column_comments",
- initialSchema: `
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- description TEXT,
- category_id INT,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id),
- INDEX idx_category (category_id)
-);
-
-CREATE TABLE categories (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(50) NOT NULL,
- PRIMARY KEY (id)
-);
-`,
- migrationDDL: `
--- Add comments to existing table and columns
-ALTER TABLE products COMMENT = 'Product catalog table storing all available products';
-ALTER TABLE products MODIFY COLUMN name VARCHAR(100) NOT NULL COMMENT 'Product display name';
-ALTER TABLE products MODIFY COLUMN price DECIMAL(10, 2) NOT NULL COMMENT 'Product price in USD';
-ALTER TABLE products MODIFY COLUMN description TEXT COMMENT 'Detailed product description';
-
--- Add comment to existing table
-ALTER TABLE categories COMMENT = 'Product categories for organization';
-ALTER TABLE categories MODIFY COLUMN name VARCHAR(50) NOT NULL COMMENT 'Category name';
-
--- Create new table with comments
-CREATE TABLE suppliers (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Unique supplier identifier',
- company_name VARCHAR(100) NOT NULL COMMENT 'Official company name',
- contact_email VARCHAR(150) COMMENT 'Primary contact email address',
- phone VARCHAR(20) COMMENT 'Contact phone number',
- address TEXT COMMENT 'Full business address',
- is_active BOOLEAN DEFAULT true COMMENT 'Supplier active status',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (contact_email),
- INDEX idx_active (is_active)
-) COMMENT = 'Supplier information and contact details';
-
--- Add new columns with comments
-ALTER TABLE products ADD COLUMN supplier_id INT COMMENT 'Reference to supplier table';
-ALTER TABLE products ADD COLUMN weight DECIMAL(8, 3) COMMENT 'Product weight in kilograms';
-ALTER TABLE products ADD COLUMN in_stock BOOLEAN DEFAULT true COMMENT 'Current stock availability';
-
--- Add foreign key with comment
-ALTER TABLE products ADD CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL;
-`,
- description: "Adding comments to tables and columns using TiDB COMMENT syntax",
- },
- {
- name: "reverse_table_and_column_comments",
- initialSchema: `
-CREATE TABLE categories (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(50) NOT NULL COMMENT 'Category name',
- PRIMARY KEY (id)
-) COMMENT = 'Product categories for organization';
-
-CREATE TABLE suppliers (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Unique supplier identifier',
- company_name VARCHAR(100) NOT NULL COMMENT 'Official company name',
- contact_email VARCHAR(150) COMMENT 'Primary contact email address',
- phone VARCHAR(20) COMMENT 'Contact phone number',
- address TEXT COMMENT 'Full business address',
- is_active BOOLEAN DEFAULT true COMMENT 'Supplier active status',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
- PRIMARY KEY (id),
- UNIQUE KEY uk_email (contact_email),
- INDEX idx_active (is_active)
-) COMMENT = 'Supplier information and contact details';
-
-CREATE TABLE products (
- id INT NOT NULL AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL COMMENT 'Product display name',
- price DECIMAL(10, 2) NOT NULL COMMENT 'Product price in USD',
- description TEXT COMMENT 'Detailed product description',
- category_id INT,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- supplier_id INT COMMENT 'Reference to supplier table',
- weight DECIMAL(8, 3) COMMENT 'Product weight in kilograms',
- in_stock BOOLEAN DEFAULT true COMMENT 'Current stock availability',
- PRIMARY KEY (id),
- INDEX idx_category (category_id),
- CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL
-) COMMENT = 'Product catalog table storing all available products';
-`,
- migrationDDL: `
--- Drop foreign key
-ALTER TABLE products DROP FOREIGN KEY fk_supplier;
-
--- Drop columns with comments
-ALTER TABLE products DROP COLUMN in_stock;
-ALTER TABLE products DROP COLUMN weight;
-ALTER TABLE products DROP COLUMN supplier_id;
-
--- Drop table with comments
-DROP TABLE suppliers;
-
--- Remove comments from columns
-ALTER TABLE categories MODIFY COLUMN name VARCHAR(50) NOT NULL;
-ALTER TABLE categories COMMENT = '';
-
--- Remove comments from products table and columns
-ALTER TABLE products MODIFY COLUMN description TEXT;
-ALTER TABLE products MODIFY COLUMN price DECIMAL(10, 2) NOT NULL;
-ALTER TABLE products MODIFY COLUMN name VARCHAR(100) NOT NULL;
-ALTER TABLE products COMMENT = '';
-`,
- description: "Reverse of table and column comments - removing comments and dropping tables",
- },
- {
- name: "modify_and_drop_comments",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Primary key identifier',
- username VARCHAR(50) NOT NULL COMMENT 'Unique username for login',
- email VARCHAR(100) NOT NULL COMMENT 'User email address',
- full_name VARCHAR(100) COMMENT 'User full display name',
- bio TEXT COMMENT 'User biography or description',
- status ENUM('active', 'inactive', 'suspended') DEFAULT 'active' COMMENT 'Account status',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Account creation date',
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update timestamp',
- PRIMARY KEY (id),
- UNIQUE KEY uk_username (username),
- UNIQUE KEY uk_email (email),
- INDEX idx_status (status)
-) COMMENT = 'User account information and profile data';
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Post unique identifier',
- user_id INT NOT NULL COMMENT 'Author user ID reference',
- title VARCHAR(200) NOT NULL COMMENT 'Post title',
- content TEXT COMMENT 'Post content body',
- status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT 'Post publication status',
- published_at DATETIME COMMENT 'Publication timestamp',
- view_count INT DEFAULT 0 COMMENT 'Number of views',
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- INDEX idx_status (status),
- CONSTRAINT fk_post_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) COMMENT = 'Blog posts and articles';
-`,
- migrationDDL: `
--- Modify existing table comments
-ALTER TABLE users COMMENT = 'Updated user account information with enhanced profile features';
-ALTER TABLE posts COMMENT = 'Blog posts with analytics and engagement tracking';
-
--- Modify existing column comments
-ALTER TABLE users MODIFY COLUMN username VARCHAR(50) NOT NULL COMMENT 'Updated: Unique username for authentication and display';
-ALTER TABLE users MODIFY COLUMN bio TEXT COMMENT 'Updated: Extended user biography with rich text support';
-ALTER TABLE users MODIFY COLUMN status ENUM('active', 'inactive', 'suspended', 'pending') DEFAULT 'active' COMMENT 'Updated: Account status with pending verification';
-
--- Remove comments from columns (set to empty string)
-ALTER TABLE users MODIFY COLUMN full_name VARCHAR(100) COMMENT '';
-ALTER TABLE posts MODIFY COLUMN view_count INT DEFAULT 0 COMMENT '';
-
--- Add new columns with comments
-ALTER TABLE users ADD COLUMN avatar_url VARCHAR(255) COMMENT 'Profile picture URL';
-ALTER TABLE users ADD COLUMN last_login DATETIME COMMENT 'Last successful login timestamp';
-ALTER TABLE users ADD COLUMN login_count INT DEFAULT 0 COMMENT 'Total number of logins';
-
--- Modify existing column comments with new information
-ALTER TABLE posts MODIFY COLUMN title VARCHAR(200) NOT NULL COMMENT 'Post title with SEO optimization';
-ALTER TABLE posts MODIFY COLUMN content TEXT COMMENT 'Rich text post content with markdown support';
-
--- Add new table with comprehensive comments
-CREATE TABLE user_preferences (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Preference record identifier',
- user_id INT NOT NULL COMMENT 'User ID foreign key reference',
- preference_key VARCHAR(100) NOT NULL COMMENT 'Configuration key name',
- preference_value TEXT COMMENT 'Configuration value in JSON format',
- is_public BOOLEAN DEFAULT false COMMENT 'Whether preference is publicly visible',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Preference creation time',
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last modification time',
- PRIMARY KEY (id),
- UNIQUE KEY uk_user_key (user_id, preference_key),
- INDEX idx_key (preference_key),
- INDEX idx_public (is_public),
- CONSTRAINT fk_pref_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) COMMENT = 'User-specific configuration and preference settings';
-`,
- description: "Modifying existing comments and removing comments from tables and columns",
- },
- {
- name: "reverse_modify_and_drop_comments",
- initialSchema: `
-CREATE TABLE users (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Primary key identifier',
- username VARCHAR(50) NOT NULL COMMENT 'Updated: Unique username for authentication and display',
- email VARCHAR(100) NOT NULL COMMENT 'User email address',
- full_name VARCHAR(100),
- bio TEXT COMMENT 'Updated: Extended user biography with rich text support',
- status ENUM('active', 'inactive', 'suspended', 'pending') DEFAULT 'active' COMMENT 'Updated: Account status with pending verification',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Account creation date',
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update timestamp',
- avatar_url VARCHAR(255) COMMENT 'Profile picture URL',
- last_login DATETIME COMMENT 'Last successful login timestamp',
- login_count INT DEFAULT 0 COMMENT 'Total number of logins',
- PRIMARY KEY (id),
- UNIQUE KEY uk_username (username),
- UNIQUE KEY uk_email (email),
- INDEX idx_status (status)
-) COMMENT = 'Updated user account information with enhanced profile features';
-
-CREATE TABLE posts (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Post unique identifier',
- user_id INT NOT NULL COMMENT 'Author user ID reference',
- title VARCHAR(200) NOT NULL COMMENT 'Post title with SEO optimization',
- content TEXT COMMENT 'Rich text post content with markdown support',
- status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT 'Post publication status',
- published_at DATETIME COMMENT 'Publication timestamp',
- view_count INT DEFAULT 0,
- PRIMARY KEY (id),
- INDEX idx_user_id (user_id),
- INDEX idx_status (status),
- CONSTRAINT fk_post_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) COMMENT = 'Blog posts with analytics and engagement tracking';
-
-CREATE TABLE user_preferences (
- id INT NOT NULL AUTO_INCREMENT COMMENT 'Preference record identifier',
- user_id INT NOT NULL COMMENT 'User ID foreign key reference',
- preference_key VARCHAR(100) NOT NULL COMMENT 'Configuration key name',
- preference_value TEXT COMMENT 'Configuration value in JSON format',
- is_public BOOLEAN DEFAULT false COMMENT 'Whether preference is publicly visible',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Preference creation time',
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last modification time',
- PRIMARY KEY (id),
- UNIQUE KEY uk_user_key (user_id, preference_key),
- INDEX idx_key (preference_key),
- INDEX idx_public (is_public),
- CONSTRAINT fk_pref_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-) COMMENT = 'User-specific configuration and preference settings';
-`,
- migrationDDL: `
--- Drop new table
-DROP TABLE user_preferences;
-
--- Restore original column comments
-ALTER TABLE posts MODIFY COLUMN content TEXT COMMENT 'Post content body';
-ALTER TABLE posts MODIFY COLUMN title VARCHAR(200) NOT NULL COMMENT 'Post title';
-
--- Drop new columns
-ALTER TABLE users DROP COLUMN login_count;
-ALTER TABLE users DROP COLUMN last_login;
-ALTER TABLE users DROP COLUMN avatar_url;
-
--- Restore comments that were removed
-ALTER TABLE posts MODIFY COLUMN view_count INT DEFAULT 0 COMMENT 'Number of views';
-ALTER TABLE users MODIFY COLUMN full_name VARCHAR(100) COMMENT 'User full display name';
-
--- Restore original column types and comments
-ALTER TABLE users MODIFY COLUMN status ENUM('active', 'inactive', 'suspended') DEFAULT 'active' COMMENT 'Account status';
-ALTER TABLE users MODIFY COLUMN bio TEXT COMMENT 'User biography or description';
-ALTER TABLE users MODIFY COLUMN username VARCHAR(50) NOT NULL COMMENT 'Unique username for login';
-
--- Restore original table comments
-ALTER TABLE posts COMMENT = 'Blog posts and articles';
-ALTER TABLE users COMMENT = 'User account information and profile data';
-`,
- description: "Reverse of modify and drop comments - restoring original comments and dropping new table",
- },
- {
- name: "comments_with_special_characters",
- initialSchema: `
-CREATE TABLE test_table (
- id INT NOT NULL AUTO_INCREMENT,
- simple_field VARCHAR(100),
- PRIMARY KEY (id)
-);
-`,
- migrationDDL: `
--- Test comments with various special characters and scenarios
-ALTER TABLE test_table COMMENT = 'Table with "double quotes" and ''single quotes'' in comment';
-
--- Add columns with special characters in comments
-ALTER TABLE test_table ADD COLUMN field_with_quotes VARCHAR(100) COMMENT 'Field with "double" and ''single'' quotes';
-ALTER TABLE test_table ADD COLUMN field_with_symbols VARCHAR(100) COMMENT 'Field with symbols: @#$%^&*()_+-={}[]|:";''<>?,./ and more!';
-ALTER TABLE test_table ADD COLUMN field_with_unicode VARCHAR(100) COMMENT 'Unicode test: 你好世界 🌍 café naïve résumé Москва العالم 한국어';
-ALTER TABLE test_table ADD COLUMN field_multiline TEXT COMMENT 'Multi-line comment:
-Line 1 with regular text
-Line 2 with "quotes" and symbols @#$
-Line 3 with unicode: 测试 🚀 café
-Final line with mixed content';
-ALTER TABLE test_table ADD COLUMN field_with_sql VARCHAR(100) COMMENT 'Comment with SQL-like content: SELECT * FROM table WHERE id = ''123'' AND name LIKE "%test%"';
-ALTER TABLE test_table ADD COLUMN field_with_html VARCHAR(100) COMMENT 'HTML content: <div class="test">Hello & "World"</div> <!-- comment -->';
-ALTER TABLE test_table ADD COLUMN field_with_json VARCHAR(100) COMMENT 'JSON example: {"name": "test", "value": 123, "nested": {"key": "value with spaces"}}';
-ALTER TABLE test_table ADD COLUMN field_with_escape VARCHAR(100) COMMENT 'Escape sequences: \n \t \r " '' \\';
-
--- Create table with complex comment containing all special character types
-CREATE TABLE special_comments_table (
- id BIGINT NOT NULL AUTO_RANDOM COMMENT 'ID with "quotes", symbols @#$, unicode 测试🌟, and
-multi-line
-content',
- data_field JSON COMMENT 'JSON field storing: {"users": ["John O''Connor", "Jane \"Doe\""], "count": 42}',
- html_field TEXT COMMENT 'HTML content field: <script>alert("XSS test & more");</script>',
- sql_field VARCHAR(255) COMMENT 'SQL patterns: SELECT * FROM users WHERE name = ''O''Brien'' AND age > 21',
- unicode_field VARCHAR(200) COMMENT '多语言支持: English, 中文, العربية, Русский, 日本語, 한국어, Français, Español',
- symbols_field VARCHAR(100) COMMENT 'All symbols: !@#$%^&*()_+-={}[]|:";''<>?,./ plus tab and newline
-test',
- url_field VARCHAR(300) COMMENT 'URL with params: https://example.com/path?param1=value1&param2="quoted value"&param3=50%+discount',
- regex_field VARCHAR(150) COMMENT 'Regex pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$ for email validation',
- PRIMARY KEY (id),
- INDEX idx_unicode (unicode_field)
-) COMMENT = 'Special characters test table with:
-- Double quotes: "test"
-- Single quotes: ''test''
-- Unicode: 特殊字符测试表 🎯
-- Symbols: @#$%^&*()
-- HTML: <div>content</div>
-- JSON: {"key": "value"}
-- URLs: https://example.com
-- Multi-line content with various encodings';
-
--- Test modifying comments with special characters
-ALTER TABLE special_comments_table MODIFY COLUMN data_field JSON COMMENT 'Updated JSON field: {"new": "structure", "with": ["array", "of", "strings"], "escapes": "\n\t\r"}';
-
--- Test removing comments that had special characters
-ALTER TABLE special_comments_table MODIFY COLUMN html_field TEXT COMMENT '';
-`,
- description: "Testing comments with special characters, quotes, Unicode, multi-line text, and edge cases",
- },
- {
- name: "reverse_comments_with_special_characters",
- initialSchema: `
-CREATE TABLE test_table (
- id INT NOT NULL AUTO_INCREMENT,
- simple_field VARCHAR(100),
- field_with_quotes VARCHAR(100) COMMENT 'Field with "double" and ''single'' quotes',
- field_with_symbols VARCHAR(100) COMMENT 'Field with symbols: @#$%^&*()_+-={}[]|:";''<>?,./ and more!',
- field_with_unicode VARCHAR(100) COMMENT 'Unicode test: 你好世界 🌍 café naïve résumé Москва العالم 한국어',
- field_multiline TEXT COMMENT 'Multi-line comment:
-Line 1 with regular text
-Line 2 with "quotes" and symbols @#$
-Line 3 with unicode: 测试 🚀 café
-Final line with mixed content',
- field_with_sql VARCHAR(100) COMMENT 'Comment with SQL-like content: SELECT * FROM table WHERE id = ''123'' AND name LIKE "%test%"',
- field_with_html VARCHAR(100) COMMENT 'HTML content: <div class="test">Hello & "World"</div> <!-- comment -->',
- field_with_json VARCHAR(100) COMMENT 'JSON example: {"name": "test", "value": 123, "nested": {"key": "value with spaces"}}',
- field_with_escape VARCHAR(100) COMMENT 'Escape sequences: \n \t \r " '' \\',
- PRIMARY KEY (id)
-) COMMENT = 'Table with "double quotes" and ''single quotes'' in comment';
-
-CREATE TABLE special_comments_table (
- id BIGINT NOT NULL AUTO_RANDOM COMMENT 'ID with "quotes", symbols @#$, unicode 测试🌟, and
-multi-line
-content',
- data_field JSON COMMENT 'Updated JSON field: {"new": "structure", "with": ["array", "of", "strings"], "escapes": "\n\t\r"}',
- html_field TEXT,
- sql_field VARCHAR(255) COMMENT 'SQL patterns: SELECT * FROM users WHERE name = ''O''Brien'' AND age > 21',
- unicode_field VARCHAR(200) COMMENT '多语言支持: English, 中文, العربية, Русский, 日本語, 한국어, Français, Español',
- symbols_field VARCHAR(100) COMMENT 'All symbols: !@#$%^&*()_+-={}[]|:";''<>?,./ plus tab and newline
-test',
- url_field VARCHAR(300) COMMENT 'URL with params: https://example.com/path?param1=value1&param2="quoted value"&param3=50%+discount',
- regex_field VARCHAR(150) COMMENT 'Regex pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$ for email validation',
- PRIMARY KEY (id),
- INDEX idx_unicode (unicode_field)
-) COMMENT = 'Special characters test table with:
-- Double quotes: "test"
-- Single quotes: ''test''
-- Unicode: 特殊字符测试表 🎯
-- Symbols: @#$%^&*()
-- HTML: <div>content</div>
-- JSON: {"key": "value"}
-- URLs: https://example.com
-- Multi-line content with various encodings';
-`,
- migrationDDL: `
--- Drop table with special comments
-DROP TABLE special_comments_table;
-
--- Drop columns with special character comments
-ALTER TABLE test_table DROP COLUMN field_with_escape;
-ALTER TABLE test_table DROP COLUMN field_with_json;
-ALTER TABLE test_table DROP COLUMN field_with_html;
-ALTER TABLE test_table DROP COLUMN field_with_sql;
-ALTER TABLE test_table DROP COLUMN field_multiline;
-ALTER TABLE test_table DROP COLUMN field_with_unicode;
-ALTER TABLE test_table DROP COLUMN field_with_symbols;
-ALTER TABLE test_table DROP COLUMN field_with_quotes;
-
--- Remove table comment
-ALTER TABLE test_table COMMENT = '';
-`,
- description: "Reverse of comments with special characters - removing all special character comments",
- },
- }
-
- for _, tc := range testCases {
- tc := tc
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
-
- // Create unique test database using UUID
- testDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", testDB))
- require.NoError(t, err, "failed to create test database")
-
- // Create driver for this test database
- driver, err := createTiDBDriver(ctx, container.GetHost(), container.GetPort(), testDB)
- require.NoError(t, err, "failed to create driver")
- defer driver.Close(ctx)
-
- // Step 1: Initialize the database schema and get schema result A
- require.NoError(t, err)
-
- // Execute initial schema
- _, err = driver.GetDB().Exec(tc.initialSchema)
- require.NoError(t, err, "Failed to execute initial schema")
-
- schemaA, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Step 2: Do some migration and get schema result B
- _, err = driver.GetDB().Exec(tc.migrationDDL)
- require.NoError(t, err, "Failed to execute migration DDL")
-
- schemaB, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Step 3: Call generate migration to get the rollback DDL
- // Convert to model.DatabaseSchema
- dbMetadataA := model.NewDatabaseMetadata(schemaA, nil, nil, storepb.Engine_TIDB, false)
- dbMetadataB := model.NewDatabaseMetadata(schemaB, nil, nil, storepb.Engine_TIDB, false)
-
- // Get diff from B to A (to generate rollback)
- diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_TIDB, dbMetadataB, dbMetadataA)
- require.NoError(t, err)
+type generateMigrationCase struct {
+ Description string `yaml:"description"`
+ OldSchema string `yaml:"oldSchema"`
+ NewSchema string `yaml:"newSchema"`
+ Expected string `yaml:"expected"`
+}
- // Generate rollback migration
- rollbackDDL, err := schema.GenerateMigration(storepb.Engine_TIDB, diff)
+// TestGenerateMigration pins the DDL that takes oldSchema to newSchema. Cases come
+// in both directions for each schema pair, so an object appears once as a create
+// and once as a drop.
+func TestGenerateMigration(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/generate_migration.yaml"
+ )
+
+ var tests []generateMigrationCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
+
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ diff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_TIDB,
+ parseSchema(t, tc.OldSchema), parseSchema(t, tc.NewSchema))
require.NoError(t, err)
- t.Logf("Rollback DDL:\n%s", rollbackDDL)
-
- // Step 4: Run rollback DDL and get schema result C
- _, err = driver.GetDB().Exec(rollbackDDL)
- require.NoError(t, err, "Failed to execute rollback DDL")
-
- schemaC, err := driver.SyncDBSchema(ctx)
+ migration, err := generateMigration(diff)
require.NoError(t, err)
- // Step 5: Compare schema result A and C to ensure they are the same
- normalizeMetadataForComparison(schemaA)
- normalizeMetadataForComparison(schemaC)
+ if !knownInvalidOutput[tc.Description] {
+ requireParses(t, migration)
+ }
- // Use cmp with protocmp for proto message comparison
- if diff := cmp.Diff(schemaA, schemaC, protocmp.Transform()); diff != "" {
- t.Errorf("Schema mismatch after rollback (-want +got):\n%s", diff)
+ if record {
+ tests[i].Expected = migration
+ return
}
+ require.Equal(t, tc.Expected, migration)
})
}
-}
-
-func normalizeMetadataForComparison(metadata *storepb.DatabaseSchemaMetadata) {
- // Clear database name as it might differ
- metadata.Name = ""
-
- // Normalize schemas
- for _, schema := range metadata.Schemas {
- // Normalize tables
- for _, table := range schema.Tables {
- table.DataSize = 0
- table.IndexSize = 0
- table.RowCount = 0
-
- // Clear auto-increment and auto-random values as they might differ
- for _, col := range table.Columns {
- if col.Default == "AUTO_INCREMENT" {
- col.Default = "AUTO_INCREMENT"
- } else if strings.HasPrefix(col.Default, "AUTO_RANDOM") {
- // Keep the AUTO_RANDOM marker but normalize the value
- col.Default = "AUTO_RANDOM"
- }
- // Clear column position as it might change during DDL operations
- col.Position = 0
- }
-
- // Sort columns by name for consistent comparison
- sortColumnsByName(table.Columns)
-
- // Sort indexes by name
- sortIndexesByName(table.Indexes)
-
- // Sort foreign keys by name
- sortForeignKeysByName(table.ForeignKeys)
-
- // Sort check constraints by name
- sortCheckConstraintsByName(table.CheckConstraints)
- // Sort triggers by name
- sortTriggersByName(table.Triggers)
- }
-
- // Sort all collections for consistent comparison
- sortTablesByName(schema.Tables)
- sortViewsByName(schema.Views)
- sortFunctionsByName(schema.Functions)
- sortProceduresByName(schema.Procedures)
+ if record {
+ yamltest.Record(t, filepath, tests)
}
-
- // Sort schemas by name
- sortSchemasByName(metadata.Schemas)
-
- // Sort extensions by name
- sortExtensionsByName(metadata.Extensions)
-}
-
-// Sorting helper functions
-func sortSchemasByName(schemas []*storepb.SchemaMetadata) {
- slices.SortFunc(schemas, func(a, b *storepb.SchemaMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
}
-func sortTablesByName(tables []*storepb.TableMetadata) {
- slices.SortFunc(tables, func(a, b *storepb.TableMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortColumnsByName(columns []*storepb.ColumnMetadata) {
- slices.SortFunc(columns, func(a, b *storepb.ColumnMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortIndexesByName(indexes []*storepb.IndexMetadata) {
- slices.SortFunc(indexes, func(a, b *storepb.IndexMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortForeignKeysByName(fks []*storepb.ForeignKeyMetadata) {
- slices.SortFunc(fks, func(a, b *storepb.ForeignKeyMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortCheckConstraintsByName(checks []*storepb.CheckConstraintMetadata) {
- slices.SortFunc(checks, func(a, b *storepb.CheckConstraintMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
-
-func sortViewsByName(views []*storepb.ViewMetadata) {
- slices.SortFunc(views, func(a, b *storepb.ViewMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
+// parseSchema reads a schema text into the model the differ takes. Empty text is
+// an empty database rather than a parse, which is how create-from-nothing and
+// drop-everything cases are written.
+func parseSchema(t *testing.T, text string) *model.DatabaseMetadata {
+ t.Helper()
+
+ metadata := &storepb.DatabaseSchemaMetadata{Schemas: []*storepb.SchemaMetadata{{}}}
+ if text != "" {
+ parsed, err := GetDatabaseMetadata(text)
+ require.NoError(t, err)
+ metadata = parsed
+ }
+ return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_TIDB, false)
}
-func sortFunctionsByName(functions []*storepb.FunctionMetadata) {
- slices.SortFunc(functions, func(a, b *storepb.FunctionMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
+// knownInvalidOutput names the cases whose generated migration is not valid
+// TiDB today: the writer puts comment text into a single-quoted literal without
+// escaping, so an apostrophe ends the string early. The golden records that
+// output as it is; fixing the writer removes the entry.
+var knownInvalidOutput = map[string]bool{
+ "Reverse of comments with special characters - removing all special character comments": true,
}
-func sortProceduresByName(procedures []*storepb.ProcedureMetadata) {
- slices.SortFunc(procedures, func(a, b *storepb.ProcedureMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
+// requireParses proves the generated migration is valid TiDB, which a golden
+// alone does not.
+func requireParses(t *testing.T, migration string) {
+ t.Helper()
-func sortExtensionsByName(extensions []*storepb.ExtensionMetadata) {
- slices.SortFunc(extensions, func(a, b *storepb.ExtensionMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
-}
+ if strings.TrimSpace(migration) == "" {
+ return
+ }
+ p := parser.New()
+ mode, err := mysql.GetSQLMode(mysql.DefaultSQLMode)
+ require.NoError(t, err)
+ p.SetSQLMode(mode)
-func sortTriggersByName(triggers []*storepb.TriggerMetadata) {
- slices.SortFunc(triggers, func(a, b *storepb.TriggerMetadata) int {
- return strings.Compare(a.Name, b.Name)
- })
+ _, _, err = p.Parse(migration, "", "")
+ require.NoError(t, err, "generated migration should parse")
}
diff --git a/backend/plugin/schema/tidb/get_database_definition_test.go b/backend/plugin/schema/tidb/get_database_definition_test.go
index 238af74cb9..ef9661ef34 100644
--- a/backend/plugin/schema/tidb/get_database_definition_test.go
+++ b/backend/plugin/schema/tidb/get_database_definition_test.go
@@ -1,337 +1,62 @@
package tidb
import (
- "context"
- "fmt"
- "strings"
+ "os"
"testing"
- // Import MySQL driver (TiDB is compatible with MySQL protocol)
- _ "github.com/go-sql-driver/mysql"
- "github.com/google/go-cmp/cmp"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
- "google.golang.org/protobuf/testing/protocmp"
+ "gopkg.in/yaml.v3"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/schema"
)
-func TestGetDatabaseDefinition(t *testing.T) {
- t.Parallel()
-
- if testing.Short() {
- t.Skip("Skipping TiDB testcontainer test in short mode")
- }
-
- ctx := context.Background()
- container := testcontainer.SharedTiDBContainer(t)
-
- type testCase struct {
- description string
- originalDDL string
- }
-
- testCases := []testCase{
- {
- description: "Basic tables with various column types",
- originalDDL: `
-CREATE TABLE users (
- id INT PRIMARY KEY AUTO_INCREMENT,
- username VARCHAR(50) NOT NULL UNIQUE,
- email VARCHAR(100) NOT NULL,
- age INT CHECK (age >= 18),
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- profile JSON,
- is_active BOOLEAN DEFAULT TRUE,
- INDEX idx_email (email),
- INDEX idx_created_at (created_at)
-);
-
-CREATE TABLE posts (
- id INT PRIMARY KEY AUTO_INCREMENT,
- user_id INT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published_at DATETIME,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE,
- INDEX idx_user_published (user_id, published_at)
-);
-`,
- },
- {
- description: "Generated columns and complex indexes",
- originalDDL: `
-CREATE TABLE products (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- price DECIMAL(10, 2) NOT NULL,
- tax_rate DECIMAL(5, 2) NOT NULL DEFAULT 0.08,
- price_with_tax DECIMAL(10, 2) AS (price * (1 + tax_rate)) STORED,
- description TEXT,
- tags JSON,
- FULLTEXT idx_fulltext (name, description)
-);
-
-CREATE TABLE inventory (
- id INT PRIMARY KEY AUTO_INCREMENT,
- product_id INT NOT NULL,
- warehouse VARCHAR(50) NOT NULL,
- quantity INT NOT NULL DEFAULT 0,
- last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- UNIQUE KEY uk_product_warehouse (product_id, warehouse),
- FOREIGN KEY (product_id) REFERENCES products(id)
-);
-`,
- },
- {
- description: "Views",
- originalDDL: `
-CREATE TABLE orders (
- id INT PRIMARY KEY AUTO_INCREMENT,
- order_number VARCHAR(20) NOT NULL UNIQUE,
- customer_name VARCHAR(100) NOT NULL,
- total_amount DECIMAL(10, 2) NOT NULL,
- status VARCHAR(20) DEFAULT 'pending',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE order_items (
- id INT PRIMARY KEY AUTO_INCREMENT,
- order_id INT NOT NULL,
- product_name VARCHAR(100) NOT NULL,
- quantity INT NOT NULL,
- unit_price DECIMAL(10, 2) NOT NULL,
- FOREIGN KEY (order_id) REFERENCES orders(id)
-);
-
-CREATE VIEW pending_orders AS
-SELECT id, order_number, customer_name, total_amount, created_at
-FROM orders
-WHERE status = 'pending'
-ORDER BY created_at DESC;
-
-CREATE VIEW order_summary AS
-SELECT
- o.id,
- o.order_number,
- o.customer_name,
- o.total_amount,
- COUNT(oi.id) AS item_count,
- SUM(oi.quantity) AS total_quantity
-FROM orders o
-LEFT JOIN order_items oi ON o.id = oi.order_id
-GROUP BY o.id, o.order_number, o.customer_name, o.total_amount;
-`,
- },
- {
- description: "TiDB specific features - AUTO_RANDOM",
- originalDDL: `
-CREATE TABLE distributed_data (
- id BIGINT AUTO_RANDOM(5) PRIMARY KEY,
- data_type VARCHAR(50) NOT NULL,
- payload JSON,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- INDEX idx_type_created (data_type, created_at)
-);
-
-CREATE TABLE users_autorand (
- id BIGINT AUTO_RANDOM PRIMARY KEY,
- username VARCHAR(100) NOT NULL UNIQUE,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-`,
- },
- {
- description: "Character sets and collations",
- originalDDL: `
-CREATE TABLE multilingual (
- id INT PRIMARY KEY AUTO_INCREMENT,
- content_utf8 VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
- content_bin VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,
- content_unicode VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
-) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-
-CREATE TABLE charset_test (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) CHARACTER SET latin1,
- description TEXT CHARACTER SET utf8mb4
-) DEFAULT CHARSET=utf8mb4;
-`,
- },
- {
- description: "TiDB clustered and non-clustered indexes",
- originalDDL: `
-CREATE TABLE clustered_pk (
- id BIGINT PRIMARY KEY /*T![clustered_index] CLUSTERED */,
- name VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- INDEX idx_name (name)
-);
-
-CREATE TABLE nonclustered_pk (
- id BIGINT PRIMARY KEY /*T![clustered_index] NONCLUSTERED */,
- code VARCHAR(50) NOT NULL UNIQUE,
- data JSON,
- INDEX idx_code (code)
-);
-`,
- },
- }
-
- for _, tc := range testCases {
- tc := tc
- t.Run(tc.description, func(t *testing.T) {
- t.Parallel()
+type getDatabaseDefinitionCase struct {
+ Description string `yaml:"description"`
+ Metadata string `yaml:"metadata"`
+ Expected string `yaml:"expected"`
+}
- // Create unique test database using UUID
- testDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", testDB))
- require.NoError(t, err)
+// TestGetDatabaseDefinition pins the DDL generated for each metadata input, and
+// re-parses that DDL to prove it is valid TiDB syntax.
+//
+// The input is metadata rather than a schema text on purpose: deriving it by
+// parsing would cap this test's reach at whatever GetDatabaseMetadata happens to
+// extract, so any generator branch the parser cannot feed would go untested.
+func TestGetDatabaseDefinition(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/get_database_definition.yaml"
+ )
- // Get the original database metadata using SyncDBSchema
- driver, err := createTiDBDriver(ctx, container.GetHost(), container.GetPort(), testDB)
- require.NoError(t, err)
- defer driver.Close(ctx)
- // Execute original DDL
- _, err = driver.GetDB().Exec(tc.originalDDL)
- require.NoError(t, err)
+ var tests []getDatabaseDefinitionCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
- originalMetadata, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ var metadata storepb.DatabaseSchemaMetadata
+ require.NoError(t, common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Metadata), &metadata))
- // Generate the database definition
- definition, err := schema.GetDatabaseDefinition(storepb.Engine_TIDB, schema.GetDefinitionContext{PrintHeader: true}, originalMetadata)
+ definition, err := GetDatabaseDefinition(schema.GetDefinitionContext{PrintHeader: true}, &metadata)
require.NoError(t, err)
require.NotEmpty(t, definition)
- // Create a new database and apply the generated definition
- newTestDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err = container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", newTestDB))
- require.NoError(t, err)
+ _, err = GetDatabaseMetadata(definition)
+ require.NoError(t, err, "generated definition should parse")
- // Get the new database metadata
- newDriver, err := createTiDBDriver(ctx, container.GetHost(), container.GetPort(), newTestDB)
- require.NoError(t, err)
- defer newDriver.Close(ctx)
-
- require.NoError(t, err)
- _, err = newDriver.GetDB().Exec(definition)
- require.NoError(t, err)
-
- newMetadata, err := newDriver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Compare the metadata
- // Ignore database name differences when comparing
- originalMetadata.Name = ""
- newMetadata.Name = ""
- diff := cmp.Diff(originalMetadata, newMetadata, protocmp.Transform())
- require.Empty(t, diff, "Database metadata should be identical")
+ if record {
+ tests[i].Expected = definition
+ return
+ }
+ require.Equal(t, tc.Expected, definition)
})
}
-}
-// TestGetDatabaseDefinitionWithConnectedDeps tests the database definition generation
-// with foreign key dependencies between tables
-func TestGetDatabaseDefinitionWithConnectedDeps(t *testing.T) {
- if testing.Short() {
- t.Skip("Skipping TiDB testcontainer test in short mode")
+ if record {
+ yamltest.Record(t, filepath, tests)
}
-
- ctx := context.Background()
- container := testcontainer.SharedTiDBContainer(t)
-
- // Create unique test database using UUID
- testDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
-
- originalDDL := `
--- Create tables with complex foreign key dependencies
-CREATE TABLE departments (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL UNIQUE,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE employees (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- department_id INT NOT NULL,
- manager_id INT,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE RESTRICT,
- FOREIGN KEY (manager_id) REFERENCES employees(id) ON DELETE SET NULL,
- INDEX idx_department (department_id),
- INDEX idx_manager (manager_id)
-);
-
-CREATE TABLE projects (
- id INT PRIMARY KEY AUTO_INCREMENT,
- name VARCHAR(100) NOT NULL,
- department_id INT NOT NULL,
- lead_id INT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE,
- FOREIGN KEY (lead_id) REFERENCES employees(id) ON DELETE RESTRICT,
- INDEX idx_department (department_id),
- INDEX idx_lead (lead_id)
-);
-
-CREATE TABLE project_members (
- project_id INT NOT NULL,
- employee_id INT NOT NULL,
- role VARCHAR(50) NOT NULL,
- joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (project_id, employee_id),
- FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
- FOREIGN KEY (employee_id) REFERENCES employees(id) ON DELETE CASCADE
-);
-`
-
- // Create database
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", testDB))
- require.NoError(t, err)
-
- // Get the original database metadata
- driver, err := createTiDBDriver(ctx, container.GetHost(), container.GetPort(), testDB)
- require.NoError(t, err)
- // Execute original DDL
- _, err = driver.GetDB().Exec(originalDDL)
- require.NoError(t, err)
- defer driver.Close(ctx)
-
- originalMetadata, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Generate the database definition
- definition, err := schema.GetDatabaseDefinition(storepb.Engine_TIDB, schema.GetDefinitionContext{PrintHeader: true}, originalMetadata)
- require.NoError(t, err)
- require.NotEmpty(t, definition)
-
- // Create a new database and apply the generated definition
- newTestDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err = container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", newTestDB))
- require.NoError(t, err)
-
- // Get the new database metadata
- newDriver, err := createTiDBDriver(ctx, container.GetHost(), container.GetPort(), newTestDB)
- require.NoError(t, err)
- defer newDriver.Close(ctx)
-
- // Apply the generated definition to the new database
- _, err = newDriver.GetDB().Exec(definition)
- require.NoError(t, err)
-
- newMetadata, err := newDriver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Compare the metadata
- // Ignore database name differences when comparing
- originalMetadata.Name = ""
- newMetadata.Name = ""
- diff := cmp.Diff(originalMetadata, newMetadata, protocmp.Transform())
- require.Empty(t, diff, "Database metadata should be identical")
}
diff --git a/backend/plugin/schema/tidb/get_database_metadata_test.go b/backend/plugin/schema/tidb/get_database_metadata_test.go
index 6ba7ac8da7..a6e00414e3 100644
--- a/backend/plugin/schema/tidb/get_database_metadata_test.go
+++ b/backend/plugin/schema/tidb/get_database_metadata_test.go
@@ -1,529 +1,54 @@
package tidb
import (
- "context"
- "fmt"
- "strings"
+ "encoding/json"
+ "os"
"testing"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
- "github.com/bytebase/bytebase/backend/common/testcontainer"
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/common/yamltest"
)
-// TestGetDatabaseMetadataWithTestcontainer tests the get_database_metadata function
-// by comparing its output with the metadata retrieved from a real TiDB instance.
-func TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {
- t.Parallel()
-
- if testing.Short() {
- t.Skip("Skipping TiDB testcontainer test in short mode")
- }
-
- ctx := context.Background()
- container := testcontainer.SharedTiDBContainer(t)
-
- // Test cases with various TiDB features
- testCases := []struct {
- name string
- ddl string
- }{
- {
- name: "basic_tables_with_constraints",
- ddl: `
-CREATE TABLE users (
- id BIGINT AUTO_INCREMENT PRIMARY KEY,
- username VARCHAR(50) NOT NULL UNIQUE,
- email VARCHAR(100) NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
-);
-
-CREATE TABLE posts (
- id BIGINT AUTO_INCREMENT PRIMARY KEY,
- user_id BIGINT NOT NULL,
- title VARCHAR(200) NOT NULL,
- content TEXT,
- published BOOLEAN DEFAULT false,
- CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
- INDEX idx_user_id (user_id),
- INDEX idx_published (published)
-);
-`,
- },
- {
- name: "table_with_various_data_types",
- ddl: `
-CREATE TABLE data_types_test (
- id BIGINT AUTO_INCREMENT PRIMARY KEY,
- tiny_int_col TINYINT,
- small_int_col SMALLINT,
- medium_int_col MEDIUMINT,
- int_col INT,
- big_int_col BIGINT,
- decimal_col DECIMAL(10, 2),
- float_col FLOAT,
- double_col DOUBLE,
- bit_col BIT(8),
- char_col CHAR(10),
- varchar_col VARCHAR(100),
- binary_col BINARY(10),
- varbinary_col VARBINARY(100),
- tinytext_col TINYTEXT,
- text_col TEXT,
- mediumtext_col MEDIUMTEXT,
- longtext_col LONGTEXT,
- tinyblob_col TINYBLOB,
- blob_col BLOB,
- mediumblob_col MEDIUMBLOB,
- longblob_col LONGBLOB,
- date_col DATE,
- time_col TIME,
- datetime_col DATETIME,
- timestamp_col TIMESTAMP,
- year_col YEAR,
- json_col JSON,
- enum_col ENUM('small', 'medium', 'large'),
- set_col SET('a', 'b', 'c')
-);
-`,
- },
- {
- name: "table_with_foreign_keys",
- ddl: `
-CREATE TABLE departments (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL
-);
-
-CREATE TABLE employees (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- dept_id INT,
- manager_id INT,
- CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE RESTRICT,
- CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(id) ON DELETE SET NULL
-);
-`,
- },
- {
- name: "views_and_comments",
- ddl: `
-CREATE TABLE orders (
- id INT AUTO_INCREMENT PRIMARY KEY,
- customer_name VARCHAR(100) COMMENT 'Customer full name',
- amount DECIMAL(10,2) COMMENT 'Order amount in USD',
- status VARCHAR(20) DEFAULT 'pending'
-) COMMENT='Order management table';
-
-CREATE VIEW active_orders AS
-SELECT id, customer_name, amount
-FROM orders
-WHERE status = 'active';
-`,
- },
- {
- name: "indexes_and_constraints",
- ddl: `
-CREATE TABLE products (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- description TEXT,
- price DECIMAL(10,2) NOT NULL,
- category VARCHAR(50),
- tags JSON,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- INDEX idx_name (name),
- INDEX idx_price_category (price, category),
- UNIQUE INDEX idx_unique_name (name),
- FULLTEXT INDEX idx_description (description)
-);
-`,
- },
- {
- name: "tidb_auto_random",
- ddl: `
-CREATE TABLE auto_random_test (
- id BIGINT /*T![auto_rand] AUTO_RANDOM(5) */ PRIMARY KEY,
- name VARCHAR(100),
- data JSON
-) COMMENT='PK_AUTO_RANDOM_BITS=5';
-`,
- },
- {
- name: "complex_table_options",
- ddl: `
-CREATE TABLE table_options_test (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- data TEXT
-) ENGINE=InnoDB
- DEFAULT CHARSET=utf8mb4
- COLLATE=utf8mb4_general_ci
- AUTO_INCREMENT=1000
- COMMENT='Table with various TiDB options';
-`,
- },
- {
- name: "self_referencing_foreign_keys",
- ddl: `
-CREATE TABLE categories (
- id INT AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100) NOT NULL,
- parent_id INT,
- CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id) ON DELETE CASCADE
-);
-`,
- },
- {
- name: "tidb_clustered_index",
- ddl: `
-CREATE TABLE clustered_test (
- id INT PRIMARY KEY CLUSTERED,
- name VARCHAR(100) NOT NULL,
- email VARCHAR(100)
-);
-
-CREATE TABLE non_clustered_test (
- id INT PRIMARY KEY NONCLUSTERED,
- name VARCHAR(100) NOT NULL,
- data TEXT
-);
-`,
- },
- }
-
- for _, tc := range testCases {
- tc := tc
- t.Run(tc.name, func(t *testing.T) {
- t.Parallel()
-
- // Create unique test database using UUID
- testDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))
- _, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE `%s`", testDB))
+type getDatabaseMetadataCase struct {
+ Description string `yaml:"description"`
+ Schema string `yaml:"schema"`
+ Metadata string `yaml:"metadata"`
+}
+
+// TestGetDatabaseMetadata pins what the parser extracts from each schema text.
+// The goldens describe this package's own output, not TiDB's catalog: whether
+// the parser agrees with a live server is engine conformance and belongs in omni.
+func TestGetDatabaseMetadata(t *testing.T) {
+ const (
+ record = false
+ filepath = "testdata/get_database_metadata.yaml"
+ )
+
+ var tests []getDatabaseMetadataCase
+ content, err := os.ReadFile(filepath)
+ require.NoError(t, err)
+ require.NoError(t, yaml.Unmarshal(content, &tests))
+
+ for i, tc := range tests {
+ t.Run(tc.Description, func(t *testing.T) {
+ metadata, err := GetDatabaseMetadata(tc.Schema)
require.NoError(t, err)
- // Create TiDB driver for this test database
- driver, err := createTiDBDriver(ctx, container.GetHost(), container.GetPort(), testDB)
- require.NoError(t, err)
- defer driver.Close(ctx)
-
- // Execute DDL statements
- require.NoError(t, err)
- _, err = driver.GetDB().Exec(tc.ddl)
+ encoded, err := json.MarshalIndent(metadata, "", " ")
require.NoError(t, err)
+ result := string(encoded) + "\n"
- // Get metadata from live database using driver
- dbMetadata, err := driver.SyncDBSchema(ctx)
- require.NoError(t, err)
-
- // Get metadata from parser
- parsedMetadata, err := GetDatabaseMetadata(tc.ddl)
- require.NoError(t, err)
-
- // Compare metadata
- compareMetadata(t, dbMetadata, parsedMetadata, tc.name)
- })
- }
-}
-
-// compareMetadata compares the metadata from the live database with the parsed metadata
-func compareMetadata(t *testing.T, dbMeta, parsedMeta *storepb.DatabaseSchemaMetadata, testName string) {
- // Normalize both metadata for comparison
- normalizeParserMetadata(dbMeta)
- normalizeParserMetadata(parsedMeta)
-
- // For TiDB, we only have one schema
- require.Equal(t, 1, len(parsedMeta.Schemas), "parsed metadata should have exactly one schema")
-
- dbMetadata := dbMeta.Schemas[0]
- parsedSchema := parsedMeta.Schemas[0]
-
- // Compare tables
- require.Equal(t, len(dbMetadata.Tables), len(parsedSchema.Tables),
- "mismatch in number of tables for test %s", testName)
-
- // Create a map for easier lookup
- dbTableMap := make(map[string]*storepb.TableMetadata)
- for _, table := range dbMetadata.Tables {
- dbTableMap[table.Name] = table
- }
-
- for _, parsedTable := range parsedSchema.Tables {
- dbTable, exists := dbTableMap[parsedTable.Name]
- require.True(t, exists, "table %s not found in database metadata", parsedTable.Name)
-
- // Compare basic table properties
- require.Equal(t, dbTable.Engine, parsedTable.Engine,
- "engine mismatch for table %s", parsedTable.Name)
-
- // Compare columns
- compareColumns(t, dbTable.Columns, parsedTable.Columns, parsedTable.Name)
-
- // Compare indexes
- compareIndexes(t, dbTable.Indexes, parsedTable.Indexes, parsedTable.Name)
-
- // Compare foreign keys
- compareForeignKeys(t, dbTable.ForeignKeys, parsedTable.ForeignKeys, parsedTable.Name)
- }
-
- // Compare views
- compareViews(t, dbMetadata.Views, parsedSchema.Views)
-}
-
-func compareColumns(t *testing.T, dbColumns, parsedColumns []*storepb.ColumnMetadata, tableName string) {
- require.Equal(t, len(dbColumns), len(parsedColumns),
- "column count mismatch for table %s", tableName)
-
- // Create a map for easier lookup
- dbColumnMap := make(map[string]*storepb.ColumnMetadata)
- for _, col := range dbColumns {
- dbColumnMap[col.Name] = col
- }
-
- for _, parsedCol := range parsedColumns {
- dbCol, exists := dbColumnMap[parsedCol.Name]
- require.True(t, exists, "column %s not found in database metadata for table %s", parsedCol.Name, tableName)
-
- // Compare basic column properties
- require.Equal(t, dbCol.Type, parsedCol.Type,
- "type mismatch for column %s.%s", tableName, parsedCol.Name)
- require.Equal(t, dbCol.Nullable, parsedCol.Nullable,
- "nullable mismatch for column %s.%s", tableName, parsedCol.Name)
- require.Equal(t, dbCol.Position, parsedCol.Position,
- "position mismatch for column %s.%s", tableName, parsedCol.Name)
-
- // Compare default expressions (with normalization)
- normalizeDefaultExpression(dbCol)
- normalizeDefaultExpression(parsedCol)
-
- // Handle case where one side has a default and the other doesn't
- // This can happen when the parser doesn't capture implicit defaults
- if dbCol.Default != "" && parsedCol.Default == "" {
- // If database has a default but parser doesn't, it might be an implicit default
- // We'll log it but not fail the test
- t.Logf("Column %s.%s: database has default '%s' but parser has empty default (might be implicit)", tableName, parsedCol.Name, dbCol.Default)
- } else if dbCol.Default == "" && parsedCol.Default != "" {
- // If parser has a default but database doesn't, this is unexpected
- t.Errorf("Column %s.%s: parser has default '%s' but database has empty default", tableName, parsedCol.Name, parsedCol.Default)
- } else {
- // Both have defaults (or both are empty), they should match
- require.Equal(t, dbCol.Default, parsedCol.Default,
- "default expression mismatch for column %s.%s", tableName, parsedCol.Name)
- }
- }
-}
-
-func compareIndexes(t *testing.T, dbIndexes, parsedIndexes []*storepb.IndexMetadata, tableName string) {
- require.Equal(t, len(dbIndexes), len(parsedIndexes),
- "index count mismatch for table %s", tableName)
-
- // Create a map for easier lookup
- dbIndexMap := make(map[string]*storepb.IndexMetadata)
- for _, idx := range dbIndexes {
- dbIndexMap[idx.Name] = idx
- }
-
- // Compare each parsed index with comprehensive IndexMetadata validation
- for _, parsedIdx := range parsedIndexes {
- dbIdx, exists := dbIndexMap[parsedIdx.Name]
- require.True(t, exists, "index %s not found in database metadata for table %s", parsedIdx.Name, tableName)
-
- // 1. Name - explicitly validate name consistency
- require.Equal(t, dbIdx.Name, parsedIdx.Name, "table %s, index %s: name should match", tableName, parsedIdx.Name)
-
- // 2. Primary - validate primary key flag
- require.Equal(t, dbIdx.Primary, parsedIdx.Primary,
- "table %s, index %s: primary flag should match", tableName, parsedIdx.Name)
-
- // 3. Unique - validate unique constraint flag
- require.Equal(t, dbIdx.Unique, parsedIdx.Unique,
- "table %s, index %s: unique flag should match", tableName, parsedIdx.Name)
-
- // 4. Type - validate index type with TiDB-specific normalization
- require.Equal(t, normalizeIndexType(dbIdx.Type), normalizeIndexType(parsedIdx.Type),
- "table %s, index %s: type should match", tableName, parsedIdx.Name)
-
- // 5. Expressions - validate column list/expressions
- require.Equal(t, dbIdx.Expressions, parsedIdx.Expressions,
- "table %s, index %s: expressions should match", tableName, parsedIdx.Name)
-
- // 6. Descending - validate descending order for each expression
- if len(dbIdx.Descending) > 0 || len(parsedIdx.Descending) > 0 {
- require.Equal(t, len(dbIdx.Descending), len(parsedIdx.Descending), "table %s, index %s: descending array length should match", tableName, parsedIdx.Name)
- for i := range dbIdx.Descending {
- if i < len(parsedIdx.Descending) {
- require.Equal(t, dbIdx.Descending[i], parsedIdx.Descending[i], "table %s, index %s: descending[%d] should match", tableName, parsedIdx.Name, i)
- }
- }
- }
-
- // 7. KeyLength - validate index key lengths (TiDB supports prefix indexes like MySQL)
- require.Equal(t, len(dbIdx.KeyLength), len(parsedIdx.KeyLength), "table %s, index %s: key length array length should match", tableName, parsedIdx.Name)
- for i := range dbIdx.KeyLength {
- if i < len(parsedIdx.KeyLength) {
- require.Equal(t, dbIdx.KeyLength[i], parsedIdx.KeyLength[i], "table %s, index %s: key length[%d] should match", tableName, parsedIdx.Name, i)
- }
- }
-
- // 8. Visible - validate index visibility (TiDB supports invisible indexes like MySQL)
- require.Equal(t, dbIdx.Visible, parsedIdx.Visible, "table %s, index %s: visible should match", tableName, parsedIdx.Name)
-
- // 9. Comment - validate index comment
- if dbIdx.Comment != "" || parsedIdx.Comment != "" {
- require.Equal(t, dbIdx.Comment, parsedIdx.Comment, "table %s, index %s: comment should match", tableName, parsedIdx.Name)
- }
-
- // 10. IsConstraint - validate if index represents a constraint
- require.Equal(t, dbIdx.IsConstraint, parsedIdx.IsConstraint, "table %s, index %s: IsConstraint should match", tableName, parsedIdx.Name)
-
- // 11. Definition - validate full index definition for comprehensive verification
- if dbIdx.Definition != "" || parsedIdx.Definition != "" {
- // Normalize definitions for comparison since TiDB formatting may vary
- dbDef := strings.TrimSpace(strings.ToLower(dbIdx.Definition))
- parsedDef := strings.TrimSpace(strings.ToLower(parsedIdx.Definition))
- if dbDef != "" && parsedDef != "" {
- require.Equal(t, dbDef, parsedDef, "table %s, index %s: definition should match", tableName, parsedIdx.Name)
- }
- }
-
- t.Logf("✓ Validated all IndexMetadata fields for index %s: name=%s, primary=%v, unique=%v, type=%s, expressions=%v, visible=%v, comment=%s",
- parsedIdx.Name, parsedIdx.Name, parsedIdx.Primary, parsedIdx.Unique, parsedIdx.Type, parsedIdx.Expressions, parsedIdx.Visible, parsedIdx.Comment)
- }
-}
-
-func compareForeignKeys(t *testing.T, dbFKs, parsedFKs []*storepb.ForeignKeyMetadata, tableName string) {
- require.Equal(t, len(dbFKs), len(parsedFKs),
- "foreign key count mismatch for table %s", tableName)
-
- // Create a map for easier lookup
- dbFKMap := make(map[string]*storepb.ForeignKeyMetadata)
- for _, fk := range dbFKs {
- dbFKMap[fk.Name] = fk
- }
-
- for _, parsedFK := range parsedFKs {
- dbFK, exists := dbFKMap[parsedFK.Name]
- require.True(t, exists, "foreign key %s not found in database metadata for table %s", parsedFK.Name, tableName)
-
- require.Equal(t, dbFK.Columns, parsedFK.Columns,
- "columns mismatch for foreign key %s.%s", tableName, parsedFK.Name)
- require.Equal(t, dbFK.ReferencedTable, parsedFK.ReferencedTable,
- "referenced table mismatch for foreign key %s.%s", tableName, parsedFK.Name)
- require.Equal(t, dbFK.ReferencedColumns, parsedFK.ReferencedColumns,
- "referenced columns mismatch for foreign key %s.%s", tableName, parsedFK.Name)
- require.Equal(t, dbFK.OnDelete, parsedFK.OnDelete,
- "on delete mismatch for foreign key %s.%s", tableName, parsedFK.Name)
- require.Equal(t, dbFK.OnUpdate, parsedFK.OnUpdate,
- "on update mismatch for foreign key %s.%s", tableName, parsedFK.Name)
- }
-}
-
-func compareViews(t *testing.T, dbViews, parsedViews []*storepb.ViewMetadata) {
- require.Equal(t, len(dbViews), len(parsedViews), "view count mismatch")
-
- // Create a map for easier lookup
- dbViewMap := make(map[string]*storepb.ViewMetadata)
- for _, view := range dbViews {
- dbViewMap[view.Name] = view
- }
-
- for _, parsedView := range parsedViews {
- dbView, exists := dbViewMap[parsedView.Name]
- require.True(t, exists, "view %s not found in database metadata", parsedView.Name)
-
- // View definitions might have formatting differences, so we do a basic check
- require.NotEmpty(t, parsedView.Definition, "parsed view definition should not be empty for %s", parsedView.Name)
- require.Contains(t, strings.ToLower(parsedView.Definition), "select",
- "parsed view definition should contain SELECT for %s", parsedView.Name)
-
- // Also check that database view has definition
- require.NotEmpty(t, dbView.Definition, "database view definition should not be empty for %s", dbView.Name)
- }
-}
-
-// normalizeParserMetadata normalizes metadata for comparison between parser and database
-func normalizeParserMetadata(metadata *storepb.DatabaseSchemaMetadata) {
- if metadata == nil {
- return
- }
-
- for _, schema := range metadata.Schemas {
- for _, table := range schema.Tables {
- // Normalize charset and collation since they may vary
- table.Charset = ""
- table.Collation = ""
-
- for _, col := range table.Columns {
- // Normalize default expressions
- normalizeDefaultExpression(col)
- }
-
- for _, idx := range table.Indexes {
- // Normalize index types
- idx.Type = normalizeIndexType(idx.Type)
+ if record {
+ tests[i].Metadata = result
+ return
}
-
- for _, fk := range table.ForeignKeys {
- // Ensure consistent foreign key actions
- if fk.OnDelete == "" {
- fk.OnDelete = "NO ACTION"
- }
- if fk.OnUpdate == "" {
- fk.OnUpdate = "NO ACTION"
- }
- }
- }
- }
-}
-
-func normalizeDefaultExpression(col *storepb.ColumnMetadata) {
- if col.Default == "" {
- return
- }
-
- // Normalize common default value formats
- expr := col.Default
-
- // Handle NULL values - normalize "NULL" string to empty string
- if strings.ToUpper(expr) == "NULL" {
- col.Default = ""
- return
- }
-
- // Remove charset prefixes
- if strings.HasPrefix(expr, "_utf8mb4") {
- if idx := strings.Index(expr, "'"); idx != -1 {
- expr = expr[idx:]
- }
- }
-
- // Remove quotes from string literals
- expr = strings.Trim(expr, "'\"")
-
- // Normalize boolean values
- if expr == "0" && (col.Type == "tinyint" || col.Type == "tinyint(1)") {
- expr = "false"
- }
- if expr == "1" && (col.Type == "tinyint" || col.Type == "tinyint(1)") {
- expr = "true"
- }
- if expr == "false" && (col.Type == "tinyint" || col.Type == "tinyint(1)") {
- expr = "false"
- }
- if expr == "true" && (col.Type == "tinyint" || col.Type == "tinyint(1)") {
- expr = "true"
+ require.Equal(t, tc.Metadata, result)
+ })
}
- col.Default = expr
-}
-
-func normalizeIndexType(indexType string) string {
- // TiDB always uses BTREE for most indexes
- if indexType == "" {
- return "BTREE"
+ if record {
+ yamltest.Record(t, filepath, tests)
}
- return strings.ToUpper(indexType)
}
diff --git a/backend/plugin/schema/tidb/main_test.go b/backend/plugin/schema/tidb/main_test.go
deleted file mode 100644
index ff37c2c076..0000000000
--- a/backend/plugin/schema/tidb/main_test.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package tidb
-
-import (
- "testing"
-
- "github.com/bytebase/bytebase/backend/common/testcontainer"
-)
-
-func TestMain(m *testing.M) { testcontainer.Main(m) }
diff --git a/backend/plugin/schema/tidb/testdata/generate_migration.yaml b/backend/plugin/schema/tidb/testdata/generate_migration.yaml
new file mode 100644
index 0000000000..ae3be680a8
--- /dev/null
+++ b/backend/plugin/schema/tidb/testdata/generate_migration.yaml
@@ -0,0 +1,1591 @@
+- description: Basic table operations with columns, constraints, and indexes
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ is_active BOOLEAN DEFAULT true,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username),
+ INDEX idx_email_active (email, is_active)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
+ );
+
+ CREATE TABLE comments (
+ id INT NOT NULL AUTO_INCREMENT,
+ post_id INT NOT NULL,
+ user_id INT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_post_user (post_id, user_id),
+ CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ expected: |+
+ DROP TABLE IF EXISTS `comments`;
+
+ DROP INDEX `idx_email_active` ON `users`;
+
+ ALTER TABLE `users` DROP COLUMN `is_active`;
+
+
+- description: Reverse of basic table operations - dropping columns, constraints, and indexes
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ is_active BOOLEAN DEFAULT true,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username),
+ INDEX idx_email_active (email, is_active)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
+ );
+
+ CREATE TABLE comments (
+ id INT NOT NULL AUTO_INCREMENT,
+ post_id INT NOT NULL,
+ user_id INT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_post_user (post_id, user_id),
+ CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ expected: |
+ CREATE TABLE IF NOT EXISTS `comments` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `post_id` int NOT NULL,
+ `user_id` int NOT NULL,
+ `content` text NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB;
+ CREATE INDEX `idx_post_user` ON `comments` (`post_id`, `user_id`);
+ CREATE INDEX `fk_comment_user` ON `comments` (`user_id`);
+ ALTER TABLE `comments` ADD CONSTRAINT `fk_comment_post` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE;
+ ALTER TABLE `comments` ADD CONSTRAINT `fk_comment_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
+ ALTER TABLE `users` ADD COLUMN `is_active` tinyint(1);
+ CREATE INDEX `idx_email_active` ON `users` (`email`, `is_active`);
+- description: TiDB specific features like AUTO_RANDOM and clustered index
+ oldSchema: |
+ CREATE TABLE products (
+ id BIGINT NOT NULL AUTO_RANDOM,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ category VARCHAR(50) DEFAULT 'general',
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id BIGINT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ );
+
+ CREATE VIEW product_inventory AS
+ SELECT
+ p.id,
+ p.name,
+ p.price,
+ p.stock,
+ COALESCE(SUM(o.quantity), 0) AS total_ordered
+ FROM products p
+ LEFT JOIN orders o ON p.id = o.product_id
+ GROUP BY p.id, p.name, p.price, p.stock;
+ newSchema: |
+ CREATE TABLE products (
+ id BIGINT NOT NULL AUTO_RANDOM,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id BIGINT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ );
+ expected: |+
+ CREATE OR REPLACE VIEW `product_inventory` AS SELECT 1;
+ DROP VIEW IF EXISTS `product_inventory`;
+
+ ALTER TABLE `products` DROP COLUMN `category`;
+
+
+- description: Reverse of TiDB specific features - dropping views and columns
+ oldSchema: |
+ CREATE TABLE products (
+ id BIGINT NOT NULL AUTO_RANDOM,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id BIGINT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ );
+ newSchema: |
+ CREATE TABLE products (
+ id BIGINT NOT NULL AUTO_RANDOM,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INT DEFAULT 0,
+ category VARCHAR(50) DEFAULT 'general',
+ PRIMARY KEY (id),
+ INDEX idx_name (name)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id BIGINT NOT NULL,
+ quantity INT NOT NULL,
+ total DECIMAL(10, 2),
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+ );
+
+ CREATE VIEW product_inventory AS
+ SELECT
+ p.id,
+ p.name,
+ p.price,
+ p.stock,
+ COALESCE(SUM(o.quantity), 0) AS total_ordered
+ FROM products p
+ LEFT JOIN orders o ON p.id = o.product_id
+ GROUP BY p.id, p.name, p.price, p.stock;
+ expected: |
+ ALTER TABLE `products` ADD COLUMN `category` varchar(50);
+ CREATE VIEW `product_inventory` AS SELECT
+ p.id,
+ p.name,
+ p.price,
+ p.stock,
+ COALESCE(SUM(o.quantity), 0) AS total_ordered
+ FROM products p
+ LEFT JOIN orders o ON p.id = o.product_id
+ GROUP BY p.id, p.name, p.price, p.stock;
+- description: Views and stored routines
+ oldSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_name VARCHAR(100) NOT NULL,
+ sale_amount DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_name, sale_date)
+ );
+
+ CREATE VIEW monthly_sales AS
+ SELECT
+ YEAR(sale_date) AS year,
+ MONTH(sale_date) AS month,
+ SUM(sale_amount) AS total_sales
+ FROM sales
+ GROUP BY YEAR(sale_date), MONTH(sale_date);
+
+ CREATE VIEW top_products AS
+ SELECT
+ product_name,
+ COUNT(*) AS sale_count,
+ SUM(sale_amount) AS total_revenue
+ FROM sales
+ GROUP BY product_name
+ ORDER BY SUM(sale_amount) DESC;
+
+ CREATE TABLE sales_reports (
+ id INT NOT NULL AUTO_INCREMENT,
+ report_type VARCHAR(50) NOT NULL,
+ report_data JSON,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_type (report_type)
+ );
+ newSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_name VARCHAR(100) NOT NULL,
+ sale_amount DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_name, sale_date)
+ );
+ expected: |+
+ CREATE OR REPLACE VIEW `monthly_sales` AS SELECT 1;
+ CREATE OR REPLACE VIEW `top_products` AS SELECT 1;
+ DROP VIEW IF EXISTS `monthly_sales`;
+
+ DROP VIEW IF EXISTS `top_products`;
+
+ DROP TABLE IF EXISTS `sales_reports`;
+
+- description: Reverse of views and procedures - dropping views and tables
+ oldSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_name VARCHAR(100) NOT NULL,
+ sale_amount DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_name, sale_date)
+ );
+ newSchema: |
+ CREATE TABLE sales (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_name VARCHAR(100) NOT NULL,
+ sale_amount DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_product_date (product_name, sale_date)
+ );
+
+ CREATE VIEW monthly_sales AS
+ SELECT
+ YEAR(sale_date) AS year,
+ MONTH(sale_date) AS month,
+ SUM(sale_amount) AS total_sales
+ FROM sales
+ GROUP BY YEAR(sale_date), MONTH(sale_date);
+
+ CREATE VIEW top_products AS
+ SELECT
+ product_name,
+ COUNT(*) AS sale_count,
+ SUM(sale_amount) AS total_revenue
+ FROM sales
+ GROUP BY product_name
+ ORDER BY SUM(sale_amount) DESC;
+
+ CREATE TABLE sales_reports (
+ id INT NOT NULL AUTO_INCREMENT,
+ report_type VARCHAR(50) NOT NULL,
+ report_data JSON,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_type (report_type)
+ );
+ expected: |
+ CREATE TABLE IF NOT EXISTS `sales_reports` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `report_type` varchar(50) NOT NULL,
+ `report_data` json,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB;
+ CREATE INDEX `idx_type` ON `sales_reports` (`report_type`);
+ CREATE VIEW `monthly_sales` AS SELECT
+ YEAR(sale_date) AS year,
+ MONTH(sale_date) AS month,
+ SUM(sale_amount) AS total_sales
+ FROM sales
+ GROUP BY YEAR(sale_date), MONTH(sale_date);
+ CREATE VIEW `top_products` AS SELECT
+ product_name,
+ COUNT(*) AS sale_count,
+ SUM(sale_amount) AS total_revenue
+ FROM sales
+ GROUP BY product_name
+ ORDER BY SUM(sale_amount) DESC;
+- description: Drop operations for views, functions, indexes, and constraints
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_sku (sku),
+ INDEX idx_name (name),
+ CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
+ );
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category VARCHAR(50),
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_sku (sku),
+ INDEX idx_name (name),
+ INDEX idx_category (category),
+ INDEX idx_price (price),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
+ );
+
+ CREATE VIEW product_summary AS
+ SELECT category, COUNT(*) as count, AVG(price) as avg_price
+ FROM products
+ GROUP BY category;
+
+ CREATE TABLE product_stats (
+ id INT NOT NULL AUTO_INCREMENT,
+ category VARCHAR(50) NOT NULL,
+ product_count INT DEFAULT 0,
+ avg_price DECIMAL(10, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_category (category)
+ );
+ expected: |
+ CREATE TABLE IF NOT EXISTS `product_stats` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `category` varchar(50) NOT NULL,
+ `product_count` int,
+ `avg_price` decimal(10,2),
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_category` (`category`)
+ ) ENGINE=InnoDB;
+ ALTER TABLE `products` ADD COLUMN `category` varchar(50);
+ CREATE INDEX `idx_category` ON `products` (`category`);
+ CREATE INDEX `idx_price` ON `products` (`price`);
+ CREATE VIEW `product_summary` AS SELECT category, COUNT(*) as count, AVG(price) as avg_price
+ FROM products
+ GROUP BY category;
+- description: Reverse of drop operations - creating views, indexes, and constraints
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category VARCHAR(50),
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_sku (sku),
+ INDEX idx_name (name),
+ INDEX idx_category (category),
+ INDEX idx_price (price),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
+ );
+
+ CREATE VIEW product_summary AS
+ SELECT category, COUNT(*) as count, AVG(price) as avg_price
+ FROM products
+ GROUP BY category;
+
+ CREATE TABLE product_stats (
+ id INT NOT NULL AUTO_INCREMENT,
+ category VARCHAR(50) NOT NULL,
+ product_count INT DEFAULT 0,
+ avg_price DECIMAL(10, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_category (category)
+ );
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2),
+ sku VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_sku (sku),
+ INDEX idx_name (name),
+ CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3)
+ );
+ expected: |+
+ CREATE OR REPLACE VIEW `product_summary` AS SELECT 1;
+ DROP VIEW IF EXISTS `product_summary`;
+
+ DROP TABLE IF EXISTS `product_stats`;
+
+ DROP INDEX `idx_category` ON `products`;
+
+ DROP INDEX `idx_price` ON `products`;
+
+ ALTER TABLE `products` DROP COLUMN `category`;
+
+
+- description: Various ALTER TABLE operations
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(150) NOT NULL,
+ age INT,
+ phone VARCHAR(20),
+ address TEXT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_email (email),
+ INDEX idx_name (name),
+ INDEX idx_age (age),
+ CONSTRAINT chk_age_positive CHECK (age > 0),
+ CONSTRAINT uk_phone UNIQUE (phone)
+ );
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL,
+ email VARCHAR(100),
+ age INT,
+ PRIMARY KEY (id),
+ INDEX idx_email (email)
+ );
+ expected: |
+ DROP INDEX `idx_age` ON `users`;
+
+ DROP INDEX `idx_name` ON `users`;
+
+ DROP INDEX `uk_phone` ON `users`;
+
+ ALTER TABLE `users` DROP COLUMN `phone`;
+
+ ALTER TABLE `users` DROP COLUMN `address`;
+
+ ALTER TABLE `users` DROP COLUMN `created_at`;
+
+
+ ALTER TABLE `users` MODIFY COLUMN `name` varchar(50) NOT NULL;
+ ALTER TABLE `users` MODIFY COLUMN `email` varchar(100);
+- description: Reverse of ALTER TABLE operations - dropping columns and constraints
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL,
+ email VARCHAR(100),
+ age INT,
+ PRIMARY KEY (id),
+ INDEX idx_email (email)
+ );
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(150) NOT NULL,
+ age INT,
+ phone VARCHAR(20),
+ address TEXT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_email (email),
+ INDEX idx_name (name),
+ INDEX idx_age (age),
+ CONSTRAINT chk_age_positive CHECK (age > 0),
+ CONSTRAINT uk_phone UNIQUE (phone)
+ );
+ expected: |
+ ALTER TABLE `users` ADD COLUMN `phone` varchar(20);
+ ALTER TABLE `users` ADD COLUMN `address` text;
+ ALTER TABLE `users` ADD COLUMN `created_at` timestamp DEFAULT CURRENT_TIMESTAMP;
+ ALTER TABLE `users` MODIFY COLUMN `name` varchar(100) NOT NULL;
+ ALTER TABLE `users` MODIFY COLUMN `email` varchar(150) NOT NULL;
+ CREATE INDEX `idx_age` ON `users` (`age`);
+ CREATE INDEX `idx_name` ON `users` (`name`);
+ ALTER TABLE `users` ADD UNIQUE KEY `uk_phone` (`phone`);
+- description: Complex table relationships with triggers
+ oldSchema: |
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ parent_id INT,
+ description TEXT,
+ PRIMARY KEY (id),
+ INDEX idx_parent (parent_id),
+ CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id)
+ );
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category_id INT,
+ price DECIMAL(10, 2),
+ weight DECIMAL(8, 3),
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id),
+ CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id)
+ );
+
+ CREATE TABLE product_attributes (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ attribute_name VARCHAR(100) NOT NULL,
+ attribute_value VARCHAR(200),
+ PRIMARY KEY (id),
+ INDEX idx_product_attr (product_id, attribute_name),
+ CONSTRAINT fk_product_attr FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
+ );
+ newSchema: |
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ parent_id INT,
+ PRIMARY KEY (id),
+ INDEX idx_parent (parent_id)
+ );
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category_id INT,
+ price DECIMAL(10, 2),
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id)
+ );
+
+ -- Add foreign keys
+ ALTER TABLE categories ADD CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id);
+ ALTER TABLE products ADD CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id);
+ expected: |+
+ ALTER TABLE `categories` DROP FOREIGN KEY `fk_parent`;
+
+ ALTER TABLE `products` DROP FOREIGN KEY `fk_category`;
+
+ DROP TABLE IF EXISTS `product_attributes`;
+
+ ALTER TABLE `categories` DROP COLUMN `description`;
+
+ ALTER TABLE `products` DROP COLUMN `weight`;
+
+
+- description: Reverse of complex relationships - dropping tables and columns
+ oldSchema: |
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ parent_id INT,
+ PRIMARY KEY (id),
+ INDEX idx_parent (parent_id)
+ );
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category_id INT,
+ price DECIMAL(10, 2),
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id)
+ );
+
+ -- Add foreign keys
+ ALTER TABLE categories ADD CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id);
+ ALTER TABLE products ADD CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id);
+ newSchema: |
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ parent_id INT,
+ description TEXT,
+ PRIMARY KEY (id),
+ INDEX idx_parent (parent_id),
+ CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id)
+ );
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ category_id INT,
+ price DECIMAL(10, 2),
+ weight DECIMAL(8, 3),
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id),
+ CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id)
+ );
+
+ CREATE TABLE product_attributes (
+ id INT NOT NULL AUTO_INCREMENT,
+ product_id INT NOT NULL,
+ attribute_name VARCHAR(100) NOT NULL,
+ attribute_value VARCHAR(200),
+ PRIMARY KEY (id),
+ INDEX idx_product_attr (product_id, attribute_name),
+ CONSTRAINT fk_product_attr FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
+ );
+ expected: |
+ CREATE TABLE IF NOT EXISTS `product_attributes` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `product_id` int NOT NULL,
+ `attribute_name` varchar(100) NOT NULL,
+ `attribute_value` varchar(200),
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB;
+ CREATE INDEX `idx_product_attr` ON `product_attributes` (`product_id`, `attribute_name`);
+ ALTER TABLE `product_attributes` ADD CONSTRAINT `fk_product_attr` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;
+ ALTER TABLE `categories` ADD COLUMN `description` text;
+ ALTER TABLE `categories` ADD CONSTRAINT `fk_parent` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`);
+ ALTER TABLE `products` ADD COLUMN `weight` decimal(8,3);
+ ALTER TABLE `products` ADD CONSTRAINT `fk_category` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`);
+- description: Operations on partitioned tables
+ oldSchema: |
+ CREATE TABLE sales_data (
+ id INT NOT NULL AUTO_INCREMENT,
+ sale_date DATE NOT NULL,
+ customer_id INT NOT NULL,
+ product_id INT NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ region VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id, sale_date),
+ INDEX idx_customer (customer_id),
+ INDEX idx_product (product_id),
+ INDEX idx_region_date (region, sale_date),
+ CONSTRAINT chk_amount_positive CHECK (amount > 0)
+ );
+
+ CREATE VIEW regional_sales AS
+ SELECT
+ region,
+ YEAR(sale_date) AS year,
+ MONTH(sale_date) AS month,
+ SUM(amount) AS total_sales,
+ COUNT(DISTINCT customer_id) AS unique_customers
+ FROM sales_data
+ GROUP BY region, YEAR(sale_date), MONTH(sale_date);
+ newSchema: |
+ CREATE TABLE sales_data (
+ id INT NOT NULL AUTO_INCREMENT,
+ sale_date DATE NOT NULL,
+ customer_id INT NOT NULL,
+ product_id INT NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ region VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id, sale_date)
+ );
+ expected: |+
+ CREATE OR REPLACE VIEW `regional_sales` AS SELECT 1;
+ DROP VIEW IF EXISTS `regional_sales`;
+
+ DROP INDEX `idx_customer` ON `sales_data`;
+
+ DROP INDEX `idx_product` ON `sales_data`;
+
+ DROP INDEX `idx_region_date` ON `sales_data`;
+
+
+- description: Reverse of partitioned table operations - dropping indexes and views
+ oldSchema: |
+ CREATE TABLE sales_data (
+ id INT NOT NULL AUTO_INCREMENT,
+ sale_date DATE NOT NULL,
+ customer_id INT NOT NULL,
+ product_id INT NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ region VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id, sale_date)
+ );
+ newSchema: |
+ CREATE TABLE sales_data (
+ id INT NOT NULL AUTO_INCREMENT,
+ sale_date DATE NOT NULL,
+ customer_id INT NOT NULL,
+ product_id INT NOT NULL,
+ amount DECIMAL(10, 2) NOT NULL,
+ region VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id, sale_date),
+ INDEX idx_customer (customer_id),
+ INDEX idx_product (product_id),
+ INDEX idx_region_date (region, sale_date),
+ CONSTRAINT chk_amount_positive CHECK (amount > 0)
+ );
+
+ CREATE VIEW regional_sales AS
+ SELECT
+ region,
+ YEAR(sale_date) AS year,
+ MONTH(sale_date) AS month,
+ SUM(amount) AS total_sales,
+ COUNT(DISTINCT customer_id) AS unique_customers
+ FROM sales_data
+ GROUP BY region, YEAR(sale_date), MONTH(sale_date);
+ expected: |
+ CREATE INDEX `idx_customer` ON `sales_data` (`customer_id`);
+ CREATE INDEX `idx_product` ON `sales_data` (`product_id`);
+ CREATE INDEX `idx_region_date` ON `sales_data` (`region`, `sale_date`);
+ CREATE VIEW `regional_sales` AS SELECT
+ region,
+ YEAR(sale_date) AS year,
+ MONTH(sale_date) AS month,
+ SUM(amount) AS total_sales,
+ COUNT(DISTINCT customer_id) AS unique_customers
+ FROM sales_data
+ GROUP BY region, YEAR(sale_date), MONTH(sale_date);
+- description: Create tables with foreign key constraints
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ expected: |
+ CREATE TABLE IF NOT EXISTS `posts` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `user_id` int NOT NULL,
+ `title` varchar(200) NOT NULL,
+ `content` text,
+ `published_at` datetime,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB;
+ CREATE INDEX `idx_user_id` ON `posts` (`user_id`);
+ CREATE TABLE IF NOT EXISTS `users` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `username` varchar(50) NOT NULL,
+ `email` varchar(100) NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_email` (`email`)
+ ) ENGINE=InnoDB;
+ CREATE INDEX `idx_username` ON `users` (`username`);
+ ALTER TABLE `posts` ADD CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
+- description: Reverse of create tables with foreign key constraints - creating from empty
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ newSchema: ""
+ expected: |+
+ DROP TABLE IF EXISTS `posts`;
+
+ DROP TABLE IF EXISTS `users`;
+
+- description: Tables with multiple foreign key constraints
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ is_active BOOLEAN DEFAULT true,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username),
+ INDEX idx_email_active (email, is_active)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
+ );
+
+ CREATE TABLE comments (
+ id INT NOT NULL AUTO_INCREMENT,
+ post_id INT NOT NULL,
+ user_id INT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_post_user (post_id, user_id),
+ CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ expected: |+
+ DROP TABLE IF EXISTS `comments`;
+
+ DROP INDEX `idx_email_active` ON `users`;
+
+ ALTER TABLE `users` DROP COLUMN `is_active`;
+
+
+- description: Reverse of multiple foreign keys - dropping tables and constraints
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ is_active BOOLEAN DEFAULT true,
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_username (username),
+ INDEX idx_email_active (email, is_active)
+ );
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT,
+ user_id INT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published_at DATETIME,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)
+ );
+
+ CREATE TABLE comments (
+ id INT NOT NULL AUTO_INCREMENT,
+ post_id INT NOT NULL,
+ user_id INT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_post_user (post_id, user_id),
+ CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ );
+ expected: |
+ CREATE TABLE IF NOT EXISTS `comments` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `post_id` int NOT NULL,
+ `user_id` int NOT NULL,
+ `content` text NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB;
+ CREATE INDEX `idx_post_user` ON `comments` (`post_id`, `user_id`);
+ CREATE INDEX `fk_comment_user` ON `comments` (`user_id`);
+ ALTER TABLE `comments` ADD CONSTRAINT `fk_comment_post` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE CASCADE;
+ ALTER TABLE `comments` ADD CONSTRAINT `fk_comment_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
+ ALTER TABLE `users` ADD COLUMN `is_active` tinyint(1);
+ CREATE INDEX `idx_email_active` ON `users` (`email`, `is_active`);
+- description: Drop and recreate foreign key constraints with different options
+ oldSchema: |
+ CREATE TABLE authors (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ );
+
+ CREATE TABLE books (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ author_id INT NOT NULL,
+ isbn VARCHAR(20),
+ published_year INT,
+ price DECIMAL(8, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_isbn (isbn),
+ INDEX idx_author (author_id),
+ INDEX idx_year (published_year),
+ CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) >= 3)
+ );
+ newSchema: |
+ CREATE TABLE authors (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ );
+
+ CREATE TABLE books (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ author_id INT NOT NULL,
+ isbn VARCHAR(20),
+ published_year INT,
+ price DECIMAL(8, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_isbn (isbn),
+ INDEX idx_author (author_id),
+ INDEX idx_year (published_year),
+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),
+ CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),
+ CONSTRAINT chk_price_positive CHECK (price > 0)
+ );
+ expected: |
+ ALTER TABLE `books` DROP FOREIGN KEY `fk_author_new`;
+
+
+ ALTER TABLE `books` ADD CONSTRAINT `fk_author` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`);
+- description: Reverse of drop and recreate foreign key constraints - restoring original constraints
+ oldSchema: |
+ CREATE TABLE authors (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ );
+
+ CREATE TABLE books (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ author_id INT NOT NULL,
+ isbn VARCHAR(20),
+ published_year INT,
+ price DECIMAL(8, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_isbn (isbn),
+ INDEX idx_author (author_id),
+ INDEX idx_year (published_year),
+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),
+ CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),
+ CONSTRAINT chk_price_positive CHECK (price > 0)
+ );
+ newSchema: |
+ CREATE TABLE authors (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (email)
+ );
+
+ CREATE TABLE books (
+ id INT NOT NULL AUTO_INCREMENT,
+ title VARCHAR(200) NOT NULL,
+ author_id INT NOT NULL,
+ isbn VARCHAR(20),
+ published_year INT,
+ price DECIMAL(8, 2),
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_isbn (isbn),
+ INDEX idx_author (author_id),
+ INDEX idx_year (published_year),
+ CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030),
+ CONSTRAINT chk_price_positive CHECK (price > 0),
+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) >= 3)
+ );
+ expected: |
+ ALTER TABLE `books` DROP FOREIGN KEY `fk_author`;
+
+
+ ALTER TABLE `books` ADD CONSTRAINT `fk_author_new` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON UPDATE CASCADE ON DELETE CASCADE;
+- description: Circular foreign key dependencies
+ oldSchema: |
+ CREATE TABLE customers (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ preferred_order_id INT,
+ PRIMARY KEY (id)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ customer_id INT NOT NULL,
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ total_amount DECIMAL(10, 2),
+ PRIMARY KEY (id)
+ );
+
+ ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;
+ ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE;
+
+ CREATE TABLE order_items (
+ id INT NOT NULL AUTO_INCREMENT,
+ order_id INT NOT NULL,
+ product_name VARCHAR(100) NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_order (order_id),
+ CONSTRAINT fk_order_item FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
+ );
+ newSchema: |
+ CREATE TABLE customers (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ preferred_order_id INT,
+ PRIMARY KEY (id)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ customer_id INT NOT NULL,
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ total_amount DECIMAL(10, 2),
+ PRIMARY KEY (id)
+ );
+ expected: |+
+ DROP TABLE IF EXISTS `order_items`;
+
+- description: Reverse of circular foreign key dependencies - dropping tables and foreign keys
+ oldSchema: |
+ CREATE TABLE customers (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ preferred_order_id INT,
+ PRIMARY KEY (id)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ customer_id INT NOT NULL,
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ total_amount DECIMAL(10, 2),
+ PRIMARY KEY (id)
+ );
+ newSchema: |
+ CREATE TABLE customers (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ preferred_order_id INT,
+ PRIMARY KEY (id)
+ );
+
+ CREATE TABLE orders (
+ id INT NOT NULL AUTO_INCREMENT,
+ customer_id INT NOT NULL,
+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
+ total_amount DECIMAL(10, 2),
+ PRIMARY KEY (id)
+ );
+
+ ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;
+ ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE;
+
+ CREATE TABLE order_items (
+ id INT NOT NULL AUTO_INCREMENT,
+ order_id INT NOT NULL,
+ product_name VARCHAR(100) NOT NULL,
+ quantity INT NOT NULL,
+ unit_price DECIMAL(10, 2) NOT NULL,
+ PRIMARY KEY (id),
+ INDEX idx_order (order_id),
+ CONSTRAINT fk_order_item FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
+ );
+ expected: |
+ CREATE TABLE IF NOT EXISTS `order_items` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `order_id` int NOT NULL,
+ `product_name` varchar(100) NOT NULL,
+ `quantity` int NOT NULL,
+ `unit_price` decimal(10,2) NOT NULL,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB;
+ CREATE INDEX `idx_order` ON `order_items` (`order_id`);
+ ALTER TABLE `order_items` ADD CONSTRAINT `fk_order_item` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE;
+- description: Adding comments to tables and columns using TiDB COMMENT syntax
+ oldSchema: |
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL COMMENT 'Category name',
+ PRIMARY KEY (id)
+ ) COMMENT = 'Product categories for organization';
+
+ CREATE TABLE suppliers (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Unique supplier identifier',
+ company_name VARCHAR(100) NOT NULL COMMENT 'Official company name',
+ contact_email VARCHAR(150) COMMENT 'Primary contact email address',
+ phone VARCHAR(20) COMMENT 'Contact phone number',
+ address TEXT COMMENT 'Full business address',
+ is_active BOOLEAN DEFAULT true COMMENT 'Supplier active status',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (contact_email),
+ INDEX idx_active (is_active)
+ ) COMMENT = 'Supplier information and contact details';
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL COMMENT 'Product display name',
+ price DECIMAL(10, 2) NOT NULL COMMENT 'Product price in USD',
+ description TEXT COMMENT 'Detailed product description',
+ category_id INT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ supplier_id INT COMMENT 'Reference to supplier table',
+ weight DECIMAL(8, 3) COMMENT 'Product weight in kilograms',
+ in_stock BOOLEAN DEFAULT true COMMENT 'Current stock availability',
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id),
+ CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL
+ ) COMMENT = 'Product catalog table storing all available products';
+ newSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ description TEXT,
+ category_id INT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id)
+ );
+
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id)
+ );
+ expected: |+
+ ALTER TABLE `products` DROP FOREIGN KEY `fk_supplier`;
+
+ DROP TABLE IF EXISTS `suppliers`;
+
+ DROP INDEX `fk_supplier` ON `products`;
+
+ ALTER TABLE `products` DROP COLUMN `supplier_id`;
+
+ ALTER TABLE `products` DROP COLUMN `weight`;
+
+ ALTER TABLE `products` DROP COLUMN `in_stock`;
+
+
+ ALTER TABLE `categories` COMMENT = '';
+
+ ALTER TABLE `products` COMMENT = '';
+
+- description: Reverse of table and column comments - removing comments and dropping tables
+ oldSchema: |
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ description TEXT,
+ category_id INT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id)
+ );
+
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL,
+ PRIMARY KEY (id)
+ );
+ newSchema: |
+ CREATE TABLE categories (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(50) NOT NULL COMMENT 'Category name',
+ PRIMARY KEY (id)
+ ) COMMENT = 'Product categories for organization';
+
+ CREATE TABLE suppliers (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Unique supplier identifier',
+ company_name VARCHAR(100) NOT NULL COMMENT 'Official company name',
+ contact_email VARCHAR(150) COMMENT 'Primary contact email address',
+ phone VARCHAR(20) COMMENT 'Contact phone number',
+ address TEXT COMMENT 'Full business address',
+ is_active BOOLEAN DEFAULT true COMMENT 'Supplier active status',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation timestamp',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_email (contact_email),
+ INDEX idx_active (is_active)
+ ) COMMENT = 'Supplier information and contact details';
+
+ CREATE TABLE products (
+ id INT NOT NULL AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL COMMENT 'Product display name',
+ price DECIMAL(10, 2) NOT NULL COMMENT 'Product price in USD',
+ description TEXT COMMENT 'Detailed product description',
+ category_id INT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ supplier_id INT COMMENT 'Reference to supplier table',
+ weight DECIMAL(8, 3) COMMENT 'Product weight in kilograms',
+ in_stock BOOLEAN DEFAULT true COMMENT 'Current stock availability',
+ PRIMARY KEY (id),
+ INDEX idx_category (category_id),
+ CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL
+ ) COMMENT = 'Product catalog table storing all available products';
+ expected: |
+ CREATE TABLE IF NOT EXISTS `suppliers` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `company_name` varchar(100) NOT NULL,
+ `contact_email` varchar(150),
+ `phone` varchar(20),
+ `address` text,
+ `is_active` tinyint(1),
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_email` (`contact_email`)
+ ) ENGINE=InnoDB COMMENT='Supplier information and contact details';
+ CREATE INDEX `idx_active` ON `suppliers` (`is_active`);
+ ALTER TABLE `categories` COMMENT = 'Product categories for organization';
+
+ ALTER TABLE `products` COMMENT = 'Product catalog table storing all available products';
+
+ ALTER TABLE `products` ADD COLUMN `supplier_id` int;
+ ALTER TABLE `products` ADD COLUMN `weight` decimal(8,3);
+ ALTER TABLE `products` ADD COLUMN `in_stock` tinyint(1);
+ CREATE INDEX `fk_supplier` ON `products` (`supplier_id`);
+ ALTER TABLE `products` ADD CONSTRAINT `fk_supplier` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`) ON DELETE SET NULL;
+- description: Modifying existing comments and removing comments from tables and columns
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Primary key identifier',
+ username VARCHAR(50) NOT NULL COMMENT 'Updated: Unique username for authentication and display',
+ email VARCHAR(100) NOT NULL COMMENT 'User email address',
+ full_name VARCHAR(100),
+ bio TEXT COMMENT 'Updated: Extended user biography with rich text support',
+ status ENUM('active', 'inactive', 'suspended', 'pending') DEFAULT 'active' COMMENT 'Updated: Account status with pending verification',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Account creation date',
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update timestamp',
+ avatar_url VARCHAR(255) COMMENT 'Profile picture URL',
+ last_login DATETIME COMMENT 'Last successful login timestamp',
+ login_count INT DEFAULT 0 COMMENT 'Total number of logins',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_username (username),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_status (status)
+ ) COMMENT = 'Updated user account information with enhanced profile features';
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Post unique identifier',
+ user_id INT NOT NULL COMMENT 'Author user ID reference',
+ title VARCHAR(200) NOT NULL COMMENT 'Post title with SEO optimization',
+ content TEXT COMMENT 'Rich text post content with markdown support',
+ status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT 'Post publication status',
+ published_at DATETIME COMMENT 'Publication timestamp',
+ view_count INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ INDEX idx_status (status),
+ CONSTRAINT fk_post_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) COMMENT = 'Blog posts with analytics and engagement tracking';
+
+ CREATE TABLE user_preferences (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Preference record identifier',
+ user_id INT NOT NULL COMMENT 'User ID foreign key reference',
+ preference_key VARCHAR(100) NOT NULL COMMENT 'Configuration key name',
+ preference_value TEXT COMMENT 'Configuration value in JSON format',
+ is_public BOOLEAN DEFAULT false COMMENT 'Whether preference is publicly visible',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Preference creation time',
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last modification time',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_user_key (user_id, preference_key),
+ INDEX idx_key (preference_key),
+ INDEX idx_public (is_public),
+ CONSTRAINT fk_pref_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) COMMENT = 'User-specific configuration and preference settings';
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Primary key identifier',
+ username VARCHAR(50) NOT NULL COMMENT 'Unique username for login',
+ email VARCHAR(100) NOT NULL COMMENT 'User email address',
+ full_name VARCHAR(100) COMMENT 'User full display name',
+ bio TEXT COMMENT 'User biography or description',
+ status ENUM('active', 'inactive', 'suspended') DEFAULT 'active' COMMENT 'Account status',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Account creation date',
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update timestamp',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_username (username),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_status (status)
+ ) COMMENT = 'User account information and profile data';
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Post unique identifier',
+ user_id INT NOT NULL COMMENT 'Author user ID reference',
+ title VARCHAR(200) NOT NULL COMMENT 'Post title',
+ content TEXT COMMENT 'Post content body',
+ status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT 'Post publication status',
+ published_at DATETIME COMMENT 'Publication timestamp',
+ view_count INT DEFAULT 0 COMMENT 'Number of views',
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ INDEX idx_status (status),
+ CONSTRAINT fk_post_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) COMMENT = 'Blog posts and articles';
+ expected: |
+ DROP TABLE IF EXISTS `user_preferences`;
+
+ ALTER TABLE `users` DROP COLUMN `avatar_url`;
+
+ ALTER TABLE `users` DROP COLUMN `last_login`;
+
+ ALTER TABLE `users` DROP COLUMN `login_count`;
+
+
+ ALTER TABLE `posts` COMMENT = 'Blog posts and articles';
+
+ ALTER TABLE `users` COMMENT = 'User account information and profile data';
+
+ ALTER TABLE `users` MODIFY COLUMN `status` enum('active','inactive','suspended');
+- description: Reverse of modify and drop comments - restoring original comments and dropping new table
+ oldSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Primary key identifier',
+ username VARCHAR(50) NOT NULL COMMENT 'Unique username for login',
+ email VARCHAR(100) NOT NULL COMMENT 'User email address',
+ full_name VARCHAR(100) COMMENT 'User full display name',
+ bio TEXT COMMENT 'User biography or description',
+ status ENUM('active', 'inactive', 'suspended') DEFAULT 'active' COMMENT 'Account status',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Account creation date',
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update timestamp',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_username (username),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_status (status)
+ ) COMMENT = 'User account information and profile data';
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Post unique identifier',
+ user_id INT NOT NULL COMMENT 'Author user ID reference',
+ title VARCHAR(200) NOT NULL COMMENT 'Post title',
+ content TEXT COMMENT 'Post content body',
+ status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT 'Post publication status',
+ published_at DATETIME COMMENT 'Publication timestamp',
+ view_count INT DEFAULT 0 COMMENT 'Number of views',
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ INDEX idx_status (status),
+ CONSTRAINT fk_post_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) COMMENT = 'Blog posts and articles';
+ newSchema: |
+ CREATE TABLE users (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Primary key identifier',
+ username VARCHAR(50) NOT NULL COMMENT 'Updated: Unique username for authentication and display',
+ email VARCHAR(100) NOT NULL COMMENT 'User email address',
+ full_name VARCHAR(100),
+ bio TEXT COMMENT 'Updated: Extended user biography with rich text support',
+ status ENUM('active', 'inactive', 'suspended', 'pending') DEFAULT 'active' COMMENT 'Updated: Account status with pending verification',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Account creation date',
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update timestamp',
+ avatar_url VARCHAR(255) COMMENT 'Profile picture URL',
+ last_login DATETIME COMMENT 'Last successful login timestamp',
+ login_count INT DEFAULT 0 COMMENT 'Total number of logins',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_username (username),
+ UNIQUE KEY uk_email (email),
+ INDEX idx_status (status)
+ ) COMMENT = 'Updated user account information with enhanced profile features';
+
+ CREATE TABLE posts (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Post unique identifier',
+ user_id INT NOT NULL COMMENT 'Author user ID reference',
+ title VARCHAR(200) NOT NULL COMMENT 'Post title with SEO optimization',
+ content TEXT COMMENT 'Rich text post content with markdown support',
+ status ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT 'Post publication status',
+ published_at DATETIME COMMENT 'Publication timestamp',
+ view_count INT DEFAULT 0,
+ PRIMARY KEY (id),
+ INDEX idx_user_id (user_id),
+ INDEX idx_status (status),
+ CONSTRAINT fk_post_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) COMMENT = 'Blog posts with analytics and engagement tracking';
+
+ CREATE TABLE user_preferences (
+ id INT NOT NULL AUTO_INCREMENT COMMENT 'Preference record identifier',
+ user_id INT NOT NULL COMMENT 'User ID foreign key reference',
+ preference_key VARCHAR(100) NOT NULL COMMENT 'Configuration key name',
+ preference_value TEXT COMMENT 'Configuration value in JSON format',
+ is_public BOOLEAN DEFAULT false COMMENT 'Whether preference is publicly visible',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Preference creation time',
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last modification time',
+ PRIMARY KEY (id),
+ UNIQUE KEY uk_user_key (user_id, preference_key),
+ INDEX idx_key (preference_key),
+ INDEX idx_public (is_public),
+ CONSTRAINT fk_pref_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ ) COMMENT = 'User-specific configuration and preference settings';
+ expected: |
+ CREATE TABLE IF NOT EXISTS `user_preferences` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `user_id` int NOT NULL,
+ `preference_key` varchar(100) NOT NULL,
+ `preference_value` text,
+ `is_public` tinyint(1),
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ `updated_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_user_key` (`user_id`, `preference_key`)
+ ) ENGINE=InnoDB COMMENT='User-specific configuration and preference settings';
+ CREATE INDEX `idx_key` ON `user_preferences` (`preference_key`);
+ CREATE INDEX `idx_public` ON `user_preferences` (`is_public`);
+ ALTER TABLE `user_preferences` ADD CONSTRAINT `fk_pref_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
+ ALTER TABLE `posts` COMMENT = 'Blog posts with analytics and engagement tracking';
+
+ ALTER TABLE `users` COMMENT = 'Updated user account information with enhanced profile features';
+
+ ALTER TABLE `users` ADD COLUMN `avatar_url` varchar(255);
+ ALTER TABLE `users` ADD COLUMN `last_login` datetime;
+ ALTER TABLE `users` ADD COLUMN `login_count` int;
+ ALTER TABLE `users` MODIFY COLUMN `status` enum('active','inactive','suspended','pending');
+- description: Testing comments with special characters, quotes, Unicode, multi-line text, and edge cases
+ oldSchema: "CREATE TABLE test_table (\n id INT NOT NULL AUTO_INCREMENT,\n simple_field VARCHAR(100),\n field_with_quotes VARCHAR(100) COMMENT 'Field with \"double\" and ''single'' quotes',\n field_with_symbols VARCHAR(100) COMMENT 'Field with symbols: @#$%^&*()_+-={}[]|:\";''<>?,./ and more!',\n field_with_unicode VARCHAR(100) COMMENT 'Unicode test: 你好世界 \U0001F30D café naïve résumé Москва العالم 한국어',\n field_multiline TEXT COMMENT 'Multi-line comment:\nLine 1 with regular text\nLine 2 with \"quotes\" and symbols @#$\nLine 3 with unicode: 测试 \U0001F680 café\nFinal line with mixed content',\n field_with_sql VARCHAR(100) COMMENT 'Comment with SQL-like content: SELECT * FROM table WHERE id = ''123'' AND name LIKE \"%test%\"',\n field_with_html VARCHAR(100) COMMENT 'HTML content: <div class=\"test\">Hello & \"World\"</div> <!-- comment -->',\n field_with_json VARCHAR(100) COMMENT 'JSON example: {\"name\": \"test\", \"value\": 123, \"nested\": {\"key\": \"value with spaces\"}}',\n field_with_escape VARCHAR(100) COMMENT 'Escape sequences: \\n \\t \\r \" '' \\\\',\n PRIMARY KEY (id)\n) COMMENT = 'Table with \"double quotes\" and ''single quotes'' in comment';\n\nCREATE TABLE special_comments_table (\n id BIGINT NOT NULL AUTO_RANDOM COMMENT 'ID with \"quotes\", symbols @#$, unicode 测试\U0001F31F, and\nmulti-line\ncontent',\n data_field JSON COMMENT 'Updated JSON field: {\"new\": \"structure\", \"with\": [\"array\", \"of\", \"strings\"], \"escapes\": \"\\n\\t\\r\"}',\n html_field TEXT,\n sql_field VARCHAR(255) COMMENT 'SQL patterns: SELECT * FROM users WHERE name = ''O''Brien'' AND age > 21',\n unicode_field VARCHAR(200) COMMENT '多语言支持: English, 中文, العربية, Русский, 日本語, 한국어, Français, Español',\n symbols_field VARCHAR(100) COMMENT 'All symbols: !@#$%^&*()_+-={}[]|:\";''<>?,./ plus tab and newline\ntest',\n url_field VARCHAR(300) COMMENT 'URL with params: https://example.com/path?param1=value1&param2=\"quoted value\"&param3=50%+discount',\n regex_field VARCHAR(150) COMMENT 'Regex pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$ for email validation',\n PRIMARY KEY (id),\n INDEX idx_unicode (unicode_field)\n) COMMENT = 'Special characters test table with:\n- Double quotes: \"test\"\n- Single quotes: ''test''\n- Unicode: 特殊字符测试表 \U0001F3AF\n- Symbols: @#$%^&*()\n- HTML: <div>content</div>\n- JSON: {\"key\": \"value\"}\n- URLs: https://example.com\n- Multi-line content with various encodings';\n"
+ newSchema: |
+ CREATE TABLE test_table (
+ id INT NOT NULL AUTO_INCREMENT,
+ simple_field VARCHAR(100),
+ PRIMARY KEY (id)
+ );
+ expected: |+
+ DROP TABLE IF EXISTS `special_comments_table`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_with_quotes`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_with_symbols`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_with_unicode`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_multiline`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_with_sql`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_with_html`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_with_json`;
+
+ ALTER TABLE `test_table` DROP COLUMN `field_with_escape`;
+
+
+ ALTER TABLE `test_table` COMMENT = '';
+
+- description: Reverse of comments with special characters - removing all special character comments
+ oldSchema: |
+ CREATE TABLE test_table (
+ id INT NOT NULL AUTO_INCREMENT,
+ simple_field VARCHAR(100),
+ PRIMARY KEY (id)
+ );
+ newSchema: "CREATE TABLE test_table (\n id INT NOT NULL AUTO_INCREMENT,\n simple_field VARCHAR(100),\n field_with_quotes VARCHAR(100) COMMENT 'Field with \"double\" and ''single'' quotes',\n field_with_symbols VARCHAR(100) COMMENT 'Field with symbols: @#$%^&*()_+-={}[]|:\";''<>?,./ and more!',\n field_with_unicode VARCHAR(100) COMMENT 'Unicode test: 你好世界 \U0001F30D café naïve résumé Москва العالم 한국어',\n field_multiline TEXT COMMENT 'Multi-line comment:\nLine 1 with regular text\nLine 2 with \"quotes\" and symbols @#$\nLine 3 with unicode: 测试 \U0001F680 café\nFinal line with mixed content',\n field_with_sql VARCHAR(100) COMMENT 'Comment with SQL-like content: SELECT * FROM table WHERE id = ''123'' AND name LIKE \"%test%\"',\n field_with_html VARCHAR(100) COMMENT 'HTML content: <div class=\"test\">Hello & \"World\"</div> <!-- comment -->',\n field_with_json VARCHAR(100) COMMENT 'JSON example: {\"name\": \"test\", \"value\": 123, \"nested\": {\"key\": \"value with spaces\"}}',\n field_with_escape VARCHAR(100) COMMENT 'Escape sequences: \\n \\t \\r \" '' \\\\',\n PRIMARY KEY (id)\n) COMMENT = 'Table with \"double quotes\" and ''single quotes'' in comment';\n\nCREATE TABLE special_comments_table (\n id BIGINT NOT NULL AUTO_RANDOM COMMENT 'ID with \"quotes\", symbols @#$, unicode 测试\U0001F31F, and\nmulti-line\ncontent',\n data_field JSON COMMENT 'Updated JSON field: {\"new\": \"structure\", \"with\": [\"array\", \"of\", \"strings\"], \"escapes\": \"\\n\\t\\r\"}',\n html_field TEXT,\n sql_field VARCHAR(255) COMMENT 'SQL patterns: SELECT * FROM users WHERE name = ''O''Brien'' AND age > 21',\n unicode_field VARCHAR(200) COMMENT '多语言支持: English, 中文, العربية, Русский, 日本語, 한국어, Français, Español',\n symbols_field VARCHAR(100) COMMENT 'All symbols: !@#$%^&*()_+-={}[]|:\";''<>?,./ plus tab and newline\ntest',\n url_field VARCHAR(300) COMMENT 'URL with params: https://example.com/path?param1=value1&param2=\"quoted value\"&param3=50%+discount',\n regex_field VARCHAR(150) COMMENT 'Regex pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$ for email validation',\n PRIMARY KEY (id),\n INDEX idx_unicode (unicode_field)\n) COMMENT = 'Special characters test table with:\n- Double quotes: \"test\"\n- Single quotes: ''test''\n- Unicode: 特殊字符测试表 \U0001F3AF\n- Symbols: @#$%^&*()\n- HTML: <div>content</div>\n- JSON: {\"key\": \"value\"}\n- URLs: https://example.com\n- Multi-line content with various encodings';\n"
+ expected: "CREATE TABLE IF NOT EXISTS `special_comments_table` (\n `id` bigint NOT NULL,\n `data_field` json,\n `html_field` text,\n `sql_field` varchar(255),\n `unicode_field` varchar(200),\n `symbols_field` varchar(100),\n `url_field` varchar(300),\n `regex_field` varchar(150),\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB COMMENT='Special characters test table with:\n- Double quotes: \"test\"\n- Single quotes: 'test'\n- Unicode: 特殊字符测试表 \U0001F3AF\n- Symbols: @#$%^&*()\n- HTML: <div>content</div>\n- JSON: {\"key\": \"value\"}\n- URLs: https://example.com\n- Multi-line content with various encodings';\nCREATE INDEX `idx_unicode` ON `special_comments_table` (`unicode_field`);\nALTER TABLE `test_table` COMMENT = 'Table with \"double quotes\" and 'single quotes' in comment';\n\nALTER TABLE `test_table` ADD COLUMN `field_with_quotes` varchar(100);\nALTER TABLE `test_table` ADD COLUMN `field_with_symbols` varchar(100);\nALTER TABLE `test_table` ADD COLUMN `field_with_unicode` varchar(100);\nALTER TABLE `test_table` ADD COLUMN `field_multiline` text;\nALTER TABLE `test_table` ADD COLUMN `field_with_sql` varchar(100);\nALTER TABLE `test_table` ADD COLUMN `field_with_html` varchar(100);\nALTER TABLE `test_table` ADD COLUMN `field_with_json` varchar(100);\nALTER TABLE `test_table` ADD COLUMN `field_with_escape` varchar(100);\n"
diff --git a/backend/plugin/schema/tidb/testdata/get_database_definition.yaml b/backend/plugin/schema/tidb/testdata/get_database_definition.yaml
new file mode 100644
index 0000000000..92cf347e99
--- /dev/null
+++ b/backend/plugin/schema/tidb/testdata/get_database_definition.yaml
@@ -0,0 +1,1457 @@
+- description: Basic tables with various column types
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "posts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "title",
+ "position": 3,
+ "type": "varchar(200)"
+ },
+ {
+ "name": "content",
+ "position": 4,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "published_at",
+ "position": 5,
+ "nullable": true,
+ "type": "datetime"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_user_published",
+ "expressions": [
+ "user_id",
+ "published_at"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_1",
+ "columns": [
+ "user_id"
+ ],
+ "referenced_table": "users",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "CASCADE"
+ }
+ ]
+ },
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "username",
+ "position": 2,
+ "type": "varchar(50)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "age",
+ "position": 4,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "updated_at",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "on_update": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "profile",
+ "position": 7,
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "is_active",
+ "position": 8,
+ "nullable": true,
+ "type": "tinyint(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "username",
+ "expressions": [
+ "username"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "idx_email",
+ "expressions": [
+ "email"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_created_at",
+ "expressions": [
+ "created_at"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `posts`
+ --
+ CREATE TABLE `posts` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `user_id` int NOT NULL,
+ `title` varchar(200) NOT NULL,
+ `content` text,
+ `published_at` datetime,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ KEY `idx_user_published` (`user_id`, `published_at`),
+ CONSTRAINT `fk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `users`
+ --
+ CREATE TABLE `users` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `username` varchar(50) NOT NULL,
+ `email` varchar(100) NOT NULL,
+ `age` int,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ `updated_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ `profile` json,
+ `is_active` tinyint(1),
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ UNIQUE KEY `username` (`username`),
+ KEY `idx_email` (`email`),
+ KEY `idx_created_at` (`created_at`)
+ ) ENGINE=InnoDB;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Generated columns and complex indexes
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "inventory",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "product_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "warehouse",
+ "position": 3,
+ "type": "varchar(50)"
+ },
+ {
+ "name": "quantity",
+ "position": 4,
+ "type": "int"
+ },
+ {
+ "name": "last_updated",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "on_update": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "uk_product_warehouse",
+ "expressions": [
+ "product_id",
+ "warehouse"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_1",
+ "columns": [
+ "product_id"
+ ],
+ "referenced_table": "products",
+ "referenced_columns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "price",
+ "position": 3,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "tax_rate",
+ "position": 4,
+ "type": "decimal(5,2)"
+ },
+ {
+ "name": "price_with_tax",
+ "position": 5,
+ "nullable": true,
+ "type": "decimal(10,2) GENERATED ALWAYS AS (price * (1 + tax_rate)) STORED"
+ },
+ {
+ "name": "description",
+ "position": 6,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "tags",
+ "position": 7,
+ "nullable": true,
+ "type": "json"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `inventory`
+ --
+ CREATE TABLE `inventory` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `product_id` int NOT NULL,
+ `warehouse` varchar(50) NOT NULL,
+ `quantity` int NOT NULL,
+ `last_updated` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ UNIQUE KEY `uk_product_warehouse` (`product_id`, `warehouse`),
+ CONSTRAINT `fk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `products`
+ --
+ CREATE TABLE `products` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `price` decimal(10,2) NOT NULL,
+ `tax_rate` decimal(5,2) NOT NULL,
+ `price_with_tax` decimal(10,2) GENERATED ALWAYS AS (price * (1 + tax_rate)) STORED,
+ `description` text,
+ `tags` json,
+ PRIMARY KEY (`id`) /*T![clustered_index] */
+ ) ENGINE=InnoDB;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Views
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "order_items",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "order_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "product_name",
+ "position": 3,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "quantity",
+ "position": 4,
+ "type": "int"
+ },
+ {
+ "name": "unit_price",
+ "position": 5,
+ "type": "decimal(10,2)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "order_id",
+ "expressions": [
+ "order_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_1",
+ "columns": [
+ "order_id"
+ ],
+ "referenced_table": "orders",
+ "referenced_columns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "order_number",
+ "position": 2,
+ "type": "varchar(20)"
+ },
+ {
+ "name": "customer_name",
+ "position": 3,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "total_amount",
+ "position": 4,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "status",
+ "position": 5,
+ "nullable": true,
+ "type": "varchar(20)"
+ },
+ {
+ "name": "created_at",
+ "position": 6,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "order_number",
+ "expressions": [
+ "order_number"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ],
+ "views": [
+ {
+ "name": "order_summary",
+ "definition": "SELECT\n o.id,\n o.order_number,\n o.customer_name,\n o.total_amount,\n COUNT(oi.id) AS item_count,\n SUM(oi.quantity) AS total_quantity\nFROM orders o\nLEFT JOIN order_items oi ON o.id = oi.order_id\nGROUP BY o.id, o.order_number, o.customer_name, o.total_amount"
+ },
+ {
+ "name": "pending_orders",
+ "definition": "SELECT id, order_number, customer_name, total_amount, created_at\nFROM orders\nWHERE status = 'pending'\nORDER BY created_at DESC"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `order_summary`
+ --
+ -- `order_summary` references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+
+ --
+ -- Temporary view structure for `pending_orders`
+ --
+ -- `pending_orders` references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+
+ --
+ -- Table structure for `order_items`
+ --
+ CREATE TABLE `order_items` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `order_id` int NOT NULL,
+ `product_name` varchar(100) NOT NULL,
+ `quantity` int NOT NULL,
+ `unit_price` decimal(10,2) NOT NULL,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ KEY `order_id` (`order_id`),
+ CONSTRAINT `fk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`)
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `orders`
+ --
+ CREATE TABLE `orders` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `order_number` varchar(20) NOT NULL,
+ `customer_name` varchar(100) NOT NULL,
+ `total_amount` decimal(10,2) NOT NULL,
+ `status` varchar(20),
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ UNIQUE KEY `order_number` (`order_number`)
+ ) ENGINE=InnoDB;
+
+ --
+ -- View structure for `order_summary`
+ --
+ DROP VIEW IF EXISTS `order_summary`;
+ CREATE VIEW `order_summary` AS SELECT
+ o.id,
+ o.order_number,
+ o.customer_name,
+ o.total_amount,
+ COUNT(oi.id) AS item_count,
+ SUM(oi.quantity) AS total_quantity
+ FROM orders o
+ LEFT JOIN order_items oi ON o.id = oi.order_id
+ GROUP BY o.id, o.order_number, o.customer_name, o.total_amount;
+
+ --
+ -- View structure for `pending_orders`
+ --
+ DROP VIEW IF EXISTS `pending_orders`;
+ CREATE VIEW `pending_orders` AS SELECT id, order_number, customer_name, total_amount, created_at
+ FROM orders
+ WHERE status = 'pending'
+ ORDER BY created_at DESC;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: TiDB specific features - AUTO_RANDOM
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "distributed_data",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_RANDOM(5)",
+ "type": "bigint"
+ },
+ {
+ "name": "data_type",
+ "position": 2,
+ "type": "varchar(50)"
+ },
+ {
+ "name": "payload",
+ "position": 3,
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_type_created",
+ "expressions": [
+ "data_type",
+ "created_at"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ },
+ {
+ "name": "users_autorand",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_RANDOM",
+ "type": "bigint"
+ },
+ {
+ "name": "username",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "username",
+ "expressions": [
+ "username"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `distributed_data`
+ --
+ CREATE TABLE `distributed_data` (
+ `id` bigint NOT NULL /*T![auto_rand] AUTO_RANDOM(5) */,
+ `data_type` varchar(50) NOT NULL,
+ `payload` json,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ KEY `idx_type_created` (`data_type`, `created_at`)
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `users_autorand`
+ --
+ CREATE TABLE `users_autorand` (
+ `id` bigint NOT NULL /*T![auto_rand] AUTO_RANDOM */,
+ `username` varchar(100) NOT NULL,
+ `email` varchar(100) NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ UNIQUE KEY `username` (`username`)
+ ) ENGINE=InnoDB;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Character sets and collations
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "charset_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(100)",
+ "character_set": "latin1"
+ },
+ {
+ "name": "description",
+ "position": 3,
+ "nullable": true,
+ "type": "text",
+ "character_set": "utf8mb4"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "charset": "utf8mb4"
+ },
+ {
+ "name": "multilingual",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "content_utf8",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(255)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_general_ci"
+ },
+ {
+ "name": "content_bin",
+ "position": 3,
+ "nullable": true,
+ "type": "varchar(255)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_bin"
+ },
+ {
+ "name": "content_unicode",
+ "position": 4,
+ "nullable": true,
+ "type": "varchar(255)",
+ "character_set": "utf8mb4",
+ "collation": "utf8mb4_unicode_ci"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "collation": "utf8mb4_general_ci",
+ "charset": "utf8mb4"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `charset_test`
+ --
+ CREATE TABLE `charset_test` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) CHARACTER SET latin1,
+ `description` text,
+ PRIMARY KEY (`id`) /*T![clustered_index] */
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+ --
+ -- Table structure for `multilingual`
+ --
+ CREATE TABLE `multilingual` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `content_utf8` varchar(255),
+ `content_bin` varchar(255) COLLATE utf8mb4_bin,
+ `content_unicode` varchar(255) COLLATE utf8mb4_unicode_ci,
+ PRIMARY KEY (`id`) /*T![clustered_index] */
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: TiDB clustered and non-clustered indexes
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "clustered_pk",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "bigint"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "created_at",
+ "position": 3,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_name",
+ "expressions": [
+ "name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "primary_key_type": "CLUSTERED"
+ },
+ {
+ "name": "nonclustered_pk",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "bigint"
+ },
+ {
+ "name": "code",
+ "position": 2,
+ "type": "varchar(50)"
+ },
+ {
+ "name": "data",
+ "position": 3,
+ "nullable": true,
+ "type": "json"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "code",
+ "expressions": [
+ "code"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ },
+ {
+ "name": "idx_code",
+ "expressions": [
+ "code"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "primary_key_type": "NONCLUSTERED"
+ }
+ ]
+ }
+ ]
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `clustered_pk`
+ --
+ CREATE TABLE `clustered_pk` (
+ `id` bigint NOT NULL,
+ `name` varchar(100) NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */,
+ KEY `idx_name` (`name`)
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `nonclustered_pk`
+ --
+ CREATE TABLE `nonclustered_pk` (
+ `id` bigint NOT NULL,
+ `code` varchar(50) NOT NULL,
+ `data` json,
+ PRIMARY KEY (`id`) /*T![clustered_index] NONCLUSTERED */,
+ UNIQUE KEY `code` (`code`),
+ KEY `idx_code` (`code`)
+ ) ENGINE=InnoDB;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Connected foreign key dependencies
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "departments",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "created_at",
+ "position": 3,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "name",
+ "expressions": [
+ "name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ },
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "department_id",
+ "position": 3,
+ "type": "int"
+ },
+ {
+ "name": "manager_id",
+ "position": 4,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_department",
+ "expressions": [
+ "department_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_manager",
+ "expressions": [
+ "manager_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_1",
+ "columns": [
+ "department_id"
+ ],
+ "referenced_table": "departments",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "RESTRICT"
+ },
+ {
+ "name": "fk_2",
+ "columns": [
+ "manager_id"
+ ],
+ "referenced_table": "employees",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL"
+ }
+ ]
+ },
+ {
+ "name": "project_members",
+ "columns": [
+ {
+ "name": "project_id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "employee_id",
+ "position": 2,
+ "type": "int"
+ },
+ {
+ "name": "role",
+ "position": 3,
+ "type": "varchar(50)"
+ },
+ {
+ "name": "joined_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "project_id",
+ "employee_id"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "employee_id",
+ "expressions": [
+ "employee_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_1",
+ "columns": [
+ "project_id"
+ ],
+ "referenced_table": "projects",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE"
+ },
+ {
+ "name": "fk_2",
+ "columns": [
+ "employee_id"
+ ],
+ "referenced_table": "employees",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE"
+ }
+ ]
+ },
+ {
+ "name": "projects",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "department_id",
+ "position": 3,
+ "type": "int"
+ },
+ {
+ "name": "lead_id",
+ "position": 4,
+ "type": "int"
+ },
+ {
+ "name": "created_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_department",
+ "expressions": [
+ "department_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_lead",
+ "expressions": [
+ "lead_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_1",
+ "columns": [
+ "department_id"
+ ],
+ "referenced_table": "departments",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE"
+ },
+ {
+ "name": "fk_2",
+ "columns": [
+ "lead_id"
+ ],
+ "referenced_table": "employees",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "RESTRICT"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ expected: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `departments`
+ --
+ CREATE TABLE `departments` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ UNIQUE KEY `name` (`name`)
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `employees`
+ --
+ CREATE TABLE `employees` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `department_id` int NOT NULL,
+ `manager_id` int,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ KEY `idx_department` (`department_id`),
+ KEY `idx_manager` (`manager_id`),
+ CONSTRAINT `fk_1` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`) ON DELETE RESTRICT,
+ CONSTRAINT `fk_2` FOREIGN KEY (`manager_id`) REFERENCES `employees` (`id`) ON DELETE SET NULL
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `project_members`
+ --
+ CREATE TABLE `project_members` (
+ `project_id` int NOT NULL,
+ `employee_id` int NOT NULL,
+ `role` varchar(50) NOT NULL,
+ `joined_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`project_id`, `employee_id`) /*T![clustered_index] */,
+ KEY `employee_id` (`employee_id`),
+ CONSTRAINT `fk_1` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE CASCADE,
+ CONSTRAINT `fk_2` FOREIGN KEY (`employee_id`) REFERENCES `employees` (`id`) ON DELETE CASCADE
+ ) ENGINE=InnoDB;
+
+ --
+ -- Table structure for `projects`
+ --
+ CREATE TABLE `projects` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `name` varchar(100) NOT NULL,
+ `department_id` int NOT NULL,
+ `lead_id` int NOT NULL,
+ `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (`id`) /*T![clustered_index] */,
+ KEY `idx_department` (`department_id`),
+ KEY `idx_lead` (`lead_id`),
+ CONSTRAINT `fk_1` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`) ON DELETE CASCADE,
+ CONSTRAINT `fk_2` FOREIGN KEY (`lead_id`) REFERENCES `employees` (`id`) ON DELETE RESTRICT
+ ) ENGINE=InnoDB;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
diff --git a/backend/plugin/schema/tidb/testdata/get_database_metadata.yaml b/backend/plugin/schema/tidb/testdata/get_database_metadata.yaml
new file mode 100644
index 0000000000..6d91686e0d
--- /dev/null
+++ b/backend/plugin/schema/tidb/testdata/get_database_metadata.yaml
@@ -0,0 +1,1273 @@
+- description: basic_tables_with_constraints
+ schema: |
+ CREATE TABLE users (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ username VARCHAR(50) NOT NULL UNIQUE,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE posts (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ user_id BIGINT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published BOOLEAN DEFAULT false,
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ INDEX idx_user_id (user_id),
+ INDEX idx_published (published)
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "posts",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "bigint"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "bigint"
+ },
+ {
+ "name": "title",
+ "position": 3,
+ "type": "varchar(200)"
+ },
+ {
+ "name": "content",
+ "position": 4,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "published",
+ "position": 5,
+ "nullable": true,
+ "type": "tinyint(1)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_user_id",
+ "expressions": [
+ "user_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_published",
+ "expressions": [
+ "published"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_user",
+ "columns": [
+ "user_id"
+ ],
+ "referenced_table": "users",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE"
+ }
+ ]
+ },
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "bigint"
+ },
+ {
+ "name": "username",
+ "position": 2,
+ "type": "varchar(50)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "updated_at",
+ "position": 5,
+ "default": "CURRENT_TIMESTAMP",
+ "on_update": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "username",
+ "expressions": [
+ "username"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+- description: table_with_various_data_types
+ schema: |
+ CREATE TABLE data_types_test (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ tiny_int_col TINYINT,
+ small_int_col SMALLINT,
+ medium_int_col MEDIUMINT,
+ int_col INT,
+ big_int_col BIGINT,
+ decimal_col DECIMAL(10, 2),
+ float_col FLOAT,
+ double_col DOUBLE,
+ bit_col BIT(8),
+ char_col CHAR(10),
+ varchar_col VARCHAR(100),
+ binary_col BINARY(10),
+ varbinary_col VARBINARY(100),
+ tinytext_col TINYTEXT,
+ text_col TEXT,
+ mediumtext_col MEDIUMTEXT,
+ longtext_col LONGTEXT,
+ tinyblob_col TINYBLOB,
+ blob_col BLOB,
+ mediumblob_col MEDIUMBLOB,
+ longblob_col LONGBLOB,
+ date_col DATE,
+ time_col TIME,
+ datetime_col DATETIME,
+ timestamp_col TIMESTAMP,
+ year_col YEAR,
+ json_col JSON,
+ enum_col ENUM('small', 'medium', 'large'),
+ set_col SET('a', 'b', 'c')
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "data_types_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "bigint"
+ },
+ {
+ "name": "tiny_int_col",
+ "position": 2,
+ "nullable": true,
+ "type": "tinyint"
+ },
+ {
+ "name": "small_int_col",
+ "position": 3,
+ "nullable": true,
+ "type": "smallint"
+ },
+ {
+ "name": "medium_int_col",
+ "position": 4,
+ "nullable": true,
+ "type": "mediumint"
+ },
+ {
+ "name": "int_col",
+ "position": 5,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "big_int_col",
+ "position": 6,
+ "nullable": true,
+ "type": "bigint"
+ },
+ {
+ "name": "decimal_col",
+ "position": 7,
+ "nullable": true,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "float_col",
+ "position": 8,
+ "nullable": true,
+ "type": "float"
+ },
+ {
+ "name": "double_col",
+ "position": 9,
+ "nullable": true,
+ "type": "double"
+ },
+ {
+ "name": "bit_col",
+ "position": 10,
+ "nullable": true,
+ "type": "bit(8)"
+ },
+ {
+ "name": "char_col",
+ "position": 11,
+ "nullable": true,
+ "type": "char(10)"
+ },
+ {
+ "name": "varchar_col",
+ "position": 12,
+ "nullable": true,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "binary_col",
+ "position": 13,
+ "nullable": true,
+ "type": "binary(10)"
+ },
+ {
+ "name": "varbinary_col",
+ "position": 14,
+ "nullable": true,
+ "type": "varbinary(100)"
+ },
+ {
+ "name": "tinytext_col",
+ "position": 15,
+ "nullable": true,
+ "type": "tinytext"
+ },
+ {
+ "name": "text_col",
+ "position": 16,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "mediumtext_col",
+ "position": 17,
+ "nullable": true,
+ "type": "mediumtext"
+ },
+ {
+ "name": "longtext_col",
+ "position": 18,
+ "nullable": true,
+ "type": "longtext"
+ },
+ {
+ "name": "tinyblob_col",
+ "position": 19,
+ "nullable": true,
+ "type": "tinyblob"
+ },
+ {
+ "name": "blob_col",
+ "position": 20,
+ "nullable": true,
+ "type": "blob"
+ },
+ {
+ "name": "mediumblob_col",
+ "position": 21,
+ "nullable": true,
+ "type": "mediumblob"
+ },
+ {
+ "name": "longblob_col",
+ "position": 22,
+ "nullable": true,
+ "type": "longblob"
+ },
+ {
+ "name": "date_col",
+ "position": 23,
+ "nullable": true,
+ "type": "date"
+ },
+ {
+ "name": "time_col",
+ "position": 24,
+ "nullable": true,
+ "type": "time"
+ },
+ {
+ "name": "datetime_col",
+ "position": 25,
+ "nullable": true,
+ "type": "datetime"
+ },
+ {
+ "name": "timestamp_col",
+ "position": 26,
+ "nullable": true,
+ "type": "timestamp"
+ },
+ {
+ "name": "year_col",
+ "position": 27,
+ "nullable": true,
+ "type": "year(4)"
+ },
+ {
+ "name": "json_col",
+ "position": 28,
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "enum_col",
+ "position": 29,
+ "nullable": true,
+ "type": "enum('small','medium','large')"
+ },
+ {
+ "name": "set_col",
+ "position": 30,
+ "nullable": true,
+ "type": "set('a','b','c')"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+- description: table_with_foreign_keys
+ schema: |
+ CREATE TABLE departments (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE employees (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ dept_id INT,
+ manager_id INT,
+ CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE RESTRICT,
+ CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(id) ON DELETE SET NULL
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "departments",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ },
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "dept_id",
+ "position": 3,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "manager_id",
+ "position": 4,
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "fk_dept",
+ "expressions": [
+ "dept_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "fk_manager",
+ "expressions": [
+ "manager_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_dept",
+ "columns": [
+ "dept_id"
+ ],
+ "referenced_table": "departments",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE",
+ "on_update": "RESTRICT"
+ },
+ {
+ "name": "fk_manager",
+ "columns": [
+ "manager_id"
+ ],
+ "referenced_table": "employees",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "SET NULL"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: views_and_comments
+ schema: |
+ CREATE TABLE orders (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ customer_name VARCHAR(100) COMMENT 'Customer full name',
+ amount DECIMAL(10,2) COMMENT 'Order amount in USD',
+ status VARCHAR(20) DEFAULT 'pending'
+ ) COMMENT='Order management table';
+
+ CREATE VIEW active_orders AS
+ SELECT id, customer_name, amount
+ FROM orders
+ WHERE status = 'active';
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "customer_name",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "amount",
+ "position": 3,
+ "nullable": true,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "status",
+ "position": 4,
+ "nullable": true,
+ "type": "varchar(20)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "comment": "Order management table"
+ }
+ ],
+ "views": [
+ {
+ "name": "active_orders",
+ "definition": "SELECT id, customer_name, amount\nFROM orders\nWHERE status = 'active'"
+ }
+ ]
+ }
+ ]
+ }
+- description: indexes_and_constraints
+ schema: |
+ CREATE TABLE products (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ price DECIMAL(10,2) NOT NULL,
+ category VARCHAR(50),
+ tags JSON,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ INDEX idx_name (name),
+ INDEX idx_price_category (price, category),
+ UNIQUE INDEX idx_unique_name (name),
+ FULLTEXT INDEX idx_description (description)
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "description",
+ "position": 3,
+ "nullable": true,
+ "type": "text"
+ },
+ {
+ "name": "price",
+ "position": 4,
+ "type": "decimal(10,2)"
+ },
+ {
+ "name": "category",
+ "position": 5,
+ "nullable": true,
+ "type": "varchar(50)"
+ },
+ {
+ "name": "tags",
+ "position": 6,
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "created_at",
+ "position": 7,
+ "default": "CURRENT_TIMESTAMP",
+ "nullable": true,
+ "type": "timestamp"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "idx_name",
+ "expressions": [
+ "name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_price_category",
+ "expressions": [
+ "price",
+ "category"
+ ],
+ "key_length": [
+ -1,
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ },
+ {
+ "name": "idx_unique_name",
+ "expressions": [
+ "name"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+- description: tidb_auto_random
+ schema: |
+ CREATE TABLE auto_random_test (
+ id BIGINT /*T![auto_rand] AUTO_RANDOM(5) */ PRIMARY KEY,
+ name VARCHAR(100),
+ data JSON
+ ) COMMENT='PK_AUTO_RANDOM_BITS=5';
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "auto_random_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_RANDOM(5)",
+ "type": "bigint"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "data",
+ "position": 3,
+ "nullable": true,
+ "type": "json"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "comment": "PK_AUTO_RANDOM_BITS=5"
+ }
+ ]
+ }
+ ]
+ }
+- description: complex_table_options
+ schema: |
+ CREATE TABLE table_options_test (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ data TEXT
+ ) ENGINE=InnoDB
+ DEFAULT CHARSET=utf8mb4
+ COLLATE=utf8mb4_general_ci
+ AUTO_INCREMENT=1000
+ COMMENT='Table with various TiDB options';
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "table_options_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "data",
+ "position": 3,
+ "nullable": true,
+ "type": "text"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "collation": "utf8mb4_general_ci",
+ "charset": "utf8mb4",
+ "comment": "Table with various TiDB options"
+ }
+ ]
+ }
+ ]
+ }
+- description: self_referencing_foreign_keys
+ schema: |
+ CREATE TABLE categories (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ parent_id INT,
+ CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id) ON DELETE CASCADE
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "categories",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_INCREMENT",
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "parent_id",
+ "position": 3,
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ },
+ {
+ "name": "fk_parent",
+ "expressions": [
+ "parent_id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "foreign_keys": [
+ {
+ "name": "fk_parent",
+ "columns": [
+ "parent_id"
+ ],
+ "referenced_table": "categories",
+ "referenced_columns": [
+ "id"
+ ],
+ "on_delete": "CASCADE"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+- description: tidb_clustered_index
+ schema: |
+ CREATE TABLE clustered_test (
+ id INT PRIMARY KEY CLUSTERED,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100)
+ );
+
+ CREATE TABLE non_clustered_test (
+ id INT PRIMARY KEY NONCLUSTERED,
+ name VARCHAR(100) NOT NULL,
+ data TEXT
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "clustered_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "nullable": true,
+ "type": "varchar(100)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ },
+ {
+ "name": "non_clustered_test",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "varchar(100)"
+ },
+ {
+ "name": "data",
+ "position": 3,
+ "nullable": true,
+ "type": "text"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+- description: unnamed_check_and_auto_random_range
+ schema: |
+ CREATE TABLE bounded (
+ id BIGINT AUTO_RANDOM(5, 54) PRIMARY KEY,
+ qty INT,
+ CHECK (qty > 0),
+ CONSTRAINT chk_qty_max CHECK (qty < 1000)
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "bounded",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "bigint"
+ },
+ {
+ "name": "qty",
+ "position": 2,
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+- description: unnamed_check_name_collision
+ schema: |
+ CREATE TABLE t (
+ a INT,
+ CONSTRAINT t_chk_2 CHECK (a > 0),
+ CHECK (a < 9),
+ CONSTRAINT named_one CHECK (a <> 5),
+ CHECK (a <> 7)
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "t",
+ "columns": [
+ {
+ "name": "a",
+ "position": 1,
+ "nullable": true,
+ "type": "int"
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+- description: implicit_binary_charset_not_recorded
+ schema: |
+ CREATE TABLE payloads (
+ id INT PRIMARY KEY,
+ doc JSON,
+ blob_col BLOB,
+ fixed BINARY(4),
+ var_bytes VARBINARY(8),
+ named VARCHAR(10) CHARACTER SET latin1,
+ collated VARCHAR(10) COLLATE utf8mb4_bin,
+ plain TEXT
+ );
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "payloads",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "int"
+ },
+ {
+ "name": "doc",
+ "position": 2,
+ "nullable": true,
+ "type": "json"
+ },
+ {
+ "name": "blob_col",
+ "position": 3,
+ "nullable": true,
+ "type": "blob"
+ },
+ {
+ "name": "fixed",
+ "position": 4,
+ "nullable": true,
+ "type": "binary(4)"
+ },
+ {
+ "name": "var_bytes",
+ "position": 5,
+ "nullable": true,
+ "type": "varbinary(8)"
+ },
+ {
+ "name": "named",
+ "position": 6,
+ "nullable": true,
+ "type": "varchar(10)"
+ },
+ {
+ "name": "collated",
+ "position": 7,
+ "nullable": true,
+ "type": "varchar(10)"
+ },
+ {
+ "name": "plain",
+ "position": 8,
+ "nullable": true,
+ "type": "text"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB"
+ }
+ ]
+ }
+ ]
+ }
+- description: auto_random_range_with_compat_comment
+ schema: |
+ CREATE TABLE sharded (
+ id BIGINT AUTO_RANDOM(5, 54) PRIMARY KEY,
+ label VARCHAR(20) DEFAULT 'pending'
+ ) COMMENT='PK_AUTO_RANDOM_BITS=5';
+ metadata: |
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "sharded",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "default": "AUTO_RANDOM(5)",
+ "type": "bigint"
+ },
+ {
+ "name": "label",
+ "position": 2,
+ "nullable": true,
+ "type": "varchar(20)"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "id"
+ ],
+ "key_length": [
+ -1
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
+ }
+ ],
+ "engine": "InnoDB",
+ "comment": "PK_AUTO_RANDOM_BITS=5"
+ }
+ ]
+ }
+ ]
+ }
diff --git a/backend/plugin/schema/tidb/testutil_test.go b/backend/plugin/schema/tidb/testutil_test.go
deleted file mode 100644
index d6726fb76f..0000000000
--- a/backend/plugin/schema/tidb/testutil_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package tidb
-
-import (
- "context"
-
- "github.com/pkg/errors"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/db"
- tidbdb "github.com/bytebase/bytebase/backend/plugin/db/tidb"
-)
-
-// createTiDBDriver creates and opens a TiDB driver connection
-func createTiDBDriver(ctx context.Context, host, port, database string) (*tidbdb.Driver, error) {
- driver := &tidbdb.Driver{}
- config := db.ConnectionConfig{
- DataSource: &storepb.DataSource{
- Type: storepb.DataSourceType_ADMIN,
- Username: "root",
- Host: host,
- Port: port,
- Database: database,
- },
- Password: "",
- ConnectionContext: db.ConnectionContext{
- EngineVersion: "8.5.0",
- DatabaseName: database,
- },
- }
- d, err := driver.Open(ctx, storepb.Engine_TIDB, config)
- if err != nil {
- return nil, err
- }
- tidbDriver, ok := d.(*tidbdb.Driver)
- if !ok {
- return nil, errors.Errorf("failed to cast to TiDB driver")
- }
- return tidbDriver, nil
-}