[Yandex Cloud documentation](../../index.md) > [Yandex Data Transfer](../index.md) > [Tutorials](index.md) > Migration > PostgreSQL cluster

# Migrating PostgreSQL clusters

To migrate your database to Yandex Managed Service for PostgreSQL, you need to directly transfer the data, acquire a write lock for the old database, and switch over the load to the database cluster in Yandex Cloud.

{% note warning %}

Users are not transferred automatically to a Managed Service for PostgreSQL cluster. You need to [create](../../managed-postgresql/operations/cluster-users.md#adduser) them again in the new cluster.

{% endnote %}

Using Data Transfer for migration allows you to:

* Eliminate the need for an intermediate VM or public internet access to your Managed Service for PostgreSQL target cluster.
* Minimize the DB downtime when migrating data.
* Migrate from older PostgreSQL versions to newer versions.

For more information, see [Problems addressed by Yandex Data Transfer](../concepts/use-cases.md).

To use these migration methods, allow connecting to the source cluster from the internet.

## Transferring data {#data-transfer}

# Migrating data using Yandex Data Transfer {#data-transfer}



### Required paid resources {#paid-resources}

* Managed Service for PostgreSQL cluster: computing resources allocated to hosts, storage and backup size (see [Managed Service for PostgreSQL pricing](../../managed-postgresql/pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* Each transfer: use of computing resources and number of transferred data rows (see [Data Transfer pricing](../pricing.md)).


### Transfer the data {#transfer-data}

1. [Prepare the source cluster](../operations/prepare.md#source-pg).
1. Set up the infrastructure:

    {% list tabs group=instructions %}

    - Manually {#manual}

        1. Create a [Managed Service for PostgreSQL target cluster](../../managed-postgresql/operations/cluster-create.md) with your preferred configuration. Enable the same [PostgreSQL extensions](../../managed-postgresql/operations/extensions/cluster-extensions.md) as in the source cluster.
        1. [Prepare the target cluster](../operations/prepare.md#target-pg).
        1. [Create a source endpoint](../operations/endpoint/index.md#create) with the following settings:

             * **Database type**: `PostgreSQL`.
             * **Endpoint parameters** → **Connection settings**: `Custom installation`.

           Configure the source cluster connection settings.

        1. [Create a target endpoint](../operations/endpoint/index.md#create) with the following settings:

             * **Database type**: `PostgreSQL`.
             * **Endpoint parameters** → **Connection settings**: `Managed Service for PostgreSQL cluster`.

           Specify the target cluster ID.

        1. [Create a transfer](../operations/transfer.md#create) of the _**Snapshot and increment**_-type that will use the new endpoints.
        1. [Activate the transfer](../operations/transfer.md#activate).

            {% note warning %}

            Do not make any data schema changes in the source or target cluster during the transfer. For more information, see [Working with databases during transfer](../operations/db-actions.md).

            {% endnote %}

    - Terraform {#tf}

        1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
        1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
        1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
        1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

        1. Download the [data-transfer-pgsql-mpg.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-from-on-premise-postgresql-to-cloud/blob/main/data-transfer-pgsql-mpg.tf) configuration file to your current working directory.

            This file describes:

            * [Network](../../vpc/concepts/network.md#network).
            * [Subnet](../../vpc/concepts/network.md#subnet).
            * [Security group](../../vpc/concepts/security-groups.md) and the rule allowing cluster connections.
            * Managed Service for PostgreSQL target cluster.
            * Source endpoint.
            * Target endpoint.
            * Transfer.

        1. In the `data-transfer-pgsql-mpg.tf` file, specify the following:

            * [Source endpoint settings](../operations/endpoint/source/postgresql.md#on-premise).
            * `pg-extensions`: List of [PostgreSQL extensions](../../managed-postgresql/operations/extensions/cluster-extensions.md) in the source cluster.
            * [Target endpoint settings](../operations/endpoint/target/postgresql.md#managed-service) inherited from the target cluster configuration:

                * `target_pgsql_version`: PostgreSQL version. This version must be the same or higher than the version in the source cluster.
                * `target_user` and `target_password`: Database owner username and password.

        1. Validate your Terraform configuration files using this command:

            ```bash
            terraform validate
            ```

            Terraform will display any configuration errors detected in your files.

        1. Create the required infrastructure:

            1. Run this command to view the planned changes:
            
               ```bash
               terraform plan
               ```
            
               If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
            
            1. If everything looks correct, apply the changes:
               1. Run this command:
            
                  ```bash
                  terraform apply
                  ```
            
               1. Confirm updating the resources.
               1. Wait for the operation to complete.

            All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

            The transfer will be activated automatically as soon as it is created.

    {% endlist %}

1. Wait for the transfer status to change to **Replicating**.
1. Remove the writing load from the source cluster.
1. On the [transfer monitoring](../operations/monitoring.md) page, wait until the **Maximum data transfer delay** value drops to zero. This means that all changes made in the source cluster after the initial data copy have been transferred to the target cluster.
1. Transfer the workload over to the target cluster.
1. [Deactivate](../operations/transfer.md#deactivate) the transfer and wait for its status to change to **Stopped**.

    For more information about transfer statuses, see [Transfer lifecycle](../concepts/transfer-lifecycle.md#statuses).


1. To minimize resource consumption, delete the resources you no longer need:

    {% list tabs group=instructions %}

    - Manually created resources {#manual}

        1. [Delete the Managed Service for PostgreSQL cluster](../../managed-postgresql/operations/cluster-delete.md).
        1. [Ensure the transfer is stopped, then delete it](../operations/transfer.md#delete).
        1. [Delete the source and target endpoints](../operations/endpoint/index.md#delete).

    - Resources created with Terraform {#tf}

        1. In the terminal window, go to the directory containing the infrastructure plan.
        
            {% note warning %}
        
            Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
        
            {% endnote %}
        
        1. Delete resources:
        
            1. Run this command:
        
                ```bash
                terraform destroy
                ```
        
            1. Confirm deleting the resources and wait for the operation to complete.
        
            All the resources described in the Terraform manifests will be deleted.

    {% endlist %}


## Quick data transfer to a new cluster {#quick-transfer}

After creating a Managed Service for PostgreSQL cluster, you can immediately transfer data from another Managed Service for PostgreSQL cluster or custom database installation into it.

This migration method provides:

* Automatic creation of a transfer and endpoints.
* One-time transfer of the data snapshot from the source to the target.

### Required paid resources {#paid-resources}

* Managed Service for PostgreSQL cluster: computing resources allocated to hosts, storage and backup size (see [Managed Service for PostgreSQL pricing](../../managed-postgresql/pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* Each transfer: use of computing resources and the number of transferred data rows (see [Data Transfer pricing](../pricing.md)).

### Transfer the data {#transfer-data-quickly}

1. Open the **Overview** page of the new Managed Service for PostgreSQL cluster.
1. At the top of the screen, click **Migrate data**.
1. Configure the source:

    {% list tabs %}

    - Custom installation

      * **Connecting**:

          * **Select existing connection**: Select this option to use an existing connection.

            * **Connection ID**: Select the connection in [Yandex Connection Manager](../../metadata-hub/quickstart/connection-manager.md).
            
            * **Database**: Enter the DB name.
          
          * **Create new connection**: Select this option to create a new connection.

            * **Hosts**: Specify the IP address or FQDN of the master host. If hosts have different ports open for connection, you can specify multiple host values in `host:port` format. In this case, the value of the **Port** field will be disregarded.

            * **Username**: Enter a username for connecting to the DB.

            * **Password**: Enter the password to access the database.

            * **Database**: Enter the DB name.

            * **TLS**: Enable this setting to use TLS connection.

              * **CA certificate**: Add the certificate file contents.
      
    - Managed Service for PostgreSQL cluster

      * **Connecting**:

        * **Select existing connection**: Select this option to use an existing connection.

          * **Cluster ID**: Select the cluster to connect to.

          * **Connection ID**: Select the connection in [Yandex Connection Manager](../../metadata-hub/quickstart/connection-manager.md).

          * **Database**: Specify the DB name in the cluster you selected.

        * **Create new connection**: Select this option to create a new connection.

          * **Cluster ID**: Select the cluster to connect to.

          * **Username**: Enter a username for connecting to the cluster DB.

          * **Password**: Enter the user password to access the cluster DB.

          * **Database**: Specify the DB name in the selected cluster.

    {% endlist %}

   {% note warning %}
   
   To use a connection from Connection Manager, the user must have [access permissions](../../metadata-hub/operations/connection-access.md) for this connection of `connection-manager.user` or higher.
   
   {% endnote %}

1. Configure the target:

    * **Connection ID**: Select the connection in Connection Manager.

    * **Database**: Specify the target cluster’s DB name.

1. Optionally, configure advanced settings:

    * **Cleanup policy**: Select the method to clean up data in the target database:

      * `Drop`: Completely delete the tables included in the transfer (default).

      * `Truncate`: Delete only the data from the tables included in the transfer but keep the schema.

    * **Included tables**: Only data from the tables listed here will be transferred.

    * **Excluded tables**: Data from the listed tables is not transferred.

      The lists include the name of the [schema](https://www.postgresql.org/docs/current/ddl-schemas.html) that describes the DB contents, structure, and integrity constraints, as well as the table name. Both lists support expressions in the following format:

      * `<schema_name>.<table_name>`: Full table name.
      * `<schema_name>.*`: All tables in the specified schema.

      Table names must match this regular expression:

      ```text
      ^"?[-_a-zA-Z0-9.]+"?\\."?[$-_a-zA-Z0-9.*]+"?$
      ```

      Double quotes within a table name are not supported. Outer quotes are only used as delimiters and will be deleted when processing paths.

    * **Schema migration**: Select the DB schema elements to migrate when activating or deactivating a transfer.

1. Click **Create** to create a transfer and endpoints.

1. [Activate](../operations/transfer.md#activate) the transfer.

1. Wait for the transfer status to change to **Completed**.

1. To minimize resource consumption, delete the resources you no longer need:

    1. [Delete the Managed Service for PostgreSQL cluster](../../managed-postgresql/operations/cluster-delete.md) if you transferred data from it.
    1. [Delete the transfer](../operations/transfer.md#delete).
    1. [Delete](../operations/endpoint/index.md#delete) the source and target endpoints.
  

## Transferring tables with data types from PostgreSQL extensions

Data Transfer allows you to copy tables, the columns of which contain data types defined in PostgreSQL and tables with derived types, i.e., arrays of these types and composite types with fields of these types. Currently, there is a limitation: the data type must implement __binary I/O functions__. This means that, for the type of data in the [pg_type](https://www.postgresql.org/docs/current/catalog-pg-type.html) system view, the `typsend` and `typreceive` column values must not be zero.

For example, for the [PostGIS](https://postgis.net/) extension, columns of the [`GEOMETRY`](https://postgis.net/docs/geometry.html), [`GEOMETRY_DUMP`](https://postgis.net/docs/geometry_dump.html), and [`GEOGRAPHY`](https://postgis.net/docs/geography.html) types can be transferred, while those of the [`BOX2D`](https://postgis.net/docs/box2d_type.html) and [`BOX3D`](https://postgis.net/docs/box3d_type.html) types cannot.

## Useful links {#see-also}

For other migration methods, see [this Yandex Managed Service for PostgreSQL tutorial](../../managed-postgresql/tutorials/data-migration.md).