mirror of
https://github.com/CarmJos/EasySQL.git
synced 2026-06-05 09:01:26 +08:00
Compare commits
75 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0a6c8ae1a9 | |||
| f00e741035 | |||
| 50c2016820 | |||
| 71b0bb98d8 | |||
| ce3deb8f12 | |||
| b5a40b0f52 | |||
| ae5ca6cb23 | |||
| 866115db99 | |||
| 332540710d | |||
| ebe51dd9a3 | |||
| 0bdfe3d556 | |||
| e60c44aaae | |||
| 28f76ae50a | |||
| ffa0b74ccc | |||
| 4b766d7794 | |||
| f12fdc9c66 | |||
| 6115e6bf21 | |||
| 6356c0f723 | |||
| 5e15c3b308 | |||
| 46b21ead05 | |||
| 8a9e4b8d1c | |||
| f21095d08a | |||
| 6fd5988e09 | |||
| 962da8f6a1 | |||
| 68b5d071ae | |||
| 2de21a4658 | |||
| 3f26c9e12e | |||
| 0640f625a1 | |||
| 7df8a67282 | |||
| 37becc7b29 | |||
| 5df61a70c3 | |||
| 4ce5fba6f1 | |||
| e3844493e5 | |||
| 7772bc58d6 | |||
| 54166b4289 | |||
| bcf9d257a9 | |||
| 0efd526c75 | |||
| 22a8172490 | |||
| 5444015b8b | |||
| 1ab23aa14f | |||
| 0f4bf90f56 | |||
| 8e57305b83 | |||
| 855a08050f | |||
| 904f1bdfda | |||
| 508a560eed | |||
| 469c204d4c | |||
| 7a2d1841db | |||
| f7d85ddf94 | |||
| a438c0e7d0 | |||
| bb4801b41c | |||
| 7acc2849ae | |||
| 5e7519dc7a | |||
| 643841a98a | |||
| 8513324046 | |||
| 6702a69f8d | |||
| 45cd4c326f | |||
| 7097ef518e | |||
| 6a67be5b8d | |||
| 73e6ebef1d | |||
| 9cbfda954c | |||
| a4036a359e | |||
| e5f6d621e1 | |||
| 03afae635b | |||
| a55809d60e | |||
| 45fafdf68a | |||
| e5c6fe1c92 | |||
| a1d531f1cc | |||
| c1dfe8dfe0 | |||
| e8debf73f1 | |||
| 7df308f8c6 | |||
| 0b275d3633 | |||
| 893511ac06 | |||
| 045dd9866e | |||
| 086a6c8b31 | |||
| 28464350ee |
@@ -1,3 +1,14 @@
|
||||
# 欢迎使用 EasySQL !
|
||||
|
||||
这个项目刚刚创建,详细的Javadoc与开发指南还在补充,请给我一点时间~
|
||||
这个项目刚刚创建,详细的Javadoc与开发指南还在补充,请给我一点时间~
|
||||
|
||||
|
||||
## 目录
|
||||
|
||||
- [Bob的EasySQL之旅(HikariCP)](USAGE-HIKARI.md) `@Ghost-Chu`
|
||||
|
||||
## 实例项目
|
||||
以下是一些实例项目,可供各位参考。
|
||||
|
||||
- UltraDepository 超级仓库插件 `@CarmJos`
|
||||
- [storage/MySQLStorage](https://github.com/CarmJos/UltraDepository/blob/master/src/main/java/cc/carm/plugin/ultradepository/storage/impl/MySQLStorage.java)
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
> 本文档由 GitHub 用户 @Ghost-chu 创建。
|
||||
> 本文撰写于 2022/02/09,适配 EasySQL 版本 `v0.3.6`。
|
||||
> 本文基于 `EasySQL-HikariPool` 版本编写。
|
||||
|
||||
# EasySQL - HikariPool 使用指南
|
||||
|
||||
## 和 EasySQL 说你好:创建你的第一个 SQLManager
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void createYourSQLManager() {
|
||||
HikariConfig hikari = YOUR_HIKARI_CONFIG;
|
||||
SQLManager sqlManager = EasySQL.createManager(hikari);
|
||||
try {
|
||||
if (!sqlManager.getConnection().isValid(5)) {
|
||||
logger.warning("Connection invalid!");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.warning("Failed to connect to database!", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
至此,你已经创建了一个 SQLManager 对象,与 EasySQL 的故事由此开始。
|
||||
|
||||
## SQL起步: 查询 (Query)
|
||||
|
||||
EasySQL 可以使用异步查询以避免产生性能影响和手动关闭连接的麻烦。本节我们将展示使用 "异步查询" 的示例代码,并讲解如何使用 "查询处理器" 和 "错误处理器"。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void trySomeQuery(SQLManager sqlManager) {
|
||||
sqlManager.createQuery() // 创建一个查询
|
||||
.inTable("table_name") // 指定表名
|
||||
.selectColumns("name", "sex", "age") // 选择 "name", "sex", "age" 三个列
|
||||
.addCondition("name", "Bob") // 限定条件,"name" 必须是 Bob
|
||||
.build()/*构建查询体*/.executeAsync(
|
||||
(query) -> { /*处理查询结果-SQLQuery*/ },
|
||||
((exception, sqlAction) -> { /*SQL异常处理-SQLExceptionHandler*/ })
|
||||
); // 异步查询~~~~
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### SQLQuery
|
||||
|
||||
SQLQuery 是 EasySQL 执行查询类请求统一返回的对象,包括如下内容:
|
||||
|
||||
* ResultSet - 查询结果
|
||||
* SQLAction - 执行的 SQL 操作
|
||||
* Action - 操作类型
|
||||
* ExecuteTime - 查询耗时
|
||||
* SQLContent - 最终执行的 SQL 语句的内容
|
||||
|
||||
如果需要,SQLQuery 还额外提供了一些其他信息,如:
|
||||
|
||||
* SQLManager - 创建此 SQLQuery 对象的 SQLManager 实例
|
||||
* Connection - 执行 SQL 操作的链接
|
||||
|
||||
等信息。
|
||||
|
||||
### SQLExceptionHandler
|
||||
|
||||
当出现 SQLException 异常时,如果你在查询中指定了一个 SQLExceptionHandler,则会被调用。 SQLExceptionHandler 接受两个参数:
|
||||
|
||||
* SQLException - 发生的 SQL 异常
|
||||
* SQLAction - 执行的 SQL 操作
|
||||
|
||||
### SQLAction
|
||||
|
||||
SQLAction 包含 EasySQL 在处理 SQL 请求时所使用到的信息:
|
||||
|
||||
* SQLContent - 最终执行的 SQL 语句的内容
|
||||
* ActionUUID - 执行的 SQL 操作的唯一标识
|
||||
* ShortID - 执行的 SQL 操作的短 ID (短8位)
|
||||
* CreateTime - SQLAction 创建的时间
|
||||
* SQLManager - 与 SQLAction 有关的 SQLManager 的实例
|
||||
|
||||
## 不仅能读,也得能写: 插入(Insert)
|
||||
|
||||
除了 SELECT 查询操作以外,EasySQL 也当然支持 INSERT 插入操作。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void doSomeInsert(SQLManager sqlManager) {
|
||||
sqlManager.createInsert("table_name")
|
||||
.setColumnNames("name", "sex", "age")
|
||||
.setParams("Alex", "female", 16)
|
||||
.executeAsync();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
EasySQL 使用 PreparedStatement 来填充参数,无需担心 SQL 注入问题。
|
||||
对于常见类型,EasySQL 也对正确的对其进行转换。
|
||||
|
||||
### 静默处理
|
||||
|
||||
细心的的小伙伴可能发现,这一次我们的 executeAsync 内容为空,没有任何 Handler。
|
||||
在这种情况下, EasySQL 将会静默失败,不会产生任何日志。
|
||||
|
||||
## 信息总是千变万化的:更新(Update)
|
||||
|
||||
Bob 是个喜欢改名的人,于是他今天给自己起了个新名字叫 Steve。因此我们需要更新数据库中已经存在的数据:
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void updateSomething(SQLManager sqlManager) {
|
||||
sqlManager.createUpdate("table_name")
|
||||
.addCondition("name", "Bob")
|
||||
.setColumnValues("name", "Steve")
|
||||
.build().executeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
至此,Bob 就改名为 Steve 啦!
|
||||
|
||||
## 旧的不去,新的不来:删除(Delete)
|
||||
|
||||
最近 Steve 把它人生中买的一套房给卖了,于是我们需要将这套房从数据库中删除。
|
||||
不过,Steve 说它不记得这套房子是多久之前买的了,不过肯定是 10 年之前。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void sayGoodBye(SQLManager sqlManager) {
|
||||
Date date = new Date(); // 使用当前日期时间戳创建一个 Date
|
||||
date.setYear(date.getYear() - 10); // 把时间滑动到 10 年之前
|
||||
sqlManager.createDelete("steve_house") // 进行删除
|
||||
.addTimeCondition("purchase_date", new Date(0), date) // 选择从1970年1月1日0点一直到10年前的所有数据
|
||||
.build()
|
||||
.executeAsync(); //执行
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
现在 Steve 真的没有他的这套房了。
|
||||
|
||||
## 不管有没有,反正都要写:替换(Replace)
|
||||
|
||||
Steve 买了一盒牛奶,他要在他的购物清单中标记牛奶已经买了。
|
||||
不过,Steve 忘记了自己有没有将牛奶加入过购物清单。但是如果暴力 INSERT 肯定会出错,但是又觉得写个 INSERT OR UPDATE 太麻烦了,于是这件棘手的事情又丢到了我们的头上来。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void putAnyway(SQLManager sqlManager) {
|
||||
sqlManager.createReplace("steve_list")
|
||||
.setColumnNames("item", "purchased")
|
||||
.setParams("milk", true)
|
||||
.executeAsync();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
生活总有简单的方法不是吗?
|
||||
|
||||
## 上司的任务:建表
|
||||
|
||||
Steve 的公司老板开发了一个 IM 软件,但是 Steve 公司运维是土豆,不会搞SQL。
|
||||
最要命的是,Steve 的公司老板还不让你碰生产环境,于是你便不能指望土豆会去帮你完成建表的任务了。
|
||||
除此之外,由于 IM 软件上的网友特能叭叭,你还需要稍微考虑下性能问题。不然你可能会被送去西伯利亚。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void newTablePlease(SQLManager sqlManager) {
|
||||
sqlManager.createTable("steve_im_history")
|
||||
.addColumn("id", "BIGINT NOT NULL", "记录ID")
|
||||
.addColumn("sender", "VARCHAR NOT NULL", "网友UUID")
|
||||
.addColumn("message", "TEXT NULL", "网友发言")
|
||||
.addAutoIncrementColumn("id") //设置 id 列自增
|
||||
.setIndex(IndexType.PRIMARY_KEY, null, "id", "sender") //配置主键
|
||||
.setIndex(IndexType.INDEX, "sender_message_index", "sender", "message") //配置索引
|
||||
.build().executeAsync();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 上司的任务2:改表
|
||||
|
||||
Steve 的公司老板和 Steve 提出了一个需求,迫不得已,Steve 要修改表结构。
|
||||
然而此时表内已经存储了大量数据,不能删表再建,Steve 要想个办法对表做出相应的修改。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void newTablePlease(SQLManager sqlManager) {
|
||||
sqlManager.alterTable("steve_im_history")
|
||||
.addColumn("ipAddress", "VARCHAR(255)")
|
||||
.executeAsync();
|
||||
sqlManager.alterTable("steve_im_history")
|
||||
.modifyColumn("message", "LONGTEXT")
|
||||
.executeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
多亏了我们的大力帮助。现在,Steve 被送去了南极担任公司的重要工作了。
|
||||
|
||||
## 北极熊的快乐生活:批量操作
|
||||
|
||||
Steve 到达南极之后,南极的员工把2FA密钥塞给Steve便骑着海豚跑路了。于是 Steve 除了日常工作以外还要照看公司的北极熊。
|
||||
北极熊饲养区有一套设备,监控生活在南极的北极熊的生活状态。设备每 1 小时会把缓存的数据存入到服务器里。
|
||||
然而,员工跑路的时候删库格盘了,现在 Steve 要自己想办法解决这个烂摊子了。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void iDontLikeHere(SQLManager sqlManager) {
|
||||
sqlManager.createInsertBatch("polarbear")
|
||||
.setColumnNames("name", "temp", "hunger")
|
||||
.addParamsBatch("Karl", -17, 100)
|
||||
.addParamsBatch("Lucy", -3, 80)
|
||||
.addParamsBatch("Lily", -10, 70)
|
||||
.setReturnGeneratedKey(true)// 设定在后续返回自增主键
|
||||
.executeAsync((list) -> {/*新增行的自增主键*/});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 北极熊的熊猫之旅!?:复杂查询
|
||||
|
||||
Steve 翻看着跑路员工留下的为数不多的资料,发现公司在南极培育北极熊是为了让它们变成熊猫!
|
||||
只要满足 “温度 < -100C, 饱食度 > 70, 名字中带有 `PANDAKING` 关键字并以符合条件的北极熊门的名字倒序排序后的第一条” 的北极熊就有希望变成熊猫!
|
||||
现在 Steve 已经迫不及待的看看是哪只熊猫如此幸运了!
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void noBearsPlease(SQLManager sqlManager) {
|
||||
sqlManager.createQuery()
|
||||
.inTable("panda_king_proj")
|
||||
.addCondition("temp", "<", -100)
|
||||
.addCondition("hunger", ">", 70)
|
||||
.addCondition("name", "LIKE", "PANDAKING")
|
||||
.orderBy("name", false)
|
||||
.setLimit(1)
|
||||
.build().executeAsync((result) -> {
|
||||
if (result.getResultSet().next()) {
|
||||
System.out.println(result.getResultSet().getString("name"));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 同步请求
|
||||
|
||||
经历人生坎坷后的 Steve 回到了自己的家:因为没能培育出熊猫来,他的老板 Async 炒了他,女友 Lambda 甩了他,连朋友 Handler 都放 Steve 鸽子,于是现在他很讨厌任何带有这两个名字的东西。
|
||||
|
||||
```java
|
||||
public class HiEasySQL {
|
||||
public static void syncLover(SQLManager sqlManager) {
|
||||
try (SQLQuery query = sqlManager.createQuery().inTable("the_end")
|
||||
.addCondition("thanks_read", "this_stupid_guide")
|
||||
.build().execute()) {
|
||||
ResultSet set = query.getResultSet(); // SQLQuery 关闭时,ResultSet 会一同关闭
|
||||
if (set.next()) {
|
||||
set.getString("see_you_next_time");
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
当然,有时候 Steve 也会选择更优雅一点的方式。
|
||||
|
||||
```java
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class HiEasySQL {
|
||||
// 调用此方法,直接返回结果,再在调用处统一处理错误
|
||||
public static @Nullable String eleganceNeverGone(SQLManager sqlManager) throws SQLException {
|
||||
return sqlManager.createQuery().inTable("the_end")
|
||||
.addCondition("thanks_read", "this_stupid_guide")
|
||||
.build().executeFunction(query -> {
|
||||
if (!query.getResultSet().next()) return null;
|
||||
else return query.getResultSet().getString("see_you_next_time");
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Steve 终究能找到继续生活下去的办法 :)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
---
|
||||
name: 问题提交 about: 描述问题并提交,帮助我们对其进行检查与修复。 title: ''
|
||||
labels: bug assignees: ''
|
||||
name: 问题提交
|
||||
about: 描述问题并提交,帮助我们对其进行检查与修复。
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
---
|
||||
name: 功能需求 about: 希望我们提供更多的功能。 title: ''
|
||||
labels: enhancement assignees: ''
|
||||
|
||||
name: 功能需求
|
||||
about: 希望我们提供更多的功能。
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
### **功能简述**
|
||||
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
run: |
|
||||
rm -rf docs
|
||||
mkdir -vp docs
|
||||
cp -vrf easysql-api/target/apidocs/* docs/
|
||||
cp -vrf api/target/apidocs/* docs/
|
||||
cp -vrf .documentation/JAVADOC-README.md docs/README.md
|
||||
|
||||
- name: "Generate the Javadoc sitemap"
|
||||
|
||||
@@ -6,6 +6,7 @@ name: Project Build & Tests
|
||||
on:
|
||||
# 支持手动触发构建
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
push:
|
||||
|
||||
jobs:
|
||||
@@ -21,7 +22,7 @@ jobs:
|
||||
java-version: '11'
|
||||
distribution: 'adopt'
|
||||
- name: "Package"
|
||||
run: mvn -B package --file pom.xml -Dmaven.javadoc.skip=true
|
||||
run: mvn -B package --file pom.xml -Dgpg.skip
|
||||
- name: "Target Stage"
|
||||
run: mkdir staging && cp */target/*.jar staging
|
||||
- name: "Upload artifact"
|
||||
|
||||
+1
-2
@@ -1,4 +1,3 @@
|
||||
/.idea/
|
||||
/target/
|
||||
/*/target/
|
||||
**/target/
|
||||
**.iml
|
||||
@@ -48,8 +48,16 @@
|
||||
|
||||
<project>
|
||||
<repositories>
|
||||
|
||||
<repository>
|
||||
<!--采用github依赖库,安全稳定,但需要配置 (推荐)-->
|
||||
<!--采用Maven中心库,安全稳定,但版本更新需要等待同步-->
|
||||
<id>maven</id>
|
||||
<name>Maven Central</name>
|
||||
<url>https://repo1.maven.org/maven2</url>
|
||||
</repository>
|
||||
|
||||
<repository>
|
||||
<!--采用github依赖库,实时更新,但需要配置 (推荐) -->
|
||||
<id>EasySQL</id>
|
||||
<name>GitHub Packages</name>
|
||||
<url>https://maven.pkg.github.com/CarmJos/EasySQL</url>
|
||||
@@ -130,7 +138,11 @@
|
||||
|
||||
```groovy
|
||||
repositories {
|
||||
// 采用github依赖库,安全稳定,但需要配置 (推荐)
|
||||
|
||||
// 采用Maven中心库,安全稳定,但版本更新需要等待同步
|
||||
mavenCentral()
|
||||
|
||||
// 采用github依赖库,实时更新,但需要配置 (推荐)
|
||||
maven { url 'https://maven.pkg.github.com/CarmJos/EasySQL' }
|
||||
|
||||
// 采用我的私人依赖库,简单方便,但可能因为变故而无法使用
|
||||
@@ -202,4 +214,4 @@ dependencies {
|
||||
> MIT 协议是所有开源许可中最宽松的一个,除了必须包含许可声明外,再无任何限制。
|
||||
>
|
||||
> *以上文字来自 [五种开源协议GPL,LGPL,BSD,MIT,Apache](https://www.oschina.net/question/54100_9455) 。*
|
||||
</details>
|
||||
</details>
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
<parent>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<version>0.3.3</version>
|
||||
<version>0.3.9</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
</properties>
|
||||
@@ -44,12 +44,12 @@
|
||||
|
||||
<issueManagement>
|
||||
<system>GitHub Issues</system>
|
||||
<url>${project.url}/issues</url>
|
||||
<url>https://github.com/CarmJos/EasySQL/issues</url>
|
||||
</issueManagement>
|
||||
|
||||
<ciManagement>
|
||||
<system>GitHub Actions</system>
|
||||
<url>${project.url}/actions/workflows/maven.yml</url>
|
||||
<url>https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml</url>
|
||||
</ciManagement>
|
||||
|
||||
<build>
|
||||
@@ -0,0 +1,212 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLFunction;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* SQLAction 是用于承载SQL语句并进行处理、返回的基本类。
|
||||
*
|
||||
* <ul>
|
||||
* <li>同步执行 {@link #execute()}, {@link #execute(SQLFunction, SQLExceptionHandler)}
|
||||
* <br>同步执行方法中有会抛出异常的方法与不抛出异常的方法,
|
||||
* <br>若选择不抛出异常,则返回值可能为空,需要特殊处理。</li>
|
||||
*
|
||||
* <li>异步执行 {@link #executeAsync(SQLHandler, SQLExceptionHandler)}
|
||||
* <br>异步执行时将提供成功与异常两种处理方式
|
||||
* <br>可自行选择是否对数据或异常进行处理
|
||||
* <br>默认的异常处理器为 {@link #defaultExceptionHandler()}
|
||||
* <br>若有特殊需要,可通过{@link #setExceptionHandler(SQLExceptionHandler)} 方法修改默认的处理器</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param <T> 需要返回的类型
|
||||
* @author CarmJos
|
||||
* @since 0.0.1
|
||||
*/
|
||||
public interface SQLAction<T> {
|
||||
|
||||
/**
|
||||
* 得到该Action的UUID
|
||||
*
|
||||
* @return UUID
|
||||
*/
|
||||
@NotNull UUID getActionUUID();
|
||||
|
||||
/**
|
||||
* 得到短八位格式的UUID
|
||||
*
|
||||
* @return UUID(8)
|
||||
*/
|
||||
@NotNull String getShortID();
|
||||
|
||||
/**
|
||||
* 得到该Action的创建时间
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getCreateTime();
|
||||
|
||||
/**
|
||||
* 得到该Action所要执行的源SQL语句
|
||||
*
|
||||
* @return 源SQL语句
|
||||
*/
|
||||
@NotNull String getSQLContent();
|
||||
|
||||
/**
|
||||
* 得到承载该Action的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
@NotNull SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 执行该Action对应的SQL语句
|
||||
*
|
||||
* @return 指定数据类型
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@NotNull T execute() throws SQLException;
|
||||
|
||||
|
||||
/**
|
||||
* 执行语句并返回值
|
||||
*
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default T execute(@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(t -> t, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(function, null, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null,_ -> !null")
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable R defaultResult,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
try {
|
||||
return executeFunction(function, defaultResult);
|
||||
} catch (SQLException exception) {
|
||||
handleException(exceptionHandler, exception);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function) throws SQLException {
|
||||
return executeFunction(function, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try {
|
||||
R result = function.apply(execute());
|
||||
return result == null ? defaultResult : result;
|
||||
} catch (SQLException exception) {
|
||||
throw new SQLException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句,采用默认异常处理,无需返回值。
|
||||
*/
|
||||
default void executeAsync() {
|
||||
executeAsync(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
*/
|
||||
default void executeAsync(@Nullable SQLHandler<T> success) {
|
||||
executeAsync(success, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
* @param failure 异常处理器 默认为 {@link SQLAction#defaultExceptionHandler()}
|
||||
*/
|
||||
void executeAsync(@Nullable SQLHandler<T> success,
|
||||
@Nullable SQLExceptionHandler failure);
|
||||
|
||||
default void handleException(@Nullable SQLExceptionHandler handler, SQLException exception) {
|
||||
if (handler == null) handler = defaultExceptionHandler();
|
||||
handler.accept(exception, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理器提供的默认异常处理器。
|
||||
* 若未使用过 {@link #setExceptionHandler(SQLExceptionHandler)} 方法,
|
||||
* 则默认返回 {@link SQLExceptionHandler#detailed(Logger)} 。
|
||||
*
|
||||
* @return {@link SQLExceptionHandler}
|
||||
*/
|
||||
default SQLExceptionHandler defaultExceptionHandler() {
|
||||
return getManager().getExceptionHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定通用的异常处理器。
|
||||
* <br> 在使用 {@link #execute(SQLExceptionHandler)} 等相关方法时,若传入的处理器为null,则会采用此处理器。
|
||||
* <br> 若该方法传入参数为 null,则会使用 {@link #defaultExceptionHandler()} 。
|
||||
*
|
||||
* @param handler 异常处理器
|
||||
*/
|
||||
default void setExceptionHandler(@Nullable SQLExceptionHandler handler) {
|
||||
getManager().setExceptionHandler(handler);
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -11,6 +11,16 @@ import org.jetbrains.annotations.NotNull;
|
||||
*/
|
||||
public interface SQLBuilder {
|
||||
|
||||
static @NotNull String withBackQuote(@NotNull String str) {
|
||||
str = str.trim();
|
||||
return !str.isEmpty() && str.charAt(0) == '`' && str.charAt(str.length() - 1) == '`' ? str : "`" + str + "`";
|
||||
}
|
||||
|
||||
static @NotNull String withQuote(@NotNull String str) {
|
||||
str = str.trim();
|
||||
return !str.isEmpty() && str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'' ? str : "'" + str + "'";
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到承载该Builder的对应{@link SQLManager}
|
||||
*
|
||||
@@ -0,0 +1,199 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.builder.*;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* SQLManager 是EasySQL的核心类,用于管理数据库连接,提供数据库操作的方法。
|
||||
*
|
||||
* @author CarmJos
|
||||
*/
|
||||
public interface SQLManager {
|
||||
|
||||
Logger getLogger();
|
||||
|
||||
boolean isDebugMode();
|
||||
|
||||
void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode);
|
||||
|
||||
default void setDebugMode(boolean enable) {
|
||||
setDebugMode(() -> enable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到连接池源
|
||||
*
|
||||
* @return DataSource
|
||||
*/
|
||||
@NotNull DataSource getDataSource();
|
||||
|
||||
/**
|
||||
* 得到一个数据库连接实例
|
||||
*
|
||||
* @return Connection
|
||||
* @throws SQLException 见 {@link DataSource#getConnection()}
|
||||
*/
|
||||
@NotNull Connection getConnection() throws SQLException;
|
||||
|
||||
/**
|
||||
* 得到正使用的查询。
|
||||
*
|
||||
* @return 查询列表
|
||||
*/
|
||||
@NotNull Map<UUID, SQLQuery> getActiveQuery();
|
||||
|
||||
/**
|
||||
* 获取改管理器提供的默认异常处理器。
|
||||
* 若未使用过 {@link #setExceptionHandler(SQLExceptionHandler)} 方法,
|
||||
* 则默认返回 {@link SQLExceptionHandler#detailed(Logger)} 。
|
||||
*
|
||||
* @return {@link SQLExceptionHandler}
|
||||
*/
|
||||
@NotNull SQLExceptionHandler getExceptionHandler();
|
||||
|
||||
/**
|
||||
* 设定通用的异常处理器。
|
||||
* <br> 在使用 {@link SQLAction#execute(SQLExceptionHandler)} 等相关方法时,若传入的处理器为null,则会采用此处理器。
|
||||
* <br> 若该方法传入参数为 null,则会使用 {@link SQLExceptionHandler#detailed(Logger)} 。
|
||||
*
|
||||
* @param handler 异常处理器
|
||||
*/
|
||||
void setExceptionHandler(@Nullable SQLExceptionHandler handler);
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的SQL语句(多用于UPDATE、REPLACE、DELETE方法)
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @return 更新的行数
|
||||
* @see SQLUpdateAction
|
||||
*/
|
||||
@Nullable Integer executeSQL(String sql);
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的预处理SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param params SQL语句中 ? 的对应参数
|
||||
* @return 更新的行数
|
||||
* @see PreparedSQLUpdateAction
|
||||
*/
|
||||
@Nullable Integer executeSQL(String sql, Object[] params);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param paramsBatch SQL语句中对应?的参数组
|
||||
* @return 对应参数返回的行数
|
||||
* @see PreparedSQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch);
|
||||
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param moreSQL 更多SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
* @see SQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
*
|
||||
* @param sqlBatch SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch);
|
||||
|
||||
/**
|
||||
* 在库中创建一个表
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder createTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 对库中的某个表执行更改
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
TableAlterBuilder alterTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 新建一个查询
|
||||
*
|
||||
* @return {@link QueryBuilder}
|
||||
*/
|
||||
QueryBuilder createQuery();
|
||||
|
||||
/**
|
||||
* 创建一条插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建一条替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建更新操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link UpdateBuilder}
|
||||
*/
|
||||
UpdateBuilder createUpdate(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建删除操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link DeleteBuilder}
|
||||
*/
|
||||
DeleteBuilder createDelete(@NotNull String tableName);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.api.action.query.QueryAction;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
/**
|
||||
* SQLQuery 是一个查询中间接口,用于查询操作的封装。
|
||||
*
|
||||
* @author CarmJos
|
||||
*/
|
||||
public interface SQLQuery extends AutoCloseable {
|
||||
|
||||
/**
|
||||
* 获取该查询创建的时间
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getExecuteTime();
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link QueryAction}
|
||||
*
|
||||
* @return {@link QueryAction} 或 {@link PreparedQueryAction}
|
||||
*/
|
||||
QueryAction getAction();
|
||||
|
||||
ResultSet getResultSet();
|
||||
|
||||
/**
|
||||
* 得到设定的SQL语句
|
||||
*
|
||||
* @return SQL语句
|
||||
*/
|
||||
String getSQLContent();
|
||||
|
||||
/**
|
||||
* 关闭所有内容
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
|
||||
Statement getStatement();
|
||||
|
||||
Connection getConnection();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
|
||||
|
||||
/**
|
||||
* 设定多组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param allParams 所有参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams);
|
||||
|
||||
/**
|
||||
* 添加一组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param params 参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction addParamsBatch(Object... params);
|
||||
|
||||
/**
|
||||
* 设定自增主键的序列
|
||||
*
|
||||
* @param keyColumnIndex 自增主键的序列
|
||||
* <br>若该值 > 0,则 {@link #execute()} 返回自增主键数值
|
||||
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
* @see #setReturnGeneratedKeys(boolean)
|
||||
*/
|
||||
@Deprecated
|
||||
default PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex) {
|
||||
return setReturnGeneratedKeys(keyColumnIndex > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作返回自增键序列。
|
||||
*
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
default PreparedSQLUpdateBatchAction returnGeneratedKeys() {
|
||||
return setReturnGeneratedKeys(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作是否返回自增键序列。
|
||||
*
|
||||
* @param returnGeneratedKey 是否返回自增键序列
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
public interface SQLUpdateAction extends SQLAction<Integer> {
|
||||
|
||||
/**
|
||||
* 设定自增主键的序列
|
||||
*
|
||||
* @param keyColumnIndex 自增主键的序列
|
||||
* <br>若该值 > 0,则 {@link #execute()} 返回自增主键数值
|
||||
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
|
||||
* @return {@link SQLUpdateAction}
|
||||
* @see #setReturnGeneratedKey(boolean)
|
||||
*/
|
||||
@Deprecated
|
||||
default SQLUpdateAction setKeyIndex(int keyColumnIndex) {
|
||||
return setReturnGeneratedKey(keyColumnIndex > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作返回自增键序列。
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
default SQLUpdateAction returnGeneratedKey() {
|
||||
return setReturnGeneratedKey(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作是否返回自增键序列。
|
||||
*
|
||||
* @param returnGeneratedKey 是否返回自增键序列
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
|
||||
|
||||
/**
|
||||
* 添加一条批量执行的SQL语句
|
||||
*
|
||||
* @param sql SQL语句
|
||||
* @return {@link SQLUpdateBatchAction}
|
||||
*/
|
||||
SQLUpdateBatchAction addBatch(@NotNull String sql);
|
||||
|
||||
@Override
|
||||
default @NotNull String getSQLContent() {
|
||||
return getSQLContents().get(0);
|
||||
}
|
||||
|
||||
List<String> getSQLContents();
|
||||
|
||||
}
|
||||
+11
-11
@@ -32,16 +32,16 @@ import java.sql.SQLException;
|
||||
*/
|
||||
public interface QueryAction extends SQLAction<SQLQuery> {
|
||||
|
||||
@Override
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> @Nullable R executeFunction(@NotNull SQLFunction<@NotNull SQLQuery, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try (SQLQuery value = execute()) {
|
||||
R result = function.apply(value);
|
||||
return result == null ? defaultResult : result;
|
||||
} catch (SQLException exception) {
|
||||
throw new SQLException(exception);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> @Nullable R executeFunction(@NotNull SQLFunction<@NotNull SQLQuery, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try (SQLQuery value = execute()) {
|
||||
R result = function.apply(value);
|
||||
return result == null ? defaultResult : result;
|
||||
} catch (SQLException exception) {
|
||||
throw new SQLException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public interface ConditionalBuilder<B extends ConditionalBuilder<B, T>, T extends SQLAction<?>> extends SQLBuilder {
|
||||
|
||||
/**
|
||||
* 将现有条件构建完整的SQL语句用于执行。
|
||||
*
|
||||
* @return {@link SQLAction}
|
||||
*/
|
||||
T build();
|
||||
|
||||
/**
|
||||
* 设定限定的条目数
|
||||
*
|
||||
* @param limit 条数限制
|
||||
* @return {@link B}
|
||||
*/
|
||||
B setLimit(int limit);
|
||||
|
||||
/**
|
||||
* 直接设定条件的源文本,不需要以WHERE开头。
|
||||
* <br>如 {@code id = 1 AND name = 'test' OR name = 'test2'} 。
|
||||
*
|
||||
* @param condition 条件文本,不需要以WHERE开头。
|
||||
* @return {@link B}
|
||||
*/
|
||||
B setConditions(@Nullable String condition);
|
||||
|
||||
/**
|
||||
* 直接设定每个条件的文本与其对应数值,将以AND链接,且不需要以WHERE开头。
|
||||
* <br>条件如 {@code id = ? },问号将被以对应的数值填充。。
|
||||
*
|
||||
* @param conditionSQLs 条件内容,将以AND链接,且不需要以WHERE开头。
|
||||
* @return {@link B}
|
||||
*/
|
||||
B setConditions(LinkedHashMap<@NotNull String, @Nullable Object> conditionSQLs);
|
||||
|
||||
B addCondition(@Nullable String condition);
|
||||
|
||||
B addCondition(@NotNull String columnName, @NotNull String operator, @Nullable Object queryValue);
|
||||
|
||||
default B addCondition(@NotNull String columnName, @Nullable Object queryValue) {
|
||||
return addCondition(columnName, "=", queryValue);
|
||||
}
|
||||
|
||||
B addCondition(@NotNull String[] columnNames, @Nullable Object[] queryValues);
|
||||
|
||||
B addNotNullCondition(@NotNull String columnName);
|
||||
|
||||
/**
|
||||
* 添加时间的限定条件。 若设定了开始时间,则限定条件为 {@code endMillis >= startMillis};
|
||||
*
|
||||
* @param columnName 判断的行
|
||||
* @param startMillis 开始时间戳,若{@code <0}则不作限定
|
||||
* @param endMillis 结束时间戳,若{@code <0}则不作限定
|
||||
* @return {@link B}
|
||||
*/
|
||||
default B addTimeCondition(@NotNull String columnName, long startMillis, long endMillis) {
|
||||
return addTimeCondition(columnName,
|
||||
startMillis > 0 ? new Date(startMillis) : null,
|
||||
endMillis > 0 ? new Date(endMillis) : null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加时间的限定条件。 若设定了开始时间,则限定条件为 {@code endDate >= startTime};
|
||||
*
|
||||
* @param columnName 判断的行
|
||||
* @param startDate 开始时间,若为null则不作限定
|
||||
* @param endDate 结束时间,若为null则不作限定
|
||||
* @return {@link B}
|
||||
*/
|
||||
B addTimeCondition(@NotNull String columnName, @Nullable java.util.Date startDate, @Nullable java.util.Date endDate);
|
||||
|
||||
|
||||
}
|
||||
+1
-1
@@ -4,6 +4,6 @@ import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
public interface DeleteBuilder extends ConditionalBuilder<DeleteBuilder, SQLAction<Integer>> {
|
||||
|
||||
String getTableName();
|
||||
String getTableName();
|
||||
|
||||
}
|
||||
+5
-5
@@ -14,12 +14,12 @@ import java.util.List;
|
||||
*/
|
||||
public interface ReplaceBuilder<T extends SQLAction<?>> {
|
||||
|
||||
String getTableName();
|
||||
String getTableName();
|
||||
|
||||
T setColumnNames(List<String> columnNames);
|
||||
T setColumnNames(List<String> columnNames);
|
||||
|
||||
default T setColumnNames(String... columnNames) {
|
||||
return setColumnNames(columnNames == null ? null : Arrays.asList(columnNames));
|
||||
}
|
||||
default T setColumnNames(String... columnNames) {
|
||||
return setColumnNames(columnNames == null ? null : Arrays.asList(columnNames));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface TableAlterBuilder extends SQLBuilder {
|
||||
|
||||
SQLAction<Integer> renameTo(@NotNull String newTableName);
|
||||
|
||||
SQLAction<Integer> changeComment(@NotNull String newTableComment);
|
||||
|
||||
SQLAction<Integer> setAutoIncrementIndex(int index);
|
||||
|
||||
SQLAction<Integer> addIndex(@NotNull IndexType indexType, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
/**
|
||||
* 为该表移除一个索引
|
||||
*
|
||||
* @param indexName 索引名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropIndex(@NotNull String indexName);
|
||||
|
||||
/**
|
||||
* 为该表移除一个外键
|
||||
*
|
||||
* @param keySymbol 外键名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropForeignKey(@NotNull String keySymbol);
|
||||
|
||||
/**
|
||||
* 为该表移除主键(须添加新主键)
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropPrimaryKey();
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
default SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return addColumn(columnName, settings, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @param afterColumn 该列增添到哪个列的后面,
|
||||
* <p> 该参数若省缺则放于最后一行
|
||||
* <p> 若为 "" 则置于首行。
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings, @Nullable String afterColumn);
|
||||
|
||||
SQLAction<Integer> renameColumn(@NotNull String columnName, @NotNull String newName);
|
||||
|
||||
SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String settings);
|
||||
|
||||
default SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String columnSettings, @NotNull String afterColumn) {
|
||||
return modifyColumn(columnName, columnSettings + " AFTER `" + afterColumn + "`");
|
||||
}
|
||||
|
||||
SQLAction<Integer> removeColumn(@NotNull String columnName);
|
||||
|
||||
SQLAction<Integer> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue);
|
||||
|
||||
SQLAction<Integer> removeColumnDefault(@NotNull String columnName);
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param primary 是否为主键,若否则只为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean primary, boolean unsigned) {
|
||||
return addColumn(columnName,
|
||||
(numberType == null ? NumberType.INT : numberType).name()
|
||||
+ (unsigned ? " UNSIGNED " : " ")
|
||||
+ "NOT NULL AUTO_INCREMENT " + (primary ? "PRIMARY KEY" : "UNIQUE KEY"),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName, @NotNull NumberType numberType) {
|
||||
return addAutoIncrementColumn(columnName, numberType, false, true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withQuote;
|
||||
|
||||
|
||||
public interface TableCreateBuilder extends SQLBuilder {
|
||||
|
||||
/**
|
||||
* 将现有条件构建完整的SQL语句用于执行。
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLUpdateAction build();
|
||||
|
||||
@NotNull String getTableName();
|
||||
|
||||
/**
|
||||
* 得到表的设定。
|
||||
* <p> 若未使用 {@link #setTableSettings(String)} 方法则会采用 {@link #defaultTablesSettings()} 。
|
||||
*
|
||||
* @return TableSettings
|
||||
*/
|
||||
@NotNull String getTableSettings();
|
||||
|
||||
TableCreateBuilder setTableSettings(@NotNull String settings);
|
||||
|
||||
/**
|
||||
* 设定表的标注,一般用于解释该表的作用。
|
||||
*
|
||||
* @param comment 表标注
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setTableComment(@Nullable String comment);
|
||||
|
||||
/**
|
||||
* 直接设定表的所有列信息
|
||||
*
|
||||
* @param columns 列的相关信息 (包括列设定)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setColumns(@NotNull String... columns);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param column 列的相关信息
|
||||
* <br>如 `uuid` VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addColumn(@NotNull String column);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
Objects.requireNonNull(columnName, "columnName could not be null");
|
||||
return addColumn(withBackQuote(columnName) + " " + settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @param comments 列的注解,用于解释该列数据的作用
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings, @NotNull String comments) {
|
||||
return addColumn(columnName, settings + " COMMENT " + withQuote(comments));
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean asPrimaryKey, boolean unsigned);
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName,
|
||||
boolean asPrimaryKey, boolean unsigned) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT, asPrimaryKey, unsigned);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, boolean asPrimaryKey) {
|
||||
return addAutoIncrementColumn(columnName, asPrimaryKey, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param columnName 索引包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder setIndex(@NotNull String columnName,
|
||||
@NotNull IndexType type) {
|
||||
return setIndex(type, null, columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param indexName 索引名称,缺省时将根据第一个索引列赋一个名称
|
||||
* @param columnName 索引包含的列
|
||||
* @param moreColumns 联合索引需要包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setIndex(@NotNull IndexType type, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定自参照外键(即自参照完整性)。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignColumn 外键关联表中对应的关联列,必须为目标表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, getTableName(), foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, null, foreignTable, foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, constraintName, foreignTable, foreignColumn, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @param updateRule 在外键被更新时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @param deleteRule 在外键被删除时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn,
|
||||
@Nullable ForeignKeyRule updateRule, @Nullable ForeignKeyRule deleteRule);
|
||||
|
||||
default String defaultTablesSettings() {
|
||||
return "ENGINE=InnoDB DEFAULT CHARSET=utf8";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, SQLAction<Integer>> {
|
||||
|
||||
String getTableName();
|
||||
|
||||
/**
|
||||
* 添加一条需要更新的字段名与值
|
||||
*
|
||||
* @param columnName 字段名
|
||||
* @param columnValue 字段名对应的值
|
||||
* @return {@link UpdateBuilder}
|
||||
* @since 0.3.7
|
||||
*/
|
||||
UpdateBuilder addColumnValue(@NotNull String columnName, @Nullable Object columnValue);
|
||||
|
||||
/**
|
||||
* 设定更新的全部字段值 <b>(此操作会覆盖之前的设定)</b>
|
||||
* <p> <b>此操作会覆盖之前的设定</b>
|
||||
*
|
||||
* @param columnData 字段名和值的键值对
|
||||
* @return {@link UpdateBuilder}
|
||||
*/
|
||||
UpdateBuilder setColumnValues(LinkedHashMap<@NotNull String, @Nullable Object> columnData);
|
||||
|
||||
/**
|
||||
* 设定更新的全部字段值 <b>(此操作会覆盖之前的设定)</b>
|
||||
* <p> <b>此操作会覆盖之前的设定</b>
|
||||
*
|
||||
* @param columnNames 字段名
|
||||
* @param columnValues 字段名对应的值
|
||||
* @return {@link UpdateBuilder}
|
||||
*/
|
||||
UpdateBuilder setColumnValues(@NotNull String[] columnNames, @Nullable Object[] columnValues);
|
||||
|
||||
/**
|
||||
* 设定更新的全部字段值 <b>(此操作会覆盖之前的设定)</b>
|
||||
* <p> 如需同时更新多条字段,请使用 {@link #setColumnValues(String[], Object[])} 或 {@link #setColumnValues(LinkedHashMap)}
|
||||
* <br>也可以使用 {@link #addColumnValue(String, Object)} 一条条的添加字段
|
||||
*
|
||||
* @param columnName 字段名
|
||||
* @param columnValue 字段名对应的值
|
||||
* @return {@link UpdateBuilder}
|
||||
*/
|
||||
default UpdateBuilder setColumnValues(@NotNull String columnName, @Nullable Object columnValue) {
|
||||
return setColumnValues(new String[]{columnName}, new Object[]{columnValue});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
/**
|
||||
* 存在则更新,不存在则插入。
|
||||
*
|
||||
* @see ReplaceBuilder
|
||||
*/
|
||||
@Deprecated
|
||||
public interface UpsertBuilder {
|
||||
|
||||
String getTableName();
|
||||
|
||||
default UpsertBuilder setColumnNames(String[] columnNames, String updateColumn) {
|
||||
throw new UnsupportedOperationException("Please use REPLACE .");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum ForeignKeyRule {
|
||||
|
||||
/**
|
||||
* 啥也不做
|
||||
* <p>注意: 在Mysql中该选项实际上等同于采用默认的 {@link #RESTRICT} 设定!
|
||||
*/
|
||||
NO_ACTION("NO ACTION"),
|
||||
|
||||
/**
|
||||
* 拒绝删除要求,直到使用删除键值的辅助表被手工删除,并且没有参照时(这是默认设置,也是最安全的设置)
|
||||
*/
|
||||
RESTRICT("RESTRICT"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用NULL值替换(只能用于已标记为NOT NULL的字段)
|
||||
*/
|
||||
SET_NULL("SET NULL"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用默认值替换(只能用于设定了DEFAULT的字段)
|
||||
*/
|
||||
SET_DEFAULT("SET DEFAULT"),
|
||||
|
||||
/**
|
||||
* <b>级联删除</b>,删除包含与已删除键值有参照关系的所有记录
|
||||
*/
|
||||
CASCADE("CASCADE");
|
||||
|
||||
final String ruleName;
|
||||
|
||||
ForeignKeyRule(String ruleName) {
|
||||
this.ruleName = ruleName;
|
||||
}
|
||||
|
||||
public String getRuleName() {
|
||||
return ruleName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum IndexType {
|
||||
|
||||
|
||||
/**
|
||||
* <b>普通索引</b>(由关键字KEY或INDEX定义的索引)的唯一任务是加快对数据的访问速度。
|
||||
* <br> 因此,应该只为那些最经常出现在查询条件(WHERE column=)或排序条件(ORDER BY column)中的数据列创建索引。
|
||||
* <br> 只要有可能,就应该选择一个数据最整齐、最紧凑的数据列(如一个整数类型的数据列)来创建索引。
|
||||
*/
|
||||
INDEX("INDEX"),
|
||||
|
||||
|
||||
/**
|
||||
* <b>唯一索引</b> 是在表上一个或者多个字段组合建立的索引,这个或者这些字段的值组合起来在表中不可以重复,用于保证数据的唯一性。
|
||||
*/
|
||||
UNIQUE_KEY("UNIQUE KEY"),
|
||||
|
||||
/**
|
||||
* <b>主键索引</b> 是唯一索引的特定类型。表中创建主键时自动创建的索引 。一个表只能建立一个主索引。
|
||||
*/
|
||||
PRIMARY_KEY("PRIMARY KEY"),
|
||||
|
||||
/**
|
||||
* <b>全文索引</b> 主要用来查找文本中的关键字,而不是直接与索引中的值相比较。
|
||||
* <br> 请搭配 MATCH 等语句使用,而不是使用 WHERE - LIKE 。
|
||||
* <br> 全文索引只可用于 CHAR、 VARCHAR 与 TEXT 系列类型。
|
||||
*/
|
||||
FULLTEXT_INDEX("FULLTEXT");
|
||||
|
||||
|
||||
final String name;
|
||||
|
||||
IndexType(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -2,10 +2,10 @@ package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum NumberType {
|
||||
|
||||
TINYINT,
|
||||
SMALLINT,
|
||||
MEDIUMINT,
|
||||
INT,
|
||||
BIGINT
|
||||
TINYINT,
|
||||
SMALLINT,
|
||||
MEDIUMINT,
|
||||
INT,
|
||||
BIGINT
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* 异常处理器。
|
||||
* <br> 在使用 {@link SQLAction#execute(SQLExceptionHandler)} 等相关方法时,
|
||||
* 如果发生异常,则会调用错误处理器进行错误内容的输出提示。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface SQLExceptionHandler extends BiConsumer<SQLException, SQLAction<?>> {
|
||||
|
||||
/**
|
||||
* 默认的异常处理器,将详细的输出相关错误与错误来源。
|
||||
*
|
||||
* @param logger 用于输出错误信息的Logger。
|
||||
* @return 输出详细信息的错误处理器。
|
||||
*/
|
||||
static SQLExceptionHandler detailed(Logger logger) {
|
||||
return (exception, sqlAction) -> {
|
||||
if (sqlAction instanceof SQLUpdateBatchAction) {
|
||||
logger.severe("Error when execute SQLs : ");
|
||||
int i = 1;
|
||||
for (String content : ((SQLUpdateBatchAction) sqlAction).getSQLContents()) {
|
||||
logger.severe(String.format("#%d {%s}", i, content));
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
logger.severe("Error when execute { " + sqlAction.getSQLContent() + " }");
|
||||
}
|
||||
exception.printStackTrace();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* “安静“ 的错误处理器,发生错误什么都不做。
|
||||
* 强烈不建议把此处理器作为默认处理器使用!
|
||||
*
|
||||
* @return 无输出的处理器。
|
||||
*/
|
||||
static SQLExceptionHandler silent() {
|
||||
return (exception, sqlAction) -> {
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -8,7 +8,7 @@ import java.sql.SQLException;
|
||||
@FunctionalInterface
|
||||
public interface SQLFunction<T, R> {
|
||||
|
||||
@Nullable
|
||||
R apply(@NotNull T t) throws SQLException;
|
||||
@Nullable
|
||||
R apply(@NotNull T t) throws SQLException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Objects;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface SQLHandler<T> {
|
||||
|
||||
void accept(@NotNull T t) throws SQLException;
|
||||
|
||||
@NotNull
|
||||
@Contract(pure = true)
|
||||
default SQLHandler<T> andThen(@NotNull SQLHandler<? super T> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (T t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public class TimeDateUtils {
|
||||
public static DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
public static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
public TimeDateUtils() {
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLFunction;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.api.function.defaults.DefaultSQLExceptionHandler;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* SQLAction 是用于承载SQL语句并进行处理、返回的基本类。
|
||||
*
|
||||
* <ul>
|
||||
* <li>同步执行 {@link #execute()}, {@link #execute(SQLFunction, SQLExceptionHandler)}
|
||||
* <br>同步执行方法中有会抛出异常的方法与不抛出异常的方法,
|
||||
* <br>若选择不抛出异常,则返回值可能为空,需要特殊处理。</li>
|
||||
*
|
||||
* <li>异步执行 {@link #executeAsync(SQLHandler, SQLExceptionHandler)}
|
||||
* <br>异步执行时将提供成功与异常两种处理方式
|
||||
* <br>可自行选择是否对数据或异常进行处理
|
||||
* <br>默认的异常处理器为 {@link #defaultExceptionHandler()}
|
||||
* <br>若有特殊需要,可通过{@link #setExceptionHandler(SQLExceptionHandler)} 方法修改默认的处理器</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param <T> 需要返回的类型
|
||||
* @author CarmJos
|
||||
* @since 0.0.1
|
||||
*/
|
||||
public interface SQLAction<T> {
|
||||
|
||||
/**
|
||||
* 得到该Action的UUID
|
||||
*
|
||||
* @return UUID
|
||||
*/
|
||||
@NotNull UUID getActionUUID();
|
||||
|
||||
/**
|
||||
* 得到短八位格式的UUID
|
||||
*
|
||||
* @return UUID(8)
|
||||
*/
|
||||
@NotNull String getShortID();
|
||||
|
||||
/**
|
||||
* 得到该Action的创建时间
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getCreateTime();
|
||||
|
||||
/**
|
||||
* 得到该Action所要执行的源SQL语句
|
||||
*
|
||||
* @return 源SQL语句
|
||||
*/
|
||||
@NotNull String getSQLContent();
|
||||
|
||||
/**
|
||||
* 得到承载该Action的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
@NotNull SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 执行该Action对应的SQL语句
|
||||
*
|
||||
* @return 指定数据类型
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@NotNull T execute() throws SQLException;
|
||||
|
||||
|
||||
/**
|
||||
* 执行语句并返回值
|
||||
*
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default T execute(@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(t -> t, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(function, null, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null,_ -> !null")
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable R defaultResult,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
try {
|
||||
return executeFunction(function, defaultResult);
|
||||
} catch (SQLException exception) {
|
||||
handleException(exceptionHandler, exception);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function) throws SQLException {
|
||||
return executeFunction(function, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try {
|
||||
R result = function.apply(execute());
|
||||
return result == null ? defaultResult : result;
|
||||
} catch (SQLException exception) {
|
||||
throw new SQLException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句,采用默认异常处理,无需返回值。
|
||||
*/
|
||||
default void executeAsync() {
|
||||
executeAsync(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
*/
|
||||
default void executeAsync(@Nullable SQLHandler<T> success) {
|
||||
executeAsync(success, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
* @param failure 异常处理器 默认为 {@link SQLAction#defaultExceptionHandler()}
|
||||
*/
|
||||
void executeAsync(@Nullable SQLHandler<T> success,
|
||||
@Nullable SQLExceptionHandler failure);
|
||||
|
||||
default void handleException(@Nullable SQLExceptionHandler handler, SQLException exception) {
|
||||
if (handler == null) handler = defaultExceptionHandler();
|
||||
handler.accept(exception, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认的异常处理器
|
||||
*
|
||||
* @return {@link DefaultSQLExceptionHandler#get(Logger)}
|
||||
* @see DefaultSQLExceptionHandler
|
||||
*/
|
||||
default SQLExceptionHandler defaultExceptionHandler() {
|
||||
return DefaultSQLExceptionHandler.get(getManager().getLogger());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定通用的异常处理器。
|
||||
* <br> 在使用 {@link #execute(SQLExceptionHandler)} 等相关方法时,若传入的处理器为null,则会采用此处理器。
|
||||
* <br> 若该方法传入参数为 null,则会使用 {@link #defaultExceptionHandler()} 。
|
||||
*
|
||||
* @param handler 异常处理器
|
||||
*/
|
||||
default void setExceptionHandler(@Nullable SQLExceptionHandler handler) {
|
||||
DefaultSQLExceptionHandler.setCustomHandler(handler);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.builder.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public interface SQLManager {
|
||||
|
||||
Logger getLogger();
|
||||
|
||||
boolean isDebugMode();
|
||||
|
||||
void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode);
|
||||
|
||||
default void setDebugMode(boolean enable) {
|
||||
setDebugMode(() -> enable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到连接池源
|
||||
*
|
||||
* @return DataSource
|
||||
*/
|
||||
@NotNull DataSource getDataSource();
|
||||
|
||||
/**
|
||||
* 得到一个数据库连接实例
|
||||
*
|
||||
* @return Connection
|
||||
* @throws SQLException 见 {@link DataSource#getConnection()}
|
||||
*/
|
||||
@NotNull Connection getConnection() throws SQLException;
|
||||
|
||||
/**
|
||||
* 得到正使用的查询。
|
||||
*
|
||||
* @return 查询列表
|
||||
*/
|
||||
@NotNull Map<UUID, SQLQuery> getActiveQuery();
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的SQL语句(多用于UPDATE、REPLACE、DELETE方法)
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @return 更新的行数
|
||||
* @see SQLUpdateAction
|
||||
*/
|
||||
@Nullable Integer executeSQL(String sql);
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的预处理SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param params SQL语句中 ? 的对应参数
|
||||
* @return 更新的行数
|
||||
* @see PreparedSQLUpdateAction
|
||||
*/
|
||||
@Nullable Integer executeSQL(String sql, Object[] params);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param paramsBatch SQL语句中对应?的参数组
|
||||
* @return 对应参数返回的行数
|
||||
* @see PreparedSQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch);
|
||||
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param moreSQL 更多SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
* @see SQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
*
|
||||
* @param sqlBatch SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch);
|
||||
|
||||
/**
|
||||
* 在库中创建一个表
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder createTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 对库中的某个表执行更改
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
TableAlterBuilder alterTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 新建一个查询
|
||||
*
|
||||
* @return {@link QueryBuilder}
|
||||
*/
|
||||
QueryBuilder createQuery();
|
||||
|
||||
/**
|
||||
* 创建一条插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建一条替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建更新操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link UpdateBuilder}
|
||||
*/
|
||||
UpdateBuilder createUpdate(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建删除操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link DeleteBuilder}
|
||||
*/
|
||||
DeleteBuilder createDelete(@NotNull String tableName);
|
||||
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.api.action.query.QueryAction;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
public interface SQLQuery extends AutoCloseable {
|
||||
|
||||
/**
|
||||
* 获取该查询创建的时间
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getExecuteTime();
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link QueryAction}
|
||||
*
|
||||
* @return {@link QueryAction} 或 {@link PreparedQueryAction}
|
||||
*/
|
||||
QueryAction getAction();
|
||||
|
||||
ResultSet getResultSet();
|
||||
|
||||
/**
|
||||
* 得到设定的SQL语句
|
||||
*
|
||||
* @return SQL语句
|
||||
*/
|
||||
String getSQLContent();
|
||||
|
||||
/**
|
||||
* 关闭所有内容
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
|
||||
Statement getStatement();
|
||||
|
||||
Connection getConnection();
|
||||
|
||||
}
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
|
||||
|
||||
/**
|
||||
* 设定多组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param allParams 所有参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams);
|
||||
|
||||
/**
|
||||
* 添加一组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param params 参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction addParamsBatch(Object... params);
|
||||
|
||||
/**
|
||||
* 设定自增主键的序列
|
||||
*
|
||||
* @param keyColumnIndex 自增主键的序列
|
||||
* <br>若该值 > 0,则 {@link #execute()} 返回自增主键数值
|
||||
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
* @see #setReturnGeneratedKeys(boolean)
|
||||
*/
|
||||
@Deprecated
|
||||
default PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex) {
|
||||
return setReturnGeneratedKeys(keyColumnIndex > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作返回自增键序列。
|
||||
*
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
default PreparedSQLUpdateBatchAction returnGeneratedKeys() {
|
||||
return setReturnGeneratedKeys(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作是否返回自增键序列。
|
||||
*
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey);
|
||||
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
public interface SQLUpdateAction extends SQLAction<Integer> {
|
||||
|
||||
/**
|
||||
* 设定自增主键的序列
|
||||
*
|
||||
* @param keyColumnIndex 自增主键的序列
|
||||
* <br>若该值 > 0,则 {@link #execute()} 返回自增主键数值
|
||||
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
|
||||
* @return {@link SQLUpdateAction}
|
||||
* @see #setReturnGeneratedKey(boolean)
|
||||
*/
|
||||
@Deprecated
|
||||
default SQLUpdateAction setKeyIndex(int keyColumnIndex) {
|
||||
return setReturnGeneratedKey(keyColumnIndex > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作返回自增键序列。
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
default SQLUpdateAction returnGeneratedKey() {
|
||||
return setReturnGeneratedKey(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作是否返回自增键序列。
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey);
|
||||
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
|
||||
|
||||
/**
|
||||
* 添加一条批量执行的SQL语句
|
||||
*
|
||||
* @param sql SQL语句
|
||||
* @return {@link SQLUpdateBatchAction}
|
||||
*/
|
||||
SQLUpdateBatchAction addBatch(@NotNull String sql);
|
||||
|
||||
@Override
|
||||
default @NotNull String getSQLContent() {
|
||||
return getSQLContents().get(0);
|
||||
}
|
||||
|
||||
List<String> getSQLContents();
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public interface ConditionalBuilder<B extends ConditionalBuilder<B, T>, T extends SQLAction<?>> extends SQLBuilder {
|
||||
|
||||
/**
|
||||
* 将现有条件构建完整的SQL语句用于执行。
|
||||
*
|
||||
* @return {@link cc.carm.lib.easysql.api.SQLAction}
|
||||
*/
|
||||
T build();
|
||||
|
||||
/**
|
||||
* 设定取出的条数
|
||||
*
|
||||
* @param limit 条数限制
|
||||
* @return {@link B}
|
||||
*/
|
||||
B setLimit(int limit);
|
||||
|
||||
B setConditions(@Nullable String condition);
|
||||
|
||||
B setConditions(LinkedHashMap<@NotNull String, @Nullable Object> conditionSQLs);
|
||||
|
||||
B addCondition(@Nullable String condition);
|
||||
|
||||
B addCondition(@NotNull String queryName, @NotNull String operator, @Nullable Object queryValue);
|
||||
|
||||
default B addCondition(@NotNull String queryName, @Nullable Object queryValue) {
|
||||
return addCondition(queryName, "=", queryValue);
|
||||
}
|
||||
|
||||
B addCondition(@NotNull String[] queryNames, @Nullable Object[] queryValues);
|
||||
|
||||
B addNotNullCondition(@NotNull String queryName);
|
||||
|
||||
default B addTimeCondition(@NotNull String queryName, long startMillis, long endMillis) {
|
||||
return addTimeCondition(queryName,
|
||||
startMillis > 0 ? new Date(startMillis) : null,
|
||||
endMillis > 0 ? new Date(endMillis) : null
|
||||
);
|
||||
}
|
||||
|
||||
B addTimeCondition(@NotNull String queryName, @Nullable java.util.Date startDate, @Nullable java.util.Date endDate);
|
||||
|
||||
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface TableAlterBuilder extends SQLBuilder {
|
||||
|
||||
SQLAction<Integer> renameTo(@NotNull String newTableName);
|
||||
|
||||
SQLAction<Integer> changeComment(@NotNull String newTableComment);
|
||||
|
||||
SQLAction<Integer> setAutoIncrementIndex(int index);
|
||||
|
||||
SQLAction<Integer> addIndex(@NotNull IndexType indexType, @NotNull String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
/**
|
||||
* 为该表移除一个索引
|
||||
*
|
||||
* @param indexName 索引名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropIndex(@NotNull String indexName);
|
||||
|
||||
/**
|
||||
* 为该表移除一个外键
|
||||
*
|
||||
* @param keySymbol 外键名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropForeignKey(@NotNull String keySymbol);
|
||||
|
||||
/**
|
||||
* 为该表移除主键(须添加新主键)
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropPrimaryKey();
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
default SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return addColumn(columnName, settings, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @param afterColumn 该列增添到哪个列的后面,
|
||||
* <p> 该参数若省缺则放于最后一行
|
||||
* <p> 若为 "" 则置于首行。
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings, @Nullable String afterColumn);
|
||||
|
||||
SQLAction<Integer> renameColumn(@NotNull String columnName, @NotNull String newName);
|
||||
|
||||
SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String settings);
|
||||
|
||||
default SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String columnSettings, @NotNull String afterColumn) {
|
||||
return modifyColumn(columnName, columnSettings + " AFTER `" + afterColumn + "`");
|
||||
}
|
||||
|
||||
SQLAction<Integer> removeColumn(@NotNull String columnName);
|
||||
|
||||
SQLAction<Integer> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue);
|
||||
|
||||
SQLAction<Integer> removeColumnDefault(@NotNull String columnName);
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param primary 是否为主键,若否则只为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean primary, boolean unsigned) {
|
||||
return addColumn(columnName,
|
||||
(numberType == null ? NumberType.INT : numberType).name()
|
||||
+ (unsigned ? " UNSIGNED " : " ")
|
||||
+ "NOT NULL AUTO_INCREMENT " + (primary ? "PRIMARY KEY" : "UNIQUE KEY"),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName, @NotNull NumberType numberType) {
|
||||
return addAutoIncrementColumn(columnName, numberType, false, true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface TableCreateBuilder extends SQLBuilder {
|
||||
|
||||
/**
|
||||
* 将现有条件构建完整的SQL语句用于执行。
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLUpdateAction build();
|
||||
|
||||
@NotNull String getTableName();
|
||||
|
||||
/**
|
||||
* 得到表的设定。
|
||||
* <p> 若未使用 {@link #setTableSettings(String)} 方法则会采用 {@link #defaultTablesSettings()} 。
|
||||
*
|
||||
* @return TableSettings
|
||||
*/
|
||||
@NotNull String getTableSettings();
|
||||
|
||||
TableCreateBuilder setTableSettings(@NotNull String settings);
|
||||
|
||||
/**
|
||||
* 设定表的标注,一般用于解释该表的作用。
|
||||
*
|
||||
* @param comment 表标注
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setTableComment(@Nullable String comment);
|
||||
|
||||
/**
|
||||
* 直接设定表的所有列信息
|
||||
*
|
||||
* @param columns 列的相关信息 (包括列设定)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setColumns(@NotNull String... columns);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param column 列的相关信息
|
||||
* <br>如 `uuid` VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addColumn(@NotNull String column);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return addColumn("`" + columnName + "` " + settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @param comments 列的注解,用于解释该列数据的作用
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings, @NotNull String comments) {
|
||||
return addColumn(columnName, settings + " COMMENT '" + comments + "'");
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean asPrimaryKey, boolean unsigned);
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName,
|
||||
boolean asPrimaryKey, boolean unsigned) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT, asPrimaryKey, unsigned);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, boolean asPrimaryKey) {
|
||||
return addAutoIncrementColumn(columnName, asPrimaryKey, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param columnName 索引包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder setIndex(@NotNull String columnName,
|
||||
@NotNull IndexType type) {
|
||||
return setIndex(type, null, columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param indexName 索引名称,缺省时将根据第一个索引列赋一个名称
|
||||
* @param columnName 索引包含的列
|
||||
* @param moreColumns 联合索引需要包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setIndex(@NotNull IndexType type, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定自参照外键(即自参照完整性)。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignColumn 外键关联表中对应的关联列,必须为目标表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, getTableName(), foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, null, foreignTable, foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, constraintName, foreignTable, foreignColumn, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @param updateRule 在外键被更新时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @param deleteRule 在外键被删除时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn,
|
||||
@Nullable ForeignKeyRule updateRule, @Nullable ForeignKeyRule deleteRule);
|
||||
|
||||
default String defaultTablesSettings() {
|
||||
return "ENGINE=InnoDB DEFAULT CHARSET=utf8";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, SQLAction<Integer>> {
|
||||
|
||||
String getTableName();
|
||||
|
||||
UpdateBuilder setColumnValues(LinkedHashMap<String, Object> columnData);
|
||||
|
||||
UpdateBuilder setColumnValues(String[] columnNames, Object[] columnValues);
|
||||
|
||||
default UpdateBuilder setColumnValues(String columnName, Object columnValue) {
|
||||
return setColumnValues(new String[]{columnName}, new Object[]{columnValue});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
/**
|
||||
* 存在则更新,不存在则插入。
|
||||
*
|
||||
* @see ReplaceBuilder
|
||||
*/
|
||||
@Deprecated
|
||||
public interface UpsertBuilder {
|
||||
|
||||
String getTableName();
|
||||
|
||||
UpsertBuilder setColumnNames(String[] columnNames, String updateColumn);
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum ForeignKeyRule {
|
||||
|
||||
/**
|
||||
* 啥也不做
|
||||
* <p>注意: 在Mysql中该选项实际上等同于采用默认的 {@link #RESTRICT} 设定!
|
||||
*/
|
||||
NO_ACTION("NO ACTION"),
|
||||
|
||||
/**
|
||||
* 拒绝删除要求,直到使用删除键值的辅助表被手工删除,并且没有参照时(这是默认设置,也是最安全的设置)
|
||||
*/
|
||||
RESTRICT("RESTRICT"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用NULL值替换(只能用于已标记为NOT NULL的字段)
|
||||
*/
|
||||
SET_NULL("SET NULL"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用默认值替换(只能用于设定了DEFAULT的字段)
|
||||
*/
|
||||
SET_DEFAULT("SET DEFAULT"),
|
||||
|
||||
/**
|
||||
* <b>级联删除</b>,删除包含与已删除键值有参照关系的所有记录
|
||||
*/
|
||||
CASCADE("CASCADE");
|
||||
|
||||
final String ruleName;
|
||||
|
||||
ForeignKeyRule(String ruleName) {
|
||||
this.ruleName = ruleName;
|
||||
}
|
||||
|
||||
public String getRuleName() {
|
||||
return ruleName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum IndexType {
|
||||
|
||||
|
||||
/**
|
||||
* <b>普通索引</b>(由关键字KEY或INDEX定义的索引)的唯一任务是加快对数据的访问速度。
|
||||
* <br> 因此,应该只为那些最经常出现在查询条件(WHERE column=)或排序条件(ORDER BY column)中的数据列创建索引。
|
||||
* <br> 只要有可能,就应该选择一个数据最整齐、最紧凑的数据列(如一个整数类型的数据列)来创建索引。
|
||||
*/
|
||||
INDEX("INDEX"),
|
||||
|
||||
|
||||
/**
|
||||
* <b>唯一索引</b> 是在表上一个或者多个字段组合建立的索引,这个或者这些字段的值组合起来在表中不可以重复,用于保证数据的唯一性。
|
||||
*/
|
||||
UNIQUE_KEY("UNIQUE KEY"),
|
||||
|
||||
/**
|
||||
* <b>主键索引</b> 是唯一索引的特定类型。表中创建主键时自动创建的索引 。一个表只能建立一个主索引。
|
||||
*/
|
||||
PRIMARY_KEY("PRIMARY KEY"),
|
||||
|
||||
/**
|
||||
* <b>全文索引</b> 主要用来查找文本中的关键字,而不是直接与索引中的值相比较。
|
||||
* <br> 请搭配 MATCH 等语句使用,而不是使用 WHERE - LIKE 。
|
||||
* <br> 全文索引只可用于 CHAR、 VARCHAR 与 TEXT 系列类型。
|
||||
*/
|
||||
FULLTEXT_INDEX("FULLTEXT");
|
||||
|
||||
|
||||
final String name;
|
||||
|
||||
IndexType(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface SQLExceptionHandler extends BiConsumer<SQLException, SQLAction<?>> {
|
||||
|
||||
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Objects;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface SQLHandler<T> {
|
||||
|
||||
void accept(@NotNull T t) throws SQLException;
|
||||
|
||||
@NotNull
|
||||
@Contract(pure = true)
|
||||
default SQLHandler<T> andThen(@NotNull SQLHandler<? super T> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (T t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.function.defaults;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class DefaultSQLExceptionHandler implements SQLExceptionHandler {
|
||||
|
||||
private static @Nullable SQLExceptionHandler customDefaultHandler = null;
|
||||
|
||||
public static void setCustomHandler(@Nullable SQLExceptionHandler handler) {
|
||||
DefaultSQLExceptionHandler.customDefaultHandler = handler;
|
||||
}
|
||||
|
||||
public static @Nullable SQLExceptionHandler getCustomHandler() {
|
||||
return customDefaultHandler;
|
||||
}
|
||||
|
||||
public static @NotNull SQLExceptionHandler get(Logger logger) {
|
||||
if (getCustomHandler() != null) return getCustomHandler();
|
||||
else return new DefaultSQLExceptionHandler(logger);
|
||||
}
|
||||
|
||||
private final Logger logger;
|
||||
|
||||
public DefaultSQLExceptionHandler(Logger logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
protected Logger getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(SQLException exception, SQLAction<?> sqlAction) {
|
||||
if (sqlAction instanceof SQLUpdateBatchAction) {
|
||||
|
||||
getLogger().severe("Error when execute SQLs : ");
|
||||
int i = 1;
|
||||
for (String content : ((SQLUpdateBatchAction) sqlAction).getSQLContents()) {
|
||||
getLogger().severe("#" + i + " {" + content + "}");
|
||||
i++;
|
||||
}
|
||||
|
||||
} else {
|
||||
getLogger().severe("Error when execute { " + sqlAction.getSQLContent() + " }");
|
||||
}
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class AbstractSQLAction<T> implements SQLAction<T> {
|
||||
|
||||
private final @NotNull SQLManagerImpl sqlManager;
|
||||
|
||||
private final @NotNull UUID uuid;
|
||||
private final long createTime;
|
||||
|
||||
protected @NotNull String sqlContent;
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
this(manager, sql, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, @NotNull UUID uuid) {
|
||||
this(manager, sql, uuid, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, long createTime) {
|
||||
this(manager, sql, UUID.randomUUID(), createTime);
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@NotNull UUID uuid, long createTime) {
|
||||
this.sqlManager = manager;
|
||||
this.sqlContent = sql;
|
||||
this.uuid = uuid;
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public @NotNull UUID getActionUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getShortID() {
|
||||
return getActionUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCreateTime() {
|
||||
return this.createTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getSQLContent() {
|
||||
return this.sqlContent.trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull SQLManagerImpl getManager() {
|
||||
return this.sqlManager;
|
||||
}
|
||||
|
||||
protected void outputDebugMessage() {
|
||||
getManager().debug("#" + getShortID() + " -> { " + getSQLContent() + " }");
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("FutureReturnValueIgnored")
|
||||
public void executeAsync(SQLHandler<T> success, SQLExceptionHandler failure) {
|
||||
getManager().getExecutorPool().submit(() -> {
|
||||
try {
|
||||
T returnedValue = execute();
|
||||
if (success != null) success.accept(returnedValue);
|
||||
} catch (SQLException e) {
|
||||
handleException(failure, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class PreparedSQLBatchUpdateActionImpl
|
||||
extends AbstractSQLAction<List<Integer>>
|
||||
implements PreparedSQLUpdateBatchAction {
|
||||
|
||||
boolean returnKeys = false;
|
||||
List<Object[]> allParams;
|
||||
|
||||
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
this.allParams = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams) {
|
||||
List<Object[]> paramsList = new ArrayList<>();
|
||||
allParams.forEach(paramsList::add);
|
||||
this.allParams = paramsList;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction addParamsBatch(Object... params) {
|
||||
this.allParams.add(params);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey) {
|
||||
this.returnKeys = returnGeneratedKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<Integer> execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
|
||||
connection, getSQLContent(), allParams, returnKeys
|
||||
)) {
|
||||
|
||||
outputDebugMessage();
|
||||
int[] executed = statement.executeBatch();
|
||||
|
||||
if (!returnKeys) return Arrays.stream(executed).boxed().collect(Collectors.toList());
|
||||
else {
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
List<Integer> generatedKeys = new ArrayList<>();
|
||||
while (resultSet.next()) {
|
||||
generatedKeys.add(resultSet.getInt(1));
|
||||
}
|
||||
return generatedKeys;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PreparedSQLUpdateActionImpl
|
||||
extends SQLUpdateActionImpl
|
||||
implements PreparedSQLUpdateAction {
|
||||
|
||||
Object[] params;
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
this(manager, sql, (Object[]) null);
|
||||
}
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@Nullable List<Object> params) {
|
||||
this(manager, sql, params == null ? null : params.toArray());
|
||||
}
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@Nullable Object[] params) {
|
||||
super(manager, sql);
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateActionImpl setParams(Object... params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateAction setParams(@Nullable Iterable<Object> params) {
|
||||
if (params == null) {
|
||||
return setParams((Object[]) null);
|
||||
} else {
|
||||
List<Object> paramsList = new ArrayList<>();
|
||||
params.forEach(paramsList::add);
|
||||
return setParams(paramsList.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Integer execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
|
||||
try (PreparedStatement statement = StatementUtil.createPrepareStatement(
|
||||
connection, getSQLContent(), params, returnGeneratedKeys
|
||||
)) {
|
||||
|
||||
outputDebugMessage();
|
||||
|
||||
int changes = statement.executeUpdate();
|
||||
if (!returnGeneratedKeys) return changes;
|
||||
else {
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
return resultSet.next() ? resultSet.getInt(1) : -1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class SQLUpdateActionImpl
|
||||
extends AbstractSQLAction<Integer>
|
||||
implements SQLUpdateAction {
|
||||
|
||||
boolean returnGeneratedKeys = false;
|
||||
|
||||
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Integer execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
outputDebugMessage();
|
||||
|
||||
if (!returnGeneratedKeys) {
|
||||
return statement.executeUpdate(getSQLContent());
|
||||
} else {
|
||||
statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS);
|
||||
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
return resultSet.next() ? resultSet.getInt(1) : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey) {
|
||||
this.returnGeneratedKeys = returnGeneratedKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class SQLUpdateBatchActionImpl
|
||||
extends AbstractSQLAction<List<Integer>>
|
||||
implements SQLUpdateBatchAction {
|
||||
|
||||
List<String> sqlContents = new ArrayList<>();
|
||||
|
||||
public SQLUpdateBatchActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
this.sqlContents.add(sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<String> getSQLContents() {
|
||||
return this.sqlContents;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLUpdateBatchAction addBatch(@NotNull String sql) {
|
||||
this.sqlContents.add(sql);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<Integer> execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
outputDebugMessage();
|
||||
|
||||
for (String content : this.sqlContents) {
|
||||
statement.addBatch(content);
|
||||
}
|
||||
|
||||
int[] executed = statement.executeBatch();
|
||||
|
||||
return Arrays.stream(executed).boxed().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void outputDebugMessage() {
|
||||
getManager().debug("#" + getShortID() + " -> {");
|
||||
for (String content : getSQLContents()) getManager().debug(" " + content);
|
||||
getManager().debug("}");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package cc.carm.lib.easysql.action.query;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.query.SQLQueryImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class PreparedQueryActionImpl extends QueryActionImpl implements PreparedQueryAction {
|
||||
|
||||
Consumer<PreparedStatement> handler;
|
||||
Object[] params;
|
||||
|
||||
public PreparedQueryActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl setParams(@Nullable Object... params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl setParams(@Nullable Iterable<Object> params) {
|
||||
if (params == null) {
|
||||
return setParams((Object[]) null);
|
||||
} else {
|
||||
List<Object> paramsList = new ArrayList<>();
|
||||
params.forEach(paramsList::add);
|
||||
return setParams(paramsList.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl handleStatement(@Nullable Consumer<PreparedStatement> statement) {
|
||||
this.handler = statement;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public @NotNull SQLQueryImpl execute() throws SQLException {
|
||||
outputDebugMessage();
|
||||
|
||||
Connection connection = getManager().getConnection();
|
||||
PreparedStatement preparedStatement;
|
||||
try {
|
||||
if (handler == null) {
|
||||
preparedStatement = StatementUtil.createPrepareStatement(connection, getSQLContent(), this.params);
|
||||
} else {
|
||||
preparedStatement = connection.prepareStatement(getSQLContent());
|
||||
handler.accept(preparedStatement);
|
||||
}
|
||||
} catch (SQLException exception) {
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
|
||||
try {
|
||||
long executeTime = System.currentTimeMillis();
|
||||
SQLQueryImpl query = new SQLQueryImpl(
|
||||
getManager(), this,
|
||||
connection, preparedStatement,
|
||||
preparedStatement.executeQuery(),
|
||||
executeTime
|
||||
);
|
||||
getManager().getActiveQuery().put(getActionUUID(), query);
|
||||
|
||||
return query;
|
||||
} catch (SQLException exception) {
|
||||
preparedStatement.close();
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package cc.carm.lib.easysql.action.query;
|
||||
|
||||
import cc.carm.lib.easysql.action.AbstractSQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.api.action.query.QueryAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.query.SQLQueryImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements QueryAction {
|
||||
|
||||
public QueryActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull SQLQueryImpl execute() throws SQLException {
|
||||
|
||||
Connection connection = getManager().getConnection();
|
||||
Statement statement;
|
||||
|
||||
try {
|
||||
statement = connection.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
connection.close();
|
||||
throw ex;
|
||||
}
|
||||
|
||||
outputDebugMessage();
|
||||
try {
|
||||
long executeTime = System.currentTimeMillis();
|
||||
SQLQueryImpl query = new SQLQueryImpl(
|
||||
getManager(), this,
|
||||
connection, statement,
|
||||
statement.executeQuery(getSQLContent()),
|
||||
executeTime
|
||||
);
|
||||
getManager().getActiveQuery().put(getActionUUID(), query);
|
||||
|
||||
return query;
|
||||
} catch (SQLException exception) {
|
||||
statement.close();
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void executeAsync(SQLHandler<SQLQuery> success, SQLExceptionHandler failure) {
|
||||
try (SQLQueryImpl query = execute()) {
|
||||
if (success != null) success.accept(query);
|
||||
} catch (SQLException exception) {
|
||||
handleException(failure, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
-145
@@ -1,145 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.ConditionalBuilder;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public abstract class AbstractConditionalBuilder<B extends ConditionalBuilder<B, T>, T extends SQLAction<?>>
|
||||
extends AbstractSQLBuilder implements ConditionalBuilder<B, T> {
|
||||
|
||||
ArrayList<String> conditionSQLs = new ArrayList<>();
|
||||
ArrayList<Object> conditionParams = new ArrayList<>();
|
||||
int limit = -1;
|
||||
|
||||
public AbstractConditionalBuilder(@NotNull SQLManagerImpl manager) {
|
||||
super(manager);
|
||||
}
|
||||
|
||||
protected abstract B getThis();
|
||||
|
||||
@Override
|
||||
public B setConditions(@Nullable String condition) {
|
||||
this.conditionSQLs = new ArrayList<>();
|
||||
this.conditionParams = new ArrayList<>();
|
||||
if (condition != null) this.conditionSQLs.add(condition);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B setConditions(
|
||||
LinkedHashMap<@NotNull String, @Nullable Object> conditions
|
||||
) {
|
||||
conditions.forEach(this::addCondition);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B addCondition(@Nullable String condition) {
|
||||
this.conditionSQLs.add(condition);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B addCondition(
|
||||
@NotNull String queryName, @NotNull String operator, @Nullable Object queryValue
|
||||
) {
|
||||
addCondition("`" + queryName + "` " + operator + " ?");
|
||||
this.conditionParams.add(queryValue);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B addCondition(
|
||||
@NotNull String[] queryNames, @Nullable Object[] queryValues
|
||||
) {
|
||||
if (queryValues == null || queryNames.length != queryValues.length) {
|
||||
throw new RuntimeException("queryNames are not match with queryValues");
|
||||
}
|
||||
for (int i = 0; i < queryNames.length; i++) {
|
||||
addCondition(queryNames[i], queryValues[i]);
|
||||
}
|
||||
return getThis();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public B addNotNullCondition(@NotNull String queryName) {
|
||||
return addCondition("`" + queryName + "` IS NOT NULL");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public B addTimeCondition(
|
||||
@NotNull String queryName, @Nullable Date startDate, @Nullable Date endDate
|
||||
) {
|
||||
if (startDate == null && endDate == null) return getThis(); // 都不限定时间,不用判断了
|
||||
if (startDate != null) {
|
||||
addCondition("`" + queryName + "` BETWEEN ? AND ?");
|
||||
this.conditionParams.add(startDate);
|
||||
if (endDate != null) {
|
||||
this.conditionParams.add(endDate);
|
||||
} else {
|
||||
if (startDate instanceof java.sql.Date) {
|
||||
this.conditionParams.add(new java.sql.Date(System.currentTimeMillis()));
|
||||
} else if (startDate instanceof Time) {
|
||||
this.conditionParams.add(new Time(System.currentTimeMillis()));
|
||||
} else {
|
||||
this.conditionParams.add(new Timestamp(System.currentTimeMillis()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
addCondition(queryName, "<=", endDate);
|
||||
}
|
||||
return getThis();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public B setLimit(int limit) {
|
||||
this.limit = limit;
|
||||
return getThis();
|
||||
}
|
||||
|
||||
protected String buildConditionSQL() {
|
||||
|
||||
if (!conditionSQLs.isEmpty()) {
|
||||
StringBuilder conditionBuilder = new StringBuilder();
|
||||
conditionBuilder.append("WHERE").append(" ");
|
||||
Iterator<String> iterator = conditionSQLs.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
conditionBuilder.append(iterator.next());
|
||||
if (iterator.hasNext()) conditionBuilder.append(" ");
|
||||
}
|
||||
return conditionBuilder.toString();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected String buildLimitSQL() {
|
||||
return limit > 0 ? "LIMIT " + limit : "";
|
||||
}
|
||||
|
||||
protected ArrayList<Object> getConditionParams() {
|
||||
return conditionParams;
|
||||
}
|
||||
|
||||
protected boolean hasConditions() {
|
||||
return this.conditionSQLs != null && !this.conditionSQLs.isEmpty();
|
||||
}
|
||||
|
||||
protected boolean hasConditionParams() {
|
||||
return hasConditions() && getConditionParams() != null && !getConditionParams().isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.PreparedSQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.builder.DeleteBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class DeleteBuilderImpl
|
||||
extends AbstractConditionalBuilder<DeleteBuilder, SQLAction<Integer>>
|
||||
implements DeleteBuilder {
|
||||
|
||||
String tableName;
|
||||
|
||||
public DeleteBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateAction build() {
|
||||
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
|
||||
sqlBuilder.append("DELETE FROM `").append(getTableName()).append("`");
|
||||
|
||||
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
|
||||
if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL());
|
||||
|
||||
return new PreparedSQLUpdateActionImpl(
|
||||
getManager(), sqlBuilder.toString(),
|
||||
hasConditionParams() ? getConditionParams() : null
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected DeleteBuilderImpl getThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.InsertBuilder;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class InsertBuilderImpl<T extends SQLAction<?>>
|
||||
extends AbstractSQLBuilder implements InsertBuilder<T> {
|
||||
|
||||
String tableName;
|
||||
|
||||
public InsertBuilderImpl(@NotNull SQLManagerImpl manager, String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
protected static String buildSQL(String tableName, List<String> columnNames) {
|
||||
int valueLength = columnNames.size();
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
|
||||
sqlBuilder.append("INSERT IGNORE INTO `").append(tableName).append("`(");
|
||||
Iterator<String> iterator = columnNames.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
sqlBuilder.append("`").append(iterator.next()).append("`");
|
||||
if (iterator.hasNext()) sqlBuilder.append(", ");
|
||||
}
|
||||
|
||||
sqlBuilder.append(") VALUES (");
|
||||
|
||||
for (int i = 0; i < valueLength; i++) {
|
||||
sqlBuilder.append("?");
|
||||
if (i != valueLength - 1) {
|
||||
sqlBuilder.append(", ");
|
||||
}
|
||||
}
|
||||
sqlBuilder.append(")");
|
||||
return sqlBuilder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.ReplaceBuilder;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class ReplaceBuilderImpl<T extends SQLAction<?>>
|
||||
extends AbstractSQLBuilder implements ReplaceBuilder<T> {
|
||||
|
||||
String tableName;
|
||||
|
||||
public ReplaceBuilderImpl(@NotNull SQLManagerImpl manager, String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
protected static String buildSQL(String tableName, List<String> columnNames) {
|
||||
int valueLength = columnNames.size();
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
|
||||
sqlBuilder.append("REPLACE INTO `").append(tableName).append("`(");
|
||||
Iterator<String> iterator = columnNames.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
sqlBuilder.append("`").append(iterator.next()).append("`");
|
||||
if (iterator.hasNext()) sqlBuilder.append(", ");
|
||||
}
|
||||
|
||||
sqlBuilder.append(") VALUES (");
|
||||
|
||||
for (int i = 0; i < valueLength; i++) {
|
||||
sqlBuilder.append("?");
|
||||
if (i != valueLength - 1) {
|
||||
sqlBuilder.append(", ");
|
||||
}
|
||||
}
|
||||
sqlBuilder.append(")");
|
||||
return sqlBuilder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
}
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.SQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.TableAlterBuilder;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class TableAlterBuilderImpl extends AbstractSQLBuilder implements TableAlterBuilder {
|
||||
|
||||
protected final @NotNull String tableName;
|
||||
|
||||
public TableAlterBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public @NotNull String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> renameTo(@NotNull String newTableName) {
|
||||
return new SQLUpdateActionImpl(getManager(),
|
||||
"ALTER TABLE `" + getTableName() + "` RENAME TO `" + newTableName + "`"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> changeComment(@NotNull String newTableComment) {
|
||||
return new SQLUpdateActionImpl(getManager(),
|
||||
"ALTER TABLE `" + getTableName() + "` COMMENT '" + newTableComment + "'"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> setAutoIncrementIndex(int index) {
|
||||
return new SQLUpdateActionImpl(getManager(),
|
||||
"ALTER TABLE `" + getTableName() + "` AUTO_INCREMENT=" + index
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> addIndex(@NotNull IndexType indexType, @NotNull String indexName, @NotNull String columnName, @NotNull String... moreColumns) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` ADD "
|
||||
+ TableCreateBuilderImpl.buildIndexSettings(indexType, indexName, columnName, moreColumns)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> dropIndex(@NotNull String indexName) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` DROP INDEX `" + indexName + "`"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> dropForeignKey(@NotNull String keySymbol) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` DROP FOREIGN KEY `" + keySymbol + "`"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> dropPrimaryKey() {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` DROP PRIMARY KEY"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings, @Nullable String afterColumn) {
|
||||
String orderSettings = null;
|
||||
if (afterColumn != null) {
|
||||
if (afterColumn.length() > 0) {
|
||||
orderSettings = "AFTER `" + afterColumn + "`";
|
||||
} else {
|
||||
orderSettings = "FIRST";
|
||||
}
|
||||
}
|
||||
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` ADD `" + columnName + "` " + settings
|
||||
+ (orderSettings != null ? " " + orderSettings : "")
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> renameColumn(@NotNull String columnName, @NotNull String newName) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` RENAME COLUMN `" + columnName + "` TO `" + newName + "`"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` MODIFY COLUMN `" + columnName + "` " + settings
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> removeColumn(@NotNull String columnName) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` DROP `" + columnName + "`"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` ALTER `" + columnName + "` SET DEFAULT " + defaultValue
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> removeColumnDefault(@NotNull String columnName) {
|
||||
return createAction(
|
||||
"ALTER TABLE `" + getTableName() + "` ALTER `" + columnName + "` DROP DEFAULT"
|
||||
);
|
||||
}
|
||||
|
||||
private SQLUpdateActionImpl createAction(@NotNull String sql) {
|
||||
return new SQLUpdateActionImpl(getManager(), sql);
|
||||
}
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.SQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.builder.TableCreateBuilder;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class TableCreateBuilderImpl extends AbstractSQLBuilder implements TableCreateBuilder {
|
||||
|
||||
protected final @NotNull String tableName;
|
||||
|
||||
@NotNull List<String> columns = new ArrayList<>();
|
||||
@NotNull List<String> indexes = new ArrayList<>();
|
||||
@NotNull List<String> foreignKeys = new ArrayList<>();
|
||||
|
||||
@NotNull String tableSettings = defaultTablesSettings();
|
||||
@Nullable String tableComment;
|
||||
|
||||
public TableCreateBuilderImpl(SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getTableName() {
|
||||
return this.tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getTableSettings() {
|
||||
return this.tableSettings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLUpdateAction build() {
|
||||
StringBuilder createSQL = new StringBuilder();
|
||||
createSQL.append("CREATE TABLE IF NOT EXISTS `").append(tableName).append("`");
|
||||
createSQL.append("(");
|
||||
createSQL.append(String.join(", ", columns));
|
||||
if (indexes.size() > 0) {
|
||||
createSQL.append(", ");
|
||||
createSQL.append(String.join(", ", indexes));
|
||||
}
|
||||
if (foreignKeys.size() > 0) {
|
||||
createSQL.append(", ");
|
||||
createSQL.append(String.join(", ", foreignKeys));
|
||||
}
|
||||
createSQL.append(") ").append(getTableSettings());
|
||||
|
||||
if (tableComment != null) {
|
||||
createSQL.append(" COMMENT '").append(tableComment).append("'");
|
||||
}
|
||||
|
||||
return new SQLUpdateActionImpl(getManager(), createSQL.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder addColumn(@NotNull String column) {
|
||||
this.columns.add(column);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean asPrimaryKey, boolean unsigned) {
|
||||
return addColumn(columnName,
|
||||
(numberType == null ? NumberType.INT : numberType).name()
|
||||
+ (unsigned ? " UNSIGNED " : " ")
|
||||
+ "NOT NULL AUTO_INCREMENT " + (asPrimaryKey ? "PRIMARY KEY" : "UNIQUE KEY")
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setIndex(@NotNull IndexType type, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns) {
|
||||
this.indexes.add(buildIndexSettings(type, indexName, columnName, moreColumns));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn,
|
||||
@Nullable ForeignKeyRule updateRule, @Nullable ForeignKeyRule deleteRule) {
|
||||
StringBuilder keyBuilder = new StringBuilder();
|
||||
|
||||
keyBuilder.append("CONSTRAINT ");
|
||||
if (constraintName == null) {
|
||||
keyBuilder.append("`").append("fk_").append(tableColumn).append("_").append(foreignTable).append("`");
|
||||
} else {
|
||||
keyBuilder.append("`").append(constraintName).append("`");
|
||||
}
|
||||
keyBuilder.append(" ");
|
||||
keyBuilder.append("FOREIGN KEY (`").append(tableColumn).append("`) ");
|
||||
keyBuilder.append("REFERENCES `").append(foreignTable).append("`(`").append(foreignColumn).append("`)");
|
||||
|
||||
if (updateRule != null) keyBuilder.append(" ON UPDATE ").append(updateRule.getRuleName());
|
||||
if (deleteRule != null) keyBuilder.append(" ON DELETE ").append(deleteRule.getRuleName());
|
||||
|
||||
this.foreignKeys.add(keyBuilder.toString());
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setColumns(@NotNull String... columns) {
|
||||
this.columns = Arrays.asList(columns);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setTableSettings(@NotNull String settings) {
|
||||
this.tableSettings = settings;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setTableComment(@Nullable String comment) {
|
||||
this.tableComment = comment;
|
||||
return this;
|
||||
}
|
||||
|
||||
protected static String buildIndexSettings(@NotNull IndexType indexType, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns) {
|
||||
|
||||
StringBuilder indexBuilder = new StringBuilder();
|
||||
|
||||
indexBuilder.append(indexType.getName()).append(" ");
|
||||
if (indexName != null) {
|
||||
indexBuilder.append("`").append(indexName).append("`");
|
||||
}
|
||||
indexBuilder.append("(");
|
||||
indexBuilder.append("`").append(columnName).append("`");
|
||||
|
||||
if (moreColumns.length > 0) {
|
||||
indexBuilder.append(", ");
|
||||
|
||||
for (int i = 0; i < moreColumns.length; i++) {
|
||||
indexBuilder.append(moreColumns[i]);
|
||||
if (i != moreColumns.length - 1) indexBuilder.append(", ");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
indexBuilder.append(")");
|
||||
|
||||
return indexBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.query.PreparedQueryActionImpl;
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.api.builder.TableQueryBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class TableQueryBuilderImpl
|
||||
extends AbstractConditionalBuilder<TableQueryBuilder, PreparedQueryAction>
|
||||
implements TableQueryBuilder {
|
||||
|
||||
@NotNull String tableName;
|
||||
|
||||
String[] columns;
|
||||
|
||||
@Nullable String orderBy;
|
||||
|
||||
int[] pageLimit;
|
||||
|
||||
public TableQueryBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl build() {
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
sqlBuilder.append("SELECT").append(" ");
|
||||
if (columns == null || columns.length < 1) {
|
||||
sqlBuilder.append("*");
|
||||
} else {
|
||||
for (int i = 0; i < columns.length; i++) {
|
||||
String name = columns[i];
|
||||
sqlBuilder.append("`").append(name).append("`");
|
||||
if (i != columns.length - 1) {
|
||||
sqlBuilder.append(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlBuilder.append(" ").append("FROM").append(" ");
|
||||
sqlBuilder.append("`").append(tableName).append("`");
|
||||
|
||||
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
|
||||
|
||||
if (orderBy != null) sqlBuilder.append(" ").append(orderBy);
|
||||
|
||||
if (pageLimit != null && pageLimit.length == 2) {
|
||||
sqlBuilder.append(" LIMIT ").append(pageLimit[0]).append(",").append(pageLimit[1]);
|
||||
} else if (limit > 0) {
|
||||
sqlBuilder.append(" ").append(buildLimitSQL());
|
||||
}
|
||||
|
||||
|
||||
return new PreparedQueryActionImpl(getManager(), sqlBuilder.toString())
|
||||
.setParams(hasConditionParams() ? getConditionParams() : null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableQueryBuilderImpl selectColumns(@NotNull String... columnNames) {
|
||||
this.columns = columnNames;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableQueryBuilder orderBy(@NotNull String columnName, boolean asc) {
|
||||
this.orderBy = "ORDER BY `" + columnName + "` " + (asc ? "ASC" : "DESC");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableQueryBuilder setPageLimit(int start, int end) {
|
||||
this.pageLimit = new int[]{start, end};
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TableQueryBuilderImpl getThis() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.PreparedSQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.builder.UpdateBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class UpdateBuilderImpl
|
||||
extends AbstractConditionalBuilder<UpdateBuilder, SQLAction<Integer>>
|
||||
implements UpdateBuilder {
|
||||
|
||||
String tableName;
|
||||
|
||||
List<String> columnNames;
|
||||
List<Object> columnValues;
|
||||
|
||||
public UpdateBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateAction build() {
|
||||
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
|
||||
sqlBuilder.append("UPDATE `").append(getTableName()).append("` SET ");
|
||||
|
||||
Iterator<String> iterator = this.columnNames.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
sqlBuilder.append("`").append(iterator.next()).append("` = ?");
|
||||
if (iterator.hasNext()) sqlBuilder.append(" , ");
|
||||
}
|
||||
List<Object> allParams = new ArrayList<>(this.columnValues);
|
||||
|
||||
if (hasConditions()) {
|
||||
sqlBuilder.append(" ").append(buildConditionSQL());
|
||||
allParams.addAll(getConditionParams());
|
||||
}
|
||||
|
||||
if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL());
|
||||
|
||||
return new PreparedSQLUpdateActionImpl(getManager(), sqlBuilder.toString(), allParams);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateBuilder setColumnValues(LinkedHashMap<String, Object> columnData) {
|
||||
this.columnNames = new ArrayList<>();
|
||||
this.columnValues = new ArrayList<>();
|
||||
columnData.forEach((name, value) -> {
|
||||
this.columnNames.add(name);
|
||||
this.columnValues.add(value);
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateBuilder setColumnValues(String[] columnNames, Object[] columnValues) {
|
||||
if (columnNames.length != columnValues.length) {
|
||||
throw new RuntimeException("columnNames are not match with columnValues");
|
||||
}
|
||||
this.columnNames = Arrays.asList(columnNames);
|
||||
this.columnValues = Arrays.asList(columnValues);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected UpdateBuilder getThis() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
package cc.carm.lib.easysql.manager;
|
||||
|
||||
import cc.carm.lib.easysql.action.PreparedSQLBatchUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.action.PreparedSQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.action.SQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.action.SQLUpdateBatchActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.builder.*;
|
||||
import cc.carm.lib.easysql.builder.impl.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class SQLManagerImpl implements SQLManager {
|
||||
|
||||
private final Logger LOGGER;
|
||||
private final DataSource dataSource;
|
||||
protected ExecutorService executorPool;
|
||||
ConcurrentHashMap<UUID, SQLQuery> activeQuery = new ConcurrentHashMap<>();
|
||||
|
||||
@NotNull Supplier<Boolean> debugMode = () -> false;
|
||||
|
||||
public SQLManagerImpl(@NotNull DataSource dataSource) {
|
||||
this(dataSource, null);
|
||||
}
|
||||
|
||||
public SQLManagerImpl(@NotNull DataSource dataSource, @Nullable String name) {
|
||||
String managerName = "SQLManager" + (name != null ? "#" + name : "");
|
||||
this.LOGGER = Logger.getLogger(managerName);
|
||||
this.dataSource = dataSource;
|
||||
this.executorPool = Executors.newFixedThreadPool(3, r -> {
|
||||
Thread thread = new Thread(r, managerName);
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugMode() {
|
||||
return this.debugMode.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode) {
|
||||
this.debugMode = debugMode;
|
||||
}
|
||||
|
||||
public void debug(String msg) {
|
||||
if (isDebugMode()) getLogger().info("[DEBUG] " + msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Logger getLogger() {
|
||||
return LOGGER;
|
||||
}
|
||||
|
||||
public ExecutorService getExecutorPool() {
|
||||
return executorPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull DataSource getDataSource() {
|
||||
return this.dataSource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Connection getConnection() throws SQLException {
|
||||
return getDataSource().getConnection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Map<UUID, SQLQuery> getActiveQuery() {
|
||||
return this.activeQuery;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer executeSQL(String sql) {
|
||||
return new SQLUpdateActionImpl(this, sql).execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer executeSQL(String sql, Object[] params) {
|
||||
return new PreparedSQLUpdateActionImpl(this, sql, params).execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch) {
|
||||
return new PreparedSQLBatchUpdateActionImpl(this, sql)
|
||||
.setAllParams(paramsBatch)
|
||||
.execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL) {
|
||||
SQLUpdateBatchAction action = new SQLUpdateBatchActionImpl(this, sql);
|
||||
if (moreSQL != null && moreSQL.length > 0) {
|
||||
Arrays.stream(moreSQL).forEach(action::addBatch);
|
||||
}
|
||||
return action.execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch) {
|
||||
Iterator<String> iterator = sqlBatch.iterator();
|
||||
if (!iterator.hasNext()) return null; // PLEASE GIVE IT SOMETHING
|
||||
|
||||
SQLUpdateBatchAction action = new SQLUpdateBatchActionImpl(this, iterator.next());
|
||||
while (iterator.hasNext()) {
|
||||
action.addBatch(iterator.next());
|
||||
}
|
||||
|
||||
return action.execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder createTable(@NotNull String tableName) {
|
||||
return new TableCreateBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableAlterBuilder alterTable(@NotNull String tableName) {
|
||||
return new TableAlterBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public QueryBuilder createQuery() {
|
||||
return new QueryBuilderImpl(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName) {
|
||||
return new InsertBuilderImpl<PreparedSQLUpdateBatchAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLBatchUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName) {
|
||||
return new InsertBuilderImpl<PreparedSQLUpdateAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName) {
|
||||
return new ReplaceBuilderImpl<PreparedSQLUpdateBatchAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLBatchUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName) {
|
||||
return new ReplaceBuilderImpl<PreparedSQLUpdateAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateBuilder createUpdate(@NotNull String tableName) {
|
||||
return new UpdateBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteBuilder createDelete(@NotNull String tableName) {
|
||||
return new DeleteBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
package cc.carm.lib.easysql.query;
|
||||
|
||||
import cc.carm.lib.easysql.action.query.QueryActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class SQLQueryImpl implements SQLQuery {
|
||||
|
||||
protected final long executeTime;
|
||||
|
||||
protected SQLManagerImpl sqlManager;
|
||||
protected QueryActionImpl queryAction;
|
||||
|
||||
Connection connection;
|
||||
Statement statement;
|
||||
|
||||
ResultSet resultSet;
|
||||
|
||||
public SQLQueryImpl(
|
||||
SQLManagerImpl sqlManager, QueryActionImpl queryAction,
|
||||
Connection connection, Statement statement, ResultSet resultSet
|
||||
) {
|
||||
this(sqlManager, queryAction, connection, statement, resultSet, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public SQLQueryImpl(
|
||||
SQLManagerImpl sqlManager, QueryActionImpl queryAction,
|
||||
Connection connection, Statement statement, ResultSet resultSet,
|
||||
long executeTime
|
||||
) {
|
||||
this.executeTime = executeTime;
|
||||
this.sqlManager = sqlManager;
|
||||
this.queryAction = queryAction;
|
||||
this.connection = connection;
|
||||
this.statement = statement;
|
||||
this.resultSet = resultSet;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getExecuteTime() {
|
||||
return this.executeTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLManagerImpl getManager() {
|
||||
return this.sqlManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public QueryActionImpl getAction() {
|
||||
return this.queryAction;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultSet getResultSet() {
|
||||
return this.resultSet;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSQLContent() {
|
||||
return getAction().getSQLContent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
if (getResultSet() != null) getResultSet().close();
|
||||
if (getStatement() != null) getStatement().close();
|
||||
if (getConnection() != null) getConnection().close();
|
||||
|
||||
getManager().debug("#" + getAction().getShortID() +
|
||||
" -> finished after " + (System.currentTimeMillis() - getExecuteTime()) + " ms."
|
||||
);
|
||||
getManager().getActiveQuery().remove(getAction().getActionUUID());
|
||||
} catch (SQLException e) {
|
||||
getAction().handleException(getAction().defaultExceptionHandler(), e);
|
||||
}
|
||||
this.queryAction = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement getStatement() {
|
||||
return this.statement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection getConnection() {
|
||||
return this.connection;
|
||||
}
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
package cc.carm.lib.easysql.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.sql.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public class StatementUtil {
|
||||
|
||||
/**
|
||||
* 创建一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param params "?"所代表的对应参数列表
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatement(
|
||||
Connection connection, String sql, Object[] params
|
||||
) throws SQLException {
|
||||
return createPrepareStatement(connection, sql, params, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param params "?"所代表的对应参数列表
|
||||
* @param returnGeneratedKey 是否会返回自增主键
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatement(
|
||||
Connection connection, String sql, Object[] params, boolean returnGeneratedKey
|
||||
) throws SQLException {
|
||||
sql = sql.trim();
|
||||
PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
|
||||
Map<Integer, Integer> nullTypeMap = new HashMap<>();
|
||||
if (params != null) fillParams(statement, Arrays.asList(params), nullTypeMap);
|
||||
statement.addBatch();
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建批量操作的一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param paramsBatch "?"所代表的对应参数列表
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatementBatch(
|
||||
Connection connection, String sql, Iterable<Object[]> paramsBatch
|
||||
) throws SQLException {
|
||||
return createPrepareStatementBatch(connection, sql, paramsBatch, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建批量操作的一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param paramsBatch "?"所代表的对应参数列表
|
||||
* @param returnGeneratedKey 是否会返回自增主键
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatementBatch(
|
||||
Connection connection, String sql, Iterable<Object[]> paramsBatch, boolean returnGeneratedKey
|
||||
) throws SQLException {
|
||||
|
||||
sql = sql.trim();
|
||||
PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
|
||||
Map<Integer, Integer> nullTypeMap = new HashMap<>();
|
||||
for (Object[] params : paramsBatch) {
|
||||
fillParams(statement, Arrays.asList(params), nullTypeMap);
|
||||
statement.addBatch();
|
||||
}
|
||||
|
||||
return statement;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 填充PreparedStatement的参数。
|
||||
*
|
||||
* @param statement PreparedStatement
|
||||
* @param params SQL参数
|
||||
* @return {@link PreparedStatement} 填充参数后的PreparedStatement
|
||||
* @throws SQLException SQL执行异常
|
||||
*/
|
||||
public static PreparedStatement fillParams(
|
||||
PreparedStatement statement, Iterable<?> params
|
||||
) throws SQLException {
|
||||
return fillParams(statement, params, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 填充PreparedStatement的参数。
|
||||
*
|
||||
* @param statement PreparedStatement
|
||||
* @param params SQL参数
|
||||
* @param nullCache null参数的类型缓存,避免循环中重复获取类型
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement fillParams(
|
||||
PreparedStatement statement, Iterable<?> params, Map<Integer, Integer> nullCache
|
||||
) throws SQLException {
|
||||
if (null == params) {
|
||||
return statement;// 无参数
|
||||
}
|
||||
|
||||
int paramIndex = 1;//第一个参数从1计数
|
||||
for (Object param : params) {
|
||||
setParam(statement, paramIndex++, param, nullCache);
|
||||
}
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取null字段对应位置的数据类型
|
||||
* 如果类型获取失败将使用默认的 {@link Types#VARCHAR}
|
||||
*
|
||||
* @param statement {@link PreparedStatement}
|
||||
* @param paramIndex 参数序列,第一位从1开始
|
||||
* @return 数据类型,默认为 {@link Types#VARCHAR}
|
||||
*/
|
||||
public static int getNullType(PreparedStatement statement, int paramIndex) {
|
||||
try {
|
||||
ParameterMetaData pmd = statement.getParameterMetaData();
|
||||
return pmd.getParameterType(paramIndex);
|
||||
} catch (SQLException ignore) {
|
||||
return Types.VARCHAR;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为 {@link PreparedStatement} 设置单个参数
|
||||
*
|
||||
* @param preparedStatement {@link PreparedStatement}
|
||||
* @param paramIndex 参数序列,从1开始
|
||||
* @param param 参数,不能为{@code null}
|
||||
* @param nullCache 用于缓存参数为null位置的类型,避免重复获取
|
||||
*/
|
||||
private static void setParam(
|
||||
PreparedStatement preparedStatement, int paramIndex, Object param,
|
||||
Map<Integer, Integer> nullCache
|
||||
) throws SQLException {
|
||||
|
||||
if (param == null) {
|
||||
Integer type = (null == nullCache) ? null : nullCache.get(paramIndex);
|
||||
if (null == type) {
|
||||
type = getNullType(preparedStatement, paramIndex);
|
||||
if (null != nullCache) {
|
||||
nullCache.put(paramIndex, type);
|
||||
}
|
||||
}
|
||||
preparedStatement.setNull(paramIndex, type);
|
||||
}
|
||||
|
||||
// 针对UUID特殊处理,避免元数据直接传入
|
||||
if (param instanceof UUID) {
|
||||
preparedStatement.setString(paramIndex, param.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
// 针对StringBuilder或StringBuffer进行处理,避免元数据传入
|
||||
if (param instanceof StringBuilder || param instanceof StringBuffer) {
|
||||
preparedStatement.setString(paramIndex, param.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
// 日期特殊处理,默认按照时间戳传入,避免精度丢失
|
||||
if (param instanceof java.util.Date) {
|
||||
if (param instanceof Date) {
|
||||
preparedStatement.setDate(paramIndex, (Date) param);
|
||||
} else if (param instanceof Time) {
|
||||
preparedStatement.setTime(paramIndex, (Time) param);
|
||||
} else {
|
||||
preparedStatement.setTimestamp(paramIndex, new Timestamp(((java.util.Date) param).getTime()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 针对大数字类型的特殊处理
|
||||
if (param instanceof Number) {
|
||||
if (param instanceof BigDecimal) {
|
||||
// BigDecimal的转换交给JDBC驱动处理
|
||||
preparedStatement.setBigDecimal(paramIndex, (BigDecimal) param);
|
||||
return;
|
||||
} else if (param instanceof BigInteger) {
|
||||
preparedStatement.setBigDecimal(paramIndex, new BigDecimal((BigInteger) param));
|
||||
return;
|
||||
}
|
||||
// 其它数字类型按照默认类型传入
|
||||
}
|
||||
|
||||
// 其它参数类型直接传入
|
||||
preparedStatement.setObject(paramIndex, param);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,14 +5,14 @@
|
||||
<parent>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<version>0.3.3</version>
|
||||
<version>0.3.9</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
<maven.javadoc.skip>true</maven.javadoc.skip>
|
||||
@@ -64,6 +64,22 @@
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<!--项目地址 https://github.com/brettwooldridge/HikariCP/ -->
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>4.0.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>2.1.210</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -0,0 +1,133 @@
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import cc.carm.lib.easysql.api.util.TimeDateUtils;
|
||||
import cc.carm.lib.easysql.api.util.UUIDUtil;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
|
||||
@TestOnly
|
||||
@SuppressWarnings("all")
|
||||
public class EasySQLDemo {
|
||||
|
||||
public void createTable(SQLManager sqlManager) {
|
||||
// 同步创建表
|
||||
sqlManager.createTable("users")
|
||||
// .addColumn("id", "INT(11) AUTO_INCREMENT NOT NULL PRIMARY KEY")
|
||||
.addAutoIncrementColumn("id", NumberType.INT, true, true)
|
||||
.addColumn("uuid", "VARCHAR(32) NOT NULL UNIQUE KEY")
|
||||
.addColumn("username", "VARCHAR(16) NOT NULL")
|
||||
.addColumn("age", "TINYINT NOT NULL DEFAULT 1")
|
||||
.addColumn("email", "VARCHAR(32)")
|
||||
.addColumn("phone", "VARCHAR(16)")
|
||||
.addColumn("registerTime", "DATETIME NOT NULL")
|
||||
// .addColumn("INDEX `phone`") // 原始方法添加索引
|
||||
.setIndex("username", IndexType.UNIQUE_KEY) // 添加唯一索引
|
||||
.setIndex(IndexType.INDEX, "contact", "email", "phone") //添加联合索引 (示例)
|
||||
.build().execute(null /* 不处理错误 */);
|
||||
|
||||
sqlManager.createTable("user_ipaddr")
|
||||
.addAutoIncrementColumn("id", NumberType.INT, true, true)
|
||||
.addColumn("uuid", "VARCHAR(32) NOT NULL")
|
||||
.addColumn("ip", "VARCHAR(16)")
|
||||
.addColumn("time", "DATETIME NOT NULL")
|
||||
.addForeignKey("uuid", null,
|
||||
"users", "uuid",
|
||||
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
|
||||
)
|
||||
.build().execute(null /* 不处理错误 */);
|
||||
}
|
||||
|
||||
public void alertTable(SQLManager sqlManager) {
|
||||
// 同步更新表
|
||||
sqlManager.alterTable("users")
|
||||
.modifyColumn("age", "TINYINT NOT NULL DEFAULT 0")
|
||||
.execute(null /* 不处理错误 */);
|
||||
}
|
||||
|
||||
|
||||
public void sqlQuery(SQLManager sqlManager) {
|
||||
// 同步SQL查询
|
||||
try (SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("users") // 在users表中查询
|
||||
.selectColumns("id", "name") // 选中 id 与 name列
|
||||
.addCondition("age", ">", 18) // 限定 age 要大于5
|
||||
.addCondition("email", null) // 限定查询 email 字段为空
|
||||
.addNotNullCondition("phone") // 限定 phone 字段不为空
|
||||
.addTimeCondition("registerTime", // 时间字段
|
||||
System.currentTimeMillis() - 100000, //限制开始时间
|
||||
-1//不限制结束时间
|
||||
).build().execute()) {
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
//do something
|
||||
|
||||
} catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
UUID userUUID = sqlManager.createQuery()
|
||||
.inTable("users") // 在users表中查询
|
||||
.selectColumns("uuid")
|
||||
.addCondition("id", 5) // 限定 id 为 5
|
||||
.setLimit(1) // 只取出一个数据
|
||||
.build().execute(query -> {
|
||||
//可以直接进行数据处理
|
||||
ResultSet result = query.getResultSet();
|
||||
return result.next() ? UUIDUtil.toUUID(result.getString("uuid")) : null;
|
||||
}, (exception, action) -> {
|
||||
// 处理异常,不想处理直接填null
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
public void sqlQueryAsync(SQLManager sqlManager) {
|
||||
// 异步SQL查询
|
||||
sqlManager.createQuery()
|
||||
.inTable("users") // 在users表中查询
|
||||
.addCondition("id", 5) // 限定 id 为 5
|
||||
.setLimit(1) // 只取出一个数据
|
||||
.build().executeAsync(success -> {
|
||||
ResultSet resultSet = success.getResultSet();
|
||||
if (resultSet != null && resultSet.next()) {
|
||||
String username = resultSet.getString("username");
|
||||
}
|
||||
}, (exception, action) -> {
|
||||
//do something
|
||||
long createTIme = action.getCreateTime();
|
||||
String shortID = action.getShortID();
|
||||
String sqlContent = action.getSQLContent();
|
||||
});
|
||||
}
|
||||
|
||||
public void sqlInsert(SQLManager sqlManager) {
|
||||
// 同步SQL插入 (不使用try-catch的情况下,返回的数值可能为空。)
|
||||
Integer id = sqlManager.createInsert("users")
|
||||
.setColumnNames("username", "phone", "email", "registerTime")
|
||||
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
|
||||
.setReturnGeneratedKey(true)// 设定在后续返回自增主键
|
||||
.execute((exception, action) -> {
|
||||
// 处理异常
|
||||
System.out.println("#" + action.getShortID() + " -> " + action.getSQLContent());
|
||||
exception.printStackTrace();
|
||||
});
|
||||
|
||||
try {
|
||||
Integer userID = sqlManager.createInsert("users")
|
||||
.setColumnNames("username", "phone", "email", "registerTime")
|
||||
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
|
||||
.setReturnGeneratedKey(true)
|
||||
.execute();
|
||||
|
||||
System.out.println("新用户的ID为 " + userID);
|
||||
|
||||
} catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package cc.carm.lib.easysql;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.tests.*;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class EasySQLTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void onTest() {
|
||||
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setDriverClassName("org.h2.Driver");
|
||||
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=MYSQL;");
|
||||
|
||||
SQLManager sqlManager = new SQLManagerImpl(new HikariDataSource(config), "test");
|
||||
|
||||
print("加载测试类...");
|
||||
Set<TestHandler> tests = new LinkedHashSet<>();
|
||||
tests.add(new TableCreateTest());
|
||||
// tests.add(new TableAlterTest());
|
||||
// tests.add(new TableRenameTest());
|
||||
// tests.add(new QueryNotCloseTest());
|
||||
tests.add(new QueryCloseTest());
|
||||
tests.add(new SQLUpdateBatchTests());
|
||||
tests.add(new SQLUpdateReturnKeysTest());
|
||||
tests.add(new QueryFunctionTest());
|
||||
tests.add(new DeleteTest());
|
||||
|
||||
print("准备进行测试...");
|
||||
|
||||
int index = 1;
|
||||
int success = 0;
|
||||
|
||||
for (TestHandler currentTest : tests) {
|
||||
print("-------------------------------------------------");
|
||||
if (currentTest.executeTest(index, sqlManager)) {
|
||||
success++;
|
||||
}
|
||||
|
||||
index++;
|
||||
try {
|
||||
Thread.sleep(1000L);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
print(" ");
|
||||
print("全部测试执行完毕,成功 %s 个,失败 %s 个。",
|
||||
success, (tests.size() - success)
|
||||
);
|
||||
|
||||
if (sqlManager.getDataSource() instanceof HikariDataSource) {
|
||||
//Close bee connection pool
|
||||
((HikariDataSource) sqlManager.getDataSource()).close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static void print(@NotNull String format, Object... params) {
|
||||
System.out.printf((format) + "%n", params);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package cc.carm.lib.easysql;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public abstract class TestHandler {
|
||||
|
||||
protected static void print(@NotNull String format, Object... params) {
|
||||
EasySQLTest.print(format, params);
|
||||
}
|
||||
|
||||
@ApiStatus.OverrideOnly
|
||||
public abstract void onTest(SQLManager sqlManager) throws SQLException;
|
||||
|
||||
public boolean executeTest(int index, SQLManager sqlManager) {
|
||||
String testName = getClass().getSimpleName();
|
||||
|
||||
print(" #%s 测试 @%s 开始", index, testName);
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
onTest(sqlManager);
|
||||
print(" #%s 测试 @%s 成功,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
print(" #%s 测试 @%s 失败,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
exception.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class DeleteTest extends TestHandler {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
Integer changes = sqlManager.createDelete("test_user_table")
|
||||
.addCondition("id", ">", 5)
|
||||
.addNotNullCondition("username")
|
||||
.build().execute();
|
||||
|
||||
System.out.println("change(s): " + changes);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryCloseTest extends TestHandler {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
try (SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute()) {
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.printf(
|
||||
"id: %d username: %s%n",
|
||||
resultSet.getInt("id"),
|
||||
resultSet.getString("username")
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryFunctionTest extends TestHandler {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
Integer id_1 = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(1)
|
||||
.build().executeFunction(query -> {
|
||||
if (!query.getResultSet().next()) return -1;
|
||||
else return query.getResultSet().getInt("id");
|
||||
});
|
||||
|
||||
System.out.println("id (ps): " + id_1);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryNotCloseTest extends TestHandler {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute();
|
||||
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.printf("id: %d username: %s%n", resultSet.getInt("id"), resultSet.getString("username"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SQLUpdateBatchTests extends TestHandler {
|
||||
|
||||
|
||||
protected static List<Object[]> generateParams() {
|
||||
return IntStream.range(0, 5).mapToObj(i -> generateParam()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected static Object[] generateParam() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
return new Object[]{uuid, uuid.toString().substring(0, 5), (int) (Math.random() * 50)};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
List<Integer> updates = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.execute();
|
||||
|
||||
System.out.println("changes " + Arrays.toString(updates.toArray()));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLUpdateReturnKeysTest extends SQLUpdateBatchTests {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
List<Integer> generatedKeys = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.returnGeneratedKeys()
|
||||
.execute();
|
||||
|
||||
System.out.println("generated " + Arrays.toString(generatedKeys.toArray()));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableAlterTest extends TestHandler {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 修改 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test", "VARCHAR(16) NOT NULL")
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test2", "VARCHAR(16) NOT NULL", "username")
|
||||
.execute();
|
||||
|
||||
|
||||
print(" 修改 test_user_info");
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addAutoIncrementColumn("num", NumberType.BIGINT, false, true)
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addColumn("a", "VARCHAR(16) NOT NULL", "")
|
||||
.execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableCreateTest extends TestHandler {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 创建 test_user_table");
|
||||
sqlManager.createTable("test_user_table")
|
||||
.addAutoIncrementColumn("id")
|
||||
.addColumn("uuid", "VARCHAR(36) NOT NULL", "用户UUID")
|
||||
.addColumn("username", "VARCHAR(16) NOT NULL", "用户名")
|
||||
.addColumn("age", "TINYINT DEFAULT 0 NOT NULL", "年龄")
|
||||
|
||||
.setIndex("uuid", IndexType.UNIQUE_KEY)
|
||||
.build().execute();
|
||||
|
||||
print(" 创建 test_user_info");
|
||||
sqlManager.createTable("test_user_info")
|
||||
.addColumn("uid", "INT UNSIGNED NOT NULL")
|
||||
.addColumn("info", "TEXT", "相关信息")
|
||||
.addForeignKey("uid", "user",
|
||||
"test_user_table", "id",
|
||||
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
|
||||
)
|
||||
.build().execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableRenameTest extends TestHandler {
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
print(" 重命名 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.renameTo("test_user_table2")
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import cc.carm.lib.easysql.api.util.TimeDateUtils;
|
||||
import cc.carm.lib.easysql.api.util.UUIDUtil;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
|
||||
@TestOnly
|
||||
@SuppressWarnings("all")
|
||||
public class EasySQLDemo {
|
||||
|
||||
public void createTable(SQLManager sqlManager) {
|
||||
// 同步创建表
|
||||
sqlManager.createTable("users")
|
||||
// .addColumn("id", "INT(11) AUTO_INCREMENT NOT NULL PRIMARY KEY")
|
||||
.addAutoIncrementColumn("id", NumberType.INT, true, true)
|
||||
.addColumn("uuid", "VARCHAR(32) NOT NULL UNIQUE KEY")
|
||||
.addColumn("username", "VARCHAR(16) NOT NULL")
|
||||
.addColumn("age", "TINYINT NOT NULL DEFAULT 1")
|
||||
.addColumn("email", "VARCHAR(32)")
|
||||
.addColumn("phone", "VARCHAR(16)")
|
||||
.addColumn("registerTime", "DATETIME NOT NULL")
|
||||
// .addColumn("INDEX `phone`") // 原始方法添加索引
|
||||
.setIndex("username", IndexType.UNIQUE_KEY) // 添加唯一索引
|
||||
.setIndex(IndexType.INDEX, "contact", "email", "phone") //添加联合索引 (示例)
|
||||
.build().execute(null /* 不处理错误 */);
|
||||
|
||||
sqlManager.createTable("user_ipaddr")
|
||||
.addAutoIncrementColumn("id", NumberType.INT, true, true)
|
||||
.addColumn("uuid", "VARCHAR(32) NOT NULL")
|
||||
.addColumn("ip", "VARCHAR(16)")
|
||||
.addColumn("time", "DATETIME NOT NULL")
|
||||
.addForeignKey("uuid", null,
|
||||
"users", "uuid",
|
||||
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
|
||||
)
|
||||
.build().execute(null /* 不处理错误 */);
|
||||
}
|
||||
|
||||
public void alertTable(SQLManager sqlManager) {
|
||||
// 同步更新表
|
||||
sqlManager.alterTable("users")
|
||||
.modifyColumn("age", "TINYINT NOT NULL DEFAULT 0")
|
||||
.execute(null /* 不处理错误 */);
|
||||
}
|
||||
|
||||
|
||||
public void sqlQuery(SQLManager sqlManager) {
|
||||
// 同步SQL查询
|
||||
try (SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("users") // 在users表中查询
|
||||
.selectColumns("id", "name") // 选中 id 与 name列
|
||||
.addCondition("age", ">", 18) // 限定 age 要大于5
|
||||
.addCondition("email", null) // 限定查询 email 字段为空
|
||||
.addNotNullCondition("phone") // 限定 phone 字段不为空
|
||||
.addTimeCondition("registerTime", // 时间字段
|
||||
System.currentTimeMillis() - 100000, //限制开始时间
|
||||
-1//不限制结束时间
|
||||
).build().execute()) {
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
//do something
|
||||
|
||||
} catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
UUID userUUID = sqlManager.createQuery()
|
||||
.inTable("users") // 在users表中查询
|
||||
.selectColumns("uuid")
|
||||
.addCondition("id", 5) // 限定 id 为 5
|
||||
.setLimit(1) // 只取出一个数据
|
||||
.build().execute(query -> {
|
||||
//可以直接进行数据处理
|
||||
ResultSet result = query.getResultSet();
|
||||
return result.next() ? UUIDUtil.toUUID(result.getString("uuid")) : null;
|
||||
}, (exception, action) -> {
|
||||
// 处理异常,不想处理直接填null
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
public void sqlQueryAsync(SQLManager sqlManager) {
|
||||
// 异步SQL查询
|
||||
sqlManager.createQuery()
|
||||
.inTable("users") // 在users表中查询
|
||||
.addCondition("id", 5) // 限定 id 为 5
|
||||
.setLimit(1) // 只取出一个数据
|
||||
.build().executeAsync(success -> {
|
||||
ResultSet resultSet = success.getResultSet();
|
||||
if (resultSet != null && resultSet.next()) {
|
||||
String username = resultSet.getString("username");
|
||||
}
|
||||
}, (exception, action) -> {
|
||||
//do something
|
||||
long createTIme = action.getCreateTime();
|
||||
String shortID = action.getShortID();
|
||||
String sqlContent = action.getSQLContent();
|
||||
});
|
||||
}
|
||||
|
||||
public void sqlInsert(SQLManager sqlManager) {
|
||||
// 同步SQL插入 (不使用try-catch的情况下,返回的数值可能为空。)
|
||||
Integer id = sqlManager.createInsert("users")
|
||||
.setColumnNames("username", "phone", "email", "registerTime")
|
||||
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
|
||||
.setKeyIndex(1) // 设定自增主键的index,将会在后续返回自增主键
|
||||
.execute((exception, action) -> {
|
||||
// 处理异常
|
||||
System.out.println("#" + action.getShortID() + " -> " + action.getSQLContent());
|
||||
exception.printStackTrace();
|
||||
});
|
||||
|
||||
try {
|
||||
Integer userID = sqlManager.createInsert("users")
|
||||
.setColumnNames("username", "phone", "email", "registerTime")
|
||||
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
|
||||
.setKeyIndex(1) // 设定自增主键的index,将会在后续返回自增主键
|
||||
.execute();
|
||||
|
||||
System.out.println("新用户的ID为 " + userID);
|
||||
|
||||
} catch (SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<version>0.3.3</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
<maven.javadoc.skip>true</maven.javadoc.skip>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
</properties>
|
||||
|
||||
<artifactId>easysql-test</artifactId>
|
||||
|
||||
<name>EasySQL-Test</name>
|
||||
<description>EasySQL的测试代码</description>
|
||||
<url>https://github.com/CarmJos/EasySQL</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>${project.parent.groupId}</groupId>
|
||||
<artifactId>easysql-hikaricp</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>8.0.25</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.29</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
<excludes>
|
||||
<exclude>META-INF/MANIFEST.MF</exclude>
|
||||
</excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
<!-- when downloading via Maven we can pull depends individually -->
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<descriptorRefs>
|
||||
<descriptRef>jar-with-dependencies</descriptRef>
|
||||
</descriptorRefs>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>cc.carm.lib.easysql.testrunner.Main</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>assembly</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -1,36 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public abstract class EasySQLTest {
|
||||
|
||||
@ApiStatus.OverrideOnly
|
||||
public abstract void onTest(SQLManager sqlManager) throws SQLException;
|
||||
|
||||
public boolean executeTest(int index, SQLManager sqlManager) {
|
||||
String testName = getClass().getSimpleName();
|
||||
|
||||
print(" #%s 测试 @%s 开始", index, testName);
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
onTest(sqlManager);
|
||||
print(" #%s 测试 @%s 成功,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
print(" #%s 测试 @%s 失败,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
exception.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected static void print(@NotNull String format, Object... params) {
|
||||
Main.print(format, params);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner;
|
||||
|
||||
import cc.carm.lib.easysql.EasySQL;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.tests.QueryCloseTest;
|
||||
import cc.carm.lib.easysql.testrunner.tests.QueryFunctionTest;
|
||||
import cc.carm.lib.easysql.testrunner.tests.TableCreateTest;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Scanner;
|
||||
import java.util.Set;
|
||||
|
||||
@TestOnly
|
||||
@SuppressWarnings("all")
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length < 4) {
|
||||
print("请提供以下参数:<数据库驱动> <数据库地址(JDBC)> <数据库用户> <数据库密码> [是否采用DEBUG(y/n)]");
|
||||
return;
|
||||
}
|
||||
|
||||
SQLManager sqlManager;
|
||||
try {
|
||||
print("初始化 SQLManager...");
|
||||
print("数据库驱动 %s", args[0]);
|
||||
print("数据库地址 %s", args[1]);
|
||||
print("数据库用户 %s", args[2]);
|
||||
print("数据库密码 %s", args[3]);
|
||||
sqlManager = EasySQL.createManager(args[0], args[1], args[2], args[3]);
|
||||
sqlManager.setDebugMode(args.length > 4);
|
||||
print("SQLManager 初始化完成!");
|
||||
} catch (Exception exception) {
|
||||
print("SQLManager 初始化失败,请检查数据库配置。");
|
||||
exception.printStackTrace();
|
||||
return;
|
||||
}
|
||||
|
||||
print("加载测试类...");
|
||||
Set<EasySQLTest> tests = new LinkedHashSet<>();
|
||||
tests.add(new TableCreateTest());
|
||||
// tests.add(new TableAlterTest());
|
||||
// tests.add(new TableRenameTest());
|
||||
// tests.add(new QueryNotCloseTest());
|
||||
tests.add(new QueryCloseTest());
|
||||
// tests.add(new SQLUpdateBatchTests());
|
||||
// tests.add(new SQLUpdateReturnKeysTest());
|
||||
tests.add(new QueryFunctionTest());
|
||||
|
||||
print("准备进行测试...");
|
||||
|
||||
int index = 1;
|
||||
int success = 0;
|
||||
|
||||
Iterator<EasySQLTest> testIterator = tests.iterator();
|
||||
|
||||
print("准备完成,请按回车键开始执行测试。");
|
||||
|
||||
while (testIterator.hasNext()) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
if (scanner.nextLine() != null) {
|
||||
|
||||
EasySQLTest currentTest = testIterator.next();
|
||||
|
||||
if (currentTest.executeTest(index, sqlManager)) {
|
||||
success++;
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
print(" ");
|
||||
print("全部测试执行完毕,成功 %s 个,失败 %s 个。",
|
||||
success, (tests.size() - success)
|
||||
);
|
||||
|
||||
EasySQL.shutdownManager(sqlManager);
|
||||
|
||||
}
|
||||
|
||||
public static void print(@NotNull String format, Object... params) {
|
||||
System.out.printf((format) + "%n", params);
|
||||
}
|
||||
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryCloseTest extends EasySQLTest {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
try (SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute()) {
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.println("id: " + resultSet.getInt("id") + " username: " + resultSet.getString("username"));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryFunctionTest extends EasySQLTest {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
Integer id_1 = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(1)
|
||||
.build().executeFunction(query -> {
|
||||
if (!query.getResultSet().next()) return -1;
|
||||
else return query.getResultSet().getInt("id");
|
||||
});
|
||||
|
||||
System.out.println("id (ps): " + id_1);
|
||||
|
||||
Integer id_2 = sqlManager.createQuery().withSQL("SELECT id FROM test_user_table ORDER BY id DESC LIMIT 1")
|
||||
.executeFunction(query -> {
|
||||
if (!query.getResultSet().next()) return -1;
|
||||
else return query.getResultSet().getInt("id");
|
||||
});
|
||||
|
||||
System.out.println("id (s): " + id_2);
|
||||
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryNotCloseTest extends EasySQLTest {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute();
|
||||
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.println("id: " + resultSet.getInt("id") + " username: " + resultSet.getString("username"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SQLUpdateBatchTests extends EasySQLTest {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
List<Integer> updates = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.execute();
|
||||
|
||||
System.out.println("changes " + Arrays.toString(updates.toArray()));
|
||||
|
||||
}
|
||||
|
||||
protected List<Object[]> generateParams() {
|
||||
return IntStream.range(0, 5).mapToObj(i -> generateParam()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected Object[] generateParam() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
return new Object[]{uuid, uuid.toString().substring(0, 5), (int) (Math.random() * 50)};
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLUpdateReturnKeysTest extends SQLUpdateBatchTests {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
List<Integer> generatedKeys = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.returnGeneratedKeys()
|
||||
.execute();
|
||||
|
||||
System.out.println("generated " + Arrays.toString(generatedKeys.toArray()));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableAlterTest extends EasySQLTest {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 修改 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test", "VARCHAR(16) NOT NULL")
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test2", "VARCHAR(16) NOT NULL", "username")
|
||||
.execute();
|
||||
|
||||
|
||||
print(" 修改 test_user_info");
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addAutoIncrementColumn("num", NumberType.BIGINT, false, true)
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addColumn("a", "VARCHAR(16) NOT NULL", "")
|
||||
.execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableCreateTest extends EasySQLTest {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 创建 test_user_table");
|
||||
sqlManager.createTable("test_user_table")
|
||||
.addAutoIncrementColumn("id")
|
||||
.addColumn("uuid", "VARCHAR(36) NOT NULL", "用户UUID")
|
||||
.addColumn("username", "VARCHAR(16) NOT NULL", "用户名")
|
||||
.addColumn("age", "TINYINT DEFAULT 0 NOT NULL", "年龄")
|
||||
|
||||
.setIndex("uuid", IndexType.UNIQUE_KEY)
|
||||
.build().execute();
|
||||
|
||||
print(" 创建 test_user_info");
|
||||
sqlManager.createTable("test_user_info")
|
||||
.addColumn("uid", "INT UNSIGNED NOT NULL")
|
||||
.addColumn("info", "TEXT", "相关信息")
|
||||
.addForeignKey("uid", "user",
|
||||
"test_user_table", "id",
|
||||
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
|
||||
)
|
||||
.setIndex(IndexType.FULLTEXT_INDEX, "sign", "info")
|
||||
.build().execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableRenameTest extends EasySQLTest {
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
print(" 重命名 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.renameTo("test_user_table2")
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN" packages="cc.carm.lib.easysql">
|
||||
<Appenders>
|
||||
<console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n"/>
|
||||
</console>
|
||||
<RollingRandomAccessFile name="File" fileName="logs/latest.log" filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
|
||||
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n"/>
|
||||
<Policies>
|
||||
<TimeBasedTriggeringPolicy/>
|
||||
<OnStartupTriggeringPolicy/>
|
||||
</Policies>
|
||||
</RollingRandomAccessFile>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<root level="info">
|
||||
<filters>
|
||||
<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY" onMismatch="NEUTRAL"/>
|
||||
</filters>
|
||||
<!-- <AppenderRef ref="WINDOWS_COMPAT" level="info"/>-->
|
||||
<AppenderRef ref="File"/>
|
||||
<appender-ref ref="Console"/>
|
||||
</root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
<parent>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<version>0.3.3</version>
|
||||
<version>0.3.9</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
</properties>
|
||||
@@ -44,12 +44,12 @@
|
||||
|
||||
<issueManagement>
|
||||
<system>GitHub Issues</system>
|
||||
<url>${project.url}/issues</url>
|
||||
<url>https://github.com/CarmJos/EasySQL/issues</url>
|
||||
</issueManagement>
|
||||
|
||||
<ciManagement>
|
||||
<system>GitHub Actions</system>
|
||||
<url>${project.url}/actions/workflows/maven.yml</url>
|
||||
<url>https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml</url>
|
||||
</ciManagement>
|
||||
|
||||
<dependencies>
|
||||
@@ -0,0 +1,86 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class AbstractSQLAction<T> implements SQLAction<T> {
|
||||
|
||||
protected final @NotNull String sqlContent;
|
||||
private final @NotNull SQLManagerImpl sqlManager;
|
||||
private final @NotNull UUID uuid;
|
||||
private final long createTime;
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
this(manager, sql, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, @NotNull UUID uuid) {
|
||||
this(manager, sql, uuid, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, long createTime) {
|
||||
this(manager, sql, UUID.randomUUID(), createTime);
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@NotNull UUID uuid, long createTime) {
|
||||
Objects.requireNonNull(manager);
|
||||
Objects.requireNonNull(sql);
|
||||
Objects.requireNonNull(uuid);
|
||||
this.sqlManager = manager;
|
||||
this.sqlContent = sql;
|
||||
this.uuid = uuid;
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public @NotNull UUID getActionUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getShortID() {
|
||||
return getActionUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCreateTime() {
|
||||
return this.createTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getSQLContent() {
|
||||
return this.sqlContent.trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull SQLManagerImpl getManager() {
|
||||
return this.sqlManager;
|
||||
}
|
||||
|
||||
protected void outputDebugMessage() {
|
||||
getManager().debug("# " + getShortID() + " -> { " + getSQLContent() + " }");
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("FutureReturnValueIgnored")
|
||||
public void executeAsync(SQLHandler<T> success, SQLExceptionHandler failure) {
|
||||
getManager().getExecutorPool().submit(() -> {
|
||||
try {
|
||||
T returnedValue = execute();
|
||||
if (success != null) success.accept(returnedValue);
|
||||
} catch (SQLException e) {
|
||||
handleException(failure, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class PreparedSQLBatchUpdateActionImpl
|
||||
extends AbstractSQLAction<List<Integer>>
|
||||
implements PreparedSQLUpdateBatchAction {
|
||||
|
||||
boolean returnKeys = false;
|
||||
List<Object[]> allParams;
|
||||
|
||||
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
this.allParams = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams) {
|
||||
List<Object[]> paramsList = new ArrayList<>();
|
||||
allParams.forEach(paramsList::add);
|
||||
this.allParams = paramsList;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction addParamsBatch(Object... params) {
|
||||
this.allParams.add(params);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey) {
|
||||
this.returnKeys = returnGeneratedKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<Integer> execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
|
||||
connection, getSQLContent(), allParams, returnKeys
|
||||
)) {
|
||||
|
||||
outputDebugMessage();
|
||||
int[] executed = statement.executeBatch();
|
||||
|
||||
if (!returnKeys) return Arrays.stream(executed).boxed().collect(Collectors.toList());
|
||||
else {
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
List<Integer> generatedKeys = new ArrayList<>();
|
||||
while (resultSet.next()) {
|
||||
generatedKeys.add(resultSet.getInt(1));
|
||||
}
|
||||
return generatedKeys;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user