1 Star 7 Fork 6

杨昌沛 / sqlman

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

SQLMan

  基于Java语言的关系型数据库迭代升级版本化管理与自动化执行插件,兼容主流关系型数据库,支持其方言的所有 DDL / DML / DCL 语法,旨在让SQL脚本成为项目代码的一部分,让数据库升级也纳入版本化管理之中。

适用场景

  项目开发中难免会伴随着数据库表结构的迭代升级和表数据更新维护,同时根据不同的开发时期又分为 LOCAL、ALPHA、BETA、PRE-PRODUCTION 以及 PRODUCTION 或更多阶段。 当一位开发者对数据库进行升级后,需要把数据库升级SQL脚本同步给所有开发者进行同样的升级,否则其他开发者将代码运行在未升级的数据库上将会得到意料之外的结果。 当开发者人数越多,其各自的LOCAL数据库版本同步以及数据状态的维护与管理也越发混乱。并且在严格情况下开发者不应该手动升级和维护数据库,应当让程序自动执行以避免人为操作的失误带来不必要的损失。

功能特性

  • 兼容主流数据库
  • 支持全部 DDL / DML / DCL 语法
  • 支持多 SQL 语句脚本 one-by-one 或 atomic 执行方式
  • 可选脚本执行事务隔离级别
  • 支持 Spring 自动配置
  • 可集成全 Java 平台框架

执行流程

  1. 获取数据库升级排它锁,这是一个逻辑锁,用于避免多个 SQLMan 实例同时升级同一个库。
  2. 创建数据库版本记录表,如果不存在则创建,存在则不做任何处理。
  3. 检测数据库当前最新版本号,即上次已执行的脚本版本号。
  4. 加载比当前最新版本号更高的SQL脚本资源,并且按照脚本版本号从低到高排序。
  5. 遍历SQL脚本资源,解析SQL脚本语句以执行,并插入当前最新版本记录。
  6. 释放数据库升级排它锁。

安装步骤

  1. 设置 jitpack.io 仓库

    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
  2. 添加 SQLMan 依赖

    <dependency>
        <groupId>com.github.core-lib</groupId>
        <artifactId>sqlman</artifactId>
        <version>v1.0.5</version>
    </dependency>

Spring-Boot 集成

SQLMan 与 Spring-Boot 集成时,只需要通过配置即可,下面展示的是 SQLMan 所有配置项及其缺省值。 为了方便说明则将其都展示出来,如果缺省配置合适的话,就无需在项目配置文件中加入这些配置。 只需要在项目中加入SQLMan依赖以及在 resource/sqlman/ 目录或子目录下放置SQL脚本即可,SQL脚本的命名规则在文档后面会详细说明。

# SQLMan 配置
sqlman:
  # 是否开启
  enabled: true
  # 管理器实现方式,目前支持 jdbc
  manager: jdbc
  # 当项目有多个数据源时,指定对应的数据源 bean 名称
  data-source: dataSource
  # 方言配置
  dialect:
    # 版本记录表表名
    table: schema_version
    # 方言类型
    type: MySQL
  # 脚本配置
  script:
    # 脚本资源提供器
    provider: classpath
    # 脚本位置的 ANT 路径表达式
    location: sqlman/**/*.sql
    # 脚本解析器
    resolver: druid
    # SQL脚本方言
    dialect: MySQL
    # SQL脚本字符集
    charset: UTF-8
    # 命名配置
    naming:
      # SQL脚本命名策略
      strategy: standard
  # 日志配置
  logger:
    # 日志提供器
    supplier: slf4j
    # 日志级别
    level: INFO

Spring-MVC 集成

SQLMan 与 Spring-MVC 集成核心的 bean 为最后面的 SqlVersionManager 并且需要注入对应的数据源 bean 和指定其初始化方法为 upgrade ,其余的注入均有其缺省值, 且缺省值如文中所示。

<!-- MySQL 数据库方言,表名为 schema_version -->
<bean id="sqlDialectSupport" class="io.sqlman.dialect.MySQLDialectSupport">
    <property name="table" value="schema_version"/>
</bean>

<!-- 标准SQL脚本命名策略 -->
<bean id="sqlNamingStrategy" class="io.sqlman.naming.StandardNamingStrategy"/>

<!-- 加载 sqlman/**/*.sql 路径的脚本,使用标准SQL脚本命名策略 -->
<bean id="sqlSourceProvider" class="io.sqlman.source.ClasspathSourceProvider">
    <property name="scriptLocation" value="sqlman/**/*.sql"/>
    <property name="namingStrategy" ref="sqlNamingStrategy"/>
</bean>

<!-- 使用 Druid SQL解析器,方言为 MySQL,字符集为 UTF-8 -->
<bean id="sqlScriptResolver" class="io.sqlman.script.DruidScriptResolver">
    <property name="dialect" value="MySQL"/>
    <property name="charset" value="UTF-8"/>
</bean>

<!-- 采用 SLF4J 日志实现,日志级别为 INFO -->
<bean id="sqlLoggerSupplier" class="io.sqlman.logger.Slf4jLoggerSupplier">
    <property name="level" value="INFO"/>
</bean>

<!-- 执行升级流程,注意这里需要有 init-method="upgrade" -->
<bean id="sqlVersionManager" class="io.sqlman.version.JdbcVersionManager" init-method="upgrade">
    <property name="dataSource" ref="dataSource"/>
    <property name="dialectSupport" ref="sqlDialectSupport"/>
    <property name="sourceProvider" ref="sqlSourceProvider"/>
    <property name="scriptResolver" ref="sqlScriptResolver"/>
    <property name="loggerSupplier" ref="sqlLoggerSupplier"/>
</bean>

代码调用

当项目采用的框架不是基于 Spring 家族的,可以参考与 Spring-MVC 集成的思路或采用纯代码调用方式来集成。同样的,只有数据源参数是必选的,其余都有其缺省值,且缺省值如下面代码所示。

// dataSource 为项目的数据源对象
JdbcVersionManager sqlman = new JdbcVersionManager(dataSource);

// MySQL 方言,表名为 schema_version
sqlman.setDialectSupport(new MySQLDialectSupport("schema_version"));

// 加载 sqlman/**/*.sql 路径的脚本,使用标准SQL脚本命名策略
sqlman.setSourceProvider(new ClasspathSourceProvider("sqlman/**/*.sql", new StandardNamingStrategy()));

// 使用 Druid SQL 解析器,方言为 MySQL,字符集为 UTF-8
sqlman.setScriptResolver(new DruidScriptResolver(JdbcUtils.MYSQL, "UTF-8"));

// 采用 SLF4J 日志实现,日志级别为 INFO
sqlman.setLoggerSupplier(new Slf4jLoggerSupplier(SqlLogger.Level.INFO));

// 执行升级流程
sqlman.upgrade();

命名规则

SQL脚本需要遵循一定的命名规则以配合SQLMan进行版本高低的区分以及执行脚本时采用的指令。

插件内部提供了一个标准的SQL脚本资源命名策略解析器(StandardNamingStrategy),其规则如下:

  1. 以 v 开头,不区分大小写。(必选)
  2. 紧跟着任意级版本数字,以 . 分隔,例如 1.0.0、2.4.13.8 或 2019.06.13 等。(必选)
  3. 指定脚本执行指令列表,以 - 为前缀,例如 -ATOMIC、-READ_COMMITTED 或 -REPEATABLE_READ 等。(可选)
  4. 添加脚本备注,以 ! 为前缀,例如 !add-some-column、!drop-useless-tables 等。(可选)
  5. 以 .sql 为后缀。(必选)

命名例子:

SQL脚本名称 规则解释
v1.0.0.sql 只有版本号
v2.4.13.8-ATOMIC.sql 版本号 + 一个指令
v2.4.13.8-ATOMIC-REPEATABLE_READ.sql 版本号 + 多个指令
v2019.06.13!drop-useless-tables.sql 版本号 + 备注
v2019.06.13-REPEATABLE_READ!init-admin-data.sql 版本号 + 指令 + 备注

标准命名策略中版本号的高低对比基于版本数字的分段对比,并不是字符串对比。例如:

  • 1.0.0 比 0.0.1 高
  • 1.2.4 比 1.2.3 高
  • 2.3.1 比 2.2.4 高
  • 3.23.5.1 比 3.23.5 高
  • 2019.06.13 比 2019.06.08 高

指令说明

指令在脚本命名中不区分大小写,目前支持的指令及其解释如下:

指令名称 指令含义 指令说明 缺省值
ATOMIC 原子性执行 当SQL脚本包含多条SQL语句时,将其置于同一个事务中执行。 非原子性执行,即一条SQL语句一个事务。
READ_UNCOMMITTED 读未提交隔离级别 设置SQL语句执行事务的隔离界别为读未提交 依赖数据源的事务隔离级别
READ_COMMITTED 读已提交隔离级别 设置SQL语句执行事务的隔离界别为读已提交 依赖数据源的事务隔离级别
REPEATABLE_READ 可重复读隔离级别 设置SQL语句执行事务的隔离界别为可重复读 依赖数据源的事务隔离级别
SERIALIZABLE 串行化隔离级别 设置SQL语句执行事务的隔离界别为串行化 依赖数据源的事务隔离级别

其中每个SQL脚本的隔离级别只能选取一种,通常情况下依赖隔离级别的脚本需要原子性执行即通过-ATOMIC指令来指定,缺省为one-by-one模式。

原子模式

  • 缺省模式的多SQL语句脚本在执行过程中,当其中某条SQL执行失败后,程序下次启动时将会从该脚本的失败SQL开始。
  • 原子模式的多SQL语句脚本在执行过程中,当其中某条SQL执行失败后,程序下次启动时将会从该脚本的首条SQL开始。

注意事项

由于部分数据库不支持 DDL 语句的失败回滚,例如 MySQL ,所以当一个原子性多SQL语句脚本中包含有 DDL 语句时, 其后面的SQL语句执行失败且进行整体回滚后,其实已成功的 DDL 并没有真正回滚,又由于是原子性脚本,所以程序下次启动时会从该脚本的首条SQL开始执行, 当执行到上次已成功但无法回滚的 DDL 时会失败,或重复执行,为了避免这种情况请尽量将 DDL 语句单独作为一个脚本,或采用缺省的 one-by-one 模式。

支持数据库

  • MySQL
  • Oracle
  • SQLServer
  • SQLite

后续将会增加更多数据库的支持。

版本记录

  • v1.0.5
    1. 第一个正式版本
    2. 增加 README

协议声明

Apache-2.0

联系作者

QQ 646742615 不会钓鱼的兔子

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

基于Java语言的关系型数据库迭代升级版本化管理与自动化执行插件,兼容主流关系型数据库,支持其方言的所有 DDL / DML / DCL 语法,旨在让SQL脚本成为项目代码的一部分,让数据库升级也纳入版本化管理之中。 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/core-lib/sqlman.git
git@gitee.com:core-lib/sqlman.git
core-lib
sqlman
sqlman
master

搜索帮助

Bbcd6f05 5694891 0cc6727d 5694891