Migrate a self-managed PostgreSQL database to AnalyticDB for MySQL 3.0

Updated at:

This topic describes how to use Data Transmission Service (DTS) to migrate data from a self-managed PostgreSQL database to an AnalyticDB for MySQL AnalyticDB for MySQL3.0 cluster. DTS supports schema migration, full data migration, and incremental data migration, so you can continue to receive source changes while historical data is migrated.

Prerequisites

  • A self-managed PostgreSQL source database is deployed, and a destination AnalyticDB for MySQL AnalyticDB for MySQL3.0 cluster is created.

    For information about the supported versions of the source and destination databases, see Overview of migration scenarios.

    The destination AnalyticDB for MySQL cluster has enough space for the data to be migrated and for the additional storage consumed during writes. For instructions, see Create a cluster.Create a cluster

  • Network connectivity and account authorization from the source and destination databases to DTS are complete. For configuration instructions, see Preparations.

  • The primary keys, data types, and value ranges of the tables to be migrated are verified against Migration scope and limits, and objects that do not meet those limits are handled in advance.

  • If incremental data migration is included, logical replication is enabled on the source database, and WAL logs are prepared to cover the full data migration phase, failure retries, and incremental catch-up.

Migration scope and limits

Note
  • DTS migrates foreign keys during schema migration.

  • During full and incremental data migration, DTS temporarily disables constraint checks and foreign key cascades at the session level. Cascade updates or deletes on the source database while the task runs may cause data inconsistency.

  • DTS does not support performing a full migration in multiple stages; the full migration must be completed in a single operation. If you need to migrate data in batches, please configure multiple migration tasks.

Note

This scenario migrates data between heterogeneous databases. DTS migrates table schemas and data. The destination database does not recreate PostgreSQL sequences, functions, triggers, views, materialized views, custom type objects, regular indexes, unique indexes, foreign keys, or CHECK constraints. Converting a custom-type column to a string does not mean that the corresponding type object or its operation rules are also migrated.

Type

Description

Source database limits

Tables with generated columns in PostgreSQL 18 do not support migration. If you configure migration for such tables, DML operations on those tables will be blocked.

  • Bandwidth requirement: The server that hosts the source database must have sufficient outbound bandwidth. Otherwise, the data migration speed will be reduced.

  • Tables that you migrate must have a primary key or a unique constraint, and the columns in the constraint must be unique. Otherwise, duplicate data may occur in the target database.

    Note

    If the destination table was not created by Data Transmission Service (DTS) because you did not select Schema Migration as the Migration Types, you must ensure that the destination table has the same primary key or non-null unique constraint as the source table. Otherwise, duplicate data may occur in the destination database.

    The name of the database to be migrated cannot contain hyphens (-), for example, dts-testdata.

  • If you select tables as migration objects and need to edit them, for example, by mapping table or column names, a single migration instance supports a maximum of 1,000 tables. If this limit is exceeded, the task reports an error upon submission. In this case, split the tables into multiple migration instances or configure a single instance to migrate the entire database.

  • If you perform an incremental migration, the following requirements for Write-Ahead Logging (WAL) apply:

    • The wal_level parameter must be set to logical.

    • For a task that performs only incremental migration, DTS requires that the WAL logs in the source database be retained for more than 24 hours. For a task that performs both full and incremental migration, DTS requires that the WAL logs be retained for at least 7 days. You can change the retention period to more than 24 hours after the full migration is complete. If DTS cannot obtain the required WAL logs, the migration instance may fail. In extreme cases, data inconsistency or loss may occur. Issues caused by a WAL log retention period shorter than the required duration are not covered by the DTS Service Level Agreement (SLA).

  • Limits on operations in the source database:

    • A primary/secondary switchover of the self-managed PostgreSQL database will cause the migration instance to fail.

    • During the full migration phase, do not perform DDL operations that change the database or table schemas. Otherwise, the migration instance will fail.

    • Due to the limitations of logical subscriptions, if a migration instance that includes incremental data migration is running and the size of a single row to be migrated exceeds 256 MB after an incremental change, the migration instance fails irrecoverably, and you must reconfigure it.

    • If you perform only a full data migration, do not write new data to the source database. Otherwise, data inconsistency will occur between the source and target databases. To maintain real-time data consistency, select both Full Data Migration and Incremental Data Migration.

  • If the source database has long-running transactions and the instance is configured for incremental migration, Write-Ahead Logging (WAL) files generated before the transactions are committed cannot be cleared. This may cause the logs to accumulate and lead to insufficient disk space in the source database.

  • If the source instance is Cloud SQL for PostgreSQL, you must specify an account with the cloudsqlsuperuser permission in the Database Account field. When you select the migration objects, select objects that this account is authorized to manage. Alternatively, grant the OWNER role for the objects to this account (for example, run the GRANT <owner_of_the_object_to_be_migrated> TO <source_database_account_used_by_the_task> command).

    Note

    An account with the cloudsqlsuperuser permission cannot manage data owned by another cloudsqlsuperuser account.

  • If you perform a major version upgrade on the source database while a migration instance is running, the instance fails irrecoverably, and you must reconfigure it.

  • Tables with generated columns in PostgreSQL 18 do not support migration. If you configure migration for such tables, DML operations on those tables will be blocked.

Other limits

  • Append-optimized (AO) tables are not supported as target tables.

  • DTS does not support migrating DATATYPE, SEQUENCE, INDEX, PROCEDURE, FUNCTION, VIEW, OPERATOR, DEFAULT_CONSTRAINT, UK, PK, RULE, DOMAIN, AGGREGATE, EXTENSION, FK, or TRIGGER objects.

  • If you use column mapping for a partial table migration, or if the source and target table schemas are different, data in columns that exist only in the source table will be lost.

  • For tasks that include incremental data migration, you must run the ALTER TABLE schema.table REPLICA IDENTITY FULL; command on the tables to be migrated in the source database before you write data to them. This ensures data consistency for the tables in the following two scenarios. To prevent deadlocks, avoid table-locking operations while this command runs. If you skip the related checks during the precheck, DTS automatically runs this command when it initializes the instance.

    • When the instance runs for the first time.

    • When the migration object granularity is set to Schema and a new table is created in the schema or an existing table is rebuilt by using the RENAME command.

    Note
    • In the command, replace schema and table with the schema name and table name of the data to be migrated.

    • Perform this operation during off-peak hours.

  • DTS creates the following temporary tables in the source database to obtain information such as DDL statements for incremental data, the schemas of incremental tables, and heartbeat data. Do not delete these temporary tables during migration. Otherwise, the DTS instance may fail. The temporary tables are automatically deleted after the DTS instance is released.

    public.dts_pg_class, public.dts_pg_attribute, public.dts_pg_type, public.dts_pg_enum, public.dts_postgres_heartbeat, public.dts_ddl_command, public.dts_args_session, and public.aliyun_dts_instance.

  • To ensure the accuracy of the incremental data migration latency display, DTS creates a heartbeat table named dts_postgres_heartbeat in the source database.

  • During incremental data migration, DTS creates a replication slot with the prefix dts_sync_ in the source database to read incremental data.

    Note

    When a migration instance is released or fails, DTS automatically cleans up the replication slot. If a primary/secondary switchover occurs on the source database, you must log on to the secondary database to manually clean up the slot.

  • A single migration instance can migrate data from only one database. To migrate multiple databases, you must configure a separate migration instance for each.

  • DTS does not support migrating TimescaleDB extension tables, tables with cross-schema inheritance, or tables with expression-based unique indexes.

  • Schemas created by plug-ins cannot be migrated and are not available for selection in the console during task configuration.

  • If a table to be migrated has a primary key, the primary key column in the destination table must be the same as that in the source table. If a table to be migrated does not have a primary key, the primary key column in the destination table must be the same as the distribution key.

  • The unique key of the destination table, including the primary key column, must contain all columns of the distribution key.

  • Before you migrate data, evaluate the performance of the source and destination databases. Perform data migration during off-peak hours. During full data migration, DTS consumes read and write resources on both the source and destination databases, which may increase the database load.

  • Full data migration involves concurrent INSERT operations, which can cause table fragmentation in the target database. As a result, tables in the target database will use more storage space than those in the source database after the full migration is complete.

  • Confirm whether the migration precision for columns of the FLOAT or DOUBLE data type meets your business requirements. DTS uses the ROUND(COLUMN,PRECISION) function to read values from these columns. If you do not explicitly define a precision, DTS uses a precision of 38 digits for FLOAT and 308 digits for DOUBLE.

  • DTS attempts to recover failed migration tasks within seven days. Therefore, before you switch your business to the destination instance, you must end or release the task, or use the revoke command to revoke the write permissions of the account that DTS uses to access the destination instance. This prevents an automatically recovered task from overwriting data on the destination instance with data from the source instance.

  • DTS validates data content but does not support validating metadata such as sequences. You must validate the metadata yourself.

  • After you switch your workloads to the target database, new sequence values will not increment from the maximum value of the corresponding sequences in the source database. Before you switch, you must query the maximum value of the sequence in the source database and then set it as the starting value for the corresponding sequence in the target database. You can run the following command to query sequence values in the source database:

    do language plpgsql $$
    declare
      nsp name;
      rel name;
      val int8;
    begin
      for nsp,rel in select nspname,relname from pg_class t2 , pg_namespace t3 where t2.relnamespace=t3.oid and t2.relkind='S'
      loop
        execute format($_$select last_value from %I.%I$_$, nsp, rel) into val;
        raise notice '%',
        format($_$select setval('%I.%I'::regclass, %s);$_$, nsp, rel, val+1);
      end loop;
    end;
    $$;
    Note

    The command output contains SQL statements for all sequences in the source database. Run the required statements on the target database based on your business requirements.

  • If a task fails, DTS support staff will attempt to restore it within eight hours. During restoration, they may restart the task or adjust its parameters.

    Note

    Only DTS task parameters are modified—not database parameters. Parameters that may be adjusted include those listed in Modify instance parameters.

  • When you migrate a partitioned table, you must include both the parent table and its child partitions as migration objects. Otherwise, data in the partitioned table may become inconsistent.

    Important
    • The parent table of a PostgreSQL partitioned table does not store data directly. All data is stored in its child partitions. A data migration task must include the parent table and all its child partitions. Otherwise, data in the child partitions may be missed, which leads to data inconsistency between the source and destination.

    • Migration of partitioned tables and inheritance tables (parent-child tables) across different databases is not supported. Ensure that the partitioned table and all its partitions are in the same database. Also, ensure that the parent table and all its child tables are in the same database.

TypeDescription
Source database limitationA single task can migrate only one PostgreSQL database. Configure a separate task for each additional database.
Source database limitationThe tables to be migrated must have a primary key, and all primary key columns must be included in the migration objects. When a table is created during the incremental phase, CREATE TABLE must define a primary key. CREATE TABLE statements without a primary key are skipped. A UNIQUE constraint alone does not meet this requirement.
Source database limitationIf incremental data migration is included, enable logical replication. wal_level, max_wal_senders, max_replication_slots, and the number of replication slots must meet the check requirements described in Preparations.
Source database limitationThe WAL log retention period must meet the requirements of the decision table in Migration types. Long-running transactions and consumption delays can cause WAL files to accumulate. Monitor the disk space of the source database. For more source database requirements, see Precautions and limits for PostgreSQL source databases.
Source database limitationDo not run DDL operations on the migration objects during schema migration or full data migration. Do not perform a major engine version upgrade while the task is running. Do not treat a primary/secondary switchover of a self-managed PostgreSQL database as a scenario that can automatically resume transmission.
Source database limitationIncremental DDL support is limited to the operations listed in SQL operations supported for incremental data migration. DDL operations outside that scope are not automatically converted. Regular one-dimensional array columns can be migrated as strings.
Source database limitationMONEY columns carry a risk of data read failures. Their schema can be mapped to DECIMAL(19,2), but some data read scenarios fail. Organize the data to be migrated into verified NUMERIC columns before you configure the task.
Destination database limitationDestination tables must have a custom primary key that uniquely identifies source records. When you create destination tables in advance, make sure that the primary key matches the source table and includes the distribution key and partition key required by the destination table. Do not rely on a primary key automatically generated by the destination database to associate source records.
Destination database limitationPostgreSQL geometric types and arrays are stored as VARCHAR. They cannot be migrated directly to native AnalyticDB for MySQL POINT or ARRAY types. AnalyticDB for MySQL 3.0 supports these types, but that does not mean this link supports the corresponding native type conversion.
Destination database limitationValues must fall within the value range of the destination column. Automatic schema conversion cannot be relied on for NUMERIC with a negative scale, a scale greater than the precision, or a definition that exceeds the destination DECIMAL precision limit. For NUMERIC without a specified precision, confirm the destination precision and the actual value range first.
Other limitationsThe character sets of the source and destination databases must be compatible. Time values are written in the configured destination time zone. The original time zone name or offset is not retained as a separate attribute. Time precision is handled at millisecond level at most, and the microsecond and nanosecond parts may be truncated.
Other limitationsSequence values, identity column values, time values, and UUID values are taken from the data already generated on the source. Do not configure dynamic default values or auto-generation expressions on destination tables to fill in values, and do not use the current time of the destination database in place of source values.
Other limitationsFor tables with dynamic default values, verify the destination CREATE TABLE definition before you start data migration. If the automatically generated definition still contains dynamic expressions such as CURRENT_TIMESTAMP, create the destination tables without those expressions in advance and disable schema migration. Remove dynamic default values even when the destination column already has explicitly written values.
Other limitationsWhen tables are created, columns are added, or column types are changed during incremental migration, the DEFAULT, regular NOT NULL, and auto-generation attributes of the source columns are not retained. The primary key requirements must still be met. Existing destination rows are not automatically backfilled with source default values.
Other limitationsBoth full and incremental writes can overwrite records with the same primary key in the destination table. Use a dedicated destination table. Other applications must not write to the same destination table while the task is running.
Other limitationsSome DDL operations that cannot be parsed or are unsupported trigger alerts and are skipped. A task that continues to run does not mean that the table schemas remain consistent. Use the task logs to verify the destination table schemas.

Billing

Migration type

Instance configuration fee

Internet traffic fee

Schema migration and full data migration

Free of charge.

When the Access Method parameter of the destination database is set to Public IP Address, you are charged for Internet traffic. For more information, see Billing overview.

Incremental data migration

Charged. For more information, see Billing overview.

Important

For tables with generated columns, a successfully converted CREATE TABLE statement does not prove that the data migrates correctly. Generation expressions are not retained in the destination. First confirm that the source can output the required column values and that full and incremental results are consistent. Do not include such tables before this verification is complete.

Migration types

  • Schema migration

    DTS migrates the schema definitions of the migration objects from the source database to the destination database.

  • Full migration

    DTS migrates all historical data of the specified migration objects from the source database to the destination database.

  • Incremental migration

    After a full migration is complete, DTS migrates incremental data updates from the source database to the destination database. Incremental migration lets you smoothly migrate data without interrupting your self-managed applications.

Migration typeDescription
Schema migrationCreates compatible table schemas in the destination database and converts column types and primary keys according to the rules for this scenario. Not all source database objects and constraints are guaranteed to be retained.
Full data migrationReads historical records from the tables to be migrated and writes them to the destination tables.
Incremental data migrationContinuously reads data changes from source WAL logs and writes them to the destination database. For the supported DDL scope, see SQL operations supported for incremental data migration.

Select a migration type combination from the following table based on your write suspension window and costs:

ScenarioMigration type combinationWrite suspension requirementWAL log retentionLink configuration fees
Migrate historical data onlySchema migration and full data migrationStop writes to source tables during migrationNot applicableNo link configuration fees are charged
Migrate historical data while continuously receiving source changesSchema migration, full data migration, and incremental data migrationSource tables can continue to accept writes during migration. Stop writes and validate the data before the final switchover.Retain for at least 7 days when full and incremental data migration run together. After the full data migration phase is complete, you can reduce this to at least 24 hours. Retain for at least 24 hours when only incremental data migration runs.Incremental data migration is charged. For the billing rules, see Billing overview. No link configuration fees are charged for schema migration or full data migration.

Billing

For the link configuration fees of each migration type combination, see the decision table in Migration types. The source database, the destination database, and the related network resources are charged according to the rules of the corresponding products. If Internet traffic is involved, also check the DTS traffic billing conditions.

Preparations

  1. Prepare database accounts based on the phases that the task requires.

    DatabasePermission requirements
    Self-managed PostgreSQLFor schema migration and full data migration only, the account must have metadata access and read permissions on the tables to be migrated. If incremental data migration is included, prepare an account with superuser permissions according to the requirements for a self-managed PostgreSQL source database.
    AnalyticDB for MySQLAnalyticDB for MySQL AnalyticDB for MySQL3.0Read and write permissions on the destination database. If schema processing or incremental DDL is included, the account must also be able to run the corresponding CREATE TABLE, ALTER TABLE, and DROP TABLE operations.

    For account requirements, see Prepare database accounts for data migration or Prepare database accounts for data synchronization.Create a database account

    Prerequisites

    Note

    Follow these steps for all versions of self-managed PostgreSQL.

    1. Log in to the server hosting your self-managed PostgreSQL database.

    2. Run the following command to query the number of used replication slots in the database.

      select count(1) from pg_replication_slots;
    3. Modify the postgresql.conf configuration file. Set the wal_level parameter to logical, and ensure that the max_wal_senders and max_replication_slots parameters are greater than the number of used replication slots plus the number of DTS instances that you plan to create.

      # - Settings -
      
      wal_level = logical			# minimal, replica, or logical
      					# (change requires restart)
      
      ......
      
      # - Sending Server(s) -
      
      # Set these on the master and on any standby that will send replication data.
      
      max_wal_senders = 10		# max number of walsender processes
      				# (change requires restart)
      #wal_keep_segments = 0		# in logfile segments, 16MB each; 0 disables
      #wal_sender_timeout = 60s	# in milliseconds; 0 disables
      
      max_replication_slots = 10	# max number of replication slots
      				# (change requires restart)
      Note

      After you modify the configuration file, you must restart the self-managed PostgreSQL database to apply the changes.

    4. Add the CIDR blocks of DTS servers to the pg_hba.conf configuration file of your self-managed PostgreSQL database. You only need to add the CIDR blocks for the DTS servers in the region where your destination database is located. For more information, see Add the CIDR blocks of DTS servers to a whitelist.

      Note
      • After you modify the configuration file, run the SELECT pg_reload_conf(); command or restart the self-managed PostgreSQL database to apply the changes.

      • For more information about the settings in this configuration file, see The pg_hba.conf File. If you have already set the trusted address to 0.0.0.0/0 (as shown in the following example), you can skip this step.

      In the pg_hba.conf file, set the addresses for IPv4 connections and replication connections to 0.0.0.0/0 and the authentication method to md5. Sample configuration:

      # "local" is for Unix domain socket connections only
      local   all             all                                     trust
      # IPv4 local connections:
      host    all             all             0.0.0.0/0               md5
      # IPv6 local connections:
      host    all             all             ::1/128                 trust
      # Allow replication connections from localhost, by a user with the
      # replication privilege.
      local   replication     postgres                                trust
      host    replication     postgres        0.0.0.0/0               md5
    5. In the destination database instance, create databases and schemas that correspond to the source objects you are migrating.

    For self-managed PostgreSQL versions 9.4.8 to 10.0, follow these additional steps.

    1. Download, compile, and install the PostgreSQL source code.

      1. Download the source code for your self-managed PostgreSQL version from the PostgreSQL official website.

      2. Run the sudo ./configure, sudo make, and sudo make install commands in sequence to configure, compile, and install the source code.

        Important
        • When you compile and install PostgreSQL, the operating system version must be compatible with the GNU Compiler Collection (GCC) version.

        • If an error occurs when you run the sudo ./configure command, you can modify the command based on the error message. For example, if the error message is readline library not found. Use --without-readline to disable readline support., change the command to sudo ./configure --without-readline.

        • If you install PostgreSQL by using another method, you must compile the ali_decoding plugin in a test environment that uses the same operating system and GCC versions as your production environment.

    2. Download, compile, and install the ali_decoding plugin provided by DTS.

      1. Download ali_decoding.

      2. Copy the entire ali_decoding directory to the contrib directory of your PostgreSQL installation.

        total 1008
        -rw-r--r--  1 1107 1107    384 Sep 27  2016 aclocal.m4
        drwxrwxrwx  2 1107 1107   4096 Sep 27  2016 config
        -rw-r--r--  1 root root 374806 Sep  7 10:10 config.log
        -rwxr-xr-x  1 root root  39032 Sep  7 10:10 config.status
        -rwxr-xr-x  1 1107 1107 471157 Sep 27  2016 configure
        -rw-r--r--  1 1107 1107  75195 Sep 27  2016 configure.in
        drwxrwxrwx 56 1107 1107   4096 Sep  7 10:28 contrib
        -rw-r--r--  1 1107 1107   1192 Sep 27  2016 COPYRIGHT
        drwxrwxrwx  3 1107 1107   4096 Sep 27  2016 doc
        -rw-r--r--  1 root root   3638 Sep  7 10:10 GNUmakefile
        -rw-r--r--  1 1107 1107   3638 Sep 27  2016 GNUmakefile.in
        -rw-r--r--  1 1107 1107    283 Sep 27  2016 HISTORY
        -rw-r--r--  1 1107 1107  75065 Sep 27  2016 INSTALL
        -rw-r--r--  1 1107 1107   1489 Sep 27  2016 Makefile
        -rw-r--r--  1 1107 1107   1209 Sep 27  2016 README
        drwxrwxrwx 16 1107 1107   4096 Sep  7 10:10 src
      3. Go to the ali_decoding directory and replace the contents of the Makefile file with the following code:

        # contrib/ali_decoding/Makefile
        MODULE_big = ali_decoding
        MODULES = ali_decoding
        OBJS    = ali_decoding.o
        
        DATA = ali_decoding--0.0.1.sql ali_decoding--unpackaged--0.0.1.sql
        
        EXTENSION = ali_decoding
        
        NAME = ali_decoding
        
        #subdir = contrib/ali_decoding
        #top_builddir = ../..
        #include $(top_builddir)/src/Makefile.global
        #include $(top_srcdir)/contrib/contrib-global.mk
        
        #PG_CONFIG = /usr/pgsql-9.6/bin/pg_config
        #pgsql_lib_dir := $(shell $(PG_CONFIG) --libdir)
        #PGXS := $(shell $(PG_CONFIG) --pgxs)
        #include $(PGXS)
        
        # Use the following for source code installation
        ifdef USE_PGXS
        PG_CONFIG = pg_config
        PGXS := $(shell $(PG_CONFIG) --pgxs)
        include $(PGXS)
        else
        subdir = contrib/ali_decoding
        top_builddir = ../..
        include $(top_builddir)/src/Makefile.global
        include $(top_srcdir)/contrib/contrib-global.mk
        endif
      4. Go to the ali_decoding directory. Run the sudo make and sudo make install commands in sequence to compile the ali_decoding plugin and generate the required installation files.

      5. Copy the following files to the specified locations.

        /usr/bin/install -c -m 755  ali_decoding.so '/usr/local/pgsql/lib/ali_decoding.so'
        /usr/bin/install -c -m 644 ./ali_decoding.control '/usr/local/pgsql/share/extension/'
        /usr/bin/install -c -m 644 ./ali_decoding--0.0.1.sql ./ali_decoding--unpackaged--0.0.1.sql  '/usr/local/pgsql/share/extension/'
        /usr/bin/install -c -m 755  ali_decoding.so '/usr/local/pgsql/lib/'
    3. In the destination database instance, create databases and schemas that correspond to the source objects you are migrating.

  2. If incremental data migration is included, configure logical replication on the source database and run the following queries to check whether the parameters have taken effect.

    SHOW wal_level;
    SHOW max_wal_senders;
    SHOW max_replication_slots;
    SELECT count(*) FROM pg_replication_slots;

    • wal_level must return logical.

    • max_wal_senders and max_replication_slots must both be greater than the sum of the number of replication slots in use (the count returned by pg_replication_slots) and the number of DTS instances that you plan to create.

      Configure the logical decoding component according to the source database version. Earlier versions require the additional installation of ali_decoding. For configuration instructions, see Prepare a self-managed PostgreSQL source database. For parameters that take effect only after a restart, check them again after you restart the database during a maintenance window.
  3. Configure the network access control of the source database and pg_hba.conf to allow database and replication connections from DTS servers in the applicable region. For the specific CIDR blocks, see Add the CIDR blocks of DTS servers to the security settings of on-premises databases.

  4. If incremental data migration is included, set full replica identity for the tables to be migrated before the first run, before you add migration objects, or before you include a new table in the migration.

    ALTER TABLE schema_name.table_name REPLICA IDENTITY FULL;
    Note

    Replace schema_name and table_name with the actual names, and run the statement during off-peak hours. This setting does not replace a primary key. If DDL operations must be migrated, also retain the DDL collection objects, heartbeat tables, and replication slots that DTS creates. Do not delete these objects while the task is running.

  5. Verify the destination primary keys, data types, time zones, and default values. For tables that require a custom destination schema, create the tables in the destination database in advance and make sure that the columns can fully receive the source records.

Procedure

This procedure uses a self-managed PostgreSQL database on an Alibaba Cloud ECS instance as the source and AnalyticDB for MySQL 3.0 as the destination, and describes how to configure a one-way migration.

  1. Navigate to the migration task list page for the destination region using one of the following methods.

    From the DTS console

    1. Log on to the Data Transmission Service (DTS) console.

    2. In the navigation pane on the left, click Data Migration.

    3. In the upper-left corner of the page, select the region where the migration instance is located.

    From the DMS console

    Note

    The actual operations may vary based on the mode and layout of the DMS console. For more information, see Simple mode console and Customize the layout and style of the DMS console.

    1. Log on to the Data Management (DMS) console.

    2. In the top menu bar, choose Data + AI > Data Transmission (DTS) > Data Migration.

    3. To the right of Data Migration Tasks, select the region where the migration instance is located.

  2. Click Create Task to navigate to the task configuration page.

  3. Open the data migration task list in the destination region.

    • Open it from the DTS console: Log on to the Data Transmission Service (DTS) console, in the left-side navigation pane, choose Data Migration, and switch to the region where the task resides.

    • Open it from the DMS console: Log on to the DMS console. From the top menu, choose Data + AI > Data Transmission (DTS) > Data Migration, and then select the region of the task.

  4. Click Create Task.

  5. Configure the source and destination database information.

    Warning

    Before you configure the task, check Data type mappings and SQL operations supported for incremental data migration. The source database accepting a SQL operation does not mean that the destination can preserve the same semantics.

    CategoryParameterDescription

    Configure the source and destination databases.

    | Basic information | Task Name |

    DTS automatically generates a task name. We recommend that you specify a descriptive name for easy identification. The name does not need to be unique.

    Enter a name that identifies the workload and the migration direction. | | Source Database | Select Existing Connection |
    • To use a database instance that has been added to the system (created or saved), select the desired database instance from the drop-down list. The database information below will be automatically configured.

      Note

      In the DMS console, this parameter is named Select a DMS database instance..

    • If you have not registered the database instance with the system, or do not need to use a registered instance, manually configure the database information below.

    If a connection is already saved, select it directly. Otherwise, enter the following information manually. | | Source database information | Database Type | Select PostgreSQL. | | Source database information | Access Method | Select based on how the source database is deployed. In this example, the source database is deployed on an ECS instance, so select Self-managed Database on ECS. For other deployment methods, select based on the actual network. Before you configure the task, complete the applicable steps in Preparations, including the network access permissions.Preparations Overview | | Source database information | Instance Region | Select the region where the source database is located. | | Source database information | ECS Instance ID | Select the ECS instance that runs the source database. | | Source database information | Port Number | Enter the actual service port. The default PostgreSQL port is 5432. | | Source database information | Database Name | Enter the name of the PostgreSQL database that contains the objects to be migrated. | | Source database information | Encryption |

    Specifies whether to encrypt the connection to the source database. You can configure this parameter based on your business requirements. In this example, Non-encrypted is selected.

    If you want to establish an SSL-encrypted connection to the source database, perform the following steps: Select SSL-encrypted, upload CA Certificate, Client Certificate, and Private Key of Client Certificate as needed, and then specify Private Key Password of Client Certificate.

    Note
    • If you set Encryption to SSL-encrypted for a self-managed PostgreSQL database, you must upload CA Certificate.

    • If you want to use the client certificate, you must upload Client Certificate and Private Key of Client Certificate and specify Private Key Password of Client Certificate.

    • For information about how to configure SSL encryption for an ApsaraDB RDS for PostgreSQL instance, see SSL encryption.

    Select based on whether SSL encryption is enabled for the source database. If it is not enabled, select a non-encrypted connection. If it is enabled, select an SSL-encrypted connection and upload the CA certificate, the client certificate, and other materials as the interface requires. | | Source database information | Database Account and Database Password |

    Enter the password for the database account.

    Enter the source database account and password that you authorized in Preparations.Migrate data from a self-managed PostgreSQL database to AnalyticDB for PostgreSQL | | Destination Database | Select Existing Connection |
    • To use a database instance that has been added to the system (created or saved), select the desired database instance from the drop-down list. The database information below will be automatically configured.

      Note

      In the DMS console, this parameter is named Select a DMS database instance..

    • If you have not registered the database instance with the system, or do not need to use a registered instance, manually configure the database information below.

    If a connection is already saved, select it directly. Otherwise, enter the following information manually. | | Destination database information | Database Type | Select AnalyticDB for MySQL 3.0. | | Destination database information | Access Method | Select Alibaba Cloud Instance. | | Destination database information | Instance Region | Select the region of the destination cluster. | | Destination database information | Instance ID | Select the destination cluster that receives the data. | | Destination database information | Database Name | Enter the name of the database in the destination instance that contains the migration objects. | | Destination database information | Database Account and Database Password |

    Enter the password for the database account.

    Enter the account and password that have read and write permissions on the destination database and the required DDL permissions.Migrate data from a self-managed PostgreSQL database to AnalyticDB for PostgreSQL |

  6. After completing the configuration, click Test Connectivity and Proceed at the bottom of the page.

    Note
    • Ensure that you add the CIDR blocks of the DTS servers (either automatically or manually) to the security settings of both the source and destination databases to allow access. For more information, see Add the IP address whitelist of DTS servers.

    • If the source or destination is a self-managed database (i.e., the Access Method is not Alibaba Cloud Instance), you must also click Test Connectivity in the CIDR Blocks of DTS Servers dialog box.

  7. Click Test Connection and Go to Next Step. If the Authorize DTS Server Access dialog box appears, verify the network authorization for the source and destination databases, and then click Test Connection.

  8. Configure the task objects.

    a. On the Object Configuration page, configure the following parameters.

    Configure the task objects.

    ParameterDescription
    Migration Types

    • If you only need to perform a full migration, select both Schema Migration and Full Data Migration.

    • To perform a migration with no downtime, select Schema Migration, Full Data Migration, and Incremental Data Migration.

    Note
    • If you do not select Schema Migration, you must ensure that a database and tables to receive the data exist in the destination database. You can also use the object name mapping feature in the Selected Objects box as needed.

    • If you do not select Incremental Data Migration, do not write new data to the source instance during data migration to ensure data consistency.

    Based on the decision table in Migration types, select Schema Migration, Full Data Migration, and Incremental Data Migration. If the destination tables are already created as required, do not select schema migration.
    Processing Mode of Conflicting Tables
    • Precheck and Report Errors: Checks whether tables with the same names exist in the destination database. If no tables with the same names exist, the precheck is passed. If tables with the same names exist, an error is reported during the precheck, and the data migration task does not start.

      Note

      If a table in the destination database has the same name but cannot be easily deleted or renamed, you can change the name of the table in the destination database. For more information, see Object name mapping.

    • Ignore Errors and Proceed: Skips the check for tables with the same names.

      Warning

      Selecting Ignore Errors and Proceed may cause data inconsistency and business risks. For example:

      • If the table schemas are consistent and a record in the destination database has the same primary key value as a record in the source database:

        • During full migration, DTS keeps the record in the destination database. The record from the source database is not migrated.

        • During incremental migration, DTS does not keep the record in the destination database. The record from the source database overwrites the record in the destination database.

      • If the table schemas are inconsistent, only some columns of data may be migrated, or the migration may fail. Proceed with caution.

    By default, select Precheck and Report Errors. Select Ignore Errors and Continue only if you must reuse existing destination tables, and first verify their schemas, primary keys, and existing data.
    Source Objects

    In the Source Objects box, click the objects to migrate, and then click Right arrow to move them to the Selected Objects box.

    Note

    The granularity for selecting migration objects is schema, table, and column. If you select only tables or columns as migration objects, other objects such as views, triggers, and stored procedures are not migrated to the destination database.

    Select the regular tables to be migrated and move them to Selected Objects. When you select by database or by schema, also exclude the unsupported objects.
    Selected ObjectsSelected ObjectsConfigure object name mapping, column selection, and filter conditions as needed.

    You can configure the case sensitivity policy for the names of migrated objects, such as databases, tables, and columns, in the destination instance. By default, DTS default policy is selected. You can also choose to keep the case sensitivity consistent with the default policy of the source or destination database. For more information, see Case sensitivity of object names in the destination database.

    Capitalization of Object Names in Destination Instance applies to object name mapping. Do not exclude primary key columns. For instructions, see Map database, table, and column names and Set filter conditions.Filter task data with an SQL condition
    DDL and DML Operations to Be SynchronizedSelect only the SQL operations that this topic supports. To receive newly created tables, the new tables must fall within the Selected Objects scope. Do not select only CREATE TABLE without configuring the corresponding object scope.Migrate data from a self-managed PostgreSQL database to AnalyticDB for PostgreSQL
    Warning

    Ignore Errors and Continue skips only the same-name table check. It does not preserve existing destination records. Both full and incremental writes on this link can replace records that share the same primary key, and inconsistent schemas can also cause write failures. Back up the destination data that must be retained first.

    b.

    Configure the task objects.

    Click Next: Advanced Settings to configure advanced parameters.

    Click Next: Advanced Settings, and configure the advanced parameters based on your business requirements.

    ParameterDescription
    Dedicated Cluster for Task Scheduling

    By default, DTS schedules tasks on a shared cluster. You do not need to select one. If you want more stable tasks, you can purchase a dedicated cluster to run DTS migration tasks.

    No selection is required when you use a shared cluster. If you have purchased a dedicated cluster, you can select that cluster.
    Retry Time for Failed Connections

    After the migration task starts, if the connection to the source or destination database fails, DTS reports an error and immediately begins to retry the connection. The default retry duration is 720 minutes. You can customize the retry time to a value from 10 to 1440 minutes. We recommend that you set the duration to more than 30 minutes. If DTS reconnects to the source and destination databases within the specified duration, the migration task automatically resumes. Otherwise, the task fails.

    Note
    • For multiple DTS instances that share the same source or destination, the network retry time is determined by the setting of the last created task.

    • Because you are charged for the task during the connection retry period, we recommend that you customize the retry time based on your business needs, or release the DTS instance as soon as possible after the source and destination database instances are released.

    Set the connection retry window based on your fault recovery objectives, and make sure that the source logs cover the time required for retries and catch-up.
    Retry Time for Other Issues

    After the migration task starts, if a non-connectivity issue, such as a DDL or DML execution exception, occurs in the source or destination database, DTS reports an error and immediately begins to retry the operation. The default retry duration is 10 minutes. You can customize the retry time to a value from 1 to 1440 minutes. We recommend that you set the duration to more than 10 minutes. If the related operations succeed within the specified retry duration, the migration task automatically resumes. Otherwise, the task fails.

    Important

    The value of Retry Time for Other Issues must be less than the value of Retry Time for Failed Connections.

    Configure the retry window for non-connection errors. It must be shorter than the connection retry window. Do not rely on retries to make up for DDL operations that were filtered out.
    Enable Throttling for Full Data Migration

    During full migration, DTS consumes read and write resources on the source and destination databases, which may increase the database load. If required, you can enable throttling for the full migration task. You can set Queries per second (QPS) to the source database, RPS of Full Data Migration, and Data migration speed for full migration (MB/s) to reduce the load on the destination database.

    Note
    • This configuration item is available only if you select Full Data Migration for Migration Types.

    • You can also adjust the full migration speed after the migration instance is running.

    When full data migration is required, set QPS, RPS, and BPS based on the source database read load and the destination write capacity.
    Enable Throttling for Incremental Data Migration

    If required, you can also choose to set speed limits for the incremental migration task. You can set RPS of Incremental Data Migration and Data migration speed for incremental migration (MB/s) to reduce the load on the destination database.

    Note
    • This configuration item is available only if you select Incremental Data Migration for Migration Types.

    • You can also adjust the incremental migration speed after the migration instance is running.

    Set throttling based on the actual write capacity to prevent sustained throttling from causing log accumulation.
    Environment TagConfigure based on your business requirements.
    Configure ETL

    Choose whether to enable the extract, transform, and load (ETL) feature. For more information, see What is ETL? Valid values:

    In this example, select No.
    Monitoring and Alerting

    Select whether to set alerts and receive alert notifications based on your business needs.

    • No: Does not set an alert.

    • Yes: Configure alerts by setting an alert threshold and an alert contact. If a migration fails or the latency exceeds the threshold, the system sends an alert notification.

    (Recommended) Configure task failure and latency alerts, and enter the alert contacts.

    c. If Migration Types includes Schema Migration, on the Next: Configure Database and Table Fields page, verify the destination column types, primary key columns, distribution keys, and partition information. The primary key and distribution rules must meet the CREATE TABLE requirements.Manage tablesDefine table distributionTasks that use pre-created destination tables must complete the same verification before they start.

    d. Go to Next: Data Verification. If verification configuration is available for the current link, create a verification task as needed. Whether or not automatic verification is enabled, verify the key fields, primary keys, row counts, and data precision for type conversions.

  9. Click Next: Data Validation to configure a data validation task.

    For more information about the data validation feature, see Configure data validation.

  10. Click Next: Save Task and Precheck.

    • If a check fails, click View Details for the item, fix the permission, connection, object, or schema problem, and then run the check again.

    • For warning items, confirm the impact before you decide whether to ignore them. Do not ignore alerts and continue running for problems such as missing primary keys, incompatible data types, or logs that do not meet the requirements.

    • A successful precheck does not mean that all actual data boundaries and business DDL operations have been verified.

  11. Save the task and run a precheck.

    • To view the parameters for configuring this instance when you call the API operation, move the pointer over the Next: Save Task Settings and Precheck button and click Preview OpenAPI parameters in the bubble that appears.

    • If you do not need to view or have finished viewing the API parameters, click Next: Save Task Settings and Precheck at the bottom of the page.

    Note
    • Before the migration task starts, DTS performs a precheck. The task starts only after it passes the precheck.

    • If the precheck fails, click View Details next to the failed check item, fix the issue based on the prompt, and then run the precheck again.

    • If a warning is reported during the precheck:

      • For check items that cannot be ignored, click View Details next to the failed item, fix the issue based on the prompt, and then run the precheck again.

      • For check items that can be ignored, you can click Confirm Alert Details, Ignore, OK, and Precheck Again to skip the alert item and run the precheck again. If you choose to ignore a warning, it may cause issues such as data inconsistency and pose risks to your business.

  12. When the Success Rate is 100%, click Next: Purchase Instance.

  13. On the Purchase page, select the link specification for the data migration instance. For more information, see the following table.

    Category

    Parameter

    Description

    New Instance Class

    Resource Group Settings

    Select the resource group to which the instance belongs. The default value is default resource group. For more information, see What is Resource Management?

    Instance Class

    DTS provides migration specifications with different performance levels. The link specification affects the migration speed. You can select a specification based on your business scenario. For more information, see Data migration link specifications.

  14. After the configuration is complete, read and select Data Transmission Service (Pay-as-you-go) Service Terms.

  15. Click Buy and Start. In the OK dialog box that appears, click OK.

    You can view the progress of the migration task on the Data Migration Tasks list page.

    Note
    • If the migration task does not include incremental migration, it stops automatically after the full migration is complete. After the task stops, its Status changes to Completed.

    • If the migration task includes incremental migration, it does not stop automatically. The incremental migration task continues to run. While the incremental migration task is running, the Status of the task is Running.

  16. AnalyticDB for MySQLAfter the precheck is successful, click Next: Purchase, and configure the resource group and the link specifications. After you verify the order and the terms of service, click Purchase and Start, and then click OK in the confirmation dialog box.

    After the task starts, view the phase progress in the data migration list, and use the task logs to verify the schema processing and data write results. After both the schema migration and full data migration phases are complete, the historical data is in place. Some DDL operations that cannot be parsed or are unsupported trigger alerts and are skipped. A task that continues to run does not mean that the table schemas remain consistent, so you must confirm the destination table schemas by using the task logs. If incremental data migration is included, the task keeps running. Stop the source writes, wait for committed changes to catch up, and complete data validation before you switch writes to the destination.

What's next

  1. After full data migration is complete, verify the destination primary keys, table schemas, row counts, and key fields. Focus on precision, time zones, NULL values, binary data, and string-converted types.

  2. If incremental data migration is included, the task keeps running. To switch over your workload, first stop the source writes, wait for committed changes to catch up, and then run data validation.

  3. After validation confirms consistency, end or release the migration task before you switch writes to the destination. This prevents the task from overwriting new destination data if it resumes. Do not switch writes to the destination if validation finds inconsistencies.

  4. Tasks that include only schema migration and full data migration can be ended after those phases are complete. Ending a task does not mean that application SQL, stored procedures, indexes, and business constraints have been refactored.

SQL operations supported for incremental data migration

Operation typeSQL statements
DMLINSERT, UPDATE, and DELETE
DDLCREATE TABLE; ADD COLUMN, DROP COLUMN, RENAME COLUMN, RENAME TO, and ALTER COLUMN ... TYPE for ALTER TABLE; DROP TABLE; and TRUNCATE TABLE.
  • Only data migration tasks created after October 1, 2020 (UTC+8)October 1, 2020 (UTC+8) support DDL operations.

    Important
  • The data migration task supports the following DDL statements. The source database account must be a privileged account:

    • CREATE TABLE, DROP TABLE

    • ALTER TABLE (including RENAME TABLE, ADD COLUMN, ADD COLUMN DEFAULT, ALTER COLUMN TYPE, DROP COLUMN, ADD CONSTRAINT, ADD CONSTRAINT CHECK, and ALTER COLUMN DROP DEFAULT)

    • TRUNCATE TABLE (The source PostgreSQL database must be version 11 or later.)

    • CREATE INDEX ON TABLE

    Important
    • Additional information in DDL statements, such as CASCADE or RESTRICT, is not migrated.

    • If a session uses the SET session_replication_role = replica command, its DDL statements are not migrated.

    • DDL statements executed by calling functions are not migrated.

    • If a single transaction from the source database contains both DML and DDL statements, the DDL statements are not migrated.

    • If a single transaction from the source database contains DDL statements for objects not selected for migration, the DDL statements are not migrated.

    • CREATE SEQUENCE is not currently supported.

    • DDL statements executed directly within a plugin through the Server Programming Interface (SPI) are not migrated.

Note
  • New tables must be included in the migration object scope, and CREATE TABLE must include a primary key. The automatically generated destination distribution key uses the primary key columns.

  • ALTER COLUMN ... TYPE applies only to type changes that the destination database allows. USING expressions are not supported as data conversion or historical data recalculation operations.

  • Changes to indexes, sequences, views, functions, triggers, COMMENT, and constraints are not supported. Incremental DDL that contains multi-dimensional array definitions, PARTITION BY, table inheritance, or cascading foreign key definitions is not supported. DROP TABLE with CASCADE is not supported.

  • Newly added columns are not automatically backfilled for existing destination rows based on source default values. Tasks that include incremental DDL require separate validation of existing data and of data changed afterwards.

  • DTS may generate auxiliary indexes for destination columns that support indexes. This does not mean that CREATE INDEX statements, index definitions, or UNIQUE constraints from the source database are migrated.

  • A single source DDL operation may be split into multiple destination statements. If an error occurs, the earlier statements may already have taken effect, so verify the complete result.

    Write semantics: Incremental INSERT and regular UPDATE operations are written to the destination as REPLACE INTO. When a primary key is updated, the record with the old primary key is deleted first, and then the new record is written. Make sure that the primary key and the row information before and after the update are complete.

Data type mappings

The following table lists the main type mappings for this link. A string mapping preserves the text representation of the data. It does not preserve the constraints, indexes, operators, or computational capabilities of the source type.

PostgreSQL typeAnalyticDB for MySQL 3.0 typeDescription
SMALLINT, INT2, and SMALLSERIALSMALLINTSMALLSERIAL migrates only the integer values generated on the source.
INTEGER, INT, INT4, and SERIALINTSERIAL is not converted into an auto-increment generation mechanism in the destination.
BIGINT, INT8, and BIGSERIALBIGINTThe destination integer value range must cover the source data.
DECIMAL(p,s) and NUMERIC(p,s)DECIMAL(p,s)Applies only to the precision and scale values that the destination supports.
NUMERIC and DECIMAL (precision not specified)DECIMALVerify the default destination precision and the source value range.
MONEYDECIMAL(19,2)A schema mapping exists, but some data read scenarios fail. This does not mean that full and incremental data migration always complete as expected. Organize the data to be migrated into verified NUMERIC columns before you configure the task.
REAL and FLOAT4FLOATFloating-point values may differ because of approximate representation.
DOUBLE PRECISION and FLOAT8DOUBLEFloating-point values may differ because of approximate representation.
BOOLEAN and BOOLBOOLEANtrue and false map to 1 and 0.
CHAR, CHARACTER, BPCHAR, VARCHAR, CHARACTER VARYING, and TEXTVARCHARFixed-length padding and length validation semantics from the source are not retained.
BYTEAVARBINARYBinary data. The destination database may display it as a BINARY type.
DATEDATESource values must fall within the destination date range.
TIME and TIME WITHOUT TIME ZONETIMETime precision beyond the range supported by the destination is not retained.
TIME WITH TIME ZONE and TIMETZTIMEThe default schema mapping is TIME, which cannot retain the original time zone offset. To retain a text representation of the time and the offset, validate the VARCHAR approach separately first.
TIMESTAMP and TIMESTAMP WITHOUT TIME ZONETIMESTAMPInterpreted according to the destination time type and the session time zone.
TIMESTAMP WITH TIME ZONE and TIMESTAMPTZTIMESTAMPTime zone conversion is applied. The original time zone marker is not retained.
INTERVALVARCHARStores interval text.
JSON and JSONBJSONJSONB is converted into destination JSON. PostgreSQL JSONB indexes and storage implementations are not migrated.
UUID and XMLVARCHARStores UUID or XML text. UUIDs are not generated automatically.
BIT, BIT VARYING, and VARBITVARCHARStores bit string text.
INET, CIDR, MACADDR, and MACADDR8VARCHARStores network address text.
POINT, LINE, LSEG, BOX, PATH, POLYGON, and CIRCLEVARCHARStores geometry text. The text format of numeric values may be normalized.
TSVECTOR and TSQUERYVARCHARStores the text representation. The full-text index capability is not retained.
ENUM and verified composite type columnsVARCHARStores enumeration value or composite value text. The corresponding TYPE objects are not created.
One-dimensional arrays such as INTEGER[], TEXT[], and VARCHAR[]VARCHARStores array text. Arrays are not mapped to a native ARRAY type.
INT4RANGE, INT8RANGE, NUMRANGE, TSRANGE, TSTZRANGE, and DATERANGEVARCHARStores range text.
OIDBIGINTStores the OID value. The database objects that the OID references are not migrated.
REGCLASS, REGPROC, REGTYPE, and PG_LSNVARCHARStores the text representation. The source object reference capability is not retained.
Note

Do not treat unlisted types or any custom types as supported merely because VARCHAR can serve as a fallback. Validate the actual data first.

For the ranges of the destination DECIMAL, VARCHAR, and time types, see Basic data types. The current maximum VARCHAR size is 16 MB. Do not use the capacity limit of source TEXT, XML, or arrays as the maximum writable size in the destination.