3: Migrate data solutions

    Design and implement data migration and replication

    Database migration into Google Cloud is the activity with the highest blast radius in a database engineer's job.

    Every other day-two operation (HA failover, restore from PITR, replica promotion) is reversible inside the same managed service and the same engine version. A migration changes the system of record.

    Once the application writes its first production transaction to the new target, every prior transaction must already be there, the new target must be capable of accepting the steady-state write rate, and the old source must be either decommissioned, kept warm as a fallback, or repurposed as a downstream replica.

    Getting any of those wrong forces a rollback under business pressure, and a rollback during cutover is the single most common reason a migration project ends up on a post-incident timeline.

    The remainder of this chapter walks the engineer through the four work streams the syllabus combines into one section:

    • choosing a strategy aligned to the downtime budget,
    • building a reverse-replication safety net,
    • planning schema conversion and the migration steps themselves,
    • picking the right tool for the source-target pair.

    Each subsection assumes the reader has already chosen a target engine using the decision matrix from the earlier chapter; the focus here is on how to move the bytes, the schema, and the cutover risk.

    Developing and executing migration strategies and plans

    Every migration belongs to one of four downtime postures.

    The choice is driven by what the application can tolerate during cutover, not by what the source or target supports.

    A workload that loses revenue at $50,000 per minute justifies the engineering cost of a CDC-based zero-downtime move; an internal HR analytics database that runs nightly batches can absorb a six-hour extended outage and reach the same end state with a fraction of the moving parts.

    Zero-downtime cutover with continuous CDC

    A zero-downtime migration runs the source and the target in parallel and uses change data capture to stream every committed transaction from the source binary log (MySQL) or write-ahead log (PostgreSQL) into the target.

    The initial load (pg_dump, mysqldump, or a Database Migration Service snapshot) is taken while the source remains open for writes. The CDC stream captures the deltas accumulated during the load and keeps draining them until the target's apply lag is in the sub-second range.

    Cutover then becomes a short read-only window during which the application is paused, the residual CDC backlog drains, and the connection string is repointed.

    How it works

    The mechanics for a Cloud SQL for PostgreSQL target look like this.

    • The source database has logical replication enabled (wal_level = logical, max_replication_slots, max_wal_senders).
    • The dedicated replication user holds REPLICATION and LOGIN plus SELECT on the schemas being moved.
    • The network path between the source and the Database Migration Service is reachable over Private Service Connect or a VPN.

    The cutover window collapses to two activities: drain the CDC backlog (typically seconds), and run gcloud database-migration migration-jobs promote to detach the target from the replication stream and unblock writes.

    # Pre-flight on the source PostgreSQL instance
    psql -h source.internal -U postgres -c "ALTER SYSTEM SET wal_level = 'logical';"
    psql -h source.internal -U postgres -c "ALTER SYSTEM SET max_replication_slots = 10;"
    psql -h source.internal -U postgres -c "ALTER SYSTEM SET max_wal_senders = 10;"
    # Restart the source for wal_level to take effect.
    
    # Replication user with the privileges DMS requires
    psql -h source.internal -U postgres <<'SQL'
    CREATE USER dms_repl WITH REPLICATION LOGIN PASSWORD 'rotated-secret';
    GRANT pg_read_all_data TO dms_repl;
    GRANT USAGE ON SCHEMA public TO dms_repl;
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO dms_repl;
    SQL
    
    # Create the connection profiles, migration job, and start it
    gcloud database-migration connection-profiles create postgresql src-prod \
     --region=us-central1 \
     --postgresql-hostname=source.internal \
     --postgresql-port=5432 \
     --postgresql-username=dms_repl \
     --postgresql-password-secret-version=projects/acme-prod/secrets/src-pw/versions/latest \
     --psc-service-attachment=projects/acme-net/regions/us-central1/serviceAttachments/src-attach
    
    gcloud database-migration connection-profiles create postgresql tgt-cloudsql \
     --region=us-central1 \
     --postgresql-cloudsql-id=projects/acme-prod/instances/orders-pg
    
    gcloud database-migration migration-jobs create orders-migration \
     --region=us-central1 \
     --type=CONTINUOUS \
     --source=src-prod \
     --destination=tgt-cloudsql \
     --dump-parallel-level=HIGH
    
    gcloud database-migration migration-jobs start orders-migration --region=us-central1
    

    While the job runs, the engineer watches three signals:

    • dump progress (gcloud database-migration migration-jobs describe)
    • CDC apply lag (the Replication delay metric on the destination Cloud SQL instance)
    • source-side replication slot LSN advancement

    Apply lag converging to zero is the green light to plan cutover; persistent lag above the application's RPO budget means CDC is throttled (typically by missing primary keys on busy tables, large TOAST columns, or a target sized smaller than the source).

    💡 Exam Trap: Database Migration Service for PostgreSQL drops and recreates indexes during the initial load to accelerate the bulk insert phase. A migration job that "completes" the dump but never advances CDC lag is often blocked on index rebuild on the target. Wait for the post-load index phase to finish before measuring apply lag, and size the target's CPU and Hyperdisk Balanced IOPS for the index rebuild concurrency, not just the steady-state OLTP workload.

    📊 Limit: Database Migration Service requires wal_level = logical on PostgreSQL sources and log_bin = ON with binlog_format = ROW and binlog_row_image = FULL on MySQL sources. The MySQL source must also retain at least the volume of binary logs that the dump duration plus expected catch-up will consume; the documented recommendation is keeping binary logs for the longer of seven days or 1.5 times the expected dump duration.

    ⚠️ Anti-Pattern: Running a zero-downtime migration without a documented cutover script. The cutover window is short; if the engineer is typing commands ad hoc to drain CDC, repoint DNS, restart pollers, and promote the job, the window stretches into a full outage. The migration plan must include a cutover runbook with timed steps, rollback decision points, and the exact gcloud invocations the operator will run.

    Near-zero-downtime cutover

    A near-zero migration accepts a small write outage (typically minutes) during cutover in exchange for simpler tooling.

    The pattern is identical to zero-downtime in the load and CDC phases, but the cutover window is widened to allow operations the engineer does not want to do under pressure:

    • a final consistency check (row counts on critical tables),
    • application configuration rollout through a slower channel (a deployment pipeline rather than a hot DNS swap),
    • a brief warm-up period on the new target before traffic resumes.

    When to use

    Near-zero is the right call when:

    • the application's SLO permits a 5-to-15-minute write freeze,
    • the team does not want to invest in zero-downtime cutover tooling,
    • the database is large enough that load-only migration would take days.

    It is also the right call for a first migration in a series: the team learns the tooling under a real-but-survivable window before raising the bar to zero-downtime for the next workload.

    The plan for a near-zero MySQL-to-Cloud-SQL-for-MySQL move looks like this:

    1. Set the source binlog_format = ROW, binlog_row_image = FULL, gtid_mode = ON, enforce_gtid_consistency = ON, and binlog_expire_logs_seconds large enough to cover the dump duration.
    2. Create the Database Migration Service connection profiles and the continuous migration job; start it and let the initial dump complete.
    3. Monitor CDC apply lag on the destination; wait for sustained convergence under the application's RPO.
    4. Enter cutover: stop application writes (read-only mode if the framework supports it, otherwise pause the upstream queue or scale the application to zero), wait for CDC lag to reach zero, verify row counts on the top tables, promote the migration job, and repoint application connections.

    Promotion is irreversible inside Database Migration Service: once the job is promoted, CDC stops and the target becomes a standalone primary. Any rollback after promotion requires the reverse-replication design covered in the next subsection.

    # Final pre-promotion check on the destination Cloud SQL for MySQL instance
    gcloud sql connect orders-mysql --user=admin <<'SQL'
    SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_ROWS
    FROM information_schema.TABLES
    WHERE TABLE_SCHEMA NOT IN ('mysql','information_schema','performance_schema','sys')
    ORDER BY TABLE_ROWS DESC
    LIMIT 20;
    SQL
    
    # Promote when CDC lag is zero and row counts match
    gcloud database-migration migration-jobs promote orders-migration --region=us-central1
    

    💡 Exam Trap: A migration job stuck in the RUNNING state with the destination Cloud SQL instance unreachable usually means the destination was created in a private services access range without authorizing the Database Migration Service network. The fix is on the Cloud SQL side (gcloud sql instances patch ... --authorized-networks=) or by routing the job through Private Service Connect, not by restarting the job.

    Extended outage with dump and restore

    The extended-outage strategy stops application writes, takes a full dump of the source, copies the dump into the target, restores it, and resumes the application against the new target.

    The tooling is the native engine path (pg_dump/pg_restore, mysqldump/mysql, bcp for SQL Server, RMAN or Data Pump for Oracle when going to a self-managed target), the operational complexity is minimal, and the downtime is the sum of dump time, transfer time, and restore time.

    Extended-outage is the right choice:

    • for small databases (single-digit GB, where dump and restore finish in minutes)
    • for batch-only workloads where a maintenance window is naturally available
    • for engines or versions Database Migration Service does not support
    • for migrations where the team does not want to provision CDC infrastructure (replication users, log retention, network paths) on a source they do not control.

    A typical extended-outage migration for a PostgreSQL workload into Cloud SQL for PostgreSQL:

    # Take a parallel dump from the source while the application is in a read-only window
    pg_dump \
     --host=source.internal \
     --username=postgres \
     --dbname=orders \
     --format=directory \
     --jobs=8 \
     --no-owner --no-privileges \
     --file=/var/dumps/orders
    
    # Upload the dump to Cloud Storage
    gsutil -m cp -r /var/dumps/orders gs://acme-migration-staging/orders/
    
    # Restore on a transient Compute Engine VM that has the Cloud SQL Auth Proxy attached
    pg_restore \
     --host=127.0.0.1 --port=5432 \
     --username=postgres \
     --dbname=orders \
     --format=directory \
     --jobs=8 \
     --no-owner --no-privileges \
     /var/dumps/orders
    

    The dump and restore commands above are deliberately symmetric: the same --jobs value on both ends keeps the parallelism predictable, and --no-owner plus --no-privileges removes role-grant errors when the source and target use different role names.

    🎯 Scenario: A finance team needs to move a 40 GB PostgreSQL database used by an overnight close batch into Cloud SQL for PostgreSQL. The batch runs from 02:00 to 05:00; the database is idle from 06:00 to 23:00. The engineer schedules the cutover for 10:00 on a Saturday, takes a parallel pg_dump at 10:00 (12 minutes), uploads the dump to Cloud Storage (4 minutes), and restores into the target Cloud SQL instance (18 minutes). Application configuration is swapped at 11:00. Total outage: 60 minutes. The team did not stand up Database Migration Service, did not configure logical replication on the source, and did not need a cutover runbook beyond the four-step plan above. Extended outage was the right call because the batch window absorbed the downtime cleanly.

    📊 Limit: pg_dump --format=directory --jobs=N parallelizes per-table dumps but serializes the schema and the pg_largeobject data. Tables with very large rows (TOASTed columns) or tables with foreign-key dependencies that force ordered restore still benefit from parallel restore via pg_restore --jobs=N. The practical ceiling on --jobs is the lower of source CPU count, target CPU count, and the network bandwidth between dump host and restore host.

    Fallback plans

    Every migration plan needs a fallback. The shape of the fallback depends on the cutover strategy:

    • Extended outage with a pre-cutover snapshot. The simplest fallback is the snapshot the engineer took right before cutover. If the new target misbehaves within the rollback window, the application is repointed back to the source, which is still intact and was held read-only during the move. This works for any workload that did not write to the source after the snapshot; if the application has any background workers that fire post-cutover (cron jobs, queue consumers), they must be paused on the source until rollback is no longer possible.
    • Near-zero with frozen source. The source remains running after promotion, accepting no writes (firewall blocks application IPs, replication role revoked from application users). If the team needs to roll back within hours, the source is unfrozen, the application is repointed, and the post-cutover deltas captured on the new target are either replayed manually (a small set of transactions) or accepted as data loss (an explicit business decision).
    • Zero-downtime with reverse replication. The new target streams CDC back to the source through a second Database Migration Service job or a third-party replicator. The source stays warm and in lock-step with the target; rollback is another short cutover in the opposite direction. This is the only fallback that loses zero transactions during a post-cutover rollback. The full design is in the next subsection.

    A documented fallback is not a fallback. It must be rehearsed in a non-production environment with the same tooling and the same connection paths the production cutover will use.

    The rehearsal verifies that the rollback runbook actually works against the size of the data set, that replication slots and connection profiles can be re-armed under time pressure, and that the application's configuration system can route writes to either endpoint within the cutover budget.

    ⚠️ Anti-Pattern: Declaring a migration complete the moment the application is repointed to the new target. The post-cutover window (commonly 24 to 72 hours) is where most migration regressions surface, because that is when previously dormant batch jobs, monthly reports, and rarely run admin queries hit the new engine for the first time. The migration plan must include an explicit "stabilization period" with elevated monitoring, on-call rotations, and the rollback path still armed, before the source is decommissioned.

    Performing reverse replication from Google Cloud to source

    Reverse replication is the asymmetric mirror of the forward migration: a CDC stream flowing from the Google Cloud target back to the original source so that the source can take over again on demand.

    It is the most expensive fallback to build (it requires double the operational surface, double the replication slots, and a fully tested rollback runbook), but it is the only one that provides true zero-data-loss rollback after the application has been writing to Google Cloud for hours or days. There are three implementation patterns the engineer should know.

    Pattern A: Native logical replication back to the source

    For a PostgreSQL-to-Cloud-SQL-for-PostgreSQL migration, reverse replication is set up by creating a publication on the Cloud SQL target and a subscription on the source. The source must be at a PostgreSQL major version equal to or newer than the target, the replication user on the target has the cloudsqlsuperuser and cloudsqlreplica role attributes appropriate for logical replication, and the network path between target and source is reachable.

    -- On the Cloud SQL for PostgreSQL target after promotion
    ALTER SYSTEM SET wal_level = 'logical';
    SELECT pg_reload_conf();
    
    CREATE PUBLICATION rollback_pub FOR ALL TABLES;
    CREATE USER reverse_repl WITH REPLICATION LOGIN PASSWORD 'rotated-secret';
    GRANT pg_read_all_data TO reverse_repl;
    
    -- On the original PostgreSQL source, after read-only mode is released for the subscription only
    CREATE SUBSCRIPTION rollback_sub
     CONNECTION 'host=target.internal port=5432 dbname=orders user=reverse_repl password=rotated-secret sslmode=require'
     PUBLICATION rollback_pub
     WITH (copy_data = false, create_slot = true, slot_name = 'rollback_slot');
    

    copy_data = false is critical: the source already has the pre-cutover state, and the subscription only needs to apply post-cutover deltas. Setting copy_data = true would re-replay every row from the target to the source, producing primary-key conflicts on every row that existed before the migration.

    💡 Exam Trap: Logical replication in PostgreSQL requires a primary key or REPLICA IDENTITY FULL on every replicated table. A table without a primary key replicates inserts correctly but silently drops updates and deletes on the subscriber. Before enabling reverse replication, the engineer must inventory every table without a primary key and either add one or set ALTER TABLE foo REPLICA IDENTITY FULL, accepting the WAL-volume penalty that comes with replicating the full pre-image of every row.

    Pattern B: Reverse Database Migration Service job

    For MySQL workloads, Database Migration Service supports a "reverse replication" mode where a second migration job is created with the Cloud SQL target as the source and the original MySQL source as the destination. This is the same product, the same connection profile model, and the same monitoring surface as the forward job, pointed in the opposite direction. The mechanics:

    # Connection profiles for the reverse direction
    gcloud database-migration connection-profiles create mysql tgt-as-src \
     --region=us-central1 \
     --mysql-cloudsql-id=projects/acme-prod/instances/orders-mysql
    
    gcloud database-migration connection-profiles create mysql src-as-tgt \
     --region=us-central1 \
     --mysql-hostname=source.internal \
     --mysql-port=3306 \
     --mysql-username=dms_reverse \
     --mysql-password-secret-version=projects/acme-prod/secrets/src-reverse-pw/versions/latest \
     --psc-service-attachment=projects/acme-net/regions/us-central1/serviceAttachments/src-attach
    
    # Reverse migration job: continuous, no initial dump (the source is already populated)
    gcloud database-migration migration-jobs create orders-reverse \
     --region=us-central1 \
     --type=CONTINUOUS \
     --source=tgt-as-src \
     --destination=src-as-tgt \
     --skip-validation \
     --dump-flags=--no-data
    

    The forward job is created with a full dump; the reverse job is created with --dump-flags=--no-data (or the equivalent path that skips initial load) because the source already has every row up to the cutover LSN. The reverse job picks up from the cutover position in the target's binary log and applies new transactions to the source.

    📊 Limit: Reverse replication in Database Migration Service requires the original source to remain accessible from Google Cloud at the network layer for the duration of the rollback window. If the source's firewall, VPN, or Interconnect path is decommissioned the day after cutover, the reverse job cannot stream and the fallback evaporates. The migration plan must keep the network path open for the full stabilization period.

    Pattern C: Third-party CDC reverse replication

    For sources where Database Migration Service does not provide reverse support (SQL Server, Oracle, MongoDB), partner tooling fills the gap. Striim, Fivetran HVR, Qlik Replicate, and Confluent Replicator all read the target's transaction log (or the Cloud SQL audit log path for engines without log access) and write back to the source.

    The setup cost is higher (an ISV agreement, a partner-supplied replicator host on Compute Engine, and an additional support relationship), but the operational shape is identical: a CDC stream keeps the source warm so the application can be repointed back within the rollback window.

    Rollback decision criteria

    The reverse-replication channel only matters if the team knows when to actually use it. The migration runbook must define the rollback decision criteria up front, in writing, before cutover. Common criteria include:

    • Application error rate above a documented threshold (e.g., HTTP 5xx ratio above 1 percent sustained for 10 minutes) attributable to database issues.
    • p99 query latency on the top three transactions exceeding the pre-cutover baseline by more than 50 percent for 30 minutes.
    • Any data corruption event (a duplicate primary key insert succeeding, a missing row on a read-after-write path).
    • Any successful replication-slot lag growth that the engineer cannot diagnose within one hour.

    The decision is binary and is made by a named decision-maker (the on-call engineering lead) using the criteria above, not by debate in a chat channel. Once the rollback is called, the runbook executes deterministic steps: pause application writes, drain the reverse CDC backlog, repoint application configuration to the source, resume writes.

    🎯 Scenario: Forty-eight hours after a near-zero-downtime move of an e-commerce orders database into AlloyDB for PostgreSQL, the team discovers that a batch job invoking an Oracle-style LISTAGG aggregate is failing on AlloyDB because the application was never re-tested for that specific stored procedure. The engineer triggers the documented rollback: the application is briefly paused, the reverse replication slot's apply lag drains in seconds, the connection string is repointed to the original source, and the application resumes. Total rollback window: 4 minutes. The team then re-tests the batch job in a staging environment, rewrites the offending function for AlloyDB, and re-cuts the migration two days later. Without the reverse replication channel, the rollback would have lost the forty-eight hours of orders written to AlloyDB.

    ⚠️ Anti-Pattern: Leaving reverse replication enabled indefinitely as a "permanent disaster recovery" channel. Reverse replication is a rollback aid, not a DR architecture. It doubles the operational surface, doubles the IAM and key-management policies, and creates a long-running replication slot on the target that will hold WAL until it is dropped. The plan must include an explicit shutdown step (drop the subscription, drop the slot, decommission the connection profile, close the network path) once the rollback window closes.

    Planning and performing database migration, including fallback plans and schema conversion

    This subsection focuses on the planning artifacts the migration engineer produces before any data moves, with special attention to schema conversion, which is the single hardest part of any heterogeneous migration.

    Migration planning artifacts

    A production migration plan is a written document with the following sections, each owned by a named individual:

    1. Source inventory. Engine, version, edition, schema list, table-level row counts, index counts, stored procedure count, trigger count, total on-disk size, peak write rate (rows per second on the top three tables), peak read rate, current connection count, and external-system dependencies (replication slaves, ETL readers, BI tools, application services).
    2. Target sizing. Machine type, edition tier (Cloud SQL Enterprise vs Enterprise Plus, AlloyDB primary node CPU count and read pool node count), storage type (Hyperdisk Balanced sized for the source's working-set IOPS), region and zone selection, HA posture, network path.
    3. Schema conversion plan. Data-type mapping table, DDL translation approach, list of stored procedures that need rewrites, list of application SQL statements that need re-testing, mitigation for source-specific extensions (Oracle DBMS_, SQL Server xp_, MySQL plugins).
    4. Migration tooling. Which tool drives the move, which tool handles schema, which tool validates row counts and checksums post-load.
    5. Cutover runbook. Timed sequence of operator steps, with the exact gcloud and psql/mysql invocations the operator will paste, the success criteria at each step, and the rollback trigger at each step.
    6. Rollback runbook. The fallback strategy (snapshot, frozen source, or reverse replication), the rollback decision criteria, the runbook owner, and the named decision-maker.
    7. Stabilization plan. Monitoring elevations, on-call rotation, the duration the rollback path stays armed, and the decommissioning steps for the source once the rollback window closes.

    Schema conversion fundamentals

    Schema conversion is the translation of DDL, data types, constraints, indexes, stored procedures, triggers, views, and engine-specific extensions from the source dialect into the target dialect.

    For homogeneous migrations (PostgreSQL to PostgreSQL, MySQL to MySQL), schema conversion is mostly identity: the dump produced by pg_dump/mysqldump is restored with minimal edits.

    For heterogeneous migrations, schema conversion is its own project. The common heterogeneous paths are:

    • Oracle to Cloud SQL for PostgreSQL or AlloyDB for PostgreSQL. The largest gap. Oracle's PL/SQL, DBMS_* packages, hierarchical queries (CONNECT BY), and proprietary types (VARCHAR2, NUMBER, BLOB semantics) all need translation. Ora2pg is the open-source tool of record; it produces PostgreSQL DDL and PL/pgSQL function bodies that the engineer then reviews, tests, and corrects. Database Migration Service has Oracle source support that handles the data move once the schema is in place.
    • SQL Server to Cloud SQL for PostgreSQL or AlloyDB. Microsoft's SQL Server Migration Assistant (SSMA) for PostgreSQL converts T-SQL into PL/pgSQL, maps SQL Server-specific types (DATETIME2, MONEY, UNIQUEIDENTIFIER) into PostgreSQL equivalents (TIMESTAMP, NUMERIC(19,4), UUID), and emits a project file the team can iterate on.
    • MySQL to Cloud SQL for PostgreSQL. Less gap than the Oracle case but more than zero. MySQL's AUTO_INCREMENT becomes PostgreSQL's GENERATED ALWAYS AS IDENTITY or a SERIAL; BOOLEAN (which is really TINYINT(1)) becomes a real BOOLEAN; DATETIME becomes TIMESTAMP; case-insensitive collation behaviors need explicit CITEXT columns or LOWER() indexes. Pgloader handles both DDL and data in a single command for MySQL to PostgreSQL.

    Data-type mapping table

    The mapping below is the most common pattern for source-to-PostgreSQL conversion. Edge cases exist for every row and need per-application validation.

    Source type (Oracle)Source type (SQL Server)Source type (MySQL)PostgreSQL target
    VARCHAR2(N)VARCHAR(N), NVARCHAR(N)VARCHAR(N)VARCHAR(N) or TEXT
    NUMBER(p,0)INT, BIGINTINT, BIGINTINTEGER, BIGINT, or NUMERIC(p,0)
    NUMBER(p,s)DECIMAL(p,s), MONEYDECIMAL(p,s)NUMERIC(p,s)
    DATEDATETIME, DATETIME2DATETIME, TIMESTAMPTIMESTAMP or TIMESTAMPTZ
    CLOBTEXT, NVARCHAR(MAX)TEXT, LONGTEXTTEXT
    BLOBVARBINARY(MAX)BLOB, LONGBLOBBYTEA or external gs:// URI
    RAW(N)BINARY(N)BINARY(N)BYTEA
    XMLTYPEXMLJSONXML or JSONB
    JSON (12c+)JSONJSONJSONB
    RAW(16) for UUIDUNIQUEIDENTIFIERCHAR(36) for UUIDUUID

    Large object handling deserves a sentence. BLOB/BYTEA columns are tolerable for blobs under a few megabytes but break down for larger payloads (the WAL volume per insert becomes the dominant cost). For large media, the practitioner pattern is to keep a gs:// URI in the row and store the bytes in Cloud Storage; the application reads through a signed URL.

    Ora2pg in practice

    Ora2pg is configured through a single ora2pg.conf file that declares the source DSN, the target schema, and per-object-type extraction toggles. The conversion happens in passes: schema (DDL), data, packages and procedures, triggers, views, and grants.

    # Single Ora2pg invocation that exports schema-only DDL for the HR schema
    ora2pg \
     -c /etc/ora2pg/ora2pg.conf \
     -t TABLE,VIEW,SEQUENCE,INDEX,FUNCTION,PROCEDURE,PACKAGE,TRIGGER \
     -o /var/migration/hr_schema.sql \
     -n HR
    

    The output hr_schema.sql is reviewed by hand. Ora2pg reports conversion difficulty per object on a scale from A to D; objects rated D (unsupported features, dynamic SQL with Oracle-specific binds, packages that depend on DBMS_SCHEDULER) need manual rewrite. The team iterates: convert, review, edit, apply to a staging PostgreSQL instance, run application tests, repeat.

    # Once schema is verified, copy data in parallel
    ora2pg \
     -c /etc/ora2pg/ora2pg.conf \
     -t COPY \
     -j 8 \
     -J 4 \
     -o /var/migration/hr_data.sql
    
    # Apply data into the target
    psql -h target.internal -U postgres -d hr -f /var/migration/hr_data.sql
    

    -j controls the per-table parallelism Ora2pg uses to extract; -J controls the number of tables extracted concurrently. The product of the two is the load on the source database, and the engineer keeps it under the source's spare capacity to avoid impacting production during extract.

    💡 Exam Trap: Ora2pg's data export reads through Oracle JDBC and writes to disk; it does not natively understand LONG RAW or LOB columns over a certain size. For tables with large LOBs, the engineer must either set LONGREADLEN to a value larger than the largest LOB the table holds or use a Database Migration Service Oracle source for the data step while keeping Ora2pg for the DDL.

    SQL Server Migration Assistant (SSMA)

    SSMA is a Windows desktop application that connects to a SQL Server source, extracts metadata, generates a PostgreSQL or MySQL target schema, and offers a per-object conversion report. The team uses SSMA to:

    1. Connect to the source SQL Server and the target Cloud SQL for PostgreSQL instance.
    2. Run "Convert Schema" to generate PostgreSQL DDL from the SQL Server source.
    3. Review the conversion report: tables convert automatically, indexes convert automatically, T-SQL stored procedures convert to PL/pgSQL with a confidence score, CLR assemblies and SQL Server-specific features are flagged as manual rewrites.
    4. Apply the converted schema to the target.
    5. Move data using SSMA's bulk-data wizard or Database Migration Service's SQL Server source.

    Pgloader for MySQL to PostgreSQL

    Pgloader is the most operationally lightweight tool for the MySQL-to-PostgreSQL path. A single configuration file describes the source DSN, the target DSN, type casting rules, and per-table options. Pgloader handles both DDL and data in one pass.

    # Pgloader command file: migrate.load
    LOAD DATABASE
     FROM mysql://app_user:secret@source.internal:3306/orders
     INTO postgresql://app_user:secret@target.internal:5432/orders
     WITH include drop, create tables, create indexes, reset sequences,
     foreign keys, downcase identifiers
     CAST type tinyint when (= precision 1) to boolean drop typemod,
     type datetime to timestamptz drop default drop not null
     ALTER schema 'orders' rename to 'public'
    ;
    
    pgloader migrate.load
    

    Pgloader's strength is the small surface area; its weakness is that it does not perform CDC, so the MySQL source must be frozen during the load. For zero-downtime MySQL-to-PostgreSQL, the engineer combines pgloader for the schema with Database Migration Service for the data and CDC.

    ⚠️ Anti-Pattern: Converting schema and data in a single tool invocation against production and hoping the result is correct. Schema conversion is iterative: the first pass produces working DDL for 60-to-80 percent of objects, the second pass cleans up the medium-difficulty items, and the third pass deals with the long tail of stored procedures and triggers that need rewrites. Each pass is applied to a staging target and validated with the application's test suite before any production migration is scheduled.

    Pre-cutover validation

    Before promoting any migration job, the engineer runs a validation pass that covers four checks:

    1. Row counts on the top 20 tables (by row count) match between source and target within an acceptable delta (typically zero for tables with no current writes, single-digit for tables with active CDC).
    2. Checksum or hash on critical reference tables (currency rates, country lookups, product catalogs) match exactly.
    3. Index inventory on the target matches the source (every index in pg_indexes or information_schema.STATISTICS).
    4. Foreign-key constraint count matches.

    Database Migration Service surfaces some of these checks in its built-in validation pass.

    Partner tooling like Striim and Qlik Replicate offers richer validation including per-row checksum sampling.

    The engineer should treat the built-in checks as a starting point and add application-specific checks for any business rule that depends on a particular schema invariant (for example, a CHECK constraint on a column that did not exist as a constraint in the source but was enforced by application code).

    -- Row-count parity query, run on both source and target
    SELECT 'orders' AS table_name, COUNT(*) AS rows FROM orders
    UNION ALL SELECT 'order_items', COUNT(*) FROM order_items
    UNION ALL SELECT 'customers', COUNT(*) FROM customers
    UNION ALL SELECT 'products', COUNT(*) FROM products
    ORDER BY table_name;
    

    📊 Limit: Database Migration Service's built-in validation runs a row-count check, not a row-content check. Two tables with the same row count can still have divergent data if a CDC event was dropped silently due to schema mismatch (a column added on the source after the dump but not propagated). For workloads where data correctness is non-negotiable (financial systems, regulated workloads), the engineer must add an application-level checksum query to the cutover validation pass.

    Determining the correct database migration tools for a given scenario

    The final subsection assembles the tools introduced above into a decision framework. The framework's input is a scenario description (source engine, source version, target engine, downtime tolerance, schema complexity), and the output is a tool recommendation that the engineer can defend in a design review.

    Tool inventory

    The full Google Cloud-native and partner-supported tool set:

    ToolSource enginesTarget enginesCDCDowntime profile
    Database Migration ServicePostgreSQL, MySQL, SQL Server, Oracle (Oracle source in preview)Cloud SQL (matching engine), AlloyDB for PostgreSQL (from PostgreSQL or Oracle)YesZero / near-zero
    DatastreamOracle, MySQL, PostgreSQL, SQL ServerBigQuery, Cloud Storage, Pub/SubYesStreaming (analytics, not OLTP target)
    Storage Transfer ServiceCloud Storage, S3, Azure Blob, on-prem file sourceCloud StorageNoBatch
    pg_dump / pg_restorePostgreSQLPostgreSQLNoExtended outage
    mysqldump / mysqlMySQL, MariaDBMySQLNoExtended outage
    PgloaderMySQL, MS SQL Server, SQLite, dBase, IXFPostgreSQLNoExtended outage
    Ora2pgOraclePostgreSQLNoSchema conversion plus extended-outage data move
    SSMASQL Server, Oracle, MySQL, Sybase, AccessPostgreSQL, MySQL, Azure SQLNoSchema conversion plus assisted data move
    AlloyDB OmniPostgreSQLAlloyDB Omni on-prem / multi-cloud, then to managed AlloyDB via DMSNo (engine-level)Staging-only for hybrid
    Striim / Fivetran HVR / Qlik Replicate / Confluent ReplicatorMost enterprise RDBMS and CDC sourcesMost targets including Cloud SQL, AlloyDB, SpannerYesZero / near-zero, heterogeneous
    Spanner Migration Tool (open source)MySQL, PostgreSQL, DynamoDB, CSVSpannerSchema conversion + bulk load + optional CDCNear-zero with HarbourBridge / data dump
    Dataflow templates (MySQL to Spanner, Cassandra to Spanner, etc.)VariousSpanner, Bigtable, FirestoreBatchExtended outage
    Cloud Bigtable HBase replicationHBaseBigtableYesNear-zero
    Firestore managed export / importFirestoreFirestore (cross-region or cross-project)NoExtended outage

    Decision matrix

    The decision tree below is the engineer's mental model for tool selection. The questions are asked in order; the first matching branch produces the recommendation.

    Worked examples

    Examples

    The framework is most useful when applied to specific scenarios. Five worked examples follow.

    Example 1: 800 GB Oracle 19c OLTP to AlloyDB, near-zero downtime, complex PL/SQL.

    The schema includes 400 stored procedures, 120 triggers, and heavy use of DBMS_SCHEDULER for in-database batch jobs. The application can tolerate a 15-minute write freeze for cutover but not the multi-hour freeze a dump-and-restore would require for 800 GB.

    Recommendation: Ora2pg for schema conversion (3 to 6 weeks of iteration with the application team to rewrite stored procedures and triggers), Database Migration Service with the Oracle source preview path for the data load and CDC. The DBMS_SCHEDULER jobs are migrated separately to Cloud Scheduler plus Cloud Run jobs (the pattern from the operations chapter) because PostgreSQL does not have an in-database scheduler equivalent. Cutover is the standard near-zero pattern: stop writes, drain CDC, promote, repoint.

    Fallback: reverse replication is built using Striim or Qlik Replicate because Database Migration Service does not provide reverse support for the Oracle path. The reverse channel is armed for 72 hours after cutover, then decommissioned.

    Example 2: 50 GB MySQL 8 e-commerce database to Cloud SQL for MySQL, true zero downtime required.

    The application is an active e-commerce checkout. Any write freeze longer than a few seconds loses revenue.

    Recommendation: Database Migration Service homogeneous MySQL path with continuous CDC. Source pre-flight (binlog_format = ROW, binlog_row_image = FULL, gtid_mode = ON, binary log retention raised to seven days). Network path through Private Service Connect. Cutover plan uses application-level dual-write coordination (the application briefly writes to both source and target during a 30-second window, then cuts to target-only) to achieve true zero data loss.

    Fallback: Database Migration Service reverse replication job, armed for 24 hours. Example 3: 4 TB SQL Server data warehouse to BigQuery for analytics.

    The source is a SQL Server-based data warehouse, the target is BigQuery for downstream analytics. There is no OLTP cutover; the BigQuery copy is a read-only analytical replica.

    Recommendation: Datastream for SQL Server to BigQuery CDC. The Datastream stream captures changes from the SQL Server transaction log and writes them into BigQuery via the BigLake / staging-table pattern. Initial load is handled by Datastream's backfill mechanism. There is no cutover because the original SQL Server stays in place; BigQuery is purely additive.

    Fallback: none required for the analytical replica; the source remains the system of record.

    Example

    Example 4: 200 GB PostgreSQL 14 to Spanner with application rewrite.

    The team wants to escape PostgreSQL's single-region scaling limits and move to globally consistent SQL on Spanner. The application is being rewritten anyway as part of the move.

    Recommendation: Spanner Migration Tool (HarbourBridge) to convert the PostgreSQL schema into a Spanner-compatible schema (primary keys become Spanner primary keys, foreign keys become Spanner interleaved tables where appropriate, sequences become UUID generation), bulk load using the tool's data-import path, and CDC during the application rewrite window using Datastream PG to Pub/Sub plus a Dataflow pipeline that applies into Spanner. Cutover is gated by the application rewrite, not by the database move.

    Fallback: keep the PostgreSQL source running in parallel for two weeks; rollback is an application configuration change, not a database operation.

    Example 5: 5 GB on-premises MariaDB to Cloud SQL for MySQL, extended outage acceptable.

    The database serves an internal HR system that is idle outside business hours. The team has a maintenance window every Saturday night.

    Recommendation: mysqldump with --single-transaction --routines --triggers --events during the maintenance window, upload to Cloud Storage, restore into Cloud SQL for MySQL via the Console import path or gcloud sql import sql. Total downtime: under 30 minutes for a database this size. No CDC, no Database Migration Service complexity, no reverse replication.

    Fallback: the dump file itself is the rollback artifact; restore on the original source if the new target misbehaves within the rollback window.

    # Example 5: extended-outage MariaDB to Cloud SQL for MySQL
    mysqldump \
     --host=source.internal \
     --user=root \
     --password \
     --single-transaction \
     --routines --triggers --events \
     --set-gtid-purged=OFF \
     --databases hr_app \
     > /var/dumps/hr_app.sql
    
    gsutil cp /var/dumps/hr_app.sql gs://acme-migration-staging/hr_app.sql
    
    gcloud sql import sql hr-mysql gs://acme-migration-staging/hr_app.sql \
     --database=hr_app
    

    💡 Exam Trap: --set-gtid-purged=OFF is required when importing into Cloud SQL for MySQL if the source has GTIDs enabled and the target Cloud SQL instance does not have a matching GTID configuration. Forgetting the flag causes the import to fail with a confusing error about GTID consistency on a target that the engineer never configured for GTIDs.

    When tooling does not exist

    Not every migration has a Google Cloud-supplied tool.

    For sources like Sybase IQ, Teradata, Vertica, or specialized graph databases, the engineer falls back to the engine's native export format (typically CSV or Parquet to object storage), uses Storage Transfer Service to land the data in Cloud Storage, and then uses Dataflow or BigQuery's external table mechanism to load the data into the target.

    Schema conversion is manual in these cases; the engineer writes the target DDL by hand using the source DDL as a reference.

    For NoSQL sources (Cassandra to Bigtable, MongoDB to Firestore), the engine-specific patterns are:

    • Cassandra to Bigtable. The Dataflow Cassandra to Bigtable template reads from Cassandra and writes to Bigtable. Row key design must be reconciled (Cassandra's partition-key-plus-clustering-key model maps onto Bigtable's single row key with a documented concatenation strategy).
    • MongoDB to Firestore. No managed template exists. The pattern is mongoexport to JSON files in Cloud Storage, then a custom Dataflow pipeline (or Cloud Run job for small data sets) that reads the JSON and writes Firestore documents. Schema conversion is application-driven because MongoDB documents are schemaless.
    • DynamoDB to Spanner. The Spanner Migration Tool has a DynamoDB path that reads from a DynamoDB export in S3 (transferred to Cloud Storage via Storage Transfer Service) and writes into Spanner. The hash-key plus sort-key DynamoDB model becomes a composite primary key in Spanner.

    The role of partner tooling

    Google Cloud's partner network includes ISVs that ship purpose-built replication products. The decision to bring in a partner usually comes from one of three constraints:

    • The source-target pair is not supported by Database Migration Service (SQL Server to AlloyDB, Oracle to Spanner, MongoDB to Cloud SQL, etc.).
    • The team needs richer validation (per-row checksums, schema-drift alerts, cell-level conflict detection) than Database Migration Service provides.
    • The team already standardizes on a CDC platform (Striim, Fivetran HVR, Qlik Replicate, Confluent Connect with Debezium) for other replication use cases and wants to use the same tool for the migration.

    Partner tooling is licensed separately, runs on partner-supplied or Compute Engine-hosted replicator nodes, and requires a support relationship with the vendor. The engineer should document the partner tool's exact version, license terms, and runbook ownership in the migration plan so that the operations team knows who to call when the replicator misbehaves.

    🎯 Scenario: A retail platform is moving from a self-managed PostgreSQL 14 cluster on AWS to AlloyDB for PostgreSQL in Google Cloud. The database is 1.2 TB, the application is multi-tenant SaaS with a strict 15-minute monthly maintenance window, and the team has six weeks to complete the move. The plan: week 1, schema review and Hyperdisk sizing for AlloyDB; week 2, stand up Private Service Connect from the AWS VPC to the AlloyDB VPC; week 3, run a Database Migration Service job in a staging Google Cloud project against a sanitized copy of production to measure dump time (8 hours) and CDC catch-up time (under 1 minute); week 4, application rewrite for AlloyDB-specific features (read pool routing, AlloyDB AI vector queries replacing the previous Pinecone integration); week 5, production migration job starts on a Sunday afternoon, dump completes Monday morning, CDC catches up by Monday evening; week 6, cutover during the monthly maintenance window with a 12-minute write freeze, reverse replication via Striim armed for 72 hours, decommission of the AWS cluster after the stabilization period closes. Tool stack: Database Migration Service for forward CDC, Striim for reverse, Ora2pg not needed (homogeneous PostgreSQL), pgaudit from the operations chapter for cutover-time audit logging, Cloud Monitoring alerts on replication lag throughout the operation.

    ⚠️ Anti-Pattern: Picking the migration tool before completing the source inventory. Tool selection depends on engine, version, edition, schema complexity, data volume, downtime tolerance, and network topology. An engineer who picks Database Migration Service before discovering that the source Oracle database uses MERGE statements with Oracle-specific syntax inside packaged procedures will end up retrofitting Ora2pg into the plan halfway through. The source inventory must be complete before the tool decision is made.

    📊 Limit: Database Migration Service for PostgreSQL does not migrate large objects (LARGE OBJECT interface, not BYTEA) by default. Tables that use pg_largeobject must be handled separately, either by converting to BYTEA before the migration or by using pg_dump/pg_restore for the large-object content while Database Migration Service handles the rest. The check is simple: SELECT COUNT(*) FROM pg_largeobject_metadata on the source; a non-zero result means the engineer needs a parallel plan for those bytes.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the GCP - Professional Cloud Database Engineer learning hub.