В этом документе описывается инструмент миграции данных mxshift.
Инструмент mxshift в настоящее время поддерживает следующие функции:
WHERE.REPLICATED) и таблицы только на мастер-узле.В данном разделе подробно описаны параметры инструмента mxshift.
Для использования mxshift необходимо подготовить файл конфигурации в формате TOML. Ниже приведено подробное описание параметров:
Для выполнения условной миграции с использованием предложения WHERE используйте следующие параметры:
| Категория | Подкатегория | Подпараметр | Подподкатегория | Подподпараметр | Описание | Обязательный |
| [transfer] категория | [transfer.table-data-where-sql] категория | --enabled | Если установлено значение `true`, фильтрует данные источника с помощью условия WHERE, мигрируя только соответствующие строки. Эта функция по умолчанию отключена и должна быть включена вручную с помощью `--enabled=true`. | Нет | ||
| --global | Глобальное выражение WHERE, применяемое ко всем таблицам. Если таблица не содержит указанного столбца, `mxshift` пропускает таблицу с предупреждением. | Нет | ||||
| [[transfer.table-data-where-sql.override]] категория | --where | Условие WHERE, специфичное для таблицы, имеет приоритет над глобальным. Применяется фильтрация на уровне таблицы. | Нет | |||
| [transfer.table-data-where-sql.override.table] категория | --schema | Имя схемы таблицы, которую нужно мигрировать | Нет | |||
| --name | Имя таблицы для миграции | Нет |
Примеры использования см. в шаблонах конфигурации ниже.
Параметры командной строки для mxshift:
| Параметр | Описание |
|---|---|
| --config | Выводит содержимое файла конфигурации по умолчанию |
| -a или --all | Запускает миграцию без подтверждения. По умолчанию пропускает уже завершённые и пустые таблицы |
| -c или --config-path | Путь к глобальному файлу конфигурации для mxshift |
| -v или --version | Отображает версию mxshift |
| -l или --show-progress | Показывает ход последней миграции. Если миграция не выполняется, показывает результат последнего запуска. Если активна — текущий прогресс. Значения STATUS: Not start — не входит в область; Skip — пропущена (уже мигрирована или пустая); Processing/Interrupted — в процессе или прервана; Complete — успешно мигрирована; Failed — миграция завершилась с ошибкой |
| -R или --redo | Повторно мигрирует таблицы, даже если они уже были мигрированы (перед повторной миграцией очищает существующие данные в целевой таблице) |
Полный шаблонный файл называется config_template.toml. Вы можете создать этот шаблон, запустив mxshift --config.
Ниже приведены примеры шаблонов для различных случаев использования. Используйте их в качестве образца и настройте с помощью текстового редактора.
[database]
[database.source]
## Name of database
db-database= "testdb"
## Hostname of database master
db-host="sdw3"
## password of database
db-password="xxxx"
## Port of database master
db-port=54322
## user name of database
db-user="gpadmin"
## Version of database(Please use the result of 'SELECT version();' as value). Required only when
## 1. Source database is un-reachable, and 'ddl.only-ddl' is enabled and 'ddl.mode' is 'input'
## 2. Target database is un-reachable, and 'ddl.mode' is 'output' */
# db-version="PostgreSQL 12 (MatrixDB 5.1.0-enterprise) (Greenplum Database 7.0.0+dev.17410.gedbdb5ef84 build dev) on arm-apple-darwin21.5.0, compiled by Apple clang version 13.0.0 (clang-1300.0.27.3), 64-bit compiled on Jun 5 2023 15:45:24"
## The installation directory of database
install-dir="/usr/local/greenplum-db-6.7.1"
[[database.source.hostname-to-ip]]
## The content within <> should be replaced with actual information and <> should be removed
node-hostname="<mdw>"
node-ip="<127.0.0.1>"
[[database.source.hostname-to-ip]]
node-hostname="<sdw1>"
node-ip="<127.0.0.2>"
[[database.source.hostname-to-ip]]
node-hostname="<sdw2>"
node-ip="<127.0.0.3>"
[database.target]
## Name of database
db-database="destdb"
## Hostname of database master
db-host="172.16.100.32"
## password of database
db-password="yyyy"
## Port of database master
db-port=5432
## user name of database
db-user="mxadmin"
## Version of database(Please use the result of 'SELECT version();' as value). Required only when
## 1. Source database is un-reachable, and 'ddl.only-ddl' is enabled and 'ddl.mode' is 'input'
## 2. Target database is un-reachable, and 'ddl.mode' is 'output' */
# db-version="PostgreSQL 12 (MatrixDB 5.1.0-enterprise) (Greenplum Database 7.0.0+dev.17410.gedbdb5ef84 build dev) on arm-apple-darwin21.5.0, compiled by Apple clang version 13.0.0 (clang-1300.0.27.3), 64-bit compiled on Jun 5 2023 15:45:24"
[scope]
## The compress method for transferring data, methods restricted to 0/gzip/lz4/zstd
compress-method="lz4"
## mode for transferring data from source to target database, and value restricted to normal/dryrun/fetch/motion.
##dryrun for only executing ddl, not transferring data
##fetch for fetching data from source and abandon
##motion for fetching data from source, redistributing and finally abandon
mode="normal"
## Sql for select segment information from source database
# select-source-segment-sql="SELECT dbid, content, port, hostname FROM gp_segment_configuration WHERE status = 'u' AND role = 'p' ORDER BY CONTENT;"
## Sql for select segment information from target database
# select-target-segment-sql="SELECT dbid, content, port, hostname FROM gp_segment_configuration WHERE status = 'u' AND role = 'p' ORDER BY CONTENT;"
[[scope.table-list]]
schema="test_schema_1"
name="table_001"
[[scope.table-list]]
schema="test_schema_2"
name="table_002"
[[scope.exclude-table-list]]
schema="test_schema_3"
name="table_003"
schema-list=["test_schema_1", "test_schema_2"]
exclude-schema-list=["test_schema_5", "test_schema_8"]
## Whether to disable data incremental migration, by default, it is true.
# disable-data-increment=true
[log]
## The log level, value restricted to: debug/verbose/info.
log-level="info"
## Print log without color.
# no-color=false
[controller]
## By default, transfer work will start from the largest table. If set 'bothway' it will start from both the largest and the smallest table
both-way=true
## The number of table transferred at the same time
concurrency=3
[transfer]
## Verity the number of record of every table
verify=true
with-index=true
[ddl]
enabled=true
# file-path="/tmp/mxshift.sql"
# mode="output"
only-ddl=false
## During the DDL transfer, whether to skip the transfer of resource queue or group, by default, it is true.
# skip-resource-queue-and-group=true
## During the DDL transfer, whether to skip the transfer of tablespace, by default, it is true.
# skip-table-space=true
[[ddl.replace]]
## Only applicable for the case of migration from Greenplum to YMatrix
category="role"
[[ddl.replace.pairs]]
old="gpadmin"
new="mxadmin"
## Whether to disable ddl incremental migration, by default, it is true.
# disable-ddl-increment=true
После подготовки TOML-файла выполните следующую команду для запуска полной миграции:
$ mxshift -c config_path_full.toml
[database]
[database.source]
## Name of database
db-database= "testdb"
## Hostname of database master
db-host="sdw3"
## password of database
db-password="xxxx"
## Port of database master
db-port=54322
## user name of database
db-user="gpadmin"
## Version of database(Please use the result of 'SELECT version();' as value). Required only when
## 1. Source database is un-reachable, and 'ddl.only-ddl' is enabled and 'ddl.mode' is 'input'
## 2. Target database is un-reachable, and 'ddl.mode' is 'output' */
# db-version="PostgreSQL 12 (MatrixDB 5.1.0-enterprise) (Greenplum Database 7.0.0+dev.17410.gedbdb5ef84 build dev) on arm-apple-darwin21.5.0, compiled by Apple clang version 13.0.0 (clang-1300.0.27.3), 64-bit compiled on Jun 5 2023 15:45:24"
## The installation directory of database
install-dir="/usr/local/greenplum-db-6.7.1"
[[database.source.hostname-to-ip]]
## The content within <> should be replaced with actual information and <> should be removed
node-hostname="<mdw>"
node-ip="<127.0.0.1>"
[[database.source.hostname-to-ip]]
node-hostname="<sdw1>"
node-ip="<127.0.0.2>"
[[database.source.hostname-to-ip]]
node-hostname="<sdw2>"
node-ip="<127.0.0.3>"
[database.target]
## Name of database
db-database="destdb"
## Hostname of database master
db-host="172.16.100.32"
## password of database
db-password="yyyy"
## Port of database master
db-port=5432
## user name of database
db-user="mxadmin"
## Version of database(Please use the result of 'SELECT version();' as value). Required only when
## 1. Source database is un-reachable, and 'ddl.only-ddl' is enabled and 'ddl.mode' is 'input'
## 2. Target database is un-reachable, and 'ddl.mode' is 'output' */
# db-version="PostgreSQL 12 (MatrixDB 5.1.0-enterprise) (Greenplum Database 7.0.0+dev.17410.gedbdb5ef84 build dev) on arm-apple-darwin21.5.0, compiled by Apple clang version 13.0.0 (clang-1300.0.27.3), 64-bit compiled on Jun 5 2023 15:45:24"
[scope]
## The compress method for transferring data, methods restricted to 0/gzip/lz4/zstd
compress-method="lz4"
## mode for transferring data from source to target database, and value restricted to normal/dryrun/fetch/motion.
##dryrun for only executing ddl, not transferring data
##fetch for fetching data from source and abandon
##motion for fetching data from source, redistributing and finally abandon
mode="normal"
## Sql for select segment information from source database
# select-source-segment-sql="SELECT dbid, content, port, hostname FROM gp_segment_configuration WHERE status = 'u' AND role = 'p' ORDER BY CONTENT;"
## Sql for select segment information from target database
# select-target-segment-sql="SELECT dbid, content, port, hostname FROM gp_segment_configuration WHERE status = 'u' AND role = 'p' ORDER BY CONTENT;"
[[scope.table-list]]
schema="test_schema_1"
name="table_001"
[[scope.table-list]]
schema="test_schema_2"
name="table_002"
[[scope.exclude-table-list]]
schema="test_schema_3"
name="table_003"
schema-list=["test_schema_1", "test_schema_2"]
exclude-schema-list=["test_schema_5", "test_schema_8"]
## Whether to disable data incremental migration. By default, it is set to `true`.
disable-data-increment=false
[log]
## The log level. Valid values are: debug, verbose, info.
log-level="info"
## Print log without color.
# no-color=false
[controller]
## By default, transfer work starts from the largest table. If set to 'bothway', it starts from both the largest and smallest tables.
both-way=true
## The number of tables to transfer concurrently.
concurrency=3
[transfer]
## Проверьте количество записей в каждой таблице.
verify=true
with-index=true
[ddl]
enabled=true
# file-path="/tmp/mxshift.sql"
# mode="output"
only-ddl=false
## Во время передачи DDL, следует ли пропускать миграцию очереди ресурсов или групп ролей. По умолчанию true.
# skip-resource-queue-and-group=true
## Во время передачи DDL, следует ли пропускать миграцию tablespace. По умолчанию true.
# skip-table-space=true
[[ddl.replace]]
## Применимо только при миграции из Greenplum в YMatrix
category="role"
[[ddl.replace.pairs]]
old="gpadmin"
new="mxadmin"
## Следует ли отключить инкрементную миграцию DDL. По умолчанию true.
disable-ddl-increment=false
After preparing the TOML file, run the following command to start mxshift for incremental migration.
$ mxshift -c config_path_incremental.toml
Используйте WHERE, чтобы выполнить миграцию данных на основе определённых условий, например, исключив устаревшие данные:
[database]
[database.source]
## Name of the source database
db-database= "testdb"
## Hostname of the source database master
db-host="sdw3"
## Password for the source database
db-password="xxxx"
## Port of the source database master
db-port=54322
## Username for the source database
db-user="gpadmin"
## Installation directory of the source database
install-dir="/usr/local/greenplum-db-6.7.1"
[database.target]
## Name of the target database
db-database="destdb"
## Hostname of the target database master
db-host="172.16.100.32"
## Password for the target database
db-password="yyyy"
## Port of the target database master
db-port=5432
## Username for the target database
db-user="mxadmin"
[scope]
## Compression method used during data transfer. Valid methods: 0 (no compression), gzip, lz4, zstd
compress-method="lz4"
## Data transfer mode. Valid values: normal, dryrun, fetch, motion
## dryrun: Execute DDL only; do not transfer data
## fetch: Extract data from source and discard
## motion: Extract data from source, redistribute across segments, then discard
mode="normal"
## SQL to query segment information from the source database
# select-source-segment-sql="SELECT dbid, content, port, hostname FROM gp_segment_configuration WHERE status = 'u' AND role = 'p' ORDER BY CONTENT;"
## SQL to query segment information from the target database
# select-target-segment-sql="SELECT dbid, content, port, hostname FROM gp_segment_configuration WHERE status = 'u' AND role = 'p' ORDER BY CONTENT;"
[[scope.table-list]]
schema=......
name=......
[[scope.table-list]]
......
[[scope.exclude-table-list]]
......
schema-list=["test_schema_1", "test_schema_2"]
exclude-schema-list=["test_schema_5", "test_schema_8"]
[log]
## The log level. Valid values are: debug, verbose, info.
log-level="info"
## Print log without color.
# no-color=false
[controller]
## By default, transfer starts from the largest table. Set to 'bothway' to start from both largest and smallest.
both-way=true
## Number of tables to transfer in parallel.
concurrency=3
[transfer]
## Verify row count for every table after transfer.
verify=true
[transfer.table-data-where-sql]
enabled=true
global="txdate >= '2022-10-01' AND batchnum >= 100000000"
[[transfer.table-data-where-sql.override]]
where="abc > 10"
[transfer.table-data-where-sql.override.table]
schema="test_schema_1"
name="table_001"
[[transfer.table-data-where-sql.override]]
where="tag != 'aabbcc' AND ts > '2022-01-01'"
[transfer.table-data-where-sql.override.table]
schema="test_schema_2"
name="another_table"
После подготовки TOML-файла запустите следующую команду для начала миграции с помощью mxshift.
$ mxshift -c config_path_conditional.toml
При миграции всей базы данных или всех реплицированных таблиц в определённой схеме дополнительная настройка в config_path.toml не требуется. mxshift автоматически распознаёт реплицированные таблицы и применяет соответствующую стратегию миграции, предотвращая дублирование данных. Вам нужно лишь настроить scope.table-list, конкретно определив schema и name.
[[scope.table-list]]
schema="public1"
name="table_replicated1"
[[scope.table-list]]
schema="public2"
name="table_replicated2"
После подготовки TOML-файла запустите следующую команду для начала миграции реплицированных таблиц с помощью mxshift.
$ mxshift -c config_path_replicated.toml
Примечание!
Полный обзор стратегий и процедур миграции данных см. в разделе Миграция данных