[Yandex Cloud documentation](../../index.md) > [Yandex Data Transfer](../index.md) > [Tutorials](index.md) > Migration with data storage type changed > PostgreSQL to YDB

# Migrating data from PostgreSQL to YDB

# Delivering data from Yandex Managed Service for PostgreSQL to Yandex Managed Service for YDB


A Managed Service for YDB cluster can ingest data from PostgreSQL databases in real time. The system will automatically insert this data into YDB tables named after the original schemas and tables.

To start data delivery:

1. [Prepare the source cluster](#prepare-source).
1. [Prepare and activate the transfer](#prepare-transfer).
1. [Test the transfer](#verify-transfer).

If you no longer need the resources you created, [delete them](#clear-out).


## 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)).
* Managed Service for YDB database (see [Managed Service for YDB pricing](../../ydb/pricing/index.md)). The cost depends on the deployment mode:

    * In serverless mode, you pay for data operations and storage volume, including stored backups.
    * In dedicated instance mode, you pay for the use of computing resources allocated to the database, storage and backup size.


## Getting started {#before-you-begin}

Set up your data delivery infrastructure:

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Create a Managed Service for PostgreSQL source cluster](../../managed-postgresql/operations/cluster-create.md) using any suitable configuration with publicly accessible hosts.

        {% note info %}
        
        Public access to cluster hosts is required if you plan to connect to the cluster via the internet. This connection option is simpler and is recommended for the purposes of this guide. You can connect to non-public hosts as well but only from Yandex Cloud virtual machines located in the same cloud network as the cluster.
        
        {% endnote %}

    1. [Create a Managed Service for YDB database](../../ydb/operations/manage-databases.md) of any suitable configuration.
    1. [In the source cluster, create a user](../../managed-postgresql/operations/cluster-users.md#adduser) and [assign them](../../managed-postgresql/operations/grant.md) the `mdb_replication` role.


- 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-mpg-ydb.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-from-postgresql-to-ydb/blob/main/data-transfer-mpg-ydb.tf) configuration file to the same 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 required for connecting to the Managed Service for PostgreSQL cluster.
        * Managed Service for PostgreSQL source cluster.
        * PostgreSQL database.
        * Managed Service for PostgreSQL user.
        * Managed Service for YDB database.
        * Source endpoint.
        * Transfer.

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

        * `source_pg_version`: PostgreSQL version in the source cluster.
        * `source_db_name`: Database name in the source cluster.
        * `source_user_name`: Username for connecting to the source cluster.
        * `source_user_password`: User password.
        * `target_db_name`: Managed Service for YDB database name.
        * `transfer_enabled`: Set to `0` to ensure that neither a source endpoint nor a transfer is created before you [manually create a target endpoint](#prepare-transfer).

    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).

{% endlist %}

## Prepare the source cluster {#prepare-source}

1. [Connect to the source cluster’s database](../../managed-postgresql/operations/connect/index.md) with your new user account.
1. Populate the database with test data. In this example, we will use a simple table with car sensor information.

    Create a table:

    ```sql
    CREATE TABLE public.sensors (
        "device_id" text PRIMARY KEY NOT NULL,
        "datetime" timestamp NOT NULL,
        "latitude" real NOT NULL,
        "longitude" real NOT NULL,
        "altitude" real NOT NULL,
        "speed" real NOT NULL,
        "battery_voltage" real,
        "cabin_temperature" real NOT NULL,
        "fuel_level" real
    );
    ```

    Populate the table with data:

    ```sql
    INSERT INTO public.sensors VALUES
        ('iv9a94th6rzt********', '2020-06-05 17:27:00', 55.70329032, 37.65472196,  427.5,    0, 23.5, 17, NULL),
        ('rhibbh3y08qm********', '2020-06-06 09:49:54', 55.71294467, 37.66542005, 429.13, 55.5, NULL, 18, 32),
        ('iv9a94th678t********', '2020-06-07 15:00:10', 55.70985913, 37.62141918,  417.0, 15.7, 10.3, 17, NULL);
    ```

1. [Prepare the source cluster for transfer](../operations/prepare.md#source-pg).

## Prepare and activate a transfer {#prepare-transfer}

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

    * **Database type**: `YDB`.
    * **Endpoint parameters**:

        * **Connection settings**:
           * **Database**: Select your Managed Service for YDB database from the list.

            

           * **Service account ID**: Select an existing service account or create a new one with the `ydb.editor` role.


1. Create a source endpoint and transfer:

    {% list tabs group=instructions %}

    - Manually {#manual}

        1. [Create an endpoint](../operations/endpoint/index.md#create) for the [previously created](#before-you-begin) PostgreSQL source with the [following settings](../operations/endpoint/source/postgresql.md):

            * **Database type**: `PostgreSQL`.
            * **Endpoint parameters**:
                * **Installation type**: `Managed Service for PostgreSQL cluster`.
                * **Managed Service for PostgreSQL cluster**: Managed Service for PostgreSQL cluster you created earlier.
                * **Database**: Name of the database you created in the Managed Service for PostgreSQL cluster.
                * **User**: Name of the user you created in the Managed Service for PostgreSQL cluster.
                * **Password**: User password.
                * **Included tables**: `<DB_name>.sensors`.

        1. [Create a transfer](../operations/transfer.md#create) of the **Snapshot and replication** type that will use the endpoints you created.
        1. [Activate](../operations/transfer.md#activate) the transfer.

    - Terraform {#tf}

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

            * `target_endpoint_id`: Target endpoint ID.
            * `transfer_enabled`: Set to `1` to create a source endpoint and a transfer.

        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.

            The transfer will be activated automatically upon creation.

    {% endlist %}

## Test the transfer {#verify-transfer}

1. Wait for the transfer status to change to **Replicating**.
1. Make sure the data from the Managed Service for PostgreSQL source cluster has been transferred to the Managed Service for YDB database:

    {% list tabs group=instructions %}

    - Management console {#console}

        1. In the [management console](https://console.yandex.cloud), select the folder containing your database.
        1. Navigate to **Managed Service for&nbsp;YDB**.
        1. Select your database from the list.
        1. Navigate to the **Navigation** tab.
        1. Check that the Managed Service for YDB database contains the `public_sensors` table with test data.

    * YDB CLI

        1. [Connect to the Managed Service for YDB database](../../ydb/operations/connection.md).
        1. Check that the database contains the `public_sensors` table with test data:

            ```bash
            ydb table query execute \
              --query "SELECT * \
              FROM public_sensors"
            ```

    {% endlist %}

1. [Connect to the Managed Service for PostgreSQL source cluster](../../managed-postgresql/operations/connect/index.md) and populate the `sensors` table with data:

    ```sql
    INSERT INTO public.sensors VALUES
        ('iv7b74th678t********', '2020-06-08 17:45:00', 53.70987913, 36.62549834, 378.0, 20.5, 5.3, 20, NULL);
    ```

1. Check that the Managed Service for YDB database shows information about the added row:

    {% list tabs group=instructions %}

    - Management console {#console}

        1. In the [management console](https://console.yandex.cloud), select the folder containing your database.
        1. Navigate to **Managed Service for&nbsp;YDB**.
        1. Select your database from the list.
        1. Navigate to the **Navigation** tab.
        1. Check that `public_sensors` now contains the new data.

    - YDB CLI {#cli}

        1. [Connect to the Managed Service for YDB database](../../ydb/operations/connection.md).
        1. Check that `public_sensors` now contains the new data:

            ```bash
            ydb table query execute \
              --query "SELECT * \
              FROM public_sensors"
            ```

    {% endlist %}

## Delete the resources you created {#clear-out}

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

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Deactivate](../operations/transfer.md#deactivate) and [delete](../operations/transfer.md#delete) the transfer.
    1. [Delete the source and target endpoints](../operations/endpoint/index.md#delete).

    
    1. If you created a service account when creating the target endpoint, [delete it](../../iam/operations/sa/delete.md).


    1. [Delete the Managed Service for YDB database](../../ydb/operations/manage-databases.md#delete-db).
    1. [Delete the Managed Service for PostgreSQL cluster](../../managed-postgresql/operations/cluster-delete.md).

- 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 %}