Database Modernization with Autohand Code
Migrate legacy databases to modern systems. Transform Oracle, SQL Server, and other legacy databases to PostgreSQL with zero downtime using Autohand Code.
Why modernize databases?
Modern database systems offer significant advantages:
- Reduced licensing costs (up to 80% savings)
- Improved performance and scalability
- Better security and compliance features
- Enhanced developer productivity
- Cloud-native capabilities and managed services
Database assessment
Assess your database for modernization opportunities:
# Create an AGENTS.md to record the target (Oracle to PostgreSQL 15)
autohand init
# Generate a migration roadmap in read-only plan mode
autohand -p "Assess the Oracle schema in db/ and its usage in the app for a move to PostgreSQL 15. Write a roadmap to docs/db-roadmap.md" --plan
# Assessment includes:
# - Schema complexity analysis
# - Data volume and migration time
# - Application dependency mapping
# - Performance benchmarking
Schema migration
Transform legacy database schemas to modern systems:
# Preview the schema conversion as a patch
autohand -p "Convert the Oracle DDL in db/schema/ to PostgreSQL 15 migrations in db/postgres/, preserving data types and constraints, and add tests" --patch --output schema.patch
git apply --check schema.patch
# Execute the schema conversion in an isolated git worktree
autohand --worktree pg-schema -p "Convert the Oracle DDL in db/schema/ to PostgreSQL 15 migrations in db/postgres/, preserving data types and constraints, and add tests"
Oracle to PostgreSQL example
-- Before (Oracle)
CREATE TABLE employees (
employee_id NUMBER(6) PRIMARY KEY,
first_name VARCHAR2(20) NOT NULL,
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25) UNIQUE NOT NULL,
hire_date DATE DEFAULT SYSDATE,
salary NUMBER(8,2) CHECK (salary > 0),
department_id NUMBER(4) REFERENCES departments(department_id)
);
CREATE SEQUENCE emp_seq START WITH 1 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER emp_trig
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
:NEW.employee_id := emp_seq.NEXTVAL;
END;
Becomes:
-- After (PostgreSQL)
CREATE TABLE employees (
employee_id BIGSERIAL PRIMARY KEY,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(25) NOT NULL,
email VARCHAR(25) UNIQUE NOT NULL,
hire_date DATE DEFAULT CURRENT_DATE,
salary NUMERIC(8,2) CHECK (salary > 0),
department_id INTEGER REFERENCES departments(department_id)
);
-- Indexes for performance
CREATE INDEX idx_employees_department_id ON employees(department_id);
CREATE INDEX idx_employees_email ON employees(email);
Data migration
Migrate data with zero downtime and data integrity:
# Plan the data transfer (read-only)
autohand -p "Plan a batched Oracle to PostgreSQL data transfer (10,000 rows per batch, 4 workers) with row-count and checksum validation" --plan
# Have Autohand write the transfer and validation scripts in a worktree
autohand --worktree pg-data -p "Write scripts/transfer.py to copy data from Oracle to PostgreSQL in batches of 10,000 rows with 4 workers, plus scripts/validate.py to compare row counts and checksums"
Migration strategies
# Change Data Capture (CDC): Autohand writes the pipeline config; your CDC tool runs it
autohand --worktree cdc -p "Create a Debezium Oracle connector config and a PostgreSQL JDBC sink config in cdc/ for the employees, departments and salaries tables, plus a README with start and monitoring steps"
Query translation
Convert database-specific SQL to standard SQL:
-- Before (Oracle-specific)
SELECT
e.employee_id,
e.first_name,
e.last_name,
d.department_name,
TO_CHAR(e.hire_date, 'YYYY-MM-DD') as hire_date
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
WHERE e.salary > (
SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id
)
ORDER BY e.hire_date DESC;
-- After (PostgreSQL)
SELECT
e.employee_id,
e.first_name,
e.last_name,
d.department_name,
TO_CHAR(e.hire_date, 'YYYY-MM-DD') as hire_date
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
WHERE e.salary > (
SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id
)
ORDER BY e.hire_date DESC;
Application compatibility
Update application code for new database:
// Before (Oracle JDBC)
String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
Connection conn = DriverManager.getConnection(url, "user", "pass");
// Oracle-specific SQL
String sql = "SELECT * FROM employees WHERE ROWNUM <= 10";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
// Date handling
java.util.Date date = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(date);
Becomes:
// After (PostgreSQL JDBC)
String url = "jdbc:postgresql://localhost:5432/company";
Connection conn = DriverManager.getConnection(url, "user", "pass");
// PostgreSQL SQL
String sql = "SELECT * FROM employees LIMIT 10";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
// Modern date handling
LocalDate date = LocalDate.now();
String dateStr = date.format(DateTimeFormatter.ISO_LOCAL_DATE);
Testing and validation
Ensure migration accuracy and performance:
# Generate migration tests
autohand -p "Write integration tests in tests/migration/ that compare row counts and checksums between Oracle and PostgreSQL"
# Validate data integrity with the generated scripts
python scripts/validate.py
# Performance testing: have Autohand write a benchmark, then run it yourself
autohand -p "Write scripts/benchmark.sh that runs the top 20 queries from docs/slow-queries.sql against both databases and prints timings"
Data validation example
# Generated validation test
def test_employee_data_integrity():
"""Verify employee data migrated correctly"""
# Compare record counts
oracle_count = execute_oracle("SELECT COUNT(*) FROM employees")
pg_count = execute_postgres("SELECT COUNT(*) FROM employees")
assert oracle_count == pg_count
# Compare sample records
sample_query = "SELECT * FROM employees WHERE employee_id = ?"
oracle_record = execute_oracle(sample_query, [1001])
pg_record = execute_postgres(sample_query, [1001])
# Validate data equality
assert oracle_record['first_name'] == pg_record['first_name']
assert oracle_record['last_name'] == pg_record['last_name']
# ... more validations
Best practices for database modernization
Pre-migration preparation
- Comprehensive backup: Create full database backups before starting
- Performance benchmarking: Document current performance metrics
- Dependency mapping: Identify all applications using the database
- Schema analysis: Analyze schema complexity and migration challenges
- Team training: Train DBAs and developers on target database
Migration strategy
- Incremental migration: Migrate database by database or table by table
- Zero downtime approach: Use CDC for real-time data synchronization
- Rollback planning: Prepare rollback procedures at each migration stage
- Parallel operation: Run both databases during transition period
- Feature flags: Use application flags to switch between databases
Data integrity
- Validation testing: Compare data between source and target
- Transaction consistency: Ensure transaction boundaries are preserved
- Constraint validation: Verify all constraints and relationships
- Data type mapping: Carefully handle data type conversions
- Performance testing: Validate query performance post-migration
Application updates
- Connection strings: Update database connection configurations
- SQL compatibility: Convert database-specific SQL to standard SQL
- Driver updates: Update database drivers and ORMs
- Query optimization: Optimize queries for target database
- Error handling: Update error handling for new database exceptions
Post-migration optimization
- Index optimization: Create appropriate indexes for performance
- Query tuning: Optimize slow queries and execution plans
- Resource allocation: Optimize memory and CPU allocation
- Monitoring setup: Implement comprehensive database monitoring
- Backup strategy: Update backup procedures for new database
Common pitfalls to avoid
- Data loss: Never proceed without comprehensive backups
- Performance regression: Monitor performance closely during migration
- Application downtime: Plan for zero-downtime migration strategies
- Schema differences: Account for database-specific features and limitations
- Security misconfiguration: Ensure security settings are properly configured