Cuando migras tu esquema, datos y metadatos de una base de datos de origen a una de destino, quieres asegurarte de que toda esta información se migre correctamente. Database Migration Service ofrece una forma de alta fidelidad de migrar objetos de bases de datos (incluidos el esquema, los datos y los metadatos) de una base de datos a otra.
Durante el proceso de migración, los datos y las restricciones se migran por separado.
Primero se migran los datos y, después del volcado y la carga iniciales, se vuelven a crear las restricciones, como las claves principales, las claves externas y los índices, en la instancia.
Todos los siguientes componentes de datos, esquemas y metadatos se migran como parte de la migración de la base de datos:
Datos
Todas las tablas de todas las bases de datos y esquemas, excepto los siguientes esquemas:
El esquema de información information_schema
Cualquier esquema que empiece por pg (por ejemplo, pg_catalog)
Solo los cambios del lenguaje de manipulación de datos (DML) se actualizan automáticamente durante las migraciones continuas. El usuario es el responsable de gestionar los cambios del lenguaje de definición de datos (DDL) para que las bases de datos de origen y destino sigan siendo compatibles. Para ello, puede usar dos métodos:
Deteniendo las operaciones de escritura en el origen y ejecutando los comandos de DDL en el origen y en el destino. Antes de ejecutar los comandos de DDL en el destino, concede el rol cloudsqlexternalsync al usuario de Cloud SQL que vaya a aplicar los cambios en el DDL. Para habilitar las consultas o los cambios en los datos, concede el rol cloudsqlexternalsync a los usuarios pertinentes de Cloud SQL.
Usa pglogical.replicate_ddl_command para permitir que se ejecute DDL en el origen y en el destino en un punto coherente. El usuario que ejecute este comando debe tener el mismo nombre de usuario en el origen y en el destino, y debe ser el superusuario o el propietario del artefacto que se va a migrar (por ejemplo, la tabla, la secuencia, la vista o la base de datos).
A continuación, te mostramos algunos ejemplos de cómo usar el pglogical.replicate_ddl_command.
Sustituye:
[SCHEMA] con el nombre del esquema de tabla que quieras usar
[TABLE_NAME] con el nombre de la tabla
[NEW_NAME_FOR_TABLE] con el nuevo nombre de la tabla al realizar la operación de cambio de nombre
Añadir una columna a una tabla de base de datos con una clave principal
Cambiar el nombre de una tabla de base de datos con una clave principal
selectpglogical.replicate_ddl_command('ALTER TABLE [SCHEMA].[TABLE_NAME] RENAME TO [NEW_NAME_FOR_TABLE]','{default}');
Cambiar el nombre de una tabla de una base de datos sin clave principal
selectpglogical.replicate_ddl_command('ALTER TABLE [SCHEMA].[TABLE_NAME] RENAME TO [NEW_NAME_FOR_TABLE]','{default_insert_only}');
Crear una tabla de base de datos con una clave principal
Ejecuta estos comandos:
selectpglogical.replicate_ddl_command(command:='CREATE TABLE [SCHEMA].[TABLE_NAME] (id INTEGER PRIMARY KEY, name VARCHAR);',replication_sets:=ARRAY['default']);
Crear una tabla de base de datos sin clave principal
Ejecuta estos comandos:
selectpglogical.replicate_ddl_command(command:='CREATE TABLE [SCHEMA].[TABLE_NAME] (id INTEGER PRIMARY KEY, name VARCHAR);',replication_sets:=ARRAY['default_insert_only']);
Database Migration Service no migra las extensiones que no son compatibles con Cloud SQL. La presencia de estas extensiones no bloquea la migración, pero, para que el proceso sea fluido, comprueba que tus objetos o aplicaciones no hagan referencia a ninguna extensión no compatible. Te recomendamos que elimines estas extensiones y referencias de tu base de datos de origen antes de continuar.
Los objetos grandes no se pueden replicar, ya que la función de decodificación lógica de PostgreSQL no admite la decodificación de cambios en objetos grandes. En las tablas que tienen el tipo de columna
oid
que hace referencia a objetos grandes, las filas se sincronizan y las nuevas filas se replican.
Sin embargo, al intentar acceder al objeto grande en la base de datos de destino (leer con lo_get, exportar con lo_export o consultar el catálogo pg_largeobject del oid), se produce un error y se muestra un mensaje que indica que el objeto grande no existe.
En el caso de las tablas que no tienen claves principales, Database Migration Service admite la migración de la copia inicial y las instrucciones INSERT durante la fase de captura de datos de cambios (CDC). Debes migrar las instrucciones UPDATE y DELETE manualmente.
Database Migration Service no migra datos de vistas materializadas, solo el esquema de la vista. Para rellenar las vistas, ejecuta el siguiente comando: REFRESH MATERIALIZED VIEW view_name.
Los estados SEQUENCE (por ejemplo, last_value) del nuevo destino pueden variar con respecto a los estados SEQUENCE de la fuente.
Los espacios de tablas personalizados no se admiten en la instancia de Cloud SQL de destino. Todos los datos de los espacios de tablas personalizados se migran al espacio de tablas pg_default predeterminado de Cloud SQL.
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-21 (UTC)."],[[["\u003cp\u003eDatabase Migration Service ensures high-fidelity migration of database objects, including schema, data, and metadata, from source to destination databases.\u003c/p\u003e\n"],["\u003cp\u003eDuring migration, data is migrated first, followed by the recreation of constraints such as primary keys, foreign keys, and indexes on the destination instance.\u003c/p\u003e\n"],["\u003cp\u003eContinuous migration automatically updates data manipulation language (DML) changes, while data definition language (DDL) changes require manual management or the use of \u003ccode\u003epglogical.replicate_ddl_command\u003c/code\u003e to maintain compatibility.\u003c/p\u003e\n"],["\u003cp\u003eCertain components are not migrated, such as unsupported Cloud SQL extensions, large objects, \u003ccode\u003eUPDATE\u003c/code\u003e and \u003ccode\u003eDELETE\u003c/code\u003e statements for tables without primary keys, and data from materialized views, where users will have to refresh it on the destination end.\u003c/p\u003e\n"],["\u003cp\u003eAll data in customized tablespaces will migrate to the default \u003ccode\u003epg_default\u003c/code\u003e tablespace in Cloud SQL, and \u003ccode\u003eSEQUENCE\u003c/code\u003e states may differ from the source to the destination.\u003c/p\u003e\n"]]],[],null,["# Migration fidelity\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n[MySQL](/database-migration/docs/mysql/migration-fidelity \"View this page for the MySQL version of Database Migration Service.\") \\| PostgreSQL \\| [PostgreSQL to AlloyDB](/database-migration/docs/postgresql-to-alloydb/migration-fidelity \"View this page for the PostgreSQL to AlloyDB version of Database Migration Service.\")\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nOverview\n--------\n\nWhen you're migrating your schema, data, and metadata from a source database to a\ndestination database, you want to ensure that all of this information is\nmigrated accurately. Database Migration Service provides a high-fidelity way to\nmigrate database objects (including the schema, data, and metadata) from one\ndatabase to another.\nDuring the migration process, data and constraints are migrated separately. Data is migrated first, and constraints such as primary keys, foreign keys, and indexes are recreated on the instance after the initial full dump and load.\n\nAll of the following data, schema, and metadata components are migrated as part\nof the database migration:\n\n### Data\n\n- All tables from all databases and schemas, excluding the following schemas:\n\n - The information schema `information_schema`\n - Any schemas beginning with `pg` (for example, `pg_catalog`)\n\n For more information about these schemas, see [Known limitations](/database-migration/docs/postgres/known-limitations).\n\n### Schema\n\n- Naming\n\n- Primary key\n\n- Data type\n\n- Ordinal position\n\n- Default value\n\n- Nullability\n\n- Auto-increment attributes\n\n- Secondary indexes\n\n### Metadata\n\n- Stored procedures\n\n- Functions\n\n- Triggers\n\n- Views\n\n- Foreign key constraints\n\n### Continuous migration\n\nOnly data manipulation language (DML) changes are updated automatically during\ncontinuous migrations. Managing data definition language (DDL) changes so that the source and destination databases remain compatible is the\nresponsibility of the user, and can be achieved in two ways:\n\n1. Stopping writes to the source and running the DDL commands in both source and destination. Before running DDL commands on the destination, grant `cloudsqlexternalsync` to the Cloud SQL user applying the DDL changes. To enable querying or changing the data, grant the `cloudsqlexternalsync` role to the relevant Cloud SQL users.\n2. Using the `pglogical.replicate_ddl_command` to allow DDL to be run on the source and destination at a consistent point. The user running this command must have the same username on both the source and the destination, and should be the superuser or the owner of the artifact being migrated (for example, the table, sequence, view, or database).\n\n Here are a few examples of using the `pglogical.replicate_ddl_command`.\n\n Replace:\n - \u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e with the name of the table schema you want to use\n - \u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e with the table name\n - \u003cvar label=\"new_table_name\" translate=\"no\"\u003e[NEW_NAME_FOR_TABLE]\u003c/var\u003e with the new name for the table when when performing the rename operation\n\n #### Add a column to a database table with a primary key\n\n \u003cbr /\u003e\n\n ```sql\n select pglogical.replicate_ddl_command(\n 'ALTER TABLE \u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e add column surname varchar(20)',\n '{default}'\n );\n ```\n\n \u003cbr /\u003e\n\n #### Add a column to a database table without a primary key\n\n \u003cbr /\u003e\n\n ```sql\n select pglogical.replicate_ddl_command(\n 'ALTER TABLE \u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e add column surname varchar(20)',\n '{default_insert_only}'\n );\n ```\n\n \u003cbr /\u003e\n\n #### Change the name of a database table with a primary key\n\n \u003cbr /\u003e\n\n ```sql\n select pglogical.replicate_ddl_command(\n 'ALTER TABLE \u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e RENAME TO \u003cvar label=\"new_table_name\" translate=\"no\"\u003e[NEW_NAME_FOR_TABLE]\u003c/var\u003e',\n '{default}'\n );\n ```\n\n \u003cbr /\u003e\n\n #### Change the name of a database table without a primary key\n\n \u003cbr /\u003e\n\n ```sql\n select pglogical.replicate_ddl_command(\n 'ALTER TABLE \u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e RENAME TO \u003cvar label=\"new_table_name\" translate=\"no\"\u003e[NEW_NAME_FOR_TABLE]\u003c/var\u003e',\n '{default_insert_only}'\n );\n ```\n\n \u003cbr /\u003e\n\n #### Create a database table with a primary key\n\n Run the following commands:\n 1.\n\n ```sql\n select pglogical.replicate_ddl_command(\n command := 'CREATE TABLE \u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e\n (id INTEGER PRIMARY KEY, name VARCHAR);',\n replication_sets := ARRAY['default']\n );\n ```\n 2.\n\n ```sql\n select pglogical.replication_set_add_table('default', '\u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e');\n ```\n\n \u003cbr /\u003e\n\n #### Create a database table without a primary key\n\n Run the following commands:\n 1.\n\n ```sql\n select pglogical.replicate_ddl_command(\n command := 'CREATE TABLE \u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e\n (id INTEGER PRIMARY KEY, name VARCHAR);',\n replication_sets := ARRAY['default_insert_only']\n );\n ```\n 2.\n\n ```sql\n select pglogical.replication_set_add_table(\n 'default_insert_only', '\u003cvar label=\"schema\" translate=\"no\"\u003e[SCHEMA]\u003c/var\u003e.\u003cvar label=\"table\" translate=\"no\"\u003e[TABLE_NAME]\u003c/var\u003e'\n );\n ```\n\n \u003cbr /\u003e\n\n### What isn't migrated\n\n- To add users to a Cloud SQL destination instance, navigate to the instance and add users\n from the **Users** tab, or add them from a PostgreSQL client. Learn more about [creating\n and managing PostgreSQL users](https://cloud.google.com/sql/docs/postgres/create-manage-users).\n\n- Database Migration Service doesn't migrate [extensions that are unsupported by\n Cloud SQL](/sql/docs/postgres/extensions). The presence of these extensions\n doesn't block the migration, but to ensure a smooth migration process\n verify that your objects or applications don't reference any unsupported\n extensions. We recommend removing these extensions and references from your\n source database before you proceed.\n\n\u003c!-- --\u003e\n\n- [Large objects](https://www.postgresql.org/docs/current/largeobjects.html)\n can't be replicated, as PostgreSQL's logical decoding facility does not support\n decoding changes to large objects. For tables that have column type\n [`oid`](https://www.postgresql.org/docs/current/datatype-oid.html)\n referencing large objects, the rows are synced, and new rows are replicated.\n However, trying to access the large object on the destination database\n (read using [`lo_get`](https://www.postgresql.org/docs/current/lo-funcs.html),\n export using [`lo_export`](https://www.postgresql.org/docs/current/lo-funcs.html),\n or check the catalog `pg_largeobject` for the given\n `oid`), fails with a message saying that the large object does\n not exist.\n\n- For tables that don't have primary keys, Database Migration Service supports migration of the **initial snapshot and `INSERT` statements during the change data capture (CDC) phase** . You should migrate `UPDATE` and `DELETE` statements manually.\n\n- Database Migration Service doesn't migrate data from materialized views, just the view schema. To populate the views, run the following command: `REFRESH MATERIALIZED VIEW `\u003cvar translate=\"no\"\u003eview_name\u003c/var\u003e.\n\n- The `SEQUENCE` states (for example, `last_value`) on the new destination might vary from the source `SEQUENCE` states.\n\n- Customized tablespaces aren't supported in the destination Cloud SQL instance. All the data inside customized tablespaces is migrated to the default `pg_default` tablespace in Cloud SQL."]]