Liquibase generateChangeLog处理不同Schema同名表数据异常问题咨询
I’ve run into this exact issue before when working with Liquibase and multiple schemas containing identical table names—here’s how to resolve it:
Root Cause
Liquibase defaults to using the table name as the CSV filename when exporting data. When you process two schemas with a table named test1 in one go, the second schema’s CSV overwrites the first, and the generated change log doesn’t properly distinguish which schema each loadData entry belongs to, leading to the wrong data being mapped to blah.test1.
Solution 1: Generate Change Logs Per Schema (Recommended)
Split your generateChangeLog command to process each schema separately. This ensures unique CSV files and correctly scoped change logs:
- First, generate the change log for the
blahschema, storing its data in a dedicated subdirectory:liquibase --dataOutputDirectory=./data/blah/ --schemas=blah --changeLogFile=changelog.blah.sql --includeSchema=true generateChangeLog - Next, generate the change log for the
dboschema, using another subdirectory to avoid file conflicts:liquibase --dataOutputDirectory=./data/dbo/ --schemas=dbo --changeLogFile=changelog.dbo.sql --includeSchema=true generateChangeLog - Create a master change log (
changelog.mssql.sql) that includes both schema-specific logs:<?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd"> <include file="changelog.blah.sql" relativeToChangelogFile="true"/> <include file="changelog.dbo.sql" relativeToChangelogFile="true"/> </databaseChangeLog>
Solution 2: Manually Fix Existing Generated Files
If you’ve already run the combined command, you can salvage the output with these steps:
- Rename the single
test1.csvfile to something liketest1_blah.csv, then re-run the generate command only for the dbo schema to gettest1_dbo.csv(or export dbo’s data separately). - Edit your
changelog.mssql.sqlto ensure eachloadDataentry specifies the correctschemaNameand points to the right CSV:-- For blah.test1 <loadData tableName="test1" schemaName="blah" file="./data/test1_blah.csv"> <!-- column mappings --> </loadData> -- For dbo.test1 <loadData tableName="test1" schemaName="dbo" file="./data/test1_dbo.csv"> <!-- column mappings --> </loadData>
Bonus: Check Liquibase Version
Older versions of Liquibase have known bugs with schema-aware data export for duplicate table names. Make sure you’re using the latest stable release—this might resolve the issue outright without manual workarounds.
内容的提问来源于stack exchange,提问作者Brian McCord

