1
mirror of https://github.com/CarmJos/EasySQL.git synced 2026-06-05 09:01:26 +08:00

Compare commits

...

45 Commits

Author SHA1 Message Date
carm 20ac8f3908 [0.3.13] 版本修复
- `[R]` 修复上一版本中 SQLDebugHandler 的处理出现空指针异常。
2022-04-13 07:12:07 +08:00
carm c079c98e3e [0.3.12] 版本更新 (破坏性)
- `[R]` 采用 slf4j-api 替代Java原生的Logger库。
- `[A]` 新增 SQLDebugHandler 用于更好的处理调试消息。
2022-04-13 06:37:19 +08:00
carm 18dd618c21 [0.3.12] 版本更新 (破坏性)
- `[R]` 采用 slf4j-api 替代Java原生的Logger库。
- `[A]` 新增 SQLDebugHandler 用于更好的处理调试消息。
2022-04-13 06:30:20 +08:00
carm 03e157d3d9 [0.3.11] (破坏性更新) 令SQLUpdateAction返回的值为 Long 以适配自增主键大小范围。 2022-04-12 16:46:42 +08:00
carm a2d972621d [0.3.11] (破坏性更新) 令SQLUpdateAction返回的值为 Long 以适配自增主键大小范围。 2022-04-12 16:43:38 +08:00
carm 903f3a5f93 [0.3.11] (破坏性更新) 令SQLUpdateAction返回的值为 Long 以适配自增主键大小范围。 2022-04-12 16:14:35 +08:00
carm 44f9392e81 [0.3.11] (破坏性更新) 令SQLUpdateAction返回的值为 Long 以适配自增主键大小范围。 2022-04-12 16:09:51 +08:00
carm 1ad196f04b Merge remote-tracking branch 'origin/master' 2022-04-12 16:08:43 +08:00
carm fd0a4e48ef [0.3.11] (破坏性更新) 令SQLUpdateAction返回的值为 Long 以适配自增主键大小范围。 2022-04-12 16:08:29 +08:00
carm 14ee6ca1f2 Merge pull request #43 from CarmJos/dependabot/maven/com.h2database-h2-2.1.212
Bump h2 from 2.1.210 to 2.1.212
2022-04-12 03:42:33 +08:00
carm 6ba58b540f [0.3.10] 新增 SQLTable 用于快速创建与该表相关的操作。 2022-04-12 03:36:53 +08:00
dependabot[bot] db33e5e830 Bump h2 from 2.1.210 to 2.1.212
Bumps [h2](https://github.com/h2database/h2database) from 2.1.210 to 2.1.212.
- [Release notes](https://github.com/h2database/h2database/releases)
- [Commits](https://github.com/h2database/h2database/compare/version-2.1.210...version-2.1.212)

---
updated-dependencies:
- dependency-name: com.h2database:h2
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-04-11 09:50:42 +00:00
carm 3fbc58acf7 移除不必要的异常构造。 2022-04-09 03:26:53 +08:00
carm 0a6c8ae1a9 [0.3.9] 版本更新
- `[R]` 修改项目结构,移除无用的 `easysql-tester` 模块, 整合相关测试到 `easysql-demo` 的`src/test` 下。
- `[U]` 移除`DefaultSQLExceptionHandler` 类,与 `SQLExceptionHandler` 接口下添加 `detailed()` 与 `silent()` 两种预设错误处理器,并支持通过 `SQLManager#setExceptionHandler()` 方法应用全局生效的默认错误处理器。
> 注意: 十分不建议使用 `silent()` 处理器为默认处理器!
2022-04-09 01:22:23 +08:00
carm f00e741035 Merge pull request #42 from CarmJos/dependabot/maven/com.github.chris2018998-beecp-3.3.5
Bump beecp from 3.3.4 to 3.3.5
2022-04-04 19:49:57 +08:00
dependabot[bot] 50c2016820 Bump beecp from 3.3.4 to 3.3.5
Bumps [beecp](https://github.com/Chris2018998/BeeCP) from 3.3.4 to 3.3.5.
- [Release notes](https://github.com/Chris2018998/BeeCP/releases)
- [Commits](https://github.com/Chris2018998/BeeCP/commits/3.3.5)

---
updated-dependencies:
- dependency-name: com.github.chris2018998:beecp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-04-04 08:41:25 +00:00
carm 71b0bb98d8 Merge pull request #41 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-shade-plugin-3.3.0
Bump maven-shade-plugin from 3.2.4 to 3.3.0
2022-03-30 20:54:39 +08:00
dependabot[bot] ce3deb8f12 Bump maven-shade-plugin from 3.2.4 to 3.3.0
Bumps [maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.2.4 to 3.3.0.
- [Release notes](https://github.com/apache/maven-shade-plugin/releases)
- [Commits](https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.2.4...maven-shade-plugin-3.3.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-shade-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-30 08:38:35 +00:00
carm b5a40b0f52 Merge pull request #40 from CarmJos/dependabot/maven/com.github.chris2018998-beecp-3.3.4
Bump beecp from 3.3.3 to 3.3.4
2022-03-28 17:08:18 +08:00
dependabot[bot] ae5ca6cb23 Bump beecp from 3.3.3 to 3.3.4
Bumps [beecp](https://github.com/Chris2018998/BeeCP) from 3.3.3 to 3.3.4.
- [Release notes](https://github.com/Chris2018998/BeeCP/releases)
- [Commits](https://github.com/Chris2018998/BeeCP/commits)

---
updated-dependencies:
- dependency-name: com.github.chris2018998:beecp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-28 08:46:21 +00:00
carm 866115db99 修改构建触发配置 2022-03-25 00:44:54 +08:00
carm 332540710d 修改构建触发配置 2022-03-25 00:44:01 +08:00
carm ebe51dd9a3 改用Format形式 2022-03-25 00:41:36 +08:00
carm 0bdfe3d556 修改文件夹名与项目配置 2022-03-25 00:40:28 +08:00
carm e60c44aaae Merge pull request #39 from CarmJos/dependabot/maven/com.github.chris2018998-beecp-3.3.3
Bump beecp from 3.3.2 to 3.3.3
2022-03-25 00:30:04 +08:00
dependabot[bot] 28f76ae50a Bump beecp from 3.3.2 to 3.3.3
Bumps [beecp](https://github.com/Chris2018998/BeeCP) from 3.3.2 to 3.3.3.
- [Release notes](https://github.com/Chris2018998/BeeCP/releases)
- [Commits](https://github.com/Chris2018998/BeeCP/compare/3.3.2...3.3.3)

---
updated-dependencies:
- dependency-name: com.github.chris2018998:beecp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-24 08:30:30 +00:00
carm ffa0b74ccc Merge pull request #37 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-compiler-plugin-3.10.1
Bump maven-compiler-plugin from 3.10.0 to 3.10.1
2022-03-11 21:42:54 +08:00
dependabot[bot] 4b766d7794 Bump maven-compiler-plugin from 3.10.0 to 3.10.1
Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.10.0 to 3.10.1.
- [Release notes](https://github.com/apache/maven-compiler-plugin/releases)
- [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.10.0...maven-compiler-plugin-3.10.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-compiler-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-11 08:33:09 +00:00
carm f12fdc9c66 Merge pull request #35 from CarmJos/dependabot/maven/org.apache.logging.log4j-log4j-slf4j-impl-2.17.2
Bump log4j-slf4j-impl from 2.17.1 to 2.17.2
2022-02-28 19:38:08 +08:00
carm 6115e6bf21 Merge pull request #36 from CarmJos/dependabot/maven/org.apache.logging.log4j-log4j-api-2.17.2
Bump log4j-api from 2.17.1 to 2.17.2
2022-02-28 19:38:00 +08:00
carm 6356c0f723 Merge pull request #34 from CarmJos/dependabot/maven/org.apache.logging.log4j-log4j-core-2.17.2
Bump log4j-core from 2.17.1 to 2.17.2
2022-02-28 19:37:51 +08:00
dependabot[bot] 5e15c3b308 Bump log4j-api from 2.17.1 to 2.17.2
Bumps log4j-api from 2.17.1 to 2.17.2.

---
updated-dependencies:
- dependency-name: org.apache.logging.log4j:log4j-api
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-28 08:37:52 +00:00
dependabot[bot] 46b21ead05 Bump log4j-slf4j-impl from 2.17.1 to 2.17.2
Bumps log4j-slf4j-impl from 2.17.1 to 2.17.2.

---
updated-dependencies:
- dependency-name: org.apache.logging.log4j:log4j-slf4j-impl
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-28 08:36:38 +00:00
dependabot[bot] 8a9e4b8d1c Bump log4j-core from 2.17.1 to 2.17.2
Bumps log4j-core from 2.17.1 to 2.17.2.

---
updated-dependencies:
- dependency-name: org.apache.logging.log4j:log4j-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-28 08:35:08 +00:00
carm f21095d08a [0.3.8] 执行相关优化
- 优化部分调用,替换制表符为空格。
- 补充残缺的 Objects.requireNonNull();
- 对于SQLQuery的auto-close额外判断ResultSet、Statement与Connection是否已关闭,避免重复关闭报错。
2022-02-21 22:59:39 +08:00
carm 6fd5988e09 [0.3.8] 执行相关优化
- 优化部分调用,替换制表符为空格。
- 补充残缺的 Objects.requireNonNull();
- 对于SQLQuery的auto-close额外判断ResultSet、Statement与Connection是否已关闭,避免重复关闭报错。
2022-02-21 20:59:11 +08:00
carm 962da8f6a1 [0.3.8] 执行相关优化
- 优化部分调用,替换制表符为空格。
- 补充残缺的 Objects.requireNonNull();
- 对于SQLQuery的auto-close额外判断ResultSet、Statement与Connection是否已关闭,避免重复关闭报错。
2022-02-21 20:56:51 +08:00
carm 68b5d071ae [0.3.8] 执行相关优化
- 优化部分调用,替换制表符为空格。
- 补充残缺的 Objects.requireNonNull();
- 对于SQLQuery的auto-close额外判断ResultSet、Statement与Connection是否已关闭,避免重复关闭报错。
2022-02-21 20:38:32 +08:00
carm 2de21a4658 Merge pull request #33 from CarmJos/dependabot/maven/com.github.chris2018998-beecp-3.3.2
Bump beecp from 3.3.1 to 3.3.2
2022-02-21 19:29:08 +08:00
dependabot[bot] 3f26c9e12e Bump beecp from 3.3.1 to 3.3.2
Bumps [beecp](https://github.com/Chris2018998/BeeCP) from 3.3.1 to 3.3.2.
- [Release notes](https://github.com/Chris2018998/BeeCP/releases)
- [Commits](https://github.com/Chris2018998/BeeCP/compare/3.3.1...3.3.2)

---
updated-dependencies:
- dependency-name: com.github.chris2018998:beecp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-21 08:35:02 +00:00
carm 0640f625a1 [no ci]Merge pull request #32 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-javadoc-plugin-3.3.2
Bump maven-javadoc-plugin from 3.3.1 to 3.3.2
2022-02-14 16:42:26 +08:00
carm 7df8a67282 [no ci]Merge pull request #31 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-compiler-plugin-3.10.0
Bump maven-compiler-plugin from 3.9.0 to 3.10.0
2022-02-14 16:42:14 +08:00
dependabot[bot] 37becc7b29 Bump maven-javadoc-plugin from 3.3.1 to 3.3.2
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.3.1 to 3.3.2.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.3.1...maven-javadoc-plugin-3.3.2)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-14 08:41:30 +00:00
dependabot[bot] 5df61a70c3 Bump maven-compiler-plugin from 3.9.0 to 3.10.0
Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.9.0 to 3.10.0.
- [Release notes](https://github.com/apache/maven-compiler-plugin/releases)
- [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.9.0...maven-compiler-plugin-3.10.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-compiler-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-14 08:34:40 +00:00
carm 4ce5fba6f1 添加部分 Objects.requireNonNull() 2022-02-13 05:40:46 +08:00
117 changed files with 3680 additions and 3437 deletions
+1 -1
View File
@@ -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"
+1
View File
@@ -6,6 +6,7 @@ name: Project Build & Tests
on:
# 支持手动触发构建
workflow_dispatch:
pull_request:
push:
jobs:
+1 -2
View File
@@ -1,4 +1,3 @@
/.idea/
/target/
/*/target/
**/target/
**.iml
+11 -3
View File
@@ -5,13 +5,13 @@
<parent>
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId>
<version>0.3.7</version>
<version>0.3.13</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>
@@ -52,6 +52,14 @@
<url>https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml</url>
</ciManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@@ -0,0 +1,223 @@
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 org.slf4j.Logger;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* 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所要执行的源SQL语句列表。
*
* @return 源SQL语句列表
*/
default @NotNull List<String> getSQLContents() {
return Collections.singletonList(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);
}
}
@@ -0,0 +1,31 @@
package cc.carm.lib.easysql.api;
import org.jetbrains.annotations.NotNull;
/**
* SQLBuilder 是用于构建SQL语句以生成SQLAction执行操作的中间类。
* <br>其连接了{@link SQLManager} 与 {@link SQLAction} ,避免大量的代码堆积
* <br>也是本接口的核心功能所在
*
* @author CarmJos
*/
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}
*
* @return {@link SQLManager}
*/
@NotNull SQLManager getManager();
}
@@ -0,0 +1,226 @@
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.SQLDebugHandler;
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
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;
/**
* SQLManager 是EasySQL的核心类,用于管理数据库连接,提供数据库操作的方法。
*
* @author CarmJos
*/
public interface SQLManager {
Logger getLogger();
boolean isDebugMode();
/**
* 设定是否启用调试模式。
* 启用调试模式后,会在每次执行SQL语句时,调用 {@link #getDebugHandler()} 来输出调试信息。
*
* @param debugMode 是否启用调试模式
*/
void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode);
/**
* 设定是否启用调试模式。
* 启用调试模式后,会在每次执行SQL语句时,调用 {@link #getDebugHandler()} 来输出调试信息。
*
* @param enable 是否启用调试模式
*/
default void setDebugMode(boolean enable) {
setDebugMode(() -> enable);
}
/**
* 获取调试处理器,用于处理调试信息。
*
* @return {@link SQLDebugHandler}
*/
@NotNull SQLDebugHandler getDebugHandler();
/**
* 设定调试处理器,默认为 {@link SQLDebugHandler#defaultHandler(Logger)} 。
*
* @param debugHandler {@link SQLDebugHandler}
*/
void setDebugHandler(@NotNull SQLDebugHandler debugHandler);
/**
* 得到连接池源
*
* @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 Long executeSQL(String sql);
/**
* 执行一条不需要返回结果的预处理SQL更改(UPDATE、REPLACE、DELETE)
*
* @param sql SQL语句内容
* @param params SQL语句中 ? 的对应参数
* @return 更新的行数
* @see PreparedSQLUpdateAction
*/
@Nullable Long executeSQL(String sql, Object[] params);
/**
* 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
*
* @param sql SQL语句内容
* @param paramsBatch SQL语句中对应?的参数组
* @return 对应参数返回的行数
* @see PreparedSQLUpdateBatchAction
*/
@Nullable List<Long> 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,135 @@
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.builder.*;
import cc.carm.lib.easysql.api.function.SQLHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
/**
* SQLTable 基于 {@link TableCreateBuilder} 构建表,用于快速创建与该表相关的操作。
* <ul>
* <li>1. 调用 {@link SQLTable#of(String, String[])} 方法创建一个 SQLTable 对象;</li>
* <li>2. 在应用初始化阶段调用 {@link SQLTable#create(SQLManager)} 方法初始化 SQLTable 对象;</li>
* <li>3. 获取已创建的{@link SQLTable} 实例,直接调用对应方法进行关于表的相关操作。</li>
* </ul>
*
* @author CarmJos
* @since 0.3.10
*/
public abstract class SQLTable {
public static @NotNull SQLTable of(@NotNull String tableName, @Nullable SQLHandler<TableCreateBuilder> table) {
return new SQLTable(tableName) {
@Override
public boolean create(SQLManager sqlManager) throws SQLException {
if (this.manager == null) this.manager = sqlManager;
TableCreateBuilder tableBuilder = sqlManager.createTable(getTableName());
if (table != null) table.accept(tableBuilder);
return tableBuilder.build().executeFunction(l -> l > 0, false);
}
};
}
public static @NotNull SQLTable of(@NotNull String tableName, @NotNull String[] columns) {
return of(tableName, columns, null);
}
public static @NotNull SQLTable of(@NotNull String tableName,
@NotNull String[] columns, @Nullable String tableSettings) {
return of(tableName, builder -> {
builder.setColumns(columns);
if (tableSettings != null) builder.setTableSettings(tableSettings);
});
}
private final @NotNull String tableName;
protected SQLManager manager;
/**
* 请调用 {@link SQLTable} 下的静态方法进行对象的初始化。
*
* @param tableName 该表的名称
*/
private SQLTable(@NotNull String tableName) {
this.tableName = tableName;
}
public @NotNull String getTableName() {
return tableName;
}
/**
* 使用指定 SQLManager 进行本示例的初始化。
*
* @param sqlManager {@link SQLManager}
* @return 本表是否为首次创建
* @throws SQLException 出现任何错误时抛出
*/
public abstract boolean create(SQLManager sqlManager) throws SQLException;
public @NotNull TableQueryBuilder createQuery(@NotNull SQLManager sqlManager) {
return sqlManager.createQuery().inTable(getTableName());
}
public @NotNull TableQueryBuilder createQuery() {
return createQuery(this.manager);
}
public @NotNull DeleteBuilder createDelete() {
return createDelete(this.manager);
}
public @NotNull DeleteBuilder createDelete(@NotNull SQLManager sqlManager) {
return sqlManager.createDelete(getTableName());
}
public @NotNull UpdateBuilder createUpdate() {
return createUpdate(this.manager);
}
public @NotNull UpdateBuilder createUpdate(@NotNull SQLManager sqlManager) {
return sqlManager.createUpdate(getTableName());
}
public @NotNull InsertBuilder<PreparedSQLUpdateAction> createInsert() {
return createInsert(this.manager);
}
public @NotNull InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull SQLManager sqlManager) {
return sqlManager.createInsert(getTableName());
}
public @NotNull InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch() {
return createInsertBatch(this.manager);
}
public @NotNull InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull SQLManager sqlManager) {
return sqlManager.createInsertBatch(getTableName());
}
public @NotNull ReplaceBuilder<PreparedSQLUpdateAction> createReplace() {
return createReplace(this.manager);
}
public @NotNull ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull SQLManager sqlManager) {
return sqlManager.createReplace(getTableName());
}
public @NotNull ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch() {
return createReplaceBatch(this.manager);
}
public @NotNull ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull SQLManager sqlManager) {
return sqlManager.createReplaceBatch(getTableName());
}
}
@@ -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<Long>> {
/**
* 设定多组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);
}
@@ -2,7 +2,7 @@ package cc.carm.lib.easysql.api.action;
import cc.carm.lib.easysql.api.SQLAction;
public interface SQLUpdateAction extends SQLAction<Integer> {
public interface SQLUpdateAction extends SQLAction<Long> {
/**
* 设定自增主键的序列
@@ -0,0 +1,27 @@
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);
}
@Override
@NotNull List<String> getSQLContents();
}
@@ -32,16 +32,14 @@ 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;
}
}
}
@@ -2,8 +2,8 @@ package cc.carm.lib.easysql.api.builder;
import cc.carm.lib.easysql.api.SQLAction;
public interface DeleteBuilder extends ConditionalBuilder<DeleteBuilder, SQLAction<Integer>> {
public interface DeleteBuilder extends ConditionalBuilder<DeleteBuilder, SQLAction<Long>> {
String getTableName();
String getTableName();
}
@@ -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<Long> renameTo(@NotNull String newTableName);
SQLAction<Long> changeComment(@NotNull String newTableComment);
SQLAction<Long> setAutoIncrementIndex(int index);
SQLAction<Long> addIndex(@NotNull IndexType indexType, @Nullable String indexName,
@NotNull String columnName, @NotNull String... moreColumns);
/**
* 为该表移除一个索引
*
* @param indexName 索引名
* @return {@link SQLUpdateAction}
*/
SQLAction<Long> dropIndex(@NotNull String indexName);
/**
* 为该表移除一个外键
*
* @param keySymbol 外键名
* @return {@link SQLUpdateAction}
*/
SQLAction<Long> dropForeignKey(@NotNull String keySymbol);
/**
* 为该表移除主键(须添加新主键)
*
* @return {@link SQLUpdateAction}
*/
SQLAction<Long> dropPrimaryKey();
/**
* 为表添加一列
*
* @param columnName 列名
* @param settings 列的相关设定
* @return {@link SQLUpdateAction}
*/
default SQLAction<Long> addColumn(@NotNull String columnName, @NotNull String settings) {
return addColumn(columnName, settings, null);
}
/**
* 为表添加一列
*
* @param columnName 列名
* @param settings 列的相关设定
* @param afterColumn 该列增添到哪个列的后面,
* <p> 该参数若省缺则放于最后一行
* <p> 若为 "" 则置于首行。
* @return {@link SQLUpdateAction}
*/
SQLAction<Long> addColumn(@NotNull String columnName, @NotNull String settings, @Nullable String afterColumn);
SQLAction<Long> renameColumn(@NotNull String columnName, @NotNull String newName);
SQLAction<Long> modifyColumn(@NotNull String columnName, @NotNull String settings);
default SQLAction<Long> modifyColumn(@NotNull String columnName, @NotNull String columnSettings, @NotNull String afterColumn) {
return modifyColumn(columnName, columnSettings + " AFTER `" + afterColumn + "`");
}
SQLAction<Long> removeColumn(@NotNull String columnName);
SQLAction<Long> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue);
SQLAction<Long> 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<Long> 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<Long> addAutoIncrementColumn(@NotNull String columnName, @NotNull NumberType numberType) {
return addAutoIncrementColumn(columnName, numberType, false, true);
}
/**
* 为该表添加一个自增列
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
* <p> 注意:一个表只允许有一个自增列!
*
* @param columnName 列名
* @return {@link TableAlterBuilder}
*/
default SQLAction<Long> 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";
}
}
@@ -6,7 +6,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.LinkedHashMap;
public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, SQLAction<Integer>> {
public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, SQLAction<Long>> {
String getTableName();
@@ -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;
}
}
@@ -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,87 @@
package cc.carm.lib.easysql.api.function;
import cc.carm.lib.easysql.api.SQLAction;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.util.Arrays;
import java.util.List;
/**
* 异常处理器。
* <br> 在使用 {@link SQLAction#execute(SQLExceptionHandler)} 等相关方法时,
* 如果发生异常,则会调用错误处理器进行错误内容的输出提示。
*/
public interface SQLDebugHandler {
/**
* 该方法将在 {@link SQLAction#execute()} 执行前调用。
*
* @param action {@link SQLAction} 对象
* @param params 执行传入的参数列表。
* 实际上,仅有 {@link PreparedSQLUpdateAction} 和 {@link PreparedSQLUpdateBatchAction} 才会有传入参数。
*/
void beforeExecute(@NotNull SQLAction<?> action, @NotNull List<@Nullable Object[]> params);
/**
* 该方法将在 {@link SQLQuery#close()} 执行后调用。
*
* @param query {@link SQLQuery} 对象
* @param executeTime 该次查询开始执行的时间
* @param closeTime 该次查询彻底关闭的时间
*/
void afterQuery(@NotNull SQLQuery query, long executeTime, long closeTime);
@SuppressWarnings("DuplicatedCode")
static SQLDebugHandler defaultHandler(Logger logger) {
return new SQLDebugHandler() {
@Override
public void beforeExecute(@NotNull SQLAction<?> action, @NotNull List<@Nullable Object[]> params) {
logger.info("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
logger.info("┣# ActionUUID: {}", action.getActionUUID());
logger.info("┣# ActionType: {}", action.getClass().getName());
if (action.getSQLContents().size() == 1) {
logger.info("┣# SQLContent: {}", action.getSQLContents().get(0));
} else {
logger.info("┣# SQLContents: ");
int i = 0;
for (String sqlContent : action.getSQLContents()) {
logger.info("┃ [{}] {}", ++i, sqlContent);
}
}
if (params.size() == 1) {
Object[] param = params.get(0);
if (param != null) {
logger.info("┣# SQLParams({}): {}", param.length, Arrays.stream(param).map(Object::toString).reduce((a, b) -> a + ", " + b).orElse(""));
}
} else if (params.size() > 1) {
logger.info("┣# SQLParams: ");
int i = 0;
for (Object[] param : params) {
if (param != null) {
logger.info("┃ [{}] {}", ++i, Arrays.stream(param).map(Object::toString).reduce((a, b) -> a + ", " + b).orElse(""));
} else {
logger.info("┃ [{}] {}", ++i, "<#NULL>");
}
}
}
logger.info("┣# createTime: {}", action.getCreateTime());
logger.info("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
@Override
public void afterQuery(@NotNull SQLQuery query, long executeTime, long closeTime) {
logger.info("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
logger.info("┣# ActionUUID: {}", query.getAction().getActionUUID());
logger.info("┣# SQLContent: {}", query.getSQLContent());
logger.info("┣# executeCost: {} ms", (closeTime - executeTime));
logger.info("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
};
}
}
@@ -0,0 +1,46 @@
package cc.carm.lib.easysql.api.function;
import cc.carm.lib.easysql.api.SQLAction;
import org.slf4j.Logger;
import java.sql.SQLException;
import java.util.function.BiConsumer;
/**
* 异常处理器。
* <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) -> {
logger.error("Error occurred while executing SQL: ");
int i = 1;
for (String content : sqlAction.getSQLContents()) {
logger.error(String.format("#%d {%s}", i, content));
i++;
}
exception.printStackTrace();
};
}
/**
* “安静“ 的错误处理器,发生错误什么都不做。
* 强烈不建议把此处理器作为默认处理器使用!
*
* @return 无输出的处理器。
*/
static SQLExceptionHandler silent() {
return (exception, sqlAction) -> {
};
}
}
@@ -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);
};
}
}
@@ -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() {
}
@@ -0,0 +1,28 @@
package cc.carm.lib.easysql.api.util;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UUIDUtil {
private static final Pattern COMPILE = Pattern.compile("-", Pattern.LITERAL);
public static UUID random() {
return UUID.randomUUID();
}
public static String toString(UUID uuid, boolean withDash) {
if (withDash) return uuid.toString();
else return COMPILE.matcher(uuid.toString()).replaceAll(Matcher.quoteReplacement(""));
}
public static UUID toUUID(String s) {
if (s.length() == 36) {
return UUID.fromString(s);
} else {
return UUID.fromString(s.substring(0, 8) + '-' + s.substring(8, 12) + '-' + s.substring(12, 16) + '-' + s.substring(16, 20) + '-' + s.substring(20));
}
}
}
@@ -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,32 +0,0 @@
package cc.carm.lib.easysql.api;
import org.jetbrains.annotations.NotNull;
/**
* SQLBuilder 是用于构建SQL语句以生成SQLAction执行操作的中间类。
* <br>其连接了{@link SQLManager} 与 {@link SQLAction} ,避免大量的代码堆积
* <br>也是本接口的核心功能所在
*
* @author CarmJos
*/
public interface SQLBuilder {
/**
* 得到承载该Builder的对应{@link SQLManager}
*
* @return {@link SQLManager}
*/
@NotNull SQLManager getManager();
static @NotNull String withBackQuote(@NotNull String str) {
str = str.trim();
return str.startsWith("`") && str.endsWith("`") ? str : "`" + str + "`";
}
static @NotNull String withQuote(@NotNull String str) {
str = str.trim();
return str.startsWith("'") && str.endsWith("'") ? str : "'" + str + "'";
}
}
@@ -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();
}
@@ -1,56 +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);
}
/**
* 设定该操作是否返回自增键序列。
*
* @param returnGeneratedKey 是否返回自增键序列
* @return {@link PreparedSQLUpdateBatchAction}
*/
PreparedSQLUpdateBatchAction setReturnGeneratedKeys(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,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,253 +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;
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) {
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";
}
}
@@ -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);
};
}
}
@@ -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,15 +0,0 @@
package cc.carm.lib.easysql.api.util;
import java.util.UUID;
public class UUIDUtil {
public static UUID toUUID(String s) {
if (s.length() == 36) {
return UUID.fromString(s);
} else {
return UUID.fromString(s.substring(0, 8) + '-' + s.substring(8, 12) + '-' + s.substring(12, 16) + '-' + s.substring(16, 20) + '-' + s.substring(20));
}
}
}
@@ -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);
}
});
}
}
@@ -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;
}
}
}
}
}
}
@@ -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("]");
}
}
@@ -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);
}
}
}
@@ -1,147 +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;
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
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 columnName, @NotNull String operator, @Nullable Object queryValue
) {
addCondition(withBackQuote(columnName) + " " + operator + " ?");
this.conditionParams.add(queryValue);
return getThis();
}
@Override
public B addCondition(
@NotNull String[] columnNames, @Nullable Object[] queryValues
) {
if (queryValues == null || columnNames.length != queryValues.length) {
throw new RuntimeException("queryNames are not match with queryValues");
}
for (int i = 0; i < columnNames.length; i++) {
addCondition(columnNames[i], queryValues[i]);
}
return getThis();
}
@Override
public B addNotNullCondition(@NotNull String columnName) {
return addCondition(withBackQuote(columnName) + " IS NOT NULL");
}
@Override
public B addTimeCondition(
@NotNull String columnName, @Nullable Date startDate, @Nullable Date endDate
) {
if (startDate == null && endDate == null) return getThis(); // 都不限定时间,不用判断了
if (startDate != null) {
addCondition(withBackQuote(columnName) + " 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(columnName, "<=", 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(" AND ");
}
return conditionBuilder.toString().trim();
} 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,50 +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;
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
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(withBackQuote(getTableName()));
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,51 +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;
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
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(withBackQuote(tableName)).append("(");
Iterator<String> iterator = columnNames.iterator();
while (iterator.hasNext()) {
sqlBuilder.append(withBackQuote(iterator.next()));
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,51 +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;
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
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(withBackQuote(tableName)).append("(");
Iterator<String> iterator = columnNames.iterator();
while (iterator.hasNext()) {
sqlBuilder.append(withBackQuote(iterator.next()));
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,133 +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;
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
import static cc.carm.lib.easysql.api.SQLBuilder.withQuote;
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 " + withBackQuote(getTableName()) + " RENAME TO " + withBackQuote(newTableName) + ""
);
}
@Override
public SQLAction<Integer> changeComment(@NotNull String newTableComment) {
return new SQLUpdateActionImpl(getManager(),
"ALTER TABLE " + withBackQuote(getTableName()) + " COMMENT " + withQuote(newTableComment)
);
}
@Override
public SQLAction<Integer> setAutoIncrementIndex(int index) {
return new SQLUpdateActionImpl(getManager(),
"ALTER TABLE " + withBackQuote(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 " + withBackQuote(getTableName()) + " ADD "
+ TableCreateBuilderImpl.buildIndexSettings(indexType, indexName, columnName, moreColumns)
);
}
@Override
public SQLAction<Integer> dropIndex(@NotNull String indexName) {
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " DROP INDEX " + withBackQuote(indexName)
);
}
@Override
public SQLAction<Integer> dropForeignKey(@NotNull String keySymbol) {
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " DROP FOREIGN KEY " + withBackQuote(keySymbol)
);
}
@Override
public SQLAction<Integer> dropPrimaryKey() {
return createAction(
"ALTER TABLE " + withBackQuote(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 " + withBackQuote(afterColumn);
} else {
orderSettings = "FIRST";
}
}
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " ADD " + withBackQuote(columnName) + " " + settings
+ (orderSettings != null ? " " + orderSettings : "")
);
}
@Override
public SQLAction<Integer> renameColumn(@NotNull String columnName, @NotNull String newName) {
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " RENAME COLUMN " + withBackQuote(columnName) + " TO " + withBackQuote(newName)
);
}
@Override
public SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String settings) {
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " MODIFY COLUMN " + withBackQuote(columnName) + " " + settings
);
}
@Override
public SQLAction<Integer> removeColumn(@NotNull String columnName) {
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " DROP " + withBackQuote(columnName)
);
}
@Override
public SQLAction<Integer> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue) {
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " ALTER " + withBackQuote(columnName) + " SET DEFAULT " + defaultValue
);
}
@Override
public SQLAction<Integer> removeColumnDefault(@NotNull String columnName) {
return createAction(
"ALTER TABLE " + withBackQuote(getTableName()) + " ALTER " + withBackQuote(columnName) + " DROP DEFAULT"
);
}
private SQLUpdateActionImpl createAction(@NotNull String sql) {
return new SQLUpdateActionImpl(getManager(), sql);
}
}
@@ -1,161 +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;
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
import static cc.carm.lib.easysql.api.SQLBuilder.withQuote;
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(withBackQuote(tableName));
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(withQuote(tableComment));
}
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(withBackQuote("fk_" + tableColumn + "_" + foreignTable));
} else {
keyBuilder.append(withBackQuote(constraintName));
}
keyBuilder.append(" ");
keyBuilder.append("FOREIGN KEY (").append(withBackQuote(tableColumn)).append(") ");
keyBuilder.append("REFERENCES ").append(withBackQuote(foreignTable)).append("(").append(withBackQuote(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(withBackQuote(indexName));
}
indexBuilder.append("(");
indexBuilder.append(withBackQuote(columnName));
if (moreColumns.length > 0) {
indexBuilder.append(", ");
for (int i = 0; i < moreColumns.length; i++) {
indexBuilder.append(withBackQuote(moreColumns[i]));
if (i != moreColumns.length - 1) indexBuilder.append(", ");
}
}
indexBuilder.append(")");
return indexBuilder.toString();
}
}
@@ -1,89 +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;
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
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(withBackQuote(name));
if (i != columns.length - 1) {
sqlBuilder.append(",");
}
}
}
sqlBuilder.append(" ").append("FROM").append(" ").append(withBackQuote(tableName));
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 " + withBackQuote(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,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,210 +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;
}
// 其它数字类型按照默认类型传入
}
if (param instanceof Enum) {
//枚举类采用 name()
preparedStatement.setString(paramIndex, ((Enum<?>) param).name());
return;
}
// 其它参数类型直接传入
preparedStatement.setObject(paramIndex, param);
}
}
@@ -5,18 +5,20 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.7</version>
<version>0.3.13</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>
<maven.deploy.skip>true</maven.deploy.skip>
<log4j.version>2.17.2</log4j.version>
</properties>
<artifactId>easysql-demo</artifactId>
@@ -64,6 +66,43 @@
<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.212</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@@ -1,5 +1,6 @@
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.api.SQLTable;
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
import cc.carm.lib.easysql.api.enums.IndexType;
import cc.carm.lib.easysql.api.enums.NumberType;
@@ -43,6 +44,33 @@ public class EasySQLDemo {
.build().execute(null /* 不处理错误 */);
}
public void useSQLTable(SQLManager sqlManager) {
SQLTable tags = SQLTable.of("servers", table -> {
table.addAutoIncrementColumn("id", true);
table.addColumn("user", "INT UNSIGNED NOT NULL");
table.addColumn("content", "TEXT NOT NULL");
table.addColumn("time", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
table.addForeignKey(
"user", "fk_user_tags",
"users", "id",
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
);
});
try {
tags.create(sqlManager);
} catch (SQLException e) {
e.printStackTrace();
}
tags.createQuery().addCondition("id", 5).build()
.executeAsync(success -> {
System.out.println("success!");
});
}
public void alertTable(SQLManager sqlManager) {
// 同步更新表
sqlManager.alterTable("users")
@@ -106,7 +134,7 @@ public class EasySQLDemo {
public void sqlInsert(SQLManager sqlManager) {
// 同步SQL插入 不使用try-catch的情况下返回的数值可能为空
Integer id = sqlManager.createInsert("users")
Long id = sqlManager.createInsert("users")
.setColumnNames("username", "phone", "email", "registerTime")
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
.setReturnGeneratedKey(true)// 设定在后续返回自增主键
@@ -117,11 +145,10 @@ public class EasySQLDemo {
});
try {
Integer userID = sqlManager.createInsert("users")
Long userID = sqlManager.createInsert("users")
.setColumnNames("username", "phone", "email", "registerTime")
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
.setReturnGeneratedKey(true)
.execute();
.returnGeneratedKey().execute();
System.out.println("新用户的ID为 " + userID);
@@ -0,0 +1,76 @@
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");
sqlManager.setDebugMode(true);
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,21 @@
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 DeleteTest extends TestHandler {
@Override
public void onTest(SQLManager sqlManager) throws SQLException {
System.out.println("change(s): " + sqlManager.createDelete("test_user_table")
.addCondition("id", ">", 5)
.addNotNullCondition("username")
.build().execute());
}
}
@@ -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<Long> 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<Long> 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();
}
}
-135
View File
@@ -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.7</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-beecp</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.28</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</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.4</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,93 +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.DeleteTest;
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());
tests.add(new DeleteTest());
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);
}
}
@@ -1,22 +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 DeleteTest extends EasySQLTest {
@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);
}
}
@@ -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"));
}
}
}
}
@@ -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);
}
}
@@ -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"));
}
}
}
@@ -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)};
}
}
@@ -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()));
}
}
@@ -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();
}
}
@@ -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();
}
}
@@ -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>
+3 -3
View File
@@ -5,13 +5,13 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.7</version>
<version>0.3.13</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>
@@ -0,0 +1,89 @@
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.List;
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 debugMessage(List<Object[]> params) {
if (getManager().isDebugMode()) {
getManager().getDebugHandler().beforeExecute(this, params);
}
}
@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,76 @@
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<Long>>
implements PreparedSQLUpdateBatchAction {
boolean returnKeys = false;
@NotNull 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<Long> execute() throws SQLException {
debugMessage(allParams);
try (Connection connection = getManager().getConnection()) {
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
connection, getSQLContent(), allParams, returnKeys
)) {
int[] executed = statement.executeBatch();
if (!returnKeys) {
return Arrays.stream(executed).mapToLong(Long::valueOf).boxed().collect(Collectors.toList());
} else {
try (ResultSet resultSet = statement.getGeneratedKeys()) {
List<Long> generatedKeys = new ArrayList<>();
while (resultSet.next()) {
generatedKeys.add(resultSet.getLong(1));
}
return generatedKeys;
}
}
}
}
}
}
@@ -0,0 +1,78 @@
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.Collections;
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 Long execute() throws SQLException {
debugMessage(Collections.singletonList(params));
try (Connection connection = getManager().getConnection()) {
try (PreparedStatement statement = StatementUtil.createPrepareStatement(
connection, getSQLContent(), params, returnGeneratedKeys
)) {
int changes = statement.executeUpdate();
if (!returnGeneratedKeys) return (long) changes;
else {
try (ResultSet resultSet = statement.getGeneratedKeys()) {
return resultSet.next() ? resultSet.getLong(1) : -1;
}
}
}
}
}
}
@@ -0,0 +1,50 @@
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;
import java.util.ArrayList;
public class SQLUpdateActionImpl
extends AbstractSQLAction<Long>
implements SQLUpdateAction {
boolean returnGeneratedKeys = false;
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
super(manager, sql);
}
@Override
public @NotNull Long execute() throws SQLException {
debugMessage(new ArrayList<>());
try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) {
if (!returnGeneratedKeys) {
return (long) statement.executeUpdate(getSQLContent());
} else {
statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS);
try (ResultSet resultSet = statement.getGeneratedKeys()) {
return resultSet.next() ? resultSet.getLong(1) : -1;
}
}
}
}
}
@Override
public SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey) {
this.returnGeneratedKeys = returnGeneratedKey;
return this;
}
}
@@ -0,0 +1,59 @@
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.Objects;
import java.util.stream.Collectors;
public class SQLUpdateBatchActionImpl
extends AbstractSQLAction<List<Integer>>
implements SQLUpdateBatchAction {
protected final 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) {
Objects.requireNonNull(sql, "sql could not be null");
this.sqlContents.add(sql);
return this;
}
@Override
public @NotNull List<Integer> execute() throws SQLException {
debugMessage(new ArrayList<>());
try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) {
for (String content : this.sqlContents) {
statement.addBatch(content);
}
int[] executed = statement.executeBatch();
return Arrays.stream(executed).boxed().collect(Collectors.toList());
}
}
}
}
@@ -0,0 +1,86 @@
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.Collections;
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 {
debugMessage(Collections.singletonList(params));
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;
}
}
}
@@ -0,0 +1,64 @@
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;
import java.util.ArrayList;
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 {
debugMessage(new ArrayList<>());
Connection connection = getManager().getConnection();
Statement statement;
try {
statement = connection.createStatement();
} catch (SQLException ex) {
connection.close();
throw ex;
}
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);
}
}
}
@@ -4,11 +4,15 @@ import cc.carm.lib.easysql.api.SQLBuilder;
import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
public abstract class AbstractSQLBuilder implements SQLBuilder {
@NotNull SQLManagerImpl sqlManager;
@NotNull
final SQLManagerImpl sqlManager;
public AbstractSQLBuilder(@NotNull SQLManagerImpl manager) {
Objects.requireNonNull(manager, "SQLManager must not be null");
this.sqlManager = manager;
}

Some files were not shown because too many files have changed in this diff Show More