# **练习-1 : 使用 `TiDB Lightning` 向 `TiDB` 导入 CSV 格式文件**

## 概述
+ 本练习中，您将使用 TiDB Lightning 来向 TiDB 数据库中导入 CSV 格式的文件

## 实验环境要求
+ 1. 注意，您的实验环境（包括IP，端口号，用户名，密码和目录）可能和手册不同。
+ 2. 可以连接到实验用虚拟机。
+ 3. TiDB 数据库提前部署完毕。
+ 4. 清理掉之前的实验数据。


## 步骤

-----------------------------------------------
#### 1. TiDB Lightning 工具集成在 tidb-toolkit 中，先进行下载安装:
+ **请从网址：https://pingcap.com/zh/product-community/ 中下载最新的 TiDB-community-toolkit 软件包，并上传到练习环境中。**  

+ **解压下载的软件包**：
    ```
     # tar xvf tidb-community-toolkit-v6.1.0-linux-amd64.tar
    ```

+ **解压 TiDB Lightning 工具**
    ```
     # cd tidb-community-toolkit-v6.1.0-linux-amd64
     # tar xvf tidb-lightning-v6.1.0-linux-amd64.tar.gz
    ```
    ```
     tidb-lightning
    ```

+ **确认安装完毕:**
     ```
     # ls tidb-lightning*
    ``` 
    ```
     tidb-lightning  tidb-lightning-ctl  tidb-lightning-v6.1.0-linux-amd64.tar.gz
    ``` 
+ **也可以将目录加入环境变量，方便后续执行:** 
    ```
     # cd
     # vi .bash_profile
    ``` 
    ```
     PATH=$PATH:$HOME/bin:/usr/local/mysql/bin:/root/tidb-community-toolkit-v6.1.0
    ``` 
-----------------------------------------------
#### 2. 查看需要导入的 CSV 格式数据文件:
+ **我们发现一共有 11 个文件分别为: emp.sal.000000000.csv ~ emp.sal.000000010.csv**
    ```
    # ls
    ```
    ```
    emp.sal.000000000.csv  emp.sal.000000002.csv  emp.sal.000000004.csv  emp.sal.000000006.csv  emp.sal.000000008.csv  emp.sal.000000010.csv
    emp.sal.000000001.csv  emp.sal.000000003.csv  emp.sal.000000005.csv  emp.sal.000000007.csv  emp.sal.000000009.csv
    ```
+ **查看 CSV 文件的数据格式**
    ```
    # vi emp.sal.000000000.csv
    ```

-----------------------------------------------
#### 3. 编辑 TiDB Lightning 工具的配置文件:
+ **编辑文件 tidb-lightning-1.toml，如下:**
    ```
    # vi tidb-lightning-1.toml
    ```

-----------------------------------------------
#### 4. 连接到目标 `TiDB` ，准备并检查导入数据前的 `TiDB` 数据库:(请根据自己实验环境输入密码)
+ **连接到目标 `TiDB` 数据库，创建 database 名为：emp，创建表 sal，如下:**
    ```sql
    # mysql -h172.31.0.135 -P4000 -uroot -ptidb
    mysql> drop database emp;
    mysql> create database emp;
    mysql> use emp;

    mysql> CREATE TABLE `sal` ( `emp_no` int(11) NOT NULL, `salary` int(11) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`from_date`));

    mysql> select count(*) from emp.sal;
    ```
-----------------------------------------------
#### 5. 使用 TiDB Lightning 工具进行数据导入:
+ **启动 TiDB Lightning，如下:**
    ```
      # ! /bin/bash
      # nohup tidb-lightning -config tidb-lightning-1.toml > nohup.out &
    ```
+ **这里请注意：此时屏幕光标会悬停在最后一行，我们可以点击回车键“Enter”，来使 nohup 的 tidb-lighting 在后台工作， 如下:**
    ```
      # nohup tidb-lightning -config tidb-lightning-1.toml > nohup.out &
      [1] 17481
      # nohup: ignoring input and redirecting stderr to stdout

      # 
    ```
+ **TiDB Lightning 导入完毕后，会出现如下字样:**
    ```
      [1]+  Done                    nohup tidb-lightning -config tidb-lightning-1.toml > nohup.out
    ```
-----------------------------------------------
#### 6. 检查数据导入结果:
+ **检查nohup日志，确认 TiDB Lightning 正常退出，如下:**
    ```
    # vi nohup.out
    ```
    
+ **如果 TiDB Lightning 没有正常退出请检查其日志文件 tidb-lightning.log，来确认出错原因，如下:**
    ```
    vi tidb-lightning.log
    ```

+ **连接到目标 `TiDB` 数据库，查看 emp.sal 表中是否有数据，如下:**
    ```sql
    # mysql -h172.31.0.135 -P4000 -uroot -ptidb
    mysql> select count(*) from emp.sal;
    +----------+
    | count(*) |
    +----------+
    |   551395 |
    +----------+
    1 row in set (0.20 sec)
    ```

+ **注意：目前我们只能确认 TiDB Lightning 将数据导入到 TiDB 目标库中，如果需要进一步验证数据的正确性，请使用 sync-diff-inspector 工具。**
-----------------------------------------------

## 输出样例

-----------------------------------------------
#### 步骤1-解压下载的软件包输出参考：
```
    # tar xvf tidb-community-toolkit-v6.1.0-linux-amd64.tar
```
```
tidb-community-toolkit-v6.1.0-linux-amd64/
tidb-community-toolkit-v6.1.0-linux-amd64/reparo
tidb-community-toolkit-v6.1.0-linux-amd64/2225.cdc.json
tidb-community-toolkit-v6.1.0-linux-amd64/9.errdoc.json
tidb-community-toolkit-v6.1.0-linux-amd64/805.dm-master.json
tidb-community-toolkit-v6.1.0-linux-amd64/2.spark.json
tidb-community-toolkit-v6.1.0-linux-amd64/1.root.json
tidb-community-toolkit-v6.1.0-linux-amd64/213.tiup.json
...
tidb-community-toolkit-v6.1.0-linux-amd64/dmctl-v6.1.0-linux-amd64.tar.gz
tidb-community-toolkit-v6.1.0-linux-amd64/root.json
```

-----------------------------------------------
#### 步骤2-查看 CSV 文件的数据格式输出参考：
```
# vi emp.sal.000000000.csv
```
```
"emp_no","salary","from_date","to_date"
10001,60117,"1986-06-26","1987-06-26"
10001,62102,"1987-06-26","1988-06-25"
10001,66074,"1988-06-25","1989-06-25"
10001,66596,"1989-06-25","1990-06-25"
10001,66961,"1990-06-25","1991-06-25"
10001,71046,"1991-06-25","1992-06-24"
10001,74333,"1992-06-24","1993-06-24"
10001,75286,"1993-06-24","1994-06-24"
10001,75994,"1994-06-24","1995-06-24"
10001,76884,"1995-06-24","1996-06-23"
10001,80013,"1996-06-23","1997-06-23"
10001,81025,"1997-06-23","1998-06-23"
...
```
-----------------------------------------------
#### 步骤3-编辑文件 tidb-lightning-1.toml 输出参考：
```
# vi tidb-lightning-1.toml
```
```
[lightning]

# 转换数据的并发数，默认为逻辑 CPU 数量，不需要配置。
# 混合部署的情况下可以配置为逻辑 CPU 的 75% 大小。
# region-concurrency = 1

# 日志
level = "info"
file = "tidb-lightning.log"

[tikv-importer]
# backend 设置为 local 模式
backend = "local"
# 设置本地临时存储路径
sorted-kv-dir = "/tmp/sorted-kv-dir"

[mydumper]
# 源数据目录。
data-source-dir = "/root/sample/csv"
# 配置通配符规则，默认规则会过滤 mysql、sys、INFORMATION_SCHEMA、PERFORMANCE_SCHEMA、METRICS_SCHEMA、INSPECTION_SCHEMA 系统数据库下的所有表
# 若不配置该项，导入系统表时会出现“找不到 schema”的异常
filter = ['*.*', '!mysql.*', '!sys.*', '!INFORMATION_SCHEMA.*', '!PERFORMANCE_SCHEMA.*', '!METRICS_SCHEMA.*', '!INSPECTION_SCHEMA.*']

[[mydumper.files]]
# 只导入 00001~05000 这些数据文件并忽略其他文件
pattern = '(?i)^(?:[^/]*/)*emp\.sal\.(00000000[0-1]|000000001)\.csv'
schema = "emp"
table = "sal"
type = "csv"

[mydumper.csv]
# 字段分隔符，支持一个或多个字符，默认值为 ','。如果数据中可能有逗号，建议源文件导出时分隔符使用非常见组合字符例如'|+|'。
separator = ','
# 引用定界符，设置为空表示字符串未加引号。
delimiter = '"'
# 行尾定界字符，支持一个或多个字符。设置为空（默认值）表示 "\n"（换行）和 "\r\n" （回车+换行），均表示行尾。
terminator = ""
# CSV 文件是否包含表头。
# 如果为 true，首行将会被跳过。
header = true
# CSV 是否包含 NULL。
# 如果为 true，CSV 文件的任何列都不能解析为 NULL。
not-null = false
# 如果 `not-null` 为 false（即 CSV 可以包含 NULL），
# 为以下值的字段将会被解析为 NULL。
null = '\N'
# 是否解析字段内的反斜线转义符。
backslash-escape = true
# 是否移除以分隔符结束的行。
trim-last-separator = false

[tidb]
# 目标集群的信息。tidb-server 的监听地址，填一个即可。
host = "172.31.0.135"
port = 4000
user = "root"
password = "tidb"
# 表架构信息在从 TiDB 的“状态端口”获取。
status-port = 10080
# pd-server 的地址，填一个即可
pd-addr = "172.31.0.233:2379"
```
-----------------------------------------------
#### 步骤6-检查数据导入结果输出参考
```
# vi nohup.out
```
```
    Verbose debug logs will be written to tidb-lightning.log

    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  # | CHECK ITEM                                                                                                            | TYPE        | PASSED |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  1 | Source csv files size is proper                                                                                       | performance | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  2 | checkpoints are valid                                                                                                 | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  3 | table schemas are valid                                                                                               | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  4 | Cluster is available                                                                                                  | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  5 | Lightning has the correct storage permission                                                                          | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |^[[33m  6 ^[[0m|^[[33m sorted-kv-dir:/tmp/sorted-kv-dir and data-source-dir:/root/sample/csv are in the same disk, may slow down performance ^[[0m|^[[33m performance ^[[0m|^[[33m false  ^[[0m|
    +^[[33m----^[[0m+^[[33m-----------------------------------------------------------------------------------------------------------------------^[[0m+^[[33m-------------^[[0m+^[[33m--------^[[0m+
    |  7 | local disk resources are rich, estimate sorted data size 20.53MiB, local available is 5.15GiB                         | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  8 | Cluster available is rich, available is 54.48GiB, we need 61.58MiB                                                    | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    |  9 | Cluster doesn't have too many empty regions                                                                           | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+
    | 10 | Cluster region distribution is balanced                                                                               | critical    | true   |
    +----+-----------------------------------------------------------------------------------------------------------------------+-------------+--------+

    tidb lightning exit successfully
```

-----------------------------------------------