Сравнить две схемы/среды (schema diff)
Oracle
-- Extract the schema DDL from both environments and take a text diff
-- (generate deterministic DDL with DBMS_METADATA)
EXEC DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SQLTERMINATOR',TRUE);
EXEC DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE',FALSE);
SELECT DBMS_METADATA.GET_DDL('TABLE', table_name) FROM user_tables ORDER BY table_name;
-- Spool the output to a file in both environments and compare with diff/fc.
-- Export the schema as a changelog with SQLcl's Liquibase integration:
-- SQL> lb generate-schema
-- Commercial: the Oracle SQL Developer 'Database Diff' tool is also used.В Oracle нет встроенного сравнения схем одной командой. Обычный способ — сгенерировать детерминированный DDL из обеих сред через DBMS_METADATA.GET_DDL (с отключёнными атрибутами STORAGE/сегментов) и сравнить текст через diff. Для визуального/автоматического сравнения используйте мастер Database Diff в SQL Developer или SQLcl.
PostgreSQL
# Dump only the schema from both databases and diff them
pg_dump --schema-only --no-owner --no-privileges sourcedb > source_schema.sql
pg_dump --schema-only --no-owner --no-privileges targetdb > target_schema.sql
diff -u source_schema.sql target_schema.sql
# Tool that generates applicable ALTERs: apgdiff (Another PostgreSQL Diff Tool)
# apgdiff source_schema.sql target_schema.sql > migration.sql
# Alternatives: migra, Liquibase diffChangeLogПроще всего снять вывод pg_dump --schema-only в обеих средах и сравнить через diff. apgdiff и migra — инструменты, которые сразу превращают разницу в исполняемые операторы ALTER. Для детерминированного вывода добавьте --no-owner --no-privileges.
MySQL
# Schema/object comparison with MySQL Utilities (5.x):
mysqldbcompare --server1=root:password@host1 --server2=root:password@host2 \
shop:shop --difftype=sql --run-all-tests
# Built-in method: take CREATE statements from both environments and diff them
mysqldump --no-data --skip-comments shop > source_schema.sql
# SHOW CREATE TABLE customer; (to see a single table definition)Инструмент mysqldbcompare из MySQL Utilities сообщает о различиях объектов/схем между двумя серверами (в виде применимых операторов при difftype=sql). Способ без инструментов — снять вывод mysqldump --no-data (только схема) или SHOW CREATE TABLE в обеих средах и сравнить через diff. mysqldbcompare уже устарел; для MariaDB/8.x предпочтительны Liquibase или Skeema.
SQL Server
-- Schema comparison/deploy report with SqlPackage (what will change before applying):
sqlpackage /Action:DeployReport /SourceFile:source.dacpac \
/TargetConnectionString:"Server=target;Database=shop;Integrated Security=true" \
/OutputPath:diff_report.xml
-- For data differences (row level), the tablediff utility:
tablediff -sourceserver S1 -sourcedatabase shop -sourcetable customer \
-destinationserver S2 -destinationdatabase shop -destinationtable customerДля различий схем SqlPackage /Action:DeployReport возвращает изменения для применения к цели в виде XML-отчёта; /Action:Script генерирует исполняемый скрипт различий. «Schema Compare» в Visual Studio / Azure Data Studio использует тот же движок. Для различий данных на уровне строк есть утилита командной строки tablediff.
MongoDB
// The schema is implicit; extract and compare the field structure of both environments.
// Read the $jsonSchema validator definition (collection rules):
db.getCollectionInfos({ name: "customer" })[0].options.validator
// External tools for inferred schema comparison by sampling:
// mongodb-schema (npm) or the Compass 'Schema' tab
// Take samples with mongoexport and diff the field/type distribution of both environments.MongoDB не имеет схемы; фиксированного DDL нет. Сравнение выполняется двумя способами: сравнить правила валидатора $jsonSchema коллекции (через getCollectionInfos) или вывести схему из данных через mongodb-schema / Compass и сравнить распределение полей и типов. Для индексов сравните вывод db.collection.getIndexes().
Redis
# Not applicable: Redis is a schemaless key-value store; there are no
# table/column definitions (DDL) to compare.
# Closest equivalent: compare the key space (namespace) structure
# redis-cli --scan --pattern 'customer:*' | sort > source_keys.txtНеприменимо: в Redis нет понятия схемы (таблица/столбец/DDL), поэтому классический schema diff не применим. Если нужно структурное сравнение, можно лишь вывести через SCAN шаблон именования ключей (namespace) и сравнить.
Elasticsearch
# Fetch the index mapping from both clusters and compare
curl -s 'http://source:9200/customer/_mapping?pretty' > source_mapping.json
curl -s 'http://target:9200/customer/_mapping?pretty' > target_mapping.json
diff -u source_mapping.json target_mapping.json
# To compare settings as well:
# GET customer/_settings and GET customer/_mappingВ Elasticsearch эквивалент схемы — mapping индекса. Стандартный способ — снять вывод GET <index>/_mapping (и при необходимости _settings) в обоих кластерах и сравнить через diff. Поскольку поля mapping в основном неизменяемы, найденное различие может потребовать нового индекса + _reindex.