---
title: "Using TiDB as the Operational Data Layer"
version: "v2"
status: "GA"
description: "In this hands-on lab, you will set up a database replication task from a MySQL source to a TiDB destination. You will also conduct real-time analysis on TiDB as changes are applied to MySQL. Thus, TiDB balances the transactional and analytical workload demands as an Operational Data Layer with TiFlash/HTAP support."
---

# Using TiDB as the Operational Data Layer

## Overview

In this lab, you will set up a database replication task from a MySQL source to a TiDB destination. You will also conduct real-time analysis on TiDB as changes are applied to MySQL. Thus, TiDB balances the transactional and analytical workload demands as an Operational Data Layer.

  ![60%](https://lab-static.pingcap.com/quick-demo/demo_012_en.png)

### Duration

+ This lab should take you approximately 90 minutes to complete.

### Tasks

+ Deploy and start a `TiDB Data Migration` service for a TiDB cluster.
+ Initiate the replication from MySQL to TiDB.
+ Apply the data changes on MySQL, and run the real-time analysis on TiDB.

> [!TIP]
> Click **Start** to launch the lab environment.
> Once the environment is ready, select **Next** on the bottom toolbar to advance to **Module 1**.
> And, follow the step-by-step lab guide to connect to the hands-on environment and begin your tasks.

## Module 1: Connect To A MySQL Server And Run Queries To Verify The Source Schema

### Step 1. Connect to a remote Linux

+ Click here - [Terminal 1](ssh://monitor1-ssh#1) to open a new terminal connected to the virtual machine assigned for your hands-on lab.

+ The banner after you logged in:

    ```output
     ,     #_
    ~\_  ####_        Amazon Linux 2
    ~~  \_#####\
    ~~     \###|      
    ~~       \#/ ___
    ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
     ~~._.   _/
        _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
      _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
    ```

### Step 2. Connect to MySQL server node

+ Connect to the MySQL server node from the remote Linux, if prompted, answer `yes`.

   ```bash
   ssh -i /home/ec2-user/.ssh/pe-class-key-${LAB:REGION_NAME}.pem rocky@${HOST_MYSQL1_PRIVATE_IP}
   ```
   ```output
   Last login: Wed Oct  9 02:16:14 2024 from 10.90.4.225
   [rocky@ip-10-90-1-132 ~]$
   ```

### Step 3. Connect to MySQL server as database user `root`

   ```bash
   mysql -h localhost -P 3306 -u root -pq1w2e3R4_ --connect-expired-password
   ```
   ```output
   mysql> 
   ```

### Step 4. Check the existing schema

+ Verify the tables and data in `sbtest` database are already exist.
   
   ```sql
   SHOW DATABASES;
   ```
   ```output
   +--------------------+
   | Database           |
   +--------------------+
   | information_schema |
   | mysql              |
   | performance_schema |
   | sbtest             |
   | sp500insight       |
   | sys                |
   +--------------------+
   6 rows in set (0.00 sec)
   ```
   ```sql
   SHOW TABLES FROM sp500insight;
   ```
   ```output
   +------------------------+
   | Tables_in_sp500insight |
   +------------------------+
   | companies              |
   | index_compositions     |
   | index_price_history    |
   | indexes                |
   | stock_price_history    |
   | user_selected_stocks   |
   | users                  |
   +------------------------+
   7 rows in set (0.00 sec)
   ```

+ Review the row count of table `sp500insight.stock_price_history` on the MySQL server. It takes more than 5 seconds for the first execution.

   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157000 |
   +----------+
   1 row in set (7.82 sec)
   ```
    
+ Exit to the MySQL server node OS prompt.
   
   ```sql
   EXIT
   ```
   ```output
   bye
   [rocky@ip-10-90-1-132 ~]$
   ```

+ Keep the terminal connected to MySQL server (the prompt you observe should be starting with `[rocky@`) and proceed to the next practice. 

## Module 2: Migrate And Replicate The Sample Database From MySQL To TiDB

### Step 1. Create a user in MySQL for migration purpose

+ On the [Terminal 1](ssh://monitor1-ssh#1), connect to MySQL server to create a dedicated user `dm_user` on MySQL for the migration and replication purpose.

   ```bash
   X=q1w2e3R4_
   mysql -h localhost -P 3306 -uroot -p$X --connect-expired-password << EOF
   DROP USER IF EXISTS dm_user@'%';
   CREATE USER dm_user@'%' IDENTIFIED BY 'q1w2e3R4_';
   GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
   EXIT
   EOF
   ```
   ```output
   mysql: [Warning] Using a password on the command line interface can be insecure.
   ```

+ Exit to the remote TiUP Control Machine.

   ```bash
   exit
   ```
   ```output
   logout
   Connection to 10.90.1.132 closed.
   ```

### Step 2. Verify that the TiDB cluster is already up and running

+ Check the TiDB cluster status. Note that there is one TiDB server, three TiKV servers, and one TiFlash server in `tidb-demo` TiDB cluster.
 
   ```bash
   ~/.tiup/bin/tiup cluster display tidb-demo
   ```
   ```output
   Cluster type:       tidb
   Cluster name:       tidb-demo
   Cluster version:    v8.1.0
   Deploy user:        ec2-user
   SSH type:           builtin
   Dashboard URL:      http://54.218.160.235:2379/dashboard
   Grafana URL:        http://10.90.4.225:3000
   ID                 Role          Host         Ports                            OS/Arch       Status  Data Dir                      Deploy Dir
   --                 ----          ----         -----                            -------       ------  --------                      ----------
   10.90.4.225:9093   alertmanager  10.90.4.225  9093/9094                        linux/x86_64  Up      /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
   10.90.4.225:3000   grafana       10.90.4.225  3000                             linux/x86_64  Up      -                             /tidb-deploy/grafana-3000
   10.90.3.54:2379    pd            10.90.3.54   2379/2380                        linux/x86_64  Up|L    /tidb-data/pd-2379            /tidb-deploy/pd-2379
   10.90.4.225:9090   prometheus    10.90.4.225  9090/12020                       linux/x86_64  Up      /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
   10.90.2.134:4000   tidb          10.90.2.134  4000/10080                       linux/x86_64  Up      -                             /tidb-deploy/tidb-4000
   10.90.4.150:9000   tiflash       10.90.4.150  9000/8123/3930/20170/20292/8234  linux/x86_64  Up      /tidb-data/tiflash-9000       /tidb-deploy/tiflash-9000
   10.90.1.183:20160  tikv          10.90.1.183  20160/20180                      linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   10.90.1.251:20160  tikv          10.90.1.251  20160/20180                      linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   10.90.1.41:20160   tikv          10.90.1.41   20160/20180                      linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   Total nodes: 9
   ```

### Step 3. Create a user for migration purpose in TiDB

+ Create a dedicated user `dm_user` on TiDB for migration and replication purpose.
   
   ```bash
   mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -uroot << 'EOF'
   DROP USER IF EXISTS dm_user@'%';
   CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
   GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
   EXIT
   EOF
   ```

### Step 4. Create a target database in TiDB

+ Create the target database `sp500insight` and its empty tables in TiDB. The tables includes `companies`, `index_compositions`, `index_price_history`, `indexes`, `stock_price_history`, `user_selected_stocks`, and `users`.
   
   ```bash
   mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -uroot
   ```
   ```sql
   CREATE DATABASE sp500insight;
   USE sp500insight;
   CREATE TABLE `companies` (
     `stock_symbol` varchar(10) NOT NULL,
     `exchange_symbol` varchar(50) NOT NULL,
     `short_name` varchar(50) DEFAULT NULL,
     `long_name` varchar(100) DEFAULT NULL,
     `sector` varchar(50) DEFAULT NULL,
     `industry` varchar(50) DEFAULT NULL,
     `current_price` decimal(18,2) DEFAULT NULL,
     `market_cap` bigint(20) DEFAULT NULL,
     `ebitda` bigint(20) DEFAULT NULL,
     `revenue_growth` float DEFAULT NULL,
     `city` varchar(50) DEFAULT NULL,
     `state` varchar(50) DEFAULT NULL,
     `country` varchar(50) DEFAULT NULL,
     `country_code` varchar(3) DEFAULT NULL,
     `full_time_employees` int(11) DEFAULT NULL,
     `long_business_summary` text DEFAULT NULL,
     PRIMARY KEY (stock_symbol, exchange_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `index_compositions` (
     `index_symbol` varchar(10) DEFAULT NULL,
     `stock_symbol` varchar(10) NOT NULL,
     `weight` double DEFAULT NULL,
     PRIMARY KEY (stock_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `index_price_history` (
     `record_date` date NOT NULL,
     `index_symbol` varchar(10) NOT NULL,
     `price` decimal(18,2) DEFAULT NULL,
     PRIMARY KEY (record_date, index_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `indexes` (
     `index_symbol` varchar(10) NOT NULL,
     `short_name` varchar(50) DEFAULT NULL,
     PRIMARY KEY (index_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `stock_price_history` (
     `record_date` date NOT NULL,
     `stock_symbol` varchar(10) NOT NULL,
     `adj_close` decimal(32,16) DEFAULT NULL,
     `close` decimal(32,16) DEFAULT NULL,
     `high` decimal(32,16) DEFAULT NULL,
     `low` decimal(32,16) DEFAULT NULL,
     `open` decimal(32,16) DEFAULT NULL,
     `volume` bigint(20) DEFAULT NULL,
     PRIMARY KEY (record_date, stock_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `user_selected_stocks` (
     `user_id` int(11) NOT NULL,
     `stock_symbol` varchar(10) NOT NULL,
     `created_date` datetime DEFAULT NULL,
     PRIMARY KEY (user_id, stock_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `users` (
     `user_id` int(11) NOT NULL,
     `created_date` datetime DEFAULT NULL,
     PRIMARY KEY (user_id)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   SET GLOBAL allow_auto_random_explicit_insert = true;
   ```

### Step 5. Enable TiFlash for analytical queries

+ Enable the TiFlash analytical columnar storage for table `sp500insight.stock_price_history`.
   
   ```sql
   ALTER TABLE sp500insight.stock_price_history SET TIFLASH REPLICA 1;
   EXIT;
   ```
   ```output
   Query OK, 0 rows affected (0.10 sec)
   Bye
   ```

### Step 6. Install TiDB Data Migration utility

+ Install TiDB Data Migration components.
   
   ```bash
   ~/.tiup/bin/tiup install dm dmctl:v${LAB:TIDB_VERSION} dm-master:v${LAB:TIDB_VERSION} dm-worker:v${LAB:TIDB_VERSION}
   ```
   ```bash
   ~/.tiup/bin/tiup list --verbose | grep dm
   ```
   ```output
   dm                 pingcap  v1.15.1,v1.16.0                     linux/amd64  Data Migration Platform manager
   dm-master          pingcap  v8.0.0,v${LAB:TIDB_VERSION}                       linux/amd64  dm-master component of Data Migration Platform.
   dm-worker          pingcap  v8.0.0,v${LAB:TIDB_VERSION}                       linux/amd64  dm-worker component of Data Migration Platform.
   dmctl              pingcap  v6.5.1,v6.5.9,v7.5.0,v${LAB:TIDB_VERSION}  linux/amd64  dmctl component of Data Migration Platform.
   ```

### Step 7. Review the TiDB Data Migration cluster topology file

+ The TiDB Data Migration cluster topology configuration file has already provisioned for you. Review the configuration, no changes are needed.

   ```bash
   cat dm-topology.yaml 
   ```
   ```output
   global:
     user: "ec2-user"
     ssh_port: 22
     deploy_dir: "/tidb-deploy"
     data_dir: "/tidb-data"
     arch: "amd64"
   master_servers:
     - host: 10.90.4.225
   worker_servers:
     - host: 10.90.4.225
   monitoring_servers:
     - host: 10.90.3.54
   grafana_servers:
     - host: 10.90.3.54
   alertmanager_servers:
     - host: 10.90.3.54
   ```

### Step 8. Deploy and start a TiDB Data Migration cluster

+ Deploy TiDB Data Migration cluster - `dm-test`

   ```bash
   ~/.tiup/bin/tiup dm deploy dm-test v${LAB:TIDB_VERSION} ./dm-topology.yaml \
    --user ec2-user \
    -i /home/ec2-user/.ssh/pe-class-key-${LAB:REGION_NAME}.pem \
    --yes
   ```
   ```output
   Starting component dm: /home/ec2-user/.tiup/components/dm/v1.16.0/tiup-dm deploy dm-test v${LAB:TIDB_VERSION} ./dm-topology.yaml --user ec2-user -i /home/ec2-user/.ssh/pe-class-key-${LAB:REGION_NAME}.pem --yes
   + Detect CPU Arch Name
   .
   .
   .
   Cluster `dm-test` deployed successfully, you can start it with command: `tiup dm start dm-test`
   ```

+ Start the TiDB Data Migration cluster - `dm-test`.

   ```bash
   ~/.tiup/bin/tiup dm start dm-test
   ```
   ```output
   Starting component dm: /home/ec2-user/.tiup/components/dm/v1.16.0/tiup-dm start dm-test
   Starting cluster dm-test...
   + [ Serial ] - SSHKeySet: privateKey=/home/ec2-user/.tiup/storage/dm/clusters/dm-test/ssh/id_rsa, publicKey=/home/ec2-user/.tiup/storage/dm/clusters/dm-test/ssh/id_rsa.pub
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.1.7
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.3.71
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.1.7
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.4.191
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.1.7
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.3.49
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.3.135
   + [ Serial ] - StartCluster
   Starting component dm-master
   	Starting instance 10.90.4.191:8261
   	Start instance 10.90.4.191:8261 success
   Starting component dm-worker
   	Starting instance 10.90.3.135:8262
   	Starting instance 10.90.3.49:8262
   	Starting instance 10.90.3.71:8262
   	Start instance 10.90.3.135:8262 success
   	Start instance 10.90.3.71:8262 success
   	Start instance 10.90.3.49:8262 success
   Starting component prometheus
   	Starting instance 10.90.1.7:9090
   	Start instance 10.90.1.7:9090 success
   Starting component grafana
   	Starting instance 10.90.1.7:3000
   	Start instance 10.90.1.7:3000 success
   Starting component alertmanager
   	Starting instance 10.90.1.7:9093
   	Start instance 10.90.1.7:9093 success
   Started cluster `dm-test` successfully
   ```
  
+ Confirm the status of TiDB Data Migration cluster is up and running.

   ```bash
   tiup dm display dm-test
   ```
   ```output
   Starting component dm: /home/ec2-user/.tiup/components/dm/v1.16.0/tiup-dm display dm-test
   Cluster type:       dm
   Cluster name:       dm-test
   Cluster version:    v${LAB:TIDB_VERSION}
   Deploy user:        ec2-user
   SSH type:           builtin
   Grafana URL:        http://10.90.3.188:3000
   ID                Role          Host         Ports      OS/Arch       Status     Data Dir                      Deploy Dir
   --                ----          ----         -----      -------       ------     --------                      ----------
   10.90.3.188:9093  alertmanager  10.90.3.188  9093/9094  linux/x86_64  Up         /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
   10.90.4.196:8261  dm-master     10.90.4.196  8261/8291  linux/x86_64  Healthy|L  /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
   10.90.4.196:8262  dm-worker     10.90.4.196  8262       linux/x86_64  Free       /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
   10.90.3.188:3000  grafana       10.90.3.188  3000       linux/x86_64  Up         -                             /tidb-deploy/grafana-3000
   10.90.3.188:9090  prometheus    10.90.3.188  9090       linux/x86_64  Up         /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
   Total nodes: 5
   ``` 

### Step 9. Configure the migration source

+ Set up the migration task source configuration.

   ```bash
   cat << EOF > mysql-source-conf1.yaml
   source-id: "mysql-replica-01"
   from:
     host: "${HOST_MYSQL1_PRIVATE_IP}"
     port: 3306
     user: "dm_user"
     password: "q1w2e3R4_"
   EOF
   cat mysql-source-conf1.yaml
   ```
   ```output
   source-id: "mysql-replica-01"
   from:
     host: "10.90.1.135"
     port: 3306
     user: "dm_user"
     password: "q1w2e3R4_"
   ```

+ Set the MySQL instance as the migration source, and verify that the source can be recognized by TiDB Data Migration cluster.   
   
   ```bash
   ~/.tiup/bin/tiup dmctl:v${LAB:TIDB_VERSION} \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 operate-source create mysql-source-conf1.yaml
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v${LAB:TIDB_VERSION}/dmctl/dmctl --master-addr=10.90.4.66:8261 operate-source create mysql-source-conf1.yaml
   {
       "result": true,
       "msg": "",
       "sources": [
           {
               "result": true,
               "msg": "",
               "source": "mysql-replica-01",
               "worker": "dm-10.90.3.187-8262"
           }
       ]
   }
   ```
   ```bash
   ~/.tiup/bin/tiup dmctl:v${LAB:TIDB_VERSION} \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 get-config source mysql-replica-01
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v${LAB:TIDB_VERSION}/dmctl/dmctl --master-addr=10.90.4.66:8261 get-config source mysql-replica-01
   {
       "result": true,
       "msg": "",
       "cfg": "enable: true\nenable-gtid: false\nauto-fix-gtid: false\nrelay-dir: relay-dir\nmeta-dir: \"\"\nflavor: mysql\ncharset: \"\"\nenable-relay: false\nrelay-binlog-name: \"\"\nrelay-binlog-gtid: \"\"\nsource-id: mysql-replica-01\nfrom:\n  host: 10.90.1.135\n  port: 3306\n  user: dm_user\n  password: '******'\n  max-allowed-packet: null\n  session: {}\n  security: null\npurge:\n  interval: 3600\n  expires: 0\n  remain-space: 15\nchecker:\n  check-enable: true\n  backoff-rollback: 5m0s\n  backoff-max: 5m0s\n  check-interval: 5s\n  backoff-min: 1s\n  backoff-jitter: true\n  backoff-factor: 2\nserver-id: 429530419\ntracer: {}\ncase-sensitive: false\nfilters: []\n"
   }
   ```
   ```bash
   ~/.tiup/bin/tiup dmctl:v${LAB:TIDB_VERSION} \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 operate-source show
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v${LAB:TIDB_VERSION}/dmctl/dmctl --master-addr=10.90.4.66:8261 operate-source show
   {
       "result": true,
       "msg": "",
       "sources": [
           {
               "result": true,
               "msg": "",
               "source": "mysql-replica-01",
               "worker": "dm-10.90.3.187-8262"
           }
       ]
   }
   ```

### Step 10. Create and start the migration task

+ Create the migration task configuration and start the migration task. The task will migrate and keep replicating the changes of database `sp500insight` from MySQL server to TiDB cluster.

+ Generate the migration task configuration.

   ```bash
   cat << EOF > dm-task.yaml
   name: "dm-task"
   task-mode: all
   ignore-checking-items: ["auto_increment_ID"]

   target-database:
     host: "${HOST_DB1_PRIVATE_IP}"
     port: 4000
     user: "dm_user"
     password: "q1w2e3R4_"

   mysql-instances:
     - source-id: "mysql-replica-01"
       route-rules: ["instance-1-user-schema-rule"]
       block-allow-list: "rule_1"
       mydumper-config-name: "global"
       loader-config-name: "global"

   routes:
     instance-1-user-schema-rule:
       schema-pattern: "sp500insight"
       target-schema: "sp500insight"

   block-allow-list:
     rule_1:
       do-dbs: ["sp500insight"]

   mydumpers:
     global:
       threads: 32
       chunk-filesize: 64

   loaders:
     global:
       pool-size: 8
       import-mode: "physical"
       pd-addr: "${HOST_PD1_PRIVATE_IP}:2379"
   EOF
   cat dm-task.yaml
   ```
    ```output
    name: "dm-task"
    task-mode: all
    ignore-checking-items: ["auto_increment_ID"]
    .
    .
    .
    loaders:
      global:
        pool-size: 32
        import-mode: "physical"
    ```

+ Pre-check the migration task. The message should be `pre-check is passed`.

  ```bash
  ~/.tiup/bin/tiup dmctl:v${LAB:TIDB_VERSION} \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 check-task ./dm-task.yaml
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v${LAB:TIDB_VERSION}/dmctl/dmctl --master-addr=10.90.4.235:8261 check-task ./dm-task.yaml
  {
  "result": true,
  "msg": "pre-check is passed. "
  }
    ```

+ Start the migration and replication task and check the progress of the migration.
   
   ```bash
   ~/.tiup/bin/tiup dmctl:v${LAB:TIDB_VERSION} \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 start-task ./dm-task.yaml
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/v${LAB:TIDB_VERSION}/dmctl/dmctl --master-addr=10.90.4.66:8261 start-task ./dm-task.yaml
   {
       "result": true,
       "msg": "",
       "sources": [
           {
               "result": true,
               "msg": "",
               "source": "mysql-replica-01",
               "worker": "dm-10.90.3.187-8262"
           }
       ],
       "checkResult": "pre-check is passed. "
   }
   ```

### Step 11. Check the migration progress

+ Check the migration status by using `query-status` action multiple times. Note the `stage`, `unit` and `progress` attributes in the `subTaskStatus`. The task contains 3 sub-task units: `Dump`, `Load`, and `Sync`.

+ Use the `watch` command to monitor the progress of the whole task. Read through the following additional information and observe the migration progress on the screen.

   ```bash
   watch -n 1 -d ~/.tiup/bin/tiup dmctl:v${LAB:TIDB_VERSION} --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 query-status ./dm-task.yaml
   ```
  
+ Unit `Dump`, stage `Running`:
   
    ```output
    {
    ...
          "subTaskStatus": [
              {
                  "name": "dm-task",
                  "stage": "Running",
                  "unit": "Dump",
                  "result": null,
                  "unresolvedDDLLockID": "",
                  "dump": {
                      "totalTables": "6",
                      "completedTables": 3,
                      "finishedBytes": 7949200595,
                      "finishedRows": 39359277,
                      "estimateTotalRows": 59224808,
                      "bps": "57472325",
                      "progress": "64.63 %"
                  },
                  "validation": null
              }
          ]
      }
    ]
    }
    ```

+ Unit `Load`, stage `Running`:

    ```output
    {
    ...
             "subTaskStatus": [
                 {
                     "name": "dm-task",
                     "stage": "Running",
                     "unit": "Load",
                     "result": null,
                     "unresolvedDDLLockID": "",
                     "load": {
                         "finishedBytes": "5307344924",
                         "totalBytes": "8161057816",
                         "progress": "65.03 %",
                         "metaBinlog": "(binlog.000008, 157240317)",
                         "metaBinlogGTID": "",
                         "bps": "62882221"
                     },
                     "validation": null
                 }
             ]
         }
     ]
    }
    ```

+ Unit `Sync`, stage `Running`. Note the target TiDB and the source MySQL are synced.

    ```output
    {
    ...
                "subTaskStatus": [
                    {
                        "name": "dm-task",
                        "stage": "Running",
                        "unit": "Sync",
                        "result": null,
                        "unresolvedDDLLockID": "",
                        "sync": {
                            "totalEvents": "19767046",
                            "totalTps": "21118",
                            "recentTps": "0",
                            "masterBinlog": "(binlog.000011, 706201359)",
                            "masterBinlogGtid": "",
                            "syncerBinlog": "(binlog.000011, 706201359)",
                            "syncerBinlogGtid": "00000000-0000-0000-0000-000000000000:0",
                            "blockingDDLs": [
                            ],
                            "unresolvedGroups": [
                            ],
                            "synced": true,
                            "binlogType": "remote",
                            "secondsBehindMaster": "0",
                            "blockDDLOwner": "",
                            "conflictMsg": "",
                            "totalRows": "19767046",
                            "totalRps": "21118",
                            "recentRps": "0"
                        },
                        "validation": null
                    }
                ]
            }
        ]
    }
    ```

+ Wait and confirm that the migration and replication `subTaskStatus` had reached the `"stage": "Running"` and `"unit": "Sync"` status. Keep the `watch` command running and proceed to the next practice. 

## Module 3: Run Changes On The MySQL Upstream and Run Real-Time Analytical Queries On The TiDB Downstream

### Step 1. Connect to TiDB server instance from remote Linux ${LAB:HOST_MONITOR1_PUBLIC_IP}

+ Click here - [Terminal 2](ssh://monitor1-ssh#2) to open a new terminal connected to the virtual machine assigned for your hands-on lab, and then the TiDB cluster.

+ The banner after you logged in:

    ```output
     ,     #_
    ~\_  ####_        Amazon Linux 2
    ~~  \_#####\
    ~~     \###|      
    ~~       \#/ ___
    ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
     ~~._.   _/
        _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
      _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
    ```

+ Connect to TiDB cluster.

   ```bash
   export MYSQL_PS1="tidb:db1> "
   mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -u root
   ```
   ```output
   tidb:db1> 
   ```

### Step 2. Run query on TiDB downstream

+ Verify the row count of table `sp500insight.stock_price_history` on TiDB. It takes less than 0.1 second for the first execution.
   
   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157000 |
   +----------+
   1 row in set (0.03 sec)
   ```

### Step 3. Run INSERT operation on MySQL upstream

+ Click here - [Terminal 3](ssh://monitor1-ssh#3) to open a new terminal connected to the virtual machine assigned for your hands-on lab, and then the MySQL server.

+ The banner after you logged in:

    ```output
     ,     #_
    ~\_  ####_        Amazon Linux 2
    ~~  \_#####\
    ~~     \###|      
    ~~       \#/ ___
    ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
     ~~._.   _/
        _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
      _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
    ```

+ Connect to MySQL server node.

   ```bash
   ssh -i /home/ec2-user/.ssh/pe-class-key-${LAB:REGION_NAME}.pem rocky@${HOST_MYSQL1_PRIVATE_IP}
   ```
   ```output
   Last login: Thu Aug  1 11:58:47 2024 from 10.90.4.90
   [rocky@ip-10-90-1-235 ~]$
   ```

+ Connect to MySQL server with a database session.

   ```bash
   mysql -h localhost -P 3306 -u root -pq1w2e3R4_ --connect-expired-password
   ```
   ```output
   mysql> 
   ```

+ On [Terminal 3](ssh://monitor1-ssh#3) (the MySQL side), `INSERT` a new row into table `sp500insight.stock_price_history`. Verify that row count had been increased from `1157000` to `1157001`
   
   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   INSERT INTO sp500insight.stock_price_history VALUES (
    '2020-01-12','MMM',60.3188858032226560,77.0199966430664000,67.4499969482421900,91.6699981689453100,91.0899963378906200,3043700);
   SELECT COUNT(*) FROM  sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157000 |
   +----------+
   1 row in set (0.17 sec)
   ...
   Query OK, 1 row affected (0.01 sec)
   ...
   +----------+
   | COUNT(*) |
   +----------+
   |  1157001 |
   +----------+
   1 row in set (0.17 sec)
   ```

### Step 4. Run query on TiDB downstream again to observe the change

+ Back to [Terminal 2](ssh://monitor1-ssh#2) (the TiDB side), observe the change result from TiDB side, the change had been already synced from MySQL. The row count should be `1157001`.
   
   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157001 |
   +----------+
   1 row in set (0.04 sec)
   ```

### Step 5. Observe the execution plan on TiDB

+ Examine the execution plan of the previous `COUNT()` query on TiDB. Note the task column, where `mpp[tiflash]` indicates that these tasks will utilize massive parallel processing in the columnar storage layer — TiFlash.
   
   ```bash
   EXPLAIN SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +------------------------------+------------+--------------+---------------------------+----------------------------------------------------------------------+
   | id                           | estRows    | task         | access object             | operator info                                                        |
   +------------------------------+------------+--------------+---------------------------+----------------------------------------------------------------------+
   | HashAgg_22                   | 1.00       | root         |                           | funcs:count(Column#11)->Column#9                                     |
   | └─TableReader_24             | 1.00       | root         |                           | MppVersion: 2, data:ExchangeSender_23                                |
   |   └─ExchangeSender_23        | 1.00       | mpp[tiflash] |                           | ExchangeType: PassThrough                                            |
   |     └─HashAgg_9              | 1.00       | mpp[tiflash] |                           | funcs:count(sp500insight.stock_price_history.record_date)->Column#11 |
   |       └─TableFullScan_21     | 1157000.00 | mpp[tiflash] | table:stock_price_history | keep order:false                                                     |
   +------------------------------+------------+--------------+---------------------------+----------------------------------------------------------------------+
   ```

+ If time permits, experiment with additional modifications on the MySQL side and observe the results in TiDB, as well as other analytical queries in TiDB. For example:
   ```sql
   USE sp500insight;
   WITH index_companies AS (
      SELECT
          c.stock_symbol, c.short_name, c.exchange_symbol, ic.weight, c.market_cap AS market_cap, c.revenue_growth AS revenue_growth
      FROM companies c
      JOIN index_compositions ic ON c.stock_symbol = ic.stock_symbol
      WHERE index_symbol = 'SP500' AND sector = 'Energy'
   ), companies_latest_price AS (
      SELECT
          stock_symbol, DATE(last_day) AS last_change_day, last_close_price, last_2nd_close_price, 
          last_close_price - last_2nd_close_price AS last_change,
          (last_close_price - last_2nd_close_price) / last_2nd_close_price AS last_change_percentage
      FROM (
        SELECT
          LAST_VALUE(stock_symbol) OVER (PARTITION BY stock_symbol ORDER BY record_date) AS stock_symbol,
          LAST_VALUE(record_date) OVER (PARTITION BY stock_symbol ORDER BY record_date) AS last_day,
          NTH_VALUE(close, 1) OVER (PARTITION BY stock_symbol ORDER BY record_date DESC) AS last_close_price,
          NTH_VALUE(close, 2) OVER (PARTITION BY stock_symbol ORDER BY record_date DESC) AS last_2nd_close_price,
          ROW_NUMBER() OVER (PARTITION BY stock_symbol ORDER BY record_date DESC) AS row_num
        FROM stock_price_history sph
        WHERE
          record_date > DATE_SUB((SELECT MAX(record_date) FROM stock_price_history), INTERVAL 2 DAY)
          AND sph.stock_symbol IN (SELECT stock_symbol FROM index_companies ic)
      ) sub
      WHERE
          row_num = 2
   )
   SELECT
      ic.stock_symbol, ic.exchange_symbol, ic.short_name, ic.weight, ic.market_cap, ic.revenue_growth,
      clp.last_change, clp.last_change_day, clp.last_close_price, clp.last_2nd_close_price, clp.last_change_percentage
   FROM index_companies ic
   LEFT JOIN companies_latest_price clp ON ic.stock_symbol = clp.stock_symbol
   ORDER BY ic.weight DESC;
   ```
   ```output
   +--------------+-----------------+---------------------------------+------------------------+--------------+----------------+---------------------+-----------------+----------------------+----------------------+-------------------------+
   | stock_symbol | exchange_symbol | short_name                      | weight                 | market_cap   | revenue_growth | last_change         | last_change_day | last_close_price     | last_2nd_close_price | last_change_percentage  |
   +--------------+-----------------+---------------------------------+------------------------+--------------+----------------+---------------------+-----------------+----------------------+----------------------+-------------------------+
   | XOM          | NYQ             | Exxon Mobil Corporation         |   0.013441937585551282 | 474511933440 |          0.689 |  1.2800064086914100 | 2023-01-10      | 111.3700027465820300 | 110.0899963378906200 |  0.01162690935843785832 |
   | CVX          | NYQ             | Chevron Corporation             |   0.009567226003564158 | 337731289088 |           0.81 | -0.8399963378906000 | 2023-01-10      | 175.1999969482422000 | 176.0399932861328000 | -0.00477162218772232275 |
   | COP          | NYQ             | ConocoPhillips                  |   0.004417814517419704 | 155952644096 |          1.237 |  0.1599960327148400 | 2023-01-10      | 118.2399978637695300 | 118.0800018310546900 |  0.00135497993084178221 |
   | SLB          | NYQ             | Schlumberger N.V.               |  0.0022377960040345308 |  78996119552 |          0.279 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | EOG          | NYQ             | EOG Resources, Inc.             |  0.0021024604924476343 |  74218659840 |          0.924 | -0.7600021362304600 | 2023-01-10      | 126.8499984741211000 | 127.6100006103515600 | -0.00595566282105957140 |
   | MPC          | NYQ             | Marathon Petroleum Corporation  |   0.002050747487098508 |  72393146368 |          0.818 |  1.0999984741211000 | 2023-01-10      | 117.5999984741211000 | 116.5000000000000000 |  0.00944204698816394850 |
   | OXY          | NYQ             | Occidental Petroleum Corporatio |   0.001695676548826279 |  59858837504 |          0.792 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | PXD          | NYQ             | Pioneer Natural Resources Compa |  0.0016017013932190817 |  56541433856 |          0.641 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | VLO          | NYQ             | Valero Energy Corporation       |  0.0015472850935959574 |  54620491776 |          0.593 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | HES          | NYQ             | Hess Corporation                |  0.0012744122628788822 |  44987846656 |          0.776 |  1.6300048828125000 | 2023-01-10      | 145.2500000000000000 | 143.6199951171875000 |  0.01134942861878312162 |
   | PSX          | NYQ             | Phillips 66                     |  0.0012589621320069535 |  44442443776 |          0.799 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | KMI          | NYQ             | Kinder Morgan, Inc.             |  0.0012062691273686955 |  42582335488 |          0.354 |  0.0400009155273440 | 2023-01-10      |  18.7800006866455080 |  18.7399997711181640 |  0.00213452059850037319 |
   | DVN          | NYQ             | Devon Energy Corporation        |  0.0012053375130788024 |  42549448704 |          0.789 | -0.2800025939941400 | 2023-01-10      |  62.8499984741210940 |  63.1300010681152340 | -0.00443533326875800678 |
   | WMB          | NYQ             | Williams Companies, Inc. (The)  |  0.0011162172177908748 |  39403425792 |          0.091 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | HAL          | NYQ             | Halliburton Company             |  0.0010393744130051477 |  36690808832 |          0.388 |  0.0500030517578160 | 2023-01-10      |  40.9900016784668000 |  40.9399986267089840 |  0.00122137404580161222 |
   | OKE          | NYQ             | ONEOK, Inc.                     |  0.0008854096904464799 |  31255721984 |          0.769 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | BKR          | NMS             | Baker Hughes Company            |  0.0008807471517968449 |  31091130368 |          0.054 | -0.0400009155273450 | 2023-01-10      |  30.8299999237060550 |  30.8700008392334000 | -0.00129578602008027511 |
   | FANG         | NMS             | Diamondback Energy, Inc.        |   0.000730020047064916 |  25770334208 |          0.565 |  0.2900085449218600 | 2023-01-10      | 142.2400054931640600 | 141.9499969482422000 |  0.00204303311839874783 |
   | MRO          | NYQ             | Marathon Oil Corporation        |  0.0005965698099807201 |  21059426304 |          0.731 |  0.0399990081787110 | 2023-01-10      |  27.0499992370605470 |  27.0100002288818360 |  0.00148089625471161593 |
   | CTRA         | NYQ             | Coterra Energy Inc.             |  0.0005690298110137097 |  20087240704 |          5.204 | -0.3899993896484380 | 2023-01-10      |  24.6900005340576170 |  25.0799999237060550 | -0.01555021494556719473 |
   | TRGP         | NYQ             | Targa Resources, Inc.           |  0.0004842024080652878 |  17092760576 |          0.773 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | APA          | NMS             | APA Corporation                 | 0.00039910236086756015 |  14088655872 |          0.374 |  0.5799980163574200 | 2023-01-10      |  43.8199996948242200 |  43.2400016784668000 |  0.01341345961709929139 |
   | EQT          | NYQ             | EQT Corporation                 |  0.0003576031445812937 |  12623697920 |          1.092 | -0.6399993896484380 | 2023-01-10      |  33.4000015258789060 |  34.0400009155273440 | -0.01880139166966068805 |
   +--------------+-----------------+---------------------------------+------------------------+--------------+----------------+---------------------+-----------------+----------------------+----------------------+-------------------------+
   23 rows in set (0.01 sec)
   ```

## Conclusion

An operational data store serves as a central repository that aggregates data from various sources, aiming to facilitate operations like real-time data analysis and reporting. Unlike a traditional data warehouse, an ODS is often updated in real-time and acts as an intermediary between the primary operational systems and the data warehouse.

```hbsptform
{
  "ui": {
    "titleLevel": 3
  },
  "portalId": "4466002",
  "formId": "89fa8368-eba1-4b84-b91e-eb9eb6613ddf",
  "region": "na1",
  "sfdcCampaignId": "701RC00000VqCODYA3"
}
```