通过Liquibase管理PostgreSQL数据库中的通用SQL代码
Liquibase复用common.sql的最优方案
针对你遇到的SQL格式变更日志无法使用include元素、避免代码重复的问题,推荐以下几个实用方案:
采用XML/YAML/JSON主变更日志串联脚本
无需放弃SQL脚本的编写,只需新增一个XML(或YAML/JSON)格式的主变更日志文件,通过内置的引入机制依次加载common.sql和对应数据库的create_db.sql。示例XML主文件结构:<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="common.sql"/> <include file="specific-db/create_db.sql"/> </databaseChangeLog>不同数据库可对应不同的主变更日志文件,或通过Liquibase的上下文(context)参数区分执行目标
create_db.sql。在SQL变更日志中使用sqlFile指令
若坚持使用纯SQL格式的变更日志,可在每个create_db.sql开头添加变更集,通过sqlFile指令引入common.sql:--liquibase formatted sql --changeset dev:1-include-common runOnChange:true --sqlFile path:../common.sql relativeToChangelogFile:true注意配置正确的相对路径,
relativeToChangelogFile:true会以当前create_db.sql的位置为基准查找common.sql。借助外部模板工具预合并脚本
用Velocity、Freemarker等模板工具,在Liquibase执行前将common.sql内容注入到create_db.sql生成临时脚本,再执行临时文件。这种方式适合需要复杂复用逻辑的场景,但需额外添加构建步骤。
内容的提问来源于stack exchange,提问作者tuk
相关产品推荐
相关产品推荐

