1
mirror of https://github.com/CarmJos/EasySQL.git synced 2026-06-14 03:15:55 +08:00

Compare commits

...

52 Commits

Author SHA1 Message Date
carm 2ea8f3cfa7 Merge remote-tracking branch 'origin/master' 2022-07-10 06:50:48 +08:00
carm 2061dc13bf fix(table): 修复 SQLTable#createReplace 方法递归调用异常 2022-07-10 06:50:33 +08:00
carm 760235fae8 chore(deps): bump log4j.version from 2.17.2 to 2.18.0
Merge pull request #52 from CarmJos/dependabot/maven/log4j.version-2.18.0
2022-07-04 17:44:13 +08:00
dependabot[bot] d3036ffe4d chore(deps): bump log4j.version from 2.17.2 to 2.18.0
Bumps `log4j.version` from 2.17.2 to 2.18.0.

Updates `log4j-api` from 2.17.2 to 2.18.0

Updates `log4j-core` from 2.17.2 to 2.18.0

Updates `log4j-slf4j-impl` from 2.17.2 to 2.18.0

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

Signed-off-by: dependabot[bot] <support@github.com>
2022-07-04 08:50:30 +00:00
carm 960989990b [ci skip] docs(usage): 修改用词。 2022-07-01 22:26:05 +08:00
carm b6026cb9f4 [ci skip] docs(usage): 修改用词。 2022-07-01 22:25:36 +08:00
carm 0d74b684e3 feat(table): 针对 SQLTable 进行重构与文档补充
[4.0.2] 针对 SQLTable 进行重构与文档补充
2022-07-01 22:22:38 +08:00
carm 07e47c2220 [ci skip] docs(usage): 添加文档 在小项目中推荐使用的数据库表实现方案 。 2022-07-01 22:19:26 +08:00
carm f795e6b421 [ci skip] docs(usage): 添加文档 在小项目中推荐使用的数据库表实现方案 。 2022-07-01 22:18:45 +08:00
carm c79d833d04 [ci skip] docs(usage): 添加文档 在小项目中推荐使用的数据库表实现方案 。 2022-07-01 22:18:35 +08:00
carm daa430cb14 [0.4.2] feat(table): 令 SQLTable 变为接口,额外添加 NamedSQLTable 抽象类用于简单实现 SQLTable。
BREAKING-CHANGE: SQLTable的类型已转变,以往的代码可能失效。
2022-07-01 22:14:37 +08:00
carm 248a6d6f34 fix(async): 尝试修复 #49 中提到的问题
fix(async): 尝试修复 #49 中提到的问题
2022-06-22 20:48:00 +08:00
carm 0495928e49 fix(async): 尝试修复 #49 中提到的问题 2022-06-22 20:42:08 +08:00
carm 421fe9f454 Merge pull request #48 from CarmJos/dependabot/maven/com.h2database-h2-2.1.214
Bump h2 from 2.1.212 to 2.1.214
2022-06-15 23:18:40 +08:00
dependabot[bot] f7745a2afe Bump h2 from 2.1.212 to 2.1.214
Bumps [h2](https://github.com/h2database/h2database) from 2.1.212 to 2.1.214.
- [Release notes](https://github.com/h2database/h2database/releases)
- [Commits](https://github.com/h2database/h2database/compare/version-2.1.212...version-2.1.214)

---
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-06-15 08:30:05 +00:00
carm 7d17324763 [0.4.0] 版本更新 2022-06-09 13:25:18 +08:00
carm 4be85f5481 feat(function): 添加 andThen 与 compose 方法
2022-06-09 13:24:23 +08:00
carm 298a5c4e81 feat(keys): 现在可以自定义返回的自增主键类型。
现在可以通过 returnGeneratedKey(Class<T> numberClass) 方法要求返回指定类型的自增主键。

BREAKING CHANGE: 移除了对于“是否返回主键”的选择,一旦定义了主键类型,就代表action将返回该类型的主键。
2022-06-09 12:12:11 +08:00
carm 9b4460f97a fix(debug): 修复debug消息中耗时计算异常的问题 2022-06-06 18:18:26 +08:00
carm f16b5f22e1 ci(deploy): 添加repo分支的相关介绍。 2022-06-03 03:24:01 +08:00
carm 1a4b5c245a ci(deploy): 修改部署配置 2022-06-03 03:17:37 +08:00
carm 91d9891532 ci(deploy): 修改部署配置 2022-06-03 03:04:22 +08:00
carm fdb7af541c chore: 修改项目结构与部署方式 2022-06-02 21:53:12 +08:00
carm b467743c2a docs(repo): 修改依赖库地址介绍 2022-06-02 21:51:43 +08:00
carm 3979c6d50c test(query): 添加SuppressWarnings标识 2022-06-02 21:42:34 +08:00
carm 9bac83f739 chore(project): 修改项目文件结构 2022-06-02 21:41:09 +08:00
carm 96ccc604ed ci(reploy): 添加 local-deploy 配置 2022-05-30 04:37:02 +08:00
carm 90db463f1d Merge remote-tracking branch 'origin/master' 2022-05-30 04:36:24 +08:00
carm 9248783a16 ci(reploy): 添加 local-deploy 配置 2022-05-30 04:36:10 +08:00
carm 75e8f02228 Merge pull request #47 from CarmJos/dependabot/maven/com.github.chris2018998-beecp-3.3.6
Bump beecp from 3.3.5 to 3.3.6
2022-05-02 21:13:11 +08:00
dependabot[bot] 02b8d561a8 Bump beecp from 3.3.5 to 3.3.6
Bumps [beecp](https://github.com/Chris2018998/BeeCP) from 3.3.5 to 3.3.6.
- [Release notes](https://github.com/Chris2018998/BeeCP/releases)
- [Commits](https://github.com/Chris2018998/BeeCP/compare/3.3.5...3.3.6)

---
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-05-02 08:31:36 +00:00
carm 19490d7508 Merge remote-tracking branch 'origin/master' 2022-04-27 02:09:07 +08:00
carm e8a01169d2 [0.3.16] 支持 IS NULL 判断(即设定queryValue为null)。 2022-04-27 02:08:58 +08:00
carm 2e1df7c7f6 Merge pull request #46 from CarmJos/dependabot/maven/org.apache.maven.plugins-maven-javadoc-plugin-3.4.0
Bump maven-javadoc-plugin from 3.3.2 to 3.4.0
2022-04-21 17:04:02 +08:00
dependabot[bot] 1812db3a16 Bump maven-javadoc-plugin from 3.3.2 to 3.4.0
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.3.2 to 3.4.0.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.3.2...maven-javadoc-plugin-3.4.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2022-04-21 08:31:13 +00:00
carm deb5de35a8 移除api与impl的shaded 2022-04-17 17:23:49 +08:00
carm e9ce0a769c [0.3.15] 版本修复
- `[F]` 修复上一版本中 SQLDebugHandler 的处理出现空指针异常。
2022-04-13 08:04:30 +08:00
carm e98e9586ef [0.3.14] 版本修复
- `[F]` 修复上一版本中 SQLDebugHandler 的处理出现空指针异常。
2022-04-13 07:52:06 +08:00
carm 6cd080210f [0.3.14] 版本修复
- `[F]` 修复上一版本中 SQLDebugHandler 的处理出现空指针异常。
2022-04-13 07:51:56 +08:00
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
62 changed files with 1315 additions and 344 deletions
+10 -1
View File
@@ -5,10 +5,19 @@
## 目录 ## 目录
- [Bob的EasySQL之旅(HikariCP)](USAGE-HIKARI.md) `@Ghost-Chu` ### 文章
- [Bob的EasySQL之旅(HikariCP)](USAGE-HIKARI.md) `by @Ghost-Chu`
- [在**小项目中**推荐使用的**数据库表**实现方案](USAGE-TABLE.md) `by @CarmJos`
### 视频
- [EasySql快速操作Mysql数据库:我的世界插件开发](https://www.bilibili.com/video/BV1w34y1p7Xs) `by @Shinyoki`
## 实例项目 ## 实例项目
以下是一些实例项目,可供各位参考。 以下是一些实例项目,可供各位参考。
- UltraDepository 超级仓库插件 `@CarmJos` - UltraDepository 超级仓库插件 `@CarmJos`
- [storage/MySQLStorage](https://github.com/CarmJos/UltraDepository/blob/master/src/main/java/cc/carm/plugin/ultradepository/storage/impl/MySQLStorage.java) - [storage/MySQLStorage](https://github.com/CarmJos/UltraDepository/blob/master/src/main/java/cc/carm/plugin/ultradepository/storage/impl/MySQLStorage.java)
- QuickShop-Hikari 快速商店插件 `@Ghost-Chu`
- [database/](https://github.com/Ghost-chu/QuickShop-Hikari/tree/hikari/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database)
+2 -2
View File
@@ -1,6 +1,6 @@
> 本文档由 GitHub 用户 @Ghost-chu 创建。 > 本文档由 GitHub 用户 @Ghost-chu 创建。
> 本文撰写于 2022/02/09,适配 EasySQL 版本 `v0.3.6`。 > 本文撰写于 2022/02/09,适配 EasySQL 版本 `v0.3.6` **(部分接口已变更)**
> 本文基于 `EasySQL-HikariPool` 版本编写。 > 本文基于 `EasySQL-Hikari` 版本编写。
# EasySQL - HikariPool 使用指南 # EasySQL - HikariPool 使用指南
+161
View File
@@ -0,0 +1,161 @@
> 本文档由 GitHub 用户 @CarmJos 创建。
> 本文撰写于 2022/07/01,基于 EasySQL 版本 `0.4.2` 。
# 在**小项目中**推荐使用的**数据库表**实现方案
## 简介
在小型项目中,我们常常需要编写数据库的表结构,并需要在开发中不断地参考、维护该结构。
在 EasySQL 中,我们提供了一个简单快捷的数据库表创建工具 `TableCreateBuilder`
基于该工具,又在后续版本中提供了 `SQLTable` 类用于快速针对指定表创建不同的数据库操作。
_SQLTable同时提供了有SQLManager参数与无参的操作方法,其中无参方法将自动调用初始化时使用的SQLManager进行操作。_
以下内容是我在许多项目中的使用方法,由于其 `便捷``易于管理``支持引用查询` ,我十分推荐您参考我的方案,并应用到自己的项目中。
### 实例项目:
- [QuickShop-Hikari (DataTables)](https://github.com/Ghost-chu/QuickShop-Hikari/blob/hikari/quickshop-bukkit/src/main/java/com/ghostchu/quickshop/database/DataTables.java)
## 利用 NamedSQLTable 快速创建枚举类以管理
这种方案的优势在于无需复制大量代码,仅需使用EasySQL已经提供的 `NamedSQLTable` 类快捷进行数据库操作。
首先,我们需要创建一个枚举类,[示例代码](../demo/src/main/java/DataTables1.java)如下所示:
```java
import cc.carm.lib.easysql.api.enums.IndexType;
import cc.carm.lib.easysql.api.enums.NumberType;
import cc.carm.lib.easysql.api.table.NamedSQLTable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
public enum DataTables {
DATA(SQLTable.of("data", (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");
})),
USER(SQLTable.of("user", (table) -> {
table.addAutoIncrementColumn("id", NumberType.INT, true, true);
table.addColumn("uuid", "VARCHAR(32) NOT NULL UNIQUE KEY");
table.addColumn("username", "VARCHAR(16) NOT NULL");
table.addColumn("age", "TINYINT NOT NULL DEFAULT 1");
table.addColumn("email", "VARCHAR(32)");
table.addColumn("phone", "VARCHAR(16)");
table.addColumn("registerTime", "DATETIME NOT NULL");
table.setIndex("username", IndexType.UNIQUE_KEY); // 添加唯一索引
table.setIndex(IndexType.INDEX, "contact", "email", "phone"); //添加联合索引 (示例)
}));
private final NamedSQLTable table;
DataTables(NamedSQLTable table) {
this.table = table;
}
public NamedSQLTable get() {
return this.table;
}
public static void initialize(@NotNull SQLManager manager, @Nullable String tablePrefix) {
for (DataTables value : values()) {
try {
value.get().create(manager, tablePrefix);
} catch (SQLException e) {
// 提示异常
}
}
}
}
```
随后,我们便可以在数据库初始化时调用 `DataTables#initialize(manager,tablePrefix)` 方法快捷的进行表的初始化。
初始化后,我们便可以通过 `DataTables#get()` 方法获取对应表的 `NamedSQLTable` 实例,以进行 `createQuery()` 等操作。
## 利用枚举类实现 SQLTable 进行操作
这种方法相较于前者代码量稍多些,但无需在每次调用先通过 `DataTables#get()` 方法获取 NamedSQLTable 实例,代码上更为简洁。
且可以通过重写 `getTableName()` 方法来自行规定表前缀。
_该方法为本人最常用,也是最推荐的方法。_
[示例代码](../demo/src/main/java/DataTables2.java)如下:
```java
import cc.carm.lib.easysql.api.builder.TableCreateBuilder;
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.sql.SQLException;
import java.util.function.Consumer;
public enum DataTables implements SQLTable {
USER((table) -> {
table.addAutoIncrementColumn("id", NumberType.INT, true, true);
table.addColumn("uuid", "VARCHAR(32) NOT NULL UNIQUE KEY");
table.addColumn("username", "VARCHAR(16) NOT NULL");
table.addColumn("age", "TINYINT NOT NULL DEFAULT 1");
table.addColumn("email", "VARCHAR(32)");
table.addColumn("phone", "VARCHAR(16)");
table.addColumn("registerTime", "DATETIME NOT NULL");
table.setIndex("username", IndexType.UNIQUE_KEY); // 添加唯一索引
table.setIndex(IndexType.INDEX, "contact", "email", "phone"); //添加联合索引 (示例)
});
private final Consumer<TableCreateBuilder> builder;
private @Nullable String tablePrefix;
private @Nullable SQLManager manager;
DataTables(Consumer<TableCreateBuilder> builder) {
this.builder = builder;
}
@Override
public @Nullable SQLManager getSQLManager() {
return this.manager;
}
@Override
public @NotNull String getTableName() {
// 这里直接选择用枚举的名称作为table的主名称
return (tablePrefix != null ? tablePrefix : "") + name().toLowerCase();
}
@Override
public boolean create(SQLManager sqlManager) throws SQLException {
return create(sqlManager, null);
}
public boolean create(@NotNull SQLManager sqlManager, @Nullable String tablePrefix) throws SQLException {
if (this.manager == null) this.manager = sqlManager;
this.tablePrefix = tablePrefix;
TableCreateBuilder tableBuilder = sqlManager.createTable(getTableName());
if (builder != null) builder.accept(tableBuilder);
return tableBuilder.build().executeFunction(l -> l > 0, false);
}
public static void initialize(@NotNull SQLManager manager, @Nullable String tablePrefix) {
for (DataTables value : values()) {
try {
value.create(manager, tablePrefix);
} catch (SQLException e) {
// 提示异常
}
}
}
}
```
+27
View File
@@ -0,0 +1,27 @@
# EasySQL Repository
采用github的repo分支进行依赖,随项目发布而自动更新。
其他依赖方式见主页介绍。
## 依赖方式
### Maven
```xml
<repositories>
<repository>
<id>EasySQL</id>
<name>GitHub Branch Repository</name>
<url>https://github.com/CarmJos/EasySQL/blob/repo/</url>
</repository>
</repositories>
```
### Gradle
```groovy
repositories {
maven { url 'https://github.com/CarmJos/EasySQL/blob/repo/' }
}
```
+81 -51
View File
@@ -11,10 +11,9 @@ on:
types: [ published ] types: [ published ]
jobs: jobs:
gh-deploy: packages-deploy:
name: "Publish Project (GitHub)" name: "Publish Project (GitHub Packages)"
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: "Set up JDK" - name: "Set up JDK"
@@ -29,63 +28,16 @@ jobs:
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
- name: "Maven Deploy With Javadoc" - name: "Packages Deploy"
run: mvn -B -Pgithub deploy --file pom.xml -DskipTests run: mvn -B -Pgithub deploy --file pom.xml -DskipTests
env: env:
MAVEN_USERNAME: ${{ github.repository_owner }} MAVEN_USERNAME: ${{ github.repository_owner }}
MAVEN_TOKEN: ${{secrets.GITHUB_TOKEN}} MAVEN_TOKEN: ${{secrets.GITHUB_TOKEN}}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
- name: "Copy Javadoc to Location"
run: |
rm -rf docs
mkdir -vp docs
cp -vrf api/target/apidocs/* docs/
cp -vrf .documentation/JAVADOC-README.md docs/README.md
- name: "Generate the Javadoc sitemap"
id: sitemap
uses: cicirello/generate-sitemap@v1
with:
base-url-path: https://carmjos.github.io/EasySQL
path-to-root: docs
- name: "Output stats"
run: |
echo "sitemap-path = ${{ steps.sitemap.outputs.sitemap-path }}"
echo "url-count = ${{ steps.sitemap.outputs.url-count }}"
echo "excluded-count = ${{ steps.sitemap.outputs.excluded-count }}"
- name: "Configure Git"
env:
DEPLOY_PRI: ${{secrets.DEPLOY_PRI}}
run: |
sudo timedatectl set-timezone "Asia/Shanghai"
mkdir -p ~/.ssh/
echo "$DEPLOY_PRI" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.name 'CarmJos'
git config --global user.email 'carm@carm.cc'
- name: "Commit documentations"
run: |
cd docs
git init
git remote add origin git@github.com:CarmJos/EasySQL.git
git checkout -b gh-pages
git add -A
git commit -m "API Document generated."
- name: "Push javadocs"
run: |
cd docs
git push origin HEAD:gh-pages --force
central-deploy: central-deploy:
name: "Deploy Project (Central Repository)" name: "Deploy Project (Central Repository)"
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: "Set up JDK" - name: "Set up JDK"
@@ -106,3 +58,81 @@ jobs:
MAVEN_USERNAME: ${{ secrets.OSSRH_USER }} MAVEN_USERNAME: ${{ secrets.OSSRH_USER }}
MAVEN_PASSWORD: ${{ secrets.OSSRH_PASS }} MAVEN_PASSWORD: ${{ secrets.OSSRH_PASS }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
github-deploy:
name: "Deploy Project (GitHub Repository)"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: "Set up JDK"
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'adopt'
cache: maven
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
- name: "Maven Deploy"
run: mvn -B -Plocal deploy --file pom.xml -DskipTests
env:
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
- name: "Copy artifacts"
run: |
rm -rf deploy
mkdir -vp deploy
cp -vrf $HOME/local-deploy/* deploy/
cp -vrf .documentation/repository/README.md deploy/README.md
- name: "Copy Javadoc"
run: |
rm -rf docs
mkdir -vp docs
cp -vrf api/target/apidocs/* docs/
cp -vrf .documentation/javadoc/README.md docs/README.md
- name: "Generate the Javadoc sitemap"
id: sitemap
uses: cicirello/generate-sitemap@v1
with:
base-url-path: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}
path-to-root: docs
- name: "Output stats"
run: |
echo "sitemap-path = ${{ steps.sitemap.outputs.sitemap-path }}"
echo "url-count = ${{ steps.sitemap.outputs.url-count }}"
echo "excluded-count = ${{ steps.sitemap.outputs.excluded-count }}"
- name: "Configure Git"
env:
DEPLOY_PRI: ${{secrets.DEPLOY_PRI}}
run: |
sudo timedatectl set-timezone "Asia/Shanghai"
mkdir -p ~/.ssh/
echo "$DEPLOY_PRI" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.name '${{ github.repository_owner }}'
git config --global user.email '${{ github.repository_owner }}@users.noreply.github.com'
- name: "Commit&Push repository files"
run: |
cd deploy
git init
git remote add origin git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git
git checkout -b repo
git add -A
git commit -m "Maven project deployment."
git push origin HEAD:repo --force
- name: "Commit&Push documentations"
run: |
cd docs
git init
git remote add origin git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git
git checkout -b gh-pages
git add -A
git commit -m "API documentation deployment."
git push origin HEAD:gh-pages --force
+15 -7
View File
@@ -10,7 +10,7 @@
# EasySQL # EasySQL
[![version](https://img.shields.io/github/v/release/CarmJos/EasySQL)](https://github.com/CarmJos/EasySQL/releases) [![version](https://img.shields.io/github/v/release/CarmJos/EasySQL)](https://github.com/CarmJos/EasySQL/releases)
[![License](https://img.shields.io/github/license/CarmJos/EasySQL)](https://opensource.org/licenses/GPL-3.0) [![License](https://img.shields.io/github/license/CarmJos/EasySQL)](https://opensource.org/licenses/MIT)
[![workflow](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml/badge.svg?branch=master)](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml) [![workflow](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml/badge.svg?branch=master)](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml)
[![CodeFactor](https://www.codefactor.io/repository/github/carmjos/easysql/badge)](https://www.codefactor.io/repository/github/carmjos/easysql) [![CodeFactor](https://www.codefactor.io/repository/github/carmjos/easysql/badge)](https://www.codefactor.io/repository/github/carmjos/easysql)
![CodeSize](https://img.shields.io/github/languages/code-size/CarmJos/EasySQL) ![CodeSize](https://img.shields.io/github/languages/code-size/CarmJos/EasySQL)
@@ -18,7 +18,7 @@
简单便捷的数据库操作工具,可自定义连接池来源。 简单便捷的数据库操作工具,可自定义连接池来源。
随项目分别提供 [BeeCP](https://github.com/Chris2018998/BeeCP) 与 [Hikari](https://github.com/brettwooldridge/HikariCP~~~~) 随项目分别提供 [BeeCP](https://github.com/Chris2018998/BeeCP) 与 [Hikari](https://github.com/brettwooldridge/HikariCP)
两个连接池的版本。 两个连接池的版本。
## 优势 ## 优势
@@ -35,7 +35,7 @@
### 示例代码 ### 示例代码
您可以 [点击这里](example/easysql-demo/src/main/java/EasySQLDemo.java) 查看部分代码演示,更多演示详见 [开发介绍](.documentation/README.md) 。 您可以 [点击这里](demo/src/main/java/EasySQLDemo.java) 查看部分代码演示,更多演示详见 [开发介绍](.documentation/README.md) 。
### 依赖方式 ### 依赖方式
@@ -57,7 +57,14 @@
</repository> </repository>
<repository> <repository>
<!--采用github依赖,实时更新,但需要配置 (推荐) --> <!--采用github的repo分支依赖,实时更新 (推荐)-->
<id>EasySQL</id>
<name>GitHub Branch Repository</name>
<url>https://github.com/CarmJos/EasySQL/blob/repo/</url>
</repository>
<repository>
<!--采用github packages依赖库,安全稳定,但需要配置 -->
<id>EasySQL</id> <id>EasySQL</id>
<name>GitHub Packages</name> <name>GitHub Packages</name>
<url>https://maven.pkg.github.com/CarmJos/EasySQL</url> <url>https://maven.pkg.github.com/CarmJos/EasySQL</url>
@@ -142,7 +149,10 @@ repositories {
// 采用Maven中心库,安全稳定,但版本更新需要等待同步 // 采用Maven中心库,安全稳定,但版本更新需要等待同步
mavenCentral() mavenCentral()
// 采用github依赖,实时更新,但需要配置 (推荐) // 采用github的repo分支依赖,实时更新 (推荐)
maven { url 'https://github.com/CarmJos/EasySQL/blob/repo/' }
// 采用github依赖库,安全稳定,但需要配置
maven { url 'https://maven.pkg.github.com/CarmJos/EasySQL' } maven { url 'https://maven.pkg.github.com/CarmJos/EasySQL' }
// 采用我的私人依赖库,简单方便,但可能因为变故而无法使用 // 采用我的私人依赖库,简单方便,但可能因为变故而无法使用
@@ -194,8 +204,6 @@ dependencies {
感谢您对开源项目的支持! 感谢您对开源项目的支持!
<img height=25% width=25% src="https://raw.githubusercontent.com/CarmJos/CarmJos/main/img/donate-code.jpg" alt=""/>
## 开源协议 ## 开源协议
本项目源码采用 [The MIT License](https://opensource.org/licenses/MIT) 开源协议。 本项目源码采用 [The MIT License](https://opensource.org/licenses/MIT) 开源协议。
+11 -7
View File
@@ -5,13 +5,13 @@
<parent> <parent>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<version>0.3.9</version> <version>0.4.3</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
@@ -52,6 +52,14 @@
<url>https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml</url> <url>https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml</url>
</ciManagement> </ciManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@@ -70,10 +78,6 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins> </plugins>
</build> </build>
@@ -6,10 +6,13 @@ import cc.carm.lib.easysql.api.function.SQLHandler;
import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Logger; import java.util.concurrent.TimeUnit;
/** /**
* SQLAction 是用于承载SQL语句并进行处理、返回的基本类。 * SQLAction 是用于承载SQL语句并进行处理、返回的基本类。
@@ -47,11 +50,23 @@ public interface SQLAction<T> {
@NotNull String getShortID(); @NotNull String getShortID();
/** /**
* 得到该Action的创建时间 * 得到该Action的创建时间
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
* *
* @return 创建时间 (毫秒)
*/
default long getCreateTime() {
return getCreateTime(TimeUnit.MILLISECONDS);
}
/**
* 得到该Action的创建时间
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
*
* @param unit 时间单位
* @return 创建时间 * @return 创建时间
*/ */
long getCreateTime(); long getCreateTime(TimeUnit unit);
/** /**
* 得到该Action所要执行的源SQL语句 * 得到该Action所要执行的源SQL语句
@@ -60,6 +75,15 @@ public interface SQLAction<T> {
*/ */
@NotNull String getSQLContent(); @NotNull String getSQLContent();
/**
* 得到该Action所要执行的源SQL语句列表。
*
* @return 源SQL语句列表
*/
default @NotNull List<String> getSQLContents() {
return Collections.singletonList(getSQLContent());
}
/** /**
* 得到承载该Action的对应{@link SQLManager} * 得到承载该Action的对应{@link SQLManager}
* *
@@ -5,9 +5,11 @@ import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.SQLUpdateAction; import cc.carm.lib.easysql.api.action.SQLUpdateAction;
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction; import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
import cc.carm.lib.easysql.api.builder.*; import cc.carm.lib.easysql.api.builder.*;
import cc.carm.lib.easysql.api.function.SQLDebugHandler;
import cc.carm.lib.easysql.api.function.SQLExceptionHandler; import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.Connection; import java.sql.Connection;
@@ -15,8 +17,9 @@ import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.logging.Logger;
/** /**
* SQLManager 是EasySQL的核心类,用于管理数据库连接,提供数据库操作的方法。 * SQLManager 是EasySQL的核心类,用于管理数据库连接,提供数据库操作的方法。
@@ -29,12 +32,55 @@ public interface SQLManager {
boolean isDebugMode(); boolean isDebugMode();
/**
* 获取用于执行 {@link SQLAction#executeAsync()} 的线程池。
* <br> 默认线程池为 {@link ThreadPoolExecutor} ,大小为 3。
*
* @return {@link ExecutorService}
*/
@NotNull ExecutorService getExecutorPool();
/**
* 设定用于执行 {@link SQLAction#executeAsync()} 的线程池。
*
* @param executorPool {@link ExecutorService}
*/
void setExecutorPool(@NotNull ExecutorService executorPool);
/**
* 设定是否启用调试模式。
* 启用调试模式后,会在每次执行SQL语句时,调用 {@link #getDebugHandler()} 来输出调试信息。
*
* @param debugMode 是否启用调试模式
*/
void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode); void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode);
/**
* 设定是否启用调试模式。
* 启用调试模式后,会在每次执行SQL语句时,调用 {@link #getDebugHandler()} 来输出调试信息。
*
* @param enable 是否启用调试模式
*/
default void setDebugMode(boolean enable) { default void setDebugMode(boolean enable) {
setDebugMode(() -> enable); setDebugMode(() -> enable);
} }
/**
* 获取调试处理器,用于处理调试信息。
*
* @return {@link SQLDebugHandler}
*/
@NotNull SQLDebugHandler getDebugHandler();
/**
* 设定调试处理器,默认为 {@link SQLDebugHandler#defaultHandler(Logger)} 。
*
* @param debugHandler {@link SQLDebugHandler}
*/
void setDebugHandler(@NotNull SQLDebugHandler debugHandler);
/** /**
* 得到连接池源 * 得到连接池源
* *
@@ -154,7 +200,7 @@ public interface SQLManager {
* @param tableName 目标表名 * @param tableName 目标表名
* @return {@link InsertBuilder} * @return {@link InsertBuilder}
*/ */
InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName); InsertBuilder<PreparedSQLUpdateAction<Integer>> createInsert(@NotNull String tableName);
/** /**
* 创建支持多组数据的插入操作 * 创建支持多组数据的插入操作
@@ -162,7 +208,7 @@ public interface SQLManager {
* @param tableName 目标表名 * @param tableName 目标表名
* @return {@link InsertBuilder} * @return {@link InsertBuilder}
*/ */
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName); InsertBuilder<PreparedSQLUpdateBatchAction<Integer>> createInsertBatch(@NotNull String tableName);
/** /**
* 创建一条替换操作 * 创建一条替换操作
@@ -170,7 +216,7 @@ public interface SQLManager {
* @param tableName 目标表名 * @param tableName 目标表名
* @return {@link ReplaceBuilder} * @return {@link ReplaceBuilder}
*/ */
ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName); ReplaceBuilder<PreparedSQLUpdateAction<Integer>> createReplace(@NotNull String tableName);
/** /**
* 创建支持多组数据的替换操作 * 创建支持多组数据的替换操作
@@ -178,7 +224,7 @@ public interface SQLManager {
* @param tableName 目标表名 * @param tableName 目标表名
* @return {@link ReplaceBuilder} * @return {@link ReplaceBuilder}
*/ */
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName); ReplaceBuilder<PreparedSQLUpdateBatchAction<Integer>> createReplaceBatch(@NotNull String tableName);
/** /**
* 创建更新操作 * 创建更新操作
@@ -6,6 +6,7 @@ import cc.carm.lib.easysql.api.action.query.QueryAction;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.Statement; import java.sql.Statement;
import java.util.concurrent.TimeUnit;
/** /**
* SQLQuery 是一个查询中间接口,用于查询操作的封装。 * SQLQuery 是一个查询中间接口,用于查询操作的封装。
@@ -16,10 +17,22 @@ public interface SQLQuery extends AutoCloseable {
/** /**
* 获取该查询创建的时间 * 获取该查询创建的时间
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
* *
* @return 创建时间 * @return 创建时间
*/ */
long getExecuteTime(); default long getExecuteTime() {
return getExecuteTime(TimeUnit.MILLISECONDS);
}
/**
* 获取该查询创建的时间
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
*
* @param timeUnit 时间单位
* @return 创建时间
*/
long getExecuteTime(TimeUnit timeUnit);
/** /**
* 得到承载该SQLQuery的对应{@link SQLManager} * 得到承载该SQLQuery的对应{@link SQLManager}
@@ -0,0 +1,149 @@
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 cc.carm.lib.easysql.api.table.NamedSQLTable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
import java.util.Optional;
/**
* SQLTable 基于 {@link TableCreateBuilder} 构建表,用于快速创建与该表相关的操作。
* <ul>
* <li>1. 调用 {@link NamedSQLTable#of(String, String[])} 方法创建一个 SQLTable 对象;</li>
* <li>2. 在应用初始化阶段调用 {@link NamedSQLTable#create(SQLManager)} 方法初始化 SQLTable 对象;</li>
* <li>3. 获取已创建的{@link NamedSQLTable} 实例,直接调用对应方法进行关于表的相关操作。</li>
* </ul>
*
* @author CarmJos
* @since 0.3.10
*/
public interface SQLTable {
static @NotNull NamedSQLTable of(@NotNull String tableName, @Nullable SQLHandler<TableCreateBuilder> table) {
return new NamedSQLTable(tableName) {
@Override
public boolean create(@NotNull SQLManager sqlManager, String tablePrefix) throws SQLException {
if (this.manager == null) this.manager = sqlManager;
this.tablePrefix = tablePrefix;
TableCreateBuilder tableBuilder = sqlManager.createTable(getTableName());
if (table != null) table.accept(tableBuilder);
return tableBuilder.build().executeFunction(l -> l > 0, false);
}
};
}
static @NotNull NamedSQLTable of(@NotNull String tableName, @NotNull String[] columns) {
return of(tableName, columns, null);
}
static @NotNull NamedSQLTable of(@NotNull String tableName,
@NotNull String[] columns, @Nullable String tableSettings) {
return of(tableName, builder -> {
builder.setColumns(columns);
if (tableSettings != null) builder.setTableSettings(tableSettings);
});
}
/**
* 以指定的 {@link SQLManager} 实例初始化并创建该表
*
* @param sqlManager {@link SQLManager} 实例
* @return 是否新创建了本表 (若已创建或创建失败则返回false)
* @throws SQLException 当数据库返回异常时抛出
*/
boolean create(SQLManager sqlManager) throws SQLException;
/**
* 得到 {@link #create(SQLManager)} 用于初始化本实例的 {@link SQLManager} 实例
*
* @return {@link SQLManager} 实例
*/
@Nullable SQLManager getSQLManager();
/**
* 得到本表表名,不得为空。
*
* @return 本表表名
*/
@NotNull String getTableName();
default @NotNull TableQueryBuilder createQuery() {
return Optional.ofNullable(getSQLManager()).map(this::createQuery)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull TableQueryBuilder createQuery(@NotNull SQLManager sqlManager) {
return sqlManager.createQuery().inTable(getTableName());
}
default @NotNull DeleteBuilder createDelete() {
return Optional.ofNullable(getSQLManager()).map(this::createDelete)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull DeleteBuilder createDelete(@NotNull SQLManager sqlManager) {
return sqlManager.createDelete(getTableName());
}
default @NotNull UpdateBuilder createUpdate() {
return Optional.ofNullable(getSQLManager()).map(this::createUpdate)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull UpdateBuilder createUpdate(@NotNull SQLManager sqlManager) {
return sqlManager.createUpdate(getTableName());
}
default @NotNull InsertBuilder<PreparedSQLUpdateAction<Integer>> createInsert() {
return Optional.ofNullable(getSQLManager()).map(this::createInsert)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull InsertBuilder<PreparedSQLUpdateAction<Integer>> createInsert(@NotNull SQLManager sqlManager) {
return sqlManager.createInsert(getTableName());
}
default @NotNull InsertBuilder<PreparedSQLUpdateBatchAction<Integer>> createInsertBatch() {
return Optional.ofNullable(getSQLManager()).map(this::createInsertBatch)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull InsertBuilder<PreparedSQLUpdateBatchAction<Integer>> createInsertBatch(@NotNull SQLManager sqlManager) {
return sqlManager.createInsertBatch(getTableName());
}
default @NotNull ReplaceBuilder<PreparedSQLUpdateAction<Integer>> createReplace() {
return Optional.ofNullable(getSQLManager()).map(this::createReplace)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull ReplaceBuilder<PreparedSQLUpdateAction<Integer>> createReplace(@NotNull SQLManager sqlManager) {
return sqlManager.createReplace(getTableName());
}
default @NotNull ReplaceBuilder<PreparedSQLUpdateBatchAction<Integer>> createReplaceBatch() {
return Optional.ofNullable(getSQLManager()).map(this::createReplaceBatch)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull ReplaceBuilder<PreparedSQLUpdateBatchAction<Integer>> createReplaceBatch(@NotNull SQLManager sqlManager) {
return sqlManager.createReplaceBatch(getTableName());
}
default @NotNull TableAlterBuilder alter() {
return Optional.ofNullable(getSQLManager()).map(this::alter)
.orElseThrow(() -> new NullPointerException("This table doesn't have a SQLManger."));
}
default @NotNull TableAlterBuilder alter(@NotNull SQLManager sqlManager) {
return sqlManager.alterTable(getTableName());
}
}
@@ -2,7 +2,7 @@ package cc.carm.lib.easysql.api.action;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public interface PreparedSQLUpdateAction extends SQLUpdateAction { public interface PreparedSQLUpdateAction<T extends Number> extends SQLUpdateAction<T> {
/** /**
* 设定SQL语句中所有 ? 对应的参数 * 设定SQL语句中所有 ? 对应的参数
@@ -10,14 +10,15 @@ public interface PreparedSQLUpdateAction extends SQLUpdateAction {
* @param params 参数内容 * @param params 参数内容
* @return {@link PreparedSQLUpdateAction} * @return {@link PreparedSQLUpdateAction}
*/ */
PreparedSQLUpdateAction setParams(Object... params); PreparedSQLUpdateAction<T> setParams(Object... params);
/** /**
* 设定SQL语句中所有 ? 对应的参数 * 设定SQL语句中所有 ? 对应的参数
* *
* @param params 参数内容 * @param params 参数内容
* @return {@link PreparedSQLUpdateAction} * @return {@link PreparedSQLUpdateAction}
* @since 0.4.0
*/ */
PreparedSQLUpdateAction setParams(@Nullable Iterable<Object> params); PreparedSQLUpdateAction<T> setParams(@Nullable Iterable<Object> params);
} }
@@ -4,7 +4,7 @@ import cc.carm.lib.easysql.api.SQLAction;
import java.util.List; import java.util.List;
public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> { public interface PreparedSQLUpdateBatchAction<T extends Number> extends SQLAction<List<T>> {
/** /**
* 设定多组SQL语句中所有 ? 对应的参数 * 设定多组SQL语句中所有 ? 对应的参数
@@ -12,7 +12,7 @@ public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
* @param allParams 所有参数内容 * @param allParams 所有参数内容
* @return {@link PreparedSQLUpdateBatchAction} * @return {@link PreparedSQLUpdateBatchAction}
*/ */
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams); PreparedSQLUpdateBatchAction<T> setAllParams(Iterable<Object[]> allParams);
/** /**
* 添加一组SQL语句中所有 ? 对应的参数 * 添加一组SQL语句中所有 ? 对应的参数
@@ -20,37 +20,23 @@ public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
* @param params 参数内容 * @param params 参数内容
* @return {@link PreparedSQLUpdateBatchAction} * @return {@link PreparedSQLUpdateBatchAction}
*/ */
PreparedSQLUpdateBatchAction addParamsBatch(Object... params); PreparedSQLUpdateBatchAction<T> 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} * @return {@link SQLUpdateAction}
*/ */
default PreparedSQLUpdateBatchAction returnGeneratedKeys() { PreparedSQLUpdateBatchAction<T> returnGeneratedKeys();
return setReturnGeneratedKeys(true);
}
/** /**
* 设定该操作是否返回自增键序列。 * 设定该操作返回自增键序列。
* *
* @param returnGeneratedKey 是否返回自增序列 * @param keyTypeClass 自增序列的数字类型
* @return {@link PreparedSQLUpdateBatchAction} * @param <N> 自增键序列类型 {@link Number}
* @return {@link SQLUpdateAction}
* @since 0.4.0
*/ */
PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey); <N extends Number> PreparedSQLUpdateBatchAction<N> returnGeneratedKeys(Class<N> keyTypeClass);
} }
@@ -2,37 +2,25 @@ package cc.carm.lib.easysql.api.action;
import cc.carm.lib.easysql.api.SQLAction; import cc.carm.lib.easysql.api.SQLAction;
public interface SQLUpdateAction extends SQLAction<Integer> { public interface SQLUpdateAction<T extends Number> extends SQLAction<T> {
/**
* 设定自增主键的序列
*
* @param keyColumnIndex 自增主键的序列
* <br>若该值 0,则 {@link #execute()} 返回自增主键数值
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
* @return {@link SQLUpdateAction}
* @see #setReturnGeneratedKey(boolean)
*/
@Deprecated
default SQLUpdateAction setKeyIndex(int keyColumnIndex) {
return setReturnGeneratedKey(keyColumnIndex > 0);
}
/** /**
* 设定该操作返回自增键序列。 * 设定该操作返回自增键序列。
* *
* @return {@link SQLUpdateAction} * @return {@link SQLUpdateAction}
*/ */
default SQLUpdateAction returnGeneratedKey() { SQLUpdateAction<T> returnGeneratedKey();
return setReturnGeneratedKey(true);
}
/** /**
* 设定该操作是否返回自增键序列。 * 设定该操作返回自增键序列。
* *
* @param returnGeneratedKey 是否返回自增序列 * @param keyTypeClass 自增序列的数字类型
* @param <N> 自增键序列类型 {@link Number}
* @return {@link SQLUpdateAction} * @return {@link SQLUpdateAction}
* @since 0.4.0
*/ */
SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey); <N extends Number> SQLUpdateAction<N> returnGeneratedKey(Class<N> keyTypeClass);
} }
@@ -21,6 +21,7 @@ public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
return getSQLContents().get(0); return getSQLContents().get(0);
} }
List<String> getSQLContents(); @Override
@NotNull List<String> getSQLContents();
} }
@@ -39,8 +39,6 @@ public interface QueryAction extends SQLAction<SQLQuery> {
try (SQLQuery value = execute()) { try (SQLQuery value = execute()) {
R result = function.apply(value); R result = function.apply(value);
return result == null ? defaultResult : result; return result == null ? defaultResult : result;
} catch (SQLException exception) {
throw new SQLException(exception);
} }
} }
@@ -47,9 +47,7 @@ public interface ConditionalBuilder<B extends ConditionalBuilder<B, T>, T extend
B addCondition(@NotNull String columnName, @NotNull String operator, @Nullable Object queryValue); B addCondition(@NotNull String columnName, @NotNull String operator, @Nullable Object queryValue);
default B addCondition(@NotNull String columnName, @Nullable Object queryValue) { B addCondition(@NotNull String columnName, @Nullable Object queryValue);
return addCondition(columnName, "=", queryValue);
}
B addCondition(@NotNull String[] columnNames, @Nullable Object[] queryValues); B addCondition(@NotNull String[] columnNames, @Nullable Object[] queryValues);
@@ -21,7 +21,7 @@ public interface TableCreateBuilder extends SQLBuilder {
* *
* @return {@link SQLUpdateAction} * @return {@link SQLUpdateAction}
*/ */
SQLUpdateAction build(); SQLUpdateAction<Integer> build();
@NotNull String getTableName(); @NotNull String getTableName();
@@ -0,0 +1,100 @@
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.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 异常处理器。
* <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 executeNanoTime 该次查询开始执行的时间 (单位:纳秒)
* @param closeNanoTime 该次查询彻底关闭的时间 (单位:纳秒)
*/
void afterQuery(@NotNull SQLQuery query, long executeNanoTime, long closeNanoTime);
default String parseParams(@Nullable Object[] params) {
if (params == null) return "<#NULL>";
else if (params.length == 0) return "<#EMPTY>";
List<String> paramsString = new ArrayList<>();
for (Object param : params) {
if (param == null) paramsString.add("NULL");
else paramsString.add(param.toString());
}
return String.join(", ", paramsString);
}
@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().getSimpleName());
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("┣# SQLParam: {}", parseParams(param));
}
} else if (params.size() > 1) {
logger.info("┣# SQLParams: ");
int i = 0;
for (Object[] param : params) {
logger.info("┃ - [{}] {}", ++i, parseParams(param));
}
}
logger.info("┣# CreateTime: {}", action.getCreateTime(TimeUnit.MILLISECONDS));
logger.info("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
@Override
public void afterQuery(@NotNull SQLQuery query, long executeNanoTime, long closeNanoTime) {
logger.info("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
logger.info("┣# ActionUUID: {}", query.getAction().getActionUUID());
logger.info("┣# SQLContent: {}", query.getSQLContent());
logger.info("┣# CloseTime: {} (cost {} ms)",
TimeUnit.NANOSECONDS.toMillis(closeNanoTime),
((double) (closeNanoTime - executeNanoTime) / 1000000)
);
logger.info("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
};
}
}
@@ -1,11 +1,10 @@
package cc.carm.lib.easysql.api.function; package cc.carm.lib.easysql.api.function;
import cc.carm.lib.easysql.api.SQLAction; import cc.carm.lib.easysql.api.SQLAction;
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction; import org.slf4j.Logger;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.logging.Logger;
/** /**
* 异常处理器。 * 异常处理器。
@@ -23,16 +22,12 @@ public interface SQLExceptionHandler extends BiConsumer<SQLException, SQLAction<
*/ */
static SQLExceptionHandler detailed(Logger logger) { static SQLExceptionHandler detailed(Logger logger) {
return (exception, sqlAction) -> { return (exception, sqlAction) -> {
if (sqlAction instanceof SQLUpdateBatchAction) { logger.error("Error occurred while executing SQL: ");
logger.severe("Error when execute SQLs : ");
int i = 1; int i = 1;
for (String content : ((SQLUpdateBatchAction) sqlAction).getSQLContents()) { for (String content : sqlAction.getSQLContents()) {
logger.severe(String.format("#%d {%s}", i, content)); logger.error(String.format("#%d {%s}", i, content));
i++; i++;
} }
} else {
logger.severe("Error when execute { " + sqlAction.getSQLContent() + " }");
}
exception.printStackTrace(); exception.printStackTrace();
}; };
} }
@@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Objects;
@FunctionalInterface @FunctionalInterface
public interface SQLFunction<T, R> { public interface SQLFunction<T, R> {
@@ -11,4 +12,23 @@ public interface SQLFunction<T, R> {
@Nullable @Nullable
R apply(@NotNull T t) throws SQLException; R apply(@NotNull T t) throws SQLException;
default <V> SQLFunction<V, R> compose(@NotNull SQLFunction<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> {
T t = before.apply(v);
if (t == null) return null;
else return apply(t);
};
}
default <V> SQLFunction<T, V> then(@NotNull SQLFunction<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> {
R r = apply(t);
if (r == null) return null;
else return after.apply(r);
};
}
} }
@@ -0,0 +1,50 @@
package cc.carm.lib.easysql.api.table;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLTable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
public abstract class NamedSQLTable implements SQLTable {
private final @NotNull String tableName;
protected @Nullable String tablePrefix;
protected @Nullable SQLManager manager;
/**
* 请调用 {@link NamedSQLTable} 下的静态方法进行对象的初始化。
*
* @param tableName 该表的名称
*/
public NamedSQLTable(@NotNull String tableName) {
this.tableName = tableName;
}
public @NotNull String getTableName() {
return (tablePrefix != null ? tablePrefix : "") + tableName;
}
@Override
public @Nullable SQLManager getSQLManager() {
return this.manager;
}
/**
* 使用指定 SQLManager 进行本示例的初始化。
*
* @param sqlManager {@link SQLManager}
* @param tablePrefix 表名前缀
* @return 本表是否为首次创建
* @throws SQLException 出现任何错误时抛出
*/
public abstract boolean create(@NotNull SQLManager sqlManager, @Nullable String tablePrefix) throws SQLException;
public boolean create(@NotNull SQLManager sqlManager) throws SQLException {
return create(sqlManager, null);
}
}
@@ -1,9 +1,22 @@
package cc.carm.lib.easysql.api.util; package cc.carm.lib.easysql.api.util;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UUIDUtil { 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) { public static UUID toUUID(String s) {
if (s.length() == 36) { if (s.length() == 36) {
return UUID.fromString(s); return UUID.fromString(s);
+29 -7
View File
@@ -5,18 +5,19 @@
<parent> <parent>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>0.3.9</version> <version>0.4.3</version>
<relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<maven.javadoc.skip>true</maven.javadoc.skip> <maven.javadoc.skip>true</maven.javadoc.skip>
<maven.deploy.skip>true</maven.deploy.skip> <maven.deploy.skip>true</maven.deploy.skip>
<log4j.version>2.18.0</log4j.version>
</properties> </properties>
<artifactId>easysql-demo</artifactId> <artifactId>easysql-demo</artifactId>
@@ -69,15 +70,31 @@
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
<version>4.0.3</version> <version>4.0.3</version>
<scope>test</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 --> <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
<version>2.1.210</version> <version>2.1.214</version>
<scope>test</scope> </dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
@@ -92,6 +109,11 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins> </plugins>
</build> </build>
</project> </project>
+52
View File
@@ -0,0 +1,52 @@
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLTable;
import cc.carm.lib.easysql.api.enums.IndexType;
import cc.carm.lib.easysql.api.enums.NumberType;
import cc.carm.lib.easysql.api.table.NamedSQLTable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
public enum DataTables1 {
DATA(SQLTable.of("data", (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");
})),
USER(SQLTable.of("user", (table) -> {
table.addAutoIncrementColumn("id", NumberType.INT, true, true);
table.addColumn("uuid", "VARCHAR(32) NOT NULL UNIQUE KEY");
table.addColumn("username", "VARCHAR(16) NOT NULL");
table.addColumn("age", "TINYINT NOT NULL DEFAULT 1");
table.addColumn("email", "VARCHAR(32)");
table.addColumn("phone", "VARCHAR(16)");
table.addColumn("registerTime", "DATETIME NOT NULL");
table.setIndex("username", IndexType.UNIQUE_KEY); // 添加唯一索引
table.setIndex(IndexType.INDEX, "contact", "email", "phone"); //添加联合索引 (示例)
}));
private final NamedSQLTable table;
DataTables1(NamedSQLTable table) {
this.table = table;
}
public NamedSQLTable get() {
return this.table;
}
public static void initialize(@NotNull SQLManager manager, @Nullable String tablePrefix) {
for (DataTables1 value : values()) {
try {
value.get().create(manager, tablePrefix);
} catch (SQLException e) {
// 提示异常
}
}
}
}
+69
View File
@@ -0,0 +1,69 @@
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLTable;
import cc.carm.lib.easysql.api.builder.TableCreateBuilder;
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.sql.SQLException;
import java.util.function.Consumer;
public enum DataTables2 implements SQLTable {
USER((table) -> {
table.addAutoIncrementColumn("id", NumberType.INT, true, true);
table.addColumn("uuid", "VARCHAR(32) NOT NULL UNIQUE KEY");
table.addColumn("username", "VARCHAR(16) NOT NULL");
table.addColumn("age", "TINYINT NOT NULL DEFAULT 1");
table.addColumn("email", "VARCHAR(32)");
table.addColumn("phone", "VARCHAR(16)");
table.addColumn("registerTime", "DATETIME NOT NULL");
table.setIndex("username", IndexType.UNIQUE_KEY); // 添加唯一索引
table.setIndex(IndexType.INDEX, "contact", "email", "phone"); //添加联合索引 (示例)
});
private final Consumer<TableCreateBuilder> builder;
private @Nullable String tablePrefix;
private @Nullable SQLManager manager;
DataTables2(Consumer<TableCreateBuilder> builder) {
this.builder = builder;
}
@Override
public @Nullable SQLManager getSQLManager() {
return this.manager;
}
@Override
public @NotNull String getTableName() {
// 这里直接选择用枚举的名称作为table的主名称
return (tablePrefix != null ? tablePrefix : "") + name().toLowerCase();
}
@Override
public boolean create(SQLManager sqlManager) throws SQLException {
return create(sqlManager, null);
}
public boolean create(@NotNull SQLManager sqlManager, @Nullable String tablePrefix) throws SQLException {
if (this.manager == null) this.manager = sqlManager;
this.tablePrefix = tablePrefix;
TableCreateBuilder tableBuilder = sqlManager.createTable(getTableName());
if (builder != null) builder.accept(tableBuilder);
return tableBuilder.build().executeFunction(l -> l > 0, false);
}
public static void initialize(@NotNull SQLManager manager, @Nullable String tablePrefix) {
for (DataTables2 value : values()) {
try {
value.create(manager, tablePrefix);
} catch (SQLException e) {
// 提示异常
}
}
}
}
@@ -1,5 +1,6 @@
import cc.carm.lib.easysql.api.SQLManager; import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery; 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.ForeignKeyRule;
import cc.carm.lib.easysql.api.enums.IndexType; import cc.carm.lib.easysql.api.enums.IndexType;
import cc.carm.lib.easysql.api.enums.NumberType; import cc.carm.lib.easysql.api.enums.NumberType;
@@ -43,6 +44,33 @@ public class EasySQLDemo {
.build().execute(null /* 不处理错误 */); .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) { public void alertTable(SQLManager sqlManager) {
// 同步更新表 // 同步更新表
sqlManager.alterTable("users") sqlManager.alterTable("users")
@@ -106,10 +134,10 @@ public class EasySQLDemo {
public void sqlInsert(SQLManager sqlManager) { public void sqlInsert(SQLManager sqlManager) {
// 同步SQL插入 不使用try-catch的情况下返回的数值可能为空 // 同步SQL插入 不使用try-catch的情况下返回的数值可能为空
Integer id = sqlManager.createInsert("users") int id = sqlManager.createInsert("users")
.setColumnNames("username", "phone", "email", "registerTime") .setColumnNames("username", "phone", "email", "registerTime")
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime()) .setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
.setReturnGeneratedKey(true)// 设定在后续返回自增主键 .returnGeneratedKey() // 设定在后续返回自增主键
.execute((exception, action) -> { .execute((exception, action) -> {
// 处理异常 // 处理异常
System.out.println("#" + action.getShortID() + " -> " + action.getSQLContent()); System.out.println("#" + action.getShortID() + " -> " + action.getSQLContent());
@@ -117,11 +145,10 @@ public class EasySQLDemo {
}); });
try { try {
Integer userID = sqlManager.createInsert("users") int userID = sqlManager.createInsert("users")
.setColumnNames("username", "phone", "email", "registerTime") .setColumnNames("username", "phone", "email", "registerTime")
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime()) .setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
.setReturnGeneratedKey(true) .returnGeneratedKey().execute();
.execute();
System.out.println("新用户的ID为 " + userID); System.out.println("新用户的ID为 " + userID);
@@ -6,6 +6,8 @@ import cc.carm.lib.easysql.tests.*;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
@@ -13,15 +15,29 @@ import java.util.Set;
public class EasySQLTest { public class EasySQLTest {
protected SQLManager sqlManager;
@Test @Before
public void onTest() { public void initialize() {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();
config.setDriverClassName("org.h2.Driver"); config.setDriverClassName("org.h2.Driver");
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=MYSQL;"); config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=MYSQL;");
SQLManager sqlManager = new SQLManagerImpl(new HikariDataSource(config), "test"); this.sqlManager = new SQLManagerImpl(new HikariDataSource(config), "test");
this.sqlManager.setDebugMode(true);
}
@After
public void shutdown() {
if (sqlManager.getDataSource() instanceof HikariDataSource) {
//Close bee connection pool
((HikariDataSource) sqlManager.getDataSource()).close();
}
}
@Test
public void onTest() {
print("加载测试类..."); print("加载测试类...");
Set<TestHandler> tests = new LinkedHashSet<>(); Set<TestHandler> tests = new LinkedHashSet<>();
@@ -29,11 +45,13 @@ public class EasySQLTest {
// tests.add(new TableAlterTest()); // tests.add(new TableAlterTest());
// tests.add(new TableRenameTest()); // tests.add(new TableRenameTest());
// tests.add(new QueryNotCloseTest()); // tests.add(new QueryNotCloseTest());
tests.add(new QueryCloseTest());
tests.add(new SQLUpdateBatchTests()); tests.add(new SQLUpdateBatchTests());
tests.add(new SQLUpdateReturnKeysTest()); tests.add(new SQLUpdateReturnKeysTest());
tests.add(new QueryCloseTest());
tests.add(new QueryFunctionTest()); tests.add(new QueryFunctionTest());
tests.add(new DeleteTest()); tests.add(new QueryAsyncTest());
// tests.add(new DeleteTest());
print("准备进行测试..."); print("准备进行测试...");
@@ -60,10 +78,6 @@ public class EasySQLTest {
success, (tests.size() - success) success, (tests.size() - success)
); );
if (sqlManager.getDataSource() instanceof HikariDataSource) {
//Close bee connection pool
((HikariDataSource) sqlManager.getDataSource()).close();
}
} }
@@ -1,7 +1,7 @@
package cc.carm.lib.easysql.tests; package cc.carm.lib.easysql.tests;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.TestHandler; import cc.carm.lib.easysql.TestHandler;
import cc.carm.lib.easysql.api.SQLManager;
import java.sql.SQLException; import java.sql.SQLException;
@@ -11,12 +11,11 @@ public class DeleteTest extends TestHandler {
@Override @Override
public void onTest(SQLManager sqlManager) throws SQLException { public void onTest(SQLManager sqlManager) throws SQLException {
Integer changes = sqlManager.createDelete("test_user_table")
System.out.println("change(s): " + sqlManager.createDelete("test_user_table")
.addCondition("id", ">", 5) .addCondition("id", ">", 5)
.addNotNullCondition("username") .addNotNullCondition("username")
.build().execute(); .build().execute());
System.out.println("change(s): " + changes);
} }
} }
@@ -0,0 +1,33 @@
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 QueryAsyncTest extends TestHandler {
@Override
public void onTest(SQLManager sqlManager) throws SQLException {
sqlManager.createQuery()
.inTable("test_user_table")
.orderBy("id", false)
.setLimit(1)
.build().executeAsync(query -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (!query.getResultSet().next()) {
System.out.println("id (ps): NULL");
} else {
System.out.println("id (ps): " + query.getResultSet().getInt("id"));
}
});
}
}
@@ -1,9 +1,10 @@
package cc.carm.lib.easysql.tests; package cc.carm.lib.easysql.tests;
import cc.carm.lib.easysql.TestHandler;
import cc.carm.lib.easysql.api.SQLManager; import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery; import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.TestHandler;
import java.math.BigInteger;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@@ -24,7 +25,7 @@ public class QueryCloseTest extends TestHandler {
System.out.printf( System.out.printf(
"id: %d username: %s%n", "id: %d username: %s%n",
resultSet.getInt("id"), resultSet.getObject("id", BigInteger.class),
resultSet.getString("username") resultSet.getString("username")
); );
@@ -16,6 +16,11 @@ public class QueryFunctionTest extends TestHandler {
.orderBy("id", false) .orderBy("id", false)
.setLimit(1) .setLimit(1)
.build().executeFunction(query -> { .build().executeFunction(query -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (!query.getResultSet().next()) return -1; if (!query.getResultSet().next()) return -1;
else return query.getResultSet().getInt("id"); else return query.getResultSet().getInt("id");
}); });
@@ -1,12 +1,13 @@
package cc.carm.lib.easysql.tests; package cc.carm.lib.easysql.tests;
import cc.carm.lib.easysql.TestHandler;
import cc.carm.lib.easysql.api.SQLManager; import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery; import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.TestHandler;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@SuppressWarnings("resource")
public class QueryNotCloseTest extends TestHandler { public class QueryNotCloseTest extends TestHandler {
@Override @Override
@@ -1,7 +1,7 @@
package cc.carm.lib.easysql.tests; package cc.carm.lib.easysql.tests;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.TestHandler; import cc.carm.lib.easysql.TestHandler;
import cc.carm.lib.easysql.api.SQLManager;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
@@ -25,9 +25,10 @@ public class SQLUpdateBatchTests extends TestHandler {
@Override @Override
public void onTest(SQLManager sqlManager) throws SQLException { public void onTest(SQLManager sqlManager) throws SQLException {
List<Integer> updates = sqlManager.createInsertBatch("test_user_table") List<Long> updates = sqlManager.createInsertBatch("test_user_table")
.setColumnNames("uuid", "username", "age") .setColumnNames("uuid", "username", "age")
.setAllParams(generateParams()) .setAllParams(generateParams())
.returnGeneratedKeys(Long.class)
.execute(); .execute();
System.out.println("changes " + Arrays.toString(updates.toArray())); System.out.println("changes " + Arrays.toString(updates.toArray()));
@@ -14,7 +14,7 @@ public class SQLUpdateReturnKeysTest extends SQLUpdateBatchTests {
List<Integer> generatedKeys = sqlManager.createInsertBatch("test_user_table") List<Integer> generatedKeys = sqlManager.createInsertBatch("test_user_table")
.setColumnNames("uuid", "username", "age") .setColumnNames("uuid", "username", "age")
.setAllParams(generateParams()) .setAllParams(generateParams())
.returnGeneratedKeys() .returnGeneratedKeys(Integer.class)
.execute(); .execute();
System.out.println("generated " + Arrays.toString(generatedKeys.toArray())); System.out.println("generated " + Arrays.toString(generatedKeys.toArray()));
@@ -1,8 +1,8 @@
package cc.carm.lib.easysql.tests; package cc.carm.lib.easysql.tests;
import cc.carm.lib.easysql.TestHandler;
import cc.carm.lib.easysql.api.SQLManager; import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.enums.NumberType; import cc.carm.lib.easysql.api.enums.NumberType;
import cc.carm.lib.easysql.TestHandler;
import java.sql.SQLException; import java.sql.SQLException;
@@ -1,9 +1,9 @@
package cc.carm.lib.easysql.tests; package cc.carm.lib.easysql.tests;
import cc.carm.lib.easysql.TestHandler;
import cc.carm.lib.easysql.api.SQLManager; import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.enums.ForeignKeyRule; import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
import cc.carm.lib.easysql.api.enums.IndexType; import cc.carm.lib.easysql.api.enums.IndexType;
import cc.carm.lib.easysql.TestHandler;
import java.sql.SQLException; import java.sql.SQLException;
@@ -1,7 +1,7 @@
package cc.carm.lib.easysql.tests; package cc.carm.lib.easysql.tests;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.TestHandler; import cc.carm.lib.easysql.TestHandler;
import cc.carm.lib.easysql.api.SQLManager;
import java.sql.SQLException; import java.sql.SQLException;
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="cc.carm.lib.easysql.EasySQLTest">
<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{nolookups}%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<OnStartupTriggeringPolicy/>
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="info">
<filters>
<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY" onMismatch="NEUTRAL"/>
<RegexFilter regex=".*\$\{[^}]*\}.*" onMatch="DENY" onMismatch="NEUTRAL"/>
</filters>
<AppenderRef ref="File"/>
<appender-ref ref="Console"/>
</Root>
</Loggers>
</Configuration>
+3 -7
View File
@@ -5,13 +5,13 @@
<parent> <parent>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>0.3.9</version> <version>0.4.3</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
@@ -81,10 +81,6 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins> </plugins>
</build> </build>
@@ -7,37 +7,39 @@ import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit;
public abstract class AbstractSQLAction<T> implements SQLAction<T> { public abstract class AbstractSQLAction<T> implements SQLAction<T> {
protected final @NotNull String sqlContent; protected final @NotNull String sqlContent;
private final @NotNull SQLManagerImpl sqlManager; private final @NotNull SQLManagerImpl sqlManager;
private final @NotNull UUID uuid; private final @NotNull UUID uuid;
private final long createTime; private final long createNanoTime;
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) { public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) {
this(manager, sql, System.currentTimeMillis()); this(manager, sql, System.nanoTime());
} }
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, @NotNull UUID uuid) { public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, @NotNull UUID uuid) {
this(manager, sql, uuid, System.currentTimeMillis()); this(manager, sql, uuid, System.nanoTime());
} }
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, long createTime) { public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, long createNanoTime) {
this(manager, sql, UUID.randomUUID(), createTime); this(manager, sql, UUID.randomUUID(), createNanoTime);
} }
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql,
@NotNull UUID uuid, long createTime) { @NotNull UUID uuid, long createNanoTime) {
Objects.requireNonNull(manager); Objects.requireNonNull(manager);
Objects.requireNonNull(sql); Objects.requireNonNull(sql);
Objects.requireNonNull(uuid); Objects.requireNonNull(uuid);
this.sqlManager = manager; this.sqlManager = manager;
this.sqlContent = sql; this.sqlContent = sql;
this.uuid = uuid; this.uuid = uuid;
this.createTime = createTime; this.createNanoTime = createNanoTime;
} }
@@ -52,8 +54,8 @@ public abstract class AbstractSQLAction<T> implements SQLAction<T> {
} }
@Override @Override
public long getCreateTime() { public long getCreateTime(TimeUnit unit) {
return this.createTime; return unit.convert(createNanoTime, TimeUnit.NANOSECONDS);
} }
@Override @Override
@@ -66,8 +68,14 @@ public abstract class AbstractSQLAction<T> implements SQLAction<T> {
return this.sqlManager; return this.sqlManager;
} }
protected void outputDebugMessage() { protected void debugMessage(List<Object[]> params) {
getManager().debug("# " + getShortID() + " -> { " + getSQLContent() + " }"); if (getManager().isDebugMode()) {
try {
getManager().getDebugHandler().beforeExecute(this, params);
} catch (Exception exception) {
exception.printStackTrace();
}
}
} }
@Override @Override
@@ -12,22 +12,33 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class PreparedSQLBatchUpdateActionImpl public class PreparedSQLBatchUpdateActionImpl<T extends Number>
extends AbstractSQLAction<List<Integer>> extends AbstractSQLAction<List<T>>
implements PreparedSQLUpdateBatchAction { implements PreparedSQLUpdateBatchAction<T> {
boolean returnKeys = false; boolean returnKeys = false;
List<Object[]> allParams; @NotNull List<Object[]> allParams = new ArrayList<>();
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) { protected final @NotNull Class<T> numberClass;
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
@NotNull String sql) {
super(manager, sql); super(manager, sql);
this.numberClass = numberClass;
this.allParams = new ArrayList<>(); this.allParams = new ArrayList<>();
} }
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
@NotNull UUID uuid, @NotNull String sql) {
super(manager, sql, uuid);
this.numberClass = numberClass;
}
@Override @Override
public PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams) { public PreparedSQLBatchUpdateActionImpl<T> setAllParams(Iterable<Object[]> allParams) {
List<Object[]> paramsList = new ArrayList<>(); List<Object[]> paramsList = new ArrayList<>();
allParams.forEach(paramsList::add); allParams.forEach(paramsList::add);
this.allParams = paramsList; this.allParams = paramsList;
@@ -35,33 +46,40 @@ public class PreparedSQLBatchUpdateActionImpl
} }
@Override @Override
public PreparedSQLUpdateBatchAction addParamsBatch(Object... params) { public PreparedSQLBatchUpdateActionImpl<T> addParamsBatch(Object... params) {
this.allParams.add(params); this.allParams.add(params);
return this; return this;
} }
@Override @Override
public PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey) { public PreparedSQLBatchUpdateActionImpl<T> returnGeneratedKeys() {
this.returnKeys = returnGeneratedKey; this.returnKeys = true;
return this; return this;
} }
@Override @Override
public @NotNull List<Integer> execute() throws SQLException { public <N extends Number> PreparedSQLBatchUpdateActionImpl<N> returnGeneratedKeys(Class<N> keyTypeClass) {
return new PreparedSQLBatchUpdateActionImpl<>(getManager(), keyTypeClass, getActionUUID(), getSQLContent())
.setAllParams(allParams).returnGeneratedKeys();
}
@Override
public @NotNull List<T> execute() throws SQLException {
debugMessage(allParams);
try (Connection connection = getManager().getConnection()) { try (Connection connection = getManager().getConnection()) {
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch( try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
connection, getSQLContent(), allParams, returnKeys connection, getSQLContent(), allParams, returnKeys
)) { )) {
outputDebugMessage();
int[] executed = statement.executeBatch(); int[] executed = statement.executeBatch();
if (!returnKeys) return Arrays.stream(executed).boxed().collect(Collectors.toList()); if (!returnKeys) {
else { return Arrays.stream(executed).mapToObj(numberClass::cast).collect(Collectors.toList());
} else {
try (ResultSet resultSet = statement.getGeneratedKeys()) { try (ResultSet resultSet = statement.getGeneratedKeys()) {
List<Integer> generatedKeys = new ArrayList<>(); List<T> generatedKeys = new ArrayList<>();
while (resultSet.next()) { while (resultSet.next()) {
generatedKeys.add(resultSet.getInt(1)); generatedKeys.add(resultSet.getObject(1, numberClass));
} }
return generatedKeys; return generatedKeys;
} }
@@ -1,6 +1,7 @@
package cc.carm.lib.easysql.action; package cc.carm.lib.easysql.action;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction; import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import cc.carm.lib.easysql.util.StatementUtil; import cc.carm.lib.easysql.util.StatementUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -11,37 +12,47 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID;
public class PreparedSQLUpdateActionImpl public class PreparedSQLUpdateActionImpl<T extends Number>
extends SQLUpdateActionImpl extends SQLUpdateActionImpl<T>
implements PreparedSQLUpdateAction { implements PreparedSQLUpdateAction<T> {
Object[] params; Object[] params;
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) { public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
this(manager, sql, (Object[]) null); @NotNull String sql) {
this(manager, numberClass, sql, (Object[]) null);
} }
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql, public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
@Nullable List<Object> params) { @NotNull String sql, @Nullable List<Object> params) {
this(manager, sql, params == null ? null : params.toArray()); this(manager, numberClass, sql, params == null ? null : params.toArray());
} }
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql, public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
@Nullable Object[] params) { @NotNull String sql, @Nullable Object[] params) {
super(manager, sql); super(manager, numberClass, sql);
this.params = params;
}
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
@NotNull UUID uuid, @NotNull String sql,
Object[] params) {
super(manager, numberClass, uuid, sql);
this.params = params; this.params = params;
} }
@Override @Override
public PreparedSQLUpdateActionImpl setParams(Object... params) { public PreparedSQLUpdateActionImpl<T> setParams(Object... params) {
this.params = params; this.params = params;
return this; return this;
} }
@Override @Override
public PreparedSQLUpdateAction setParams(@Nullable Iterable<Object> params) { public PreparedSQLUpdateActionImpl<T> setParams(@Nullable Iterable<Object> params) {
if (params == null) { if (params == null) {
return setParams((Object[]) null); return setParams((Object[]) null);
} else { } else {
@@ -52,20 +63,20 @@ public class PreparedSQLUpdateActionImpl
} }
@Override @Override
public @NotNull Integer execute() throws SQLException { public @NotNull T execute() throws SQLException {
debugMessage(Collections.singletonList(params));
try (Connection connection = getManager().getConnection()) { try (Connection connection = getManager().getConnection()) {
try (PreparedStatement statement = StatementUtil.createPrepareStatement( try (PreparedStatement statement = StatementUtil.createPrepareStatement(
connection, getSQLContent(), params, returnGeneratedKeys connection, getSQLContent(), params, returnGeneratedKeys
)) { )) {
outputDebugMessage();
int changes = statement.executeUpdate(); int changes = statement.executeUpdate();
if (!returnGeneratedKeys) return changes; if (!returnGeneratedKeys) return numberClass.cast(changes);
else { else {
try (ResultSet resultSet = statement.getGeneratedKeys()) { try (ResultSet resultSet = statement.getGeneratedKeys()) {
return resultSet.next() ? resultSet.getInt(1) : -1; return resultSet.next() ? resultSet.getObject(1, numberClass) : numberClass.cast(0);
} }
} }
@@ -74,4 +85,10 @@ public class PreparedSQLUpdateActionImpl
} }
@Override
public <N extends Number> SQLUpdateAction<N> returnGeneratedKey(Class<N> keyTypeClass) {
PreparedSQLUpdateActionImpl<N> newAction = new PreparedSQLUpdateActionImpl<>(getManager(), keyTypeClass, getActionUUID(), getSQLContent(), params);
newAction.returnGeneratedKey();
return newAction;
}
} }
@@ -8,41 +8,58 @@ import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList;
import java.util.UUID;
public class SQLUpdateActionImpl public class SQLUpdateActionImpl<T extends Number>
extends AbstractSQLAction<Integer> extends AbstractSQLAction<T>
implements SQLUpdateAction { implements SQLUpdateAction<T> {
boolean returnGeneratedKeys = false; protected final @NotNull Class<T> numberClass;
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) { protected boolean returnGeneratedKeys = false;
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
@NotNull String sql) {
super(manager, sql); super(manager, sql);
this.numberClass = numberClass;
}
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull Class<T> numberClass,
@NotNull UUID uuid, @NotNull String sql) {
super(manager, sql, uuid);
this.numberClass = numberClass;
} }
@Override @Override
public @NotNull Integer execute() throws SQLException { public @NotNull T execute() throws SQLException {
debugMessage(new ArrayList<>());
try (Connection connection = getManager().getConnection()) { try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
outputDebugMessage();
if (!returnGeneratedKeys) { if (!returnGeneratedKeys) {
return statement.executeUpdate(getSQLContent()); return numberClass.cast(statement.executeUpdate(getSQLContent()));
} else { } else {
statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS); statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS);
try (ResultSet resultSet = statement.getGeneratedKeys()) { try (ResultSet resultSet = statement.getGeneratedKeys()) {
return resultSet.next() ? resultSet.getInt(1) : -1; return resultSet.next() ? resultSet.getObject(1, numberClass) : numberClass.cast(0);
} }
} }
} }
} }
} }
@Override @Override
public SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey) { public SQLUpdateAction<T> returnGeneratedKey() {
this.returnGeneratedKeys = returnGeneratedKey; this.returnGeneratedKeys = true;
return this; return this;
} }
@Override
public <N extends Number> SQLUpdateAction<N> returnGeneratedKey(Class<N> keyTypeClass) {
return new SQLUpdateActionImpl<>(getManager(), keyTypeClass, getActionUUID(), getSQLContent()).returnGeneratedKey();
}
} }
@@ -38,10 +38,11 @@ public class SQLUpdateBatchActionImpl
@Override @Override
public @NotNull List<Integer> execute() throws SQLException { public @NotNull List<Integer> execute() throws SQLException {
debugMessage(new ArrayList<>());
try (Connection connection = getManager().getConnection()) { try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
outputDebugMessage();
for (String content : this.sqlContents) { for (String content : this.sqlContents) {
statement.addBatch(content); statement.addBatch(content);
@@ -55,12 +56,4 @@ public class SQLUpdateBatchActionImpl
} }
} }
@Override
protected void outputDebugMessage() {
getManager().debug("# " + getShortID() + " -> [");
for (String content : getSQLContents()) getManager().debug(String.format(" { %s }", content));
getManager().debug("]");
}
} }
@@ -11,6 +11,7 @@ import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -49,7 +50,7 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
@Override @Override
public @NotNull SQLQueryImpl execute() throws SQLException { public @NotNull SQLQueryImpl execute() throws SQLException {
outputDebugMessage(); debugMessage(Collections.singletonList(params));
Connection connection = getManager().getConnection(); Connection connection = getManager().getConnection();
PreparedStatement preparedStatement; PreparedStatement preparedStatement;
@@ -66,15 +67,12 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
} }
try { try {
long executeTime = System.currentTimeMillis();
SQLQueryImpl query = new SQLQueryImpl( SQLQueryImpl query = new SQLQueryImpl(
getManager(), this, getManager(), this,
connection, preparedStatement, connection, preparedStatement,
preparedStatement.executeQuery(), preparedStatement.executeQuery()
executeTime
); );
getManager().getActiveQuery().put(getActionUUID(), query); getManager().getActiveQuery().put(getActionUUID(), query);
return query; return query;
} catch (SQLException exception) { } catch (SQLException exception) {
preparedStatement.close(); preparedStatement.close();
@@ -12,6 +12,7 @@ import org.jetbrains.annotations.NotNull;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList;
public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements QueryAction { public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements QueryAction {
@@ -21,6 +22,7 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
@Override @Override
public @NotNull SQLQueryImpl execute() throws SQLException { public @NotNull SQLQueryImpl execute() throws SQLException {
debugMessage(new ArrayList<>());
Connection connection = getManager().getConnection(); Connection connection = getManager().getConnection();
Statement statement; Statement statement;
@@ -32,14 +34,11 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
throw ex; throw ex;
} }
outputDebugMessage();
try { try {
long executeTime = System.currentTimeMillis();
SQLQueryImpl query = new SQLQueryImpl( SQLQueryImpl query = new SQLQueryImpl(
getManager(), this, getManager(), this,
connection, statement, connection, statement,
statement.executeQuery(getSQLContent()), statement.executeQuery(getSQLContent())
executeTime
); );
getManager().getActiveQuery().put(getActionUUID(), query); getManager().getActiveQuery().put(getActionUUID(), query);
@@ -54,10 +53,12 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
@Override @Override
public void executeAsync(SQLHandler<SQLQuery> success, SQLExceptionHandler failure) { public void executeAsync(SQLHandler<SQLQuery> success, SQLExceptionHandler failure) {
getManager().getExecutorPool().submit(() -> {
try (SQLQueryImpl query = execute()) { try (SQLQueryImpl query = execute()) {
if (success != null) success.accept(query); if (success != null) success.accept(query);
} catch (SQLException exception) { } catch (SQLException exception) {
handleException(failure, exception); handleException(failure, exception);
} }
});
} }
} }
@@ -48,6 +48,16 @@ public abstract class AbstractConditionalBuilder<B extends ConditionalBuilder<B,
return getThis(); return getThis();
} }
@Override
public B addCondition(@NotNull String columnName, @Nullable Object queryValue) {
Objects.requireNonNull(columnName, "columnName could not be null");
if (queryValue == null) {
return addCondition(withBackQuote(columnName) + " IS NULL");
} else {
return addCondition(columnName, "=", queryValue);
}
}
@Override @Override
public B addCondition( public B addCondition(
@NotNull String columnName, @NotNull String operator, @Nullable Object queryValue @NotNull String columnName, @NotNull String operator, @Nullable Object queryValue
@@ -24,7 +24,7 @@ public class DeleteBuilderImpl
} }
@Override @Override
public PreparedSQLUpdateAction build() { public PreparedSQLUpdateAction<Integer> build() {
StringBuilder sqlBuilder = new StringBuilder(); StringBuilder sqlBuilder = new StringBuilder();
@@ -33,9 +33,9 @@ public class DeleteBuilderImpl
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL()); if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL()); if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL());
return new PreparedSQLUpdateActionImpl( return new PreparedSQLUpdateActionImpl<>(
getManager(), sqlBuilder.toString(), getManager(), Integer.class, sqlBuilder.toString(),
hasConditionParams() ? getConditionParams() : null (hasConditionParams() ? getConditionParams() : null)
); );
} }
@@ -10,6 +10,8 @@ import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
import cc.carm.lib.easysql.manager.SQLManagerImpl; import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects; import java.util.Objects;
public class QueryBuilderImpl extends AbstractSQLBuilder implements QueryBuilder { public class QueryBuilderImpl extends AbstractSQLBuilder implements QueryBuilder {
@@ -30,24 +30,18 @@ public class TableAlterBuilderImpl extends AbstractSQLBuilder implements TableAl
@Override @Override
public SQLAction<Integer> renameTo(@NotNull String newTableName) { public SQLAction<Integer> renameTo(@NotNull String newTableName) {
Objects.requireNonNull(newTableName, "table name could not be null"); Objects.requireNonNull(newTableName, "table name could not be null");
return new SQLUpdateActionImpl(getManager(), return createAction("ALTER TABLE " + withBackQuote(tableName) + " RENAME TO " + withBackQuote(newTableName));
"ALTER TABLE " + withBackQuote(tableName) + " RENAME TO " + withBackQuote(newTableName)
);
} }
@Override @Override
public SQLAction<Integer> changeComment(@NotNull String newTableComment) { public SQLAction<Integer> changeComment(@NotNull String newTableComment) {
Objects.requireNonNull(newTableComment, "table comment could not be null"); Objects.requireNonNull(newTableComment, "table comment could not be null");
return new SQLUpdateActionImpl(getManager(), return createAction("ALTER TABLE " + withBackQuote(getTableName()) + " COMMENT " + withQuote(newTableComment));
"ALTER TABLE " + withBackQuote(getTableName()) + " COMMENT " + withQuote(newTableComment)
);
} }
@Override @Override
public SQLAction<Integer> setAutoIncrementIndex(int index) { public SQLAction<Integer> setAutoIncrementIndex(int index) {
return new SQLUpdateActionImpl(getManager(), return createAction("ALTER TABLE " + withBackQuote(getTableName()) + " AUTO_INCREMENT=" + index);
"ALTER TABLE " + withBackQuote(getTableName()) + " AUTO_INCREMENT=" + index
);
} }
@Override @Override
@@ -147,7 +141,7 @@ public class TableAlterBuilderImpl extends AbstractSQLBuilder implements TableAl
); );
} }
private SQLUpdateActionImpl createAction(@NotNull String sql) { private SQLUpdateActionImpl<Integer> createAction(@NotNull String sql) {
return new SQLUpdateActionImpl(getManager(), sql); return new SQLUpdateActionImpl<>(getManager(), Integer.class, sql);
} }
} }
@@ -75,7 +75,7 @@ public class TableCreateBuilderImpl extends AbstractSQLBuilder implements TableC
} }
@Override @Override
public SQLUpdateAction build() { public SQLUpdateAction<Integer> build() {
StringBuilder createSQL = new StringBuilder(); StringBuilder createSQL = new StringBuilder();
createSQL.append("CREATE TABLE IF NOT EXISTS ").append(withBackQuote(tableName)); createSQL.append("CREATE TABLE IF NOT EXISTS ").append(withBackQuote(tableName));
createSQL.append("("); createSQL.append("(");
@@ -94,7 +94,7 @@ public class TableCreateBuilderImpl extends AbstractSQLBuilder implements TableC
createSQL.append(" COMMENT ").append(withQuote(tableComment)); createSQL.append(" COMMENT ").append(withQuote(tableComment));
} }
return new SQLUpdateActionImpl(getManager(), createSQL.toString()); return new SQLUpdateActionImpl<>(getManager(), Integer.class, createSQL.toString());
} }
@Override @Override
@@ -27,7 +27,7 @@ public class UpdateBuilderImpl
} }
@Override @Override
public PreparedSQLUpdateAction build() { public PreparedSQLUpdateAction<Integer> build() {
StringBuilder sqlBuilder = new StringBuilder(); StringBuilder sqlBuilder = new StringBuilder();
@@ -47,7 +47,7 @@ public class UpdateBuilderImpl
if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL()); if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL());
return new PreparedSQLUpdateActionImpl(getManager(), sqlBuilder.toString(), allParams); return new PreparedSQLUpdateActionImpl<>(getManager(), Integer.class, sqlBuilder.toString(), allParams);
} }
@Override @Override
@@ -10,10 +10,13 @@ import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction; import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction; import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
import cc.carm.lib.easysql.api.builder.*; import cc.carm.lib.easysql.api.builder.*;
import cc.carm.lib.easysql.api.function.SQLDebugHandler;
import cc.carm.lib.easysql.api.function.SQLExceptionHandler; import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
import cc.carm.lib.easysql.builder.impl.*; import cc.carm.lib.easysql.builder.impl.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.Connection; import java.sql.Connection;
@@ -23,7 +26,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.logging.Logger;
public class SQLManagerImpl implements SQLManager { public class SQLManagerImpl implements SQLManager {
@@ -34,14 +36,19 @@ public class SQLManagerImpl implements SQLManager {
@NotNull Supplier<Boolean> debugMode = () -> Boolean.FALSE; @NotNull Supplier<Boolean> debugMode = () -> Boolean.FALSE;
@NotNull SQLExceptionHandler exceptionHandler; @NotNull SQLExceptionHandler exceptionHandler;
@NotNull SQLDebugHandler debugHandler;
public SQLManagerImpl(@NotNull DataSource dataSource) { public SQLManagerImpl(@NotNull DataSource dataSource) {
this(dataSource, null); this(dataSource, null);
} }
public SQLManagerImpl(@NotNull DataSource dataSource, @Nullable String name) { public SQLManagerImpl(@NotNull DataSource dataSource, @Nullable String name) {
this(dataSource, LoggerFactory.getLogger(SQLManagerImpl.class), name);
}
public SQLManagerImpl(@NotNull DataSource dataSource, @NotNull Logger logger, @Nullable String name) {
String managerName = "SQLManager" + (name != null ? "#" + name : ""); String managerName = "SQLManager" + (name != null ? "#" + name : "");
this.LOGGER = Logger.getLogger(managerName); this.LOGGER = logger;
this.dataSource = dataSource; this.dataSource = dataSource;
this.executorPool = Executors.newFixedThreadPool(3, r -> { this.executorPool = Executors.newFixedThreadPool(3, r -> {
Thread thread = new Thread(r, managerName); Thread thread = new Thread(r, managerName);
@@ -50,6 +57,7 @@ public class SQLManagerImpl implements SQLManager {
}); });
this.exceptionHandler = SQLExceptionHandler.detailed(getLogger()); this.exceptionHandler = SQLExceptionHandler.detailed(getLogger());
this.debugHandler = SQLDebugHandler.defaultHandler(getLogger());
} }
@Override @Override
@@ -62,6 +70,16 @@ public class SQLManagerImpl implements SQLManager {
this.debugMode = debugMode; this.debugMode = debugMode;
} }
@Override
public @NotNull SQLDebugHandler getDebugHandler() {
return this.debugHandler;
}
@Override
public void setDebugHandler(@NotNull SQLDebugHandler debugHandler) {
this.debugHandler = debugHandler;
}
public void debug(String msg) { public void debug(String msg) {
if (isDebugMode()) getLogger().info("[DEBUG] " + msg); if (isDebugMode()) getLogger().info("[DEBUG] " + msg);
} }
@@ -71,10 +89,14 @@ public class SQLManagerImpl implements SQLManager {
return LOGGER; return LOGGER;
} }
public ExecutorService getExecutorPool() { public @NotNull ExecutorService getExecutorPool() {
return executorPool; return executorPool;
} }
public void setExecutorPool(@NotNull ExecutorService executorPool) {
this.executorPool = executorPool;
}
@Override @Override
public @NotNull DataSource getDataSource() { public @NotNull DataSource getDataSource() {
return this.dataSource; return this.dataSource;
@@ -103,19 +125,17 @@ public class SQLManagerImpl implements SQLManager {
@Override @Override
public Integer executeSQL(String sql) { public Integer executeSQL(String sql) {
return new SQLUpdateActionImpl(this, sql).execute(null); return new SQLUpdateActionImpl<>(this, Integer.class, sql).execute(null);
} }
@Override @Override
public Integer executeSQL(String sql, Object[] params) { public Integer executeSQL(String sql, Object[] params) {
return new PreparedSQLUpdateActionImpl(this, sql, params).execute(null); return new PreparedSQLUpdateActionImpl<>(this, Integer.class, sql, params).execute(null);
} }
@Override @Override
public List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch) { public List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch) {
return new PreparedSQLBatchUpdateActionImpl(this, sql) return new PreparedSQLBatchUpdateActionImpl<>(this, Integer.class, sql).setAllParams(paramsBatch).execute(null);
.setAllParams(paramsBatch)
.execute(null);
} }
@Override @Override
@@ -156,41 +176,41 @@ public class SQLManagerImpl implements SQLManager {
} }
@Override @Override
public InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName) { public InsertBuilder<PreparedSQLUpdateBatchAction<Integer>> createInsertBatch(@NotNull String tableName) {
return new InsertBuilderImpl<PreparedSQLUpdateBatchAction>(this, tableName) { return new InsertBuilderImpl<PreparedSQLUpdateBatchAction<Integer>>(this, tableName) {
@Override @Override
public PreparedSQLUpdateBatchAction setColumnNames(List<String> columnNames) { public PreparedSQLUpdateBatchAction<Integer> setColumnNames(List<String> columnNames) {
return new PreparedSQLBatchUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames)); return new PreparedSQLBatchUpdateActionImpl<>(getManager(), Integer.class, buildSQL(getTableName(), columnNames));
} }
}; };
} }
@Override @Override
public InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName) { public InsertBuilder<PreparedSQLUpdateAction<Integer>> createInsert(@NotNull String tableName) {
return new InsertBuilderImpl<PreparedSQLUpdateAction>(this, tableName) { return new InsertBuilderImpl<PreparedSQLUpdateAction<Integer>>(this, tableName) {
@Override @Override
public PreparedSQLUpdateAction setColumnNames(List<String> columnNames) { public PreparedSQLUpdateAction<Integer> setColumnNames(List<String> columnNames) {
return new PreparedSQLUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames)); return new PreparedSQLUpdateActionImpl<>(getManager(), Integer.class, buildSQL(getTableName(), columnNames));
} }
}; };
} }
@Override @Override
public ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName) { public ReplaceBuilder<PreparedSQLUpdateBatchAction<Integer>> createReplaceBatch(@NotNull String tableName) {
return new ReplaceBuilderImpl<PreparedSQLUpdateBatchAction>(this, tableName) { return new ReplaceBuilderImpl<PreparedSQLUpdateBatchAction<Integer>>(this, tableName) {
@Override @Override
public PreparedSQLUpdateBatchAction setColumnNames(List<String> columnNames) { public PreparedSQLUpdateBatchAction<Integer> setColumnNames(List<String> columnNames) {
return new PreparedSQLBatchUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames)); return new PreparedSQLBatchUpdateActionImpl<>(getManager(), Integer.class, buildSQL(getTableName(), columnNames));
} }
}; };
} }
@Override @Override
public ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName) { public ReplaceBuilder<PreparedSQLUpdateAction<Integer>> createReplace(@NotNull String tableName) {
return new ReplaceBuilderImpl<PreparedSQLUpdateAction>(this, tableName) { return new ReplaceBuilderImpl<PreparedSQLUpdateAction<Integer>>(this, tableName) {
@Override @Override
public PreparedSQLUpdateAction setColumnNames(List<String> columnNames) { public PreparedSQLUpdateAction<Integer> setColumnNames(List<String> columnNames) {
return new PreparedSQLUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames)); return new PreparedSQLUpdateActionImpl<>(getManager(), Integer.class, buildSQL(getTableName(), columnNames));
} }
}; };
} }
@@ -8,22 +8,23 @@ import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.concurrent.TimeUnit;
public class SQLQueryImpl implements SQLQuery { public class SQLQueryImpl implements SQLQuery {
protected final long executeTime; protected final long executeTime;
protected final SQLManagerImpl sqlManager; protected final SQLManagerImpl sqlManager;
final Connection connection; protected final Connection connection;
final Statement statement; protected final Statement statement;
final ResultSet resultSet; protected final ResultSet resultSet;
protected QueryActionImpl queryAction; protected QueryActionImpl queryAction;
public SQLQueryImpl( public SQLQueryImpl(
SQLManagerImpl sqlManager, QueryActionImpl queryAction, SQLManagerImpl sqlManager, QueryActionImpl queryAction,
Connection connection, Statement statement, ResultSet resultSet Connection connection, Statement statement, ResultSet resultSet
) { ) {
this(sqlManager, queryAction, connection, statement, resultSet, System.currentTimeMillis()); this(sqlManager, queryAction, connection, statement, resultSet, System.nanoTime());
} }
public SQLQueryImpl( public SQLQueryImpl(
@@ -40,8 +41,8 @@ public class SQLQueryImpl implements SQLQuery {
} }
@Override @Override
public long getExecuteTime() { public long getExecuteTime(TimeUnit timeUnit) {
return this.executeTime; return timeUnit.convert(this.executeTime, TimeUnit.NANOSECONDS);
} }
@Override @Override
@@ -71,9 +72,13 @@ public class SQLQueryImpl implements SQLQuery {
if (getStatement() != null && !getStatement().isClosed()) getStatement().close(); if (getStatement() != null && !getStatement().isClosed()) getStatement().close();
if (getConnection() != null && !getConnection().isClosed()) getConnection().close(); if (getConnection() != null && !getConnection().isClosed()) getConnection().close();
getManager().debug("#" + getAction().getShortID() + if (getManager().isDebugMode()) {
" -> finished after " + (System.currentTimeMillis() - getExecuteTime()) + " ms." try {
); getManager().getDebugHandler().afterQuery(this, getExecuteTime(TimeUnit.NANOSECONDS), System.nanoTime());
} catch (Exception ex) {
ex.printStackTrace();
}
}
getManager().getActiveQuery().remove(getAction().getActionUUID()); getManager().getActiveQuery().remove(getAction().getActionUUID());
} catch (SQLException e) { } catch (SQLException e) {
getAction().handleException(getAction().defaultExceptionHandler(), e); getAction().handleException(getAction().defaultExceptionHandler(), e);
+24 -10
View File
@@ -5,11 +5,13 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<java.version>8</java.version> <jdk.version>8</jdk.version>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<sonar.organization>carmjos</sonar.organization> <sonar.organization>carmjos</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url> <sonar.host.url>https://sonarcloud.io</sonar.host.url>
</properties> </properties>
@@ -17,7 +19,7 @@
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<version>0.3.9</version> <version>0.4.3</version>
<modules> <modules>
<module>api</module> <module>api</module>
@@ -26,7 +28,7 @@
<module>with-pool/beecp</module> <module>with-pool/beecp</module>
<module>with-pool/hikaricp</module> <module>with-pool/hikaricp</module>
<module>example/demo</module> <module>demo</module>
</modules> </modules>
<name>EasySQL</name> <name>EasySQL</name>
@@ -94,14 +96,12 @@
</repositories> </repositories>
<distributionManagement> <distributionManagement>
<downloadUrl>https://github.com/CarmJos/EasySQL/releases</downloadUrl> <downloadUrl>https://github.com/CarmJos/EasySQL/releases</downloadUrl>
<site> <site>
<id>easysql-javadoc</id> <id>easysql-javadoc</id>
<name>EasySQL JavaDoc (on Github Pages)</name> <name>EasySQL JavaDoc (on Github Pages)</name>
<url>https://CarmJos.github.io/EasySQL</url> <url>https://CarmJos.github.io/EasySQL</url>
</site> </site>
</distributionManagement> </distributionManagement>
<dependencies> <dependencies>
@@ -169,7 +169,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.2</version> <version>3.4.0</version>
<configuration> <configuration>
<classifier>javadoc</classifier> <classifier>javadoc</classifier>
<detectJavaApiLink>false</detectJavaApiLink> <detectJavaApiLink>false</detectJavaApiLink>
@@ -198,8 +198,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version> <version>3.10.1</version>
<configuration> <configuration>
<source>${java.version}</source> <source>${jdk.version}</source>
<target>${java.version}</target> <target>${jdk.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<compilerArgument>-parameters</compilerArgument> <compilerArgument>-parameters</compilerArgument>
</configuration> </configuration>
@@ -302,6 +302,20 @@
</distributionManagement> </distributionManagement>
</profile> </profile>
<profile>
<id>local</id>
<distributionManagement>
<snapshotRepository>
<id>localRepository</id>
<url>file:${user.home}/local-deploy/</url>
</snapshotRepository>
<repository>
<id>localRepository</id>
<url>file:${user.home}/local-deploy/</url>
</repository>
</distributionManagement>
</profile>
</profiles> </profiles>
</project> </project>
+10 -4
View File
@@ -5,14 +5,14 @@
<parent> <parent>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>0.3.9</version> <version>0.4.3</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
@@ -40,6 +40,12 @@
<license> <license>
<name>The MIT License</name> <name>The MIT License</name>
<url>https://opensource.org/licenses/MIT</url> <url>https://opensource.org/licenses/MIT</url>
<comments>EasySQL的基础源代码采用MIT开源协议。</comments>
</license>
<license>
<name>GNU Lesser General Public License v2.1</name>
<url>https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html</url>
<comments>该版本打包了BeeCP,因此相关代码继续遵循LGPL协议。</comments>
</license> </license>
</licenses> </licenses>
@@ -73,7 +79,7 @@
<!--项目地址 https://github.com/Chris2018998/BeeCP --> <!--项目地址 https://github.com/Chris2018998/BeeCP -->
<groupId>com.github.chris2018998</groupId> <groupId>com.github.chris2018998</groupId>
<artifactId>beecp</artifactId> <artifactId>beecp</artifactId>
<version>3.3.5</version> <version>3.3.6</version>
<optional>true</optional> <optional>true</optional>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@@ -24,11 +24,11 @@ public class EasySQL {
public static void shutdownManager(SQLManager manager, boolean forceClose, boolean outputActiveQuery) { public static void shutdownManager(SQLManager manager, boolean forceClose, boolean outputActiveQuery) {
if (!manager.getActiveQuery().isEmpty()) { if (!manager.getActiveQuery().isEmpty()) {
manager.getLogger().severe("There are " + manager.getActiveQuery().size() + " connections still running"); manager.getLogger().warn("There are " + manager.getActiveQuery().size() + " connections still running");
for (SQLQuery value : manager.getActiveQuery().values()) { for (SQLQuery value : manager.getActiveQuery().values()) {
if (outputActiveQuery) { if (outputActiveQuery) {
manager.getLogger().severe(String.format("#%s -> %s", value.getAction().getShortID(), value.getSQLContent())); manager.getLogger().warn(String.format("#%s -> %s", value.getAction().getShortID(), value.getSQLContent()));
manager.getLogger().severe(String.format("- execute at %s", TimeDateUtils.getTimeString(value.getExecuteTime()))); manager.getLogger().warn(String.format("- execute at %s", TimeDateUtils.getTimeString(value.getExecuteTime())));
} }
if (forceClose) value.close(); if (forceClose) value.close();
} }
+4 -3
View File
@@ -5,14 +5,14 @@
<parent> <parent>
<artifactId>easysql-parent</artifactId> <artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId> <groupId>cc.carm.lib</groupId>
<version>0.3.9</version> <version>0.4.3</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${jdk.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties> </properties>
@@ -39,6 +39,7 @@
<license> <license>
<name>The MIT License</name> <name>The MIT License</name>
<url>https://opensource.org/licenses/MIT</url> <url>https://opensource.org/licenses/MIT</url>
<comments>EasySQL与HikariCP均采用MIT开源协议。</comments>
</license> </license>
</licenses> </licenses>
@@ -34,11 +34,11 @@ public class EasySQL {
public static void shutdownManager(SQLManager manager, boolean forceClose, boolean outputActiveQuery) { public static void shutdownManager(SQLManager manager, boolean forceClose, boolean outputActiveQuery) {
if (!manager.getActiveQuery().isEmpty()) { if (!manager.getActiveQuery().isEmpty()) {
manager.getLogger().severe("There are " + manager.getActiveQuery().size() + " connections still running"); manager.getLogger().warn("There are " + manager.getActiveQuery().size() + " connections still running");
for (SQLQuery value : manager.getActiveQuery().values()) { for (SQLQuery value : manager.getActiveQuery().values()) {
if (outputActiveQuery) { if (outputActiveQuery) {
manager.getLogger().severe(String.format("#%s -> %s", value.getAction().getShortID(), value.getSQLContent())); manager.getLogger().warn(String.format("#%s -> %s", value.getAction().getShortID(), value.getSQLContent()));
manager.getLogger().severe(String.format("- execute at %s", TimeDateUtils.getTimeString(value.getExecuteTime()))); manager.getLogger().warn(String.format("- execute at %s", TimeDateUtils.getTimeString(value.getExecuteTime())));
} }
if (forceClose) value.close(); if (forceClose) value.close();
} }