mirror of
https://github.com/CarmJos/EasySQL.git
synced 2026-06-05 09:01:26 +08:00
Compare commits
66 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b4460f97a | |||
| f16b5f22e1 | |||
| 1a4b5c245a | |||
| 91d9891532 | |||
| fdb7af541c | |||
| b467743c2a | |||
| 3979c6d50c | |||
| 9bac83f739 | |||
| 96ccc604ed | |||
| 90db463f1d | |||
| 9248783a16 | |||
| 75e8f02228 | |||
| 02b8d561a8 | |||
| 19490d7508 | |||
| e8a01169d2 | |||
| 2e1df7c7f6 | |||
| 1812db3a16 | |||
| deb5de35a8 | |||
| e9ce0a769c | |||
| e98e9586ef | |||
| 6cd080210f | |||
| 20ac8f3908 | |||
| c079c98e3e | |||
| 18dd618c21 | |||
| 03e157d3d9 | |||
| a2d972621d | |||
| 903f3a5f93 | |||
| 44f9392e81 | |||
| 1ad196f04b | |||
| fd0a4e48ef | |||
| 14ee6ca1f2 | |||
| 6ba58b540f | |||
| db33e5e830 | |||
| 3fbc58acf7 | |||
| 0a6c8ae1a9 | |||
| f00e741035 | |||
| 50c2016820 | |||
| 71b0bb98d8 | |||
| ce3deb8f12 | |||
| b5a40b0f52 | |||
| ae5ca6cb23 | |||
| 866115db99 | |||
| 332540710d | |||
| ebe51dd9a3 | |||
| 0bdfe3d556 | |||
| e60c44aaae | |||
| 28f76ae50a | |||
| ffa0b74ccc | |||
| 4b766d7794 | |||
| f12fdc9c66 | |||
| 6115e6bf21 | |||
| 6356c0f723 | |||
| 5e15c3b308 | |||
| 46b21ead05 | |||
| 8a9e4b8d1c | |||
| f21095d08a | |||
| 6fd5988e09 | |||
| 962da8f6a1 | |||
| 68b5d071ae | |||
| 2de21a4658 | |||
| 3f26c9e12e | |||
| 0640f625a1 | |||
| 7df8a67282 | |||
| 37becc7b29 | |||
| 5df61a70c3 | |||
| 4ce5fba6f1 |
@@ -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/' }
|
||||
}
|
||||
```
|
||||
@@ -11,10 +11,9 @@ on:
|
||||
types: [ published ]
|
||||
|
||||
jobs:
|
||||
gh-deploy:
|
||||
name: "Publish Project (GitHub)"
|
||||
packages-deploy:
|
||||
name: "Publish Project (GitHub Packages)"
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- 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-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
|
||||
env:
|
||||
MAVEN_USERNAME: ${{ github.repository_owner }}
|
||||
MAVEN_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
|
||||
|
||||
- name: "Copy Javadoc to Location"
|
||||
run: |
|
||||
rm -rf docs
|
||||
mkdir -vp docs
|
||||
cp -vrf easysql-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:
|
||||
name: "Deploy Project (Central Repository)"
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: "Set up JDK"
|
||||
@@ -105,4 +57,82 @@ jobs:
|
||||
env:
|
||||
MAVEN_USERNAME: ${{ secrets.OSSRH_USER }}
|
||||
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
|
||||
@@ -6,6 +6,7 @@ name: Project Build & Tests
|
||||
on:
|
||||
# 支持手动触发构建
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
push:
|
||||
|
||||
jobs:
|
||||
|
||||
+1
-2
@@ -1,4 +1,3 @@
|
||||
/.idea/
|
||||
/target/
|
||||
/*/target/
|
||||
**/target/
|
||||
**.iml
|
||||
@@ -10,7 +10,7 @@
|
||||
# EasySQL
|
||||
|
||||
[](https://github.com/CarmJos/EasySQL/releases)
|
||||
[](https://opensource.org/licenses/GPL-3.0)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml)
|
||||
[](https://www.codefactor.io/repository/github/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) 。
|
||||
|
||||
### 依赖方式
|
||||
|
||||
@@ -55,9 +55,16 @@
|
||||
<name>Maven Central</name>
|
||||
<url>https://repo1.maven.org/maven2</url>
|
||||
</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>
|
||||
<name>GitHub Packages</name>
|
||||
<url>https://maven.pkg.github.com/CarmJos/EasySQL</url>
|
||||
@@ -141,8 +148,11 @@ repositories {
|
||||
|
||||
// 采用Maven中心库,安全稳定,但版本更新需要等待同步
|
||||
mavenCentral()
|
||||
|
||||
// 采用github依赖库,实时更新,但需要配置 (推荐)
|
||||
|
||||
// 采用github的repo分支依赖,实时更新。 (推荐)
|
||||
maven { url 'https://github.com/CarmJos/EasySQL/blob/repo/' }
|
||||
|
||||
// 采用github依赖库,安全稳定,但需要配置
|
||||
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) 开源协议。
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
<parent>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<version>0.3.7</version>
|
||||
<version>0.3.18</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<maven.compiler.source>${jdk.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${jdk.version}</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
</properties>
|
||||
@@ -52,6 +52,14 @@
|
||||
<url>https://github.com/CarmJos/EasySQL/actions/workflows/maven.yml</url>
|
||||
</ciManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.36</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@@ -70,10 +78,6 @@
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLFunction;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* SQLAction 是用于承载SQL语句并进行处理、返回的基本类。
|
||||
*
|
||||
* <ul>
|
||||
* <li>同步执行 {@link #execute()}, {@link #execute(SQLFunction, SQLExceptionHandler)}
|
||||
* <br>同步执行方法中有会抛出异常的方法与不抛出异常的方法,
|
||||
* <br>若选择不抛出异常,则返回值可能为空,需要特殊处理。</li>
|
||||
*
|
||||
* <li>异步执行 {@link #executeAsync(SQLHandler, SQLExceptionHandler)}
|
||||
* <br>异步执行时将提供成功与异常两种处理方式
|
||||
* <br>可自行选择是否对数据或异常进行处理
|
||||
* <br>默认的异常处理器为 {@link #defaultExceptionHandler()}
|
||||
* <br>若有特殊需要,可通过{@link #setExceptionHandler(SQLExceptionHandler)} 方法修改默认的处理器</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param <T> 需要返回的类型
|
||||
* @author CarmJos
|
||||
* @since 0.0.1
|
||||
*/
|
||||
public interface SQLAction<T> {
|
||||
|
||||
/**
|
||||
* 得到该Action的UUID
|
||||
*
|
||||
* @return UUID
|
||||
*/
|
||||
@NotNull UUID getActionUUID();
|
||||
|
||||
/**
|
||||
* 得到短八位格式的UUID
|
||||
*
|
||||
* @return UUID(8)
|
||||
*/
|
||||
@NotNull String getShortID();
|
||||
|
||||
/**
|
||||
* 得到该Action的创建时间。
|
||||
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
|
||||
*
|
||||
* @return 创建时间 (毫秒)
|
||||
*/
|
||||
default long getCreateTime() {
|
||||
return getCreateTime(TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到该Action的创建时间
|
||||
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
|
||||
*
|
||||
* @param unit 时间单位
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getCreateTime(TimeUnit unit);
|
||||
|
||||
/**
|
||||
* 得到该Action所要执行的源SQL语句
|
||||
*
|
||||
* @return 源SQL语句
|
||||
*/
|
||||
@NotNull String getSQLContent();
|
||||
|
||||
/**
|
||||
* 得到该Action所要执行的源SQL语句列表。
|
||||
*
|
||||
* @return 源SQL语句列表
|
||||
*/
|
||||
default @NotNull List<String> getSQLContents() {
|
||||
return Collections.singletonList(getSQLContent());
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到承载该Action的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
@NotNull SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 执行该Action对应的SQL语句
|
||||
*
|
||||
* @return 指定数据类型
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@NotNull T execute() throws SQLException;
|
||||
|
||||
|
||||
/**
|
||||
* 执行语句并返回值
|
||||
*
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default T execute(@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(t -> t, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(function, null, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null,_ -> !null")
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable R defaultResult,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
try {
|
||||
return executeFunction(function, defaultResult);
|
||||
} catch (SQLException exception) {
|
||||
handleException(exceptionHandler, exception);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function) throws SQLException {
|
||||
return executeFunction(function, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try {
|
||||
R result = function.apply(execute());
|
||||
return result == null ? defaultResult : result;
|
||||
} catch (SQLException exception) {
|
||||
throw new SQLException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句,采用默认异常处理,无需返回值。
|
||||
*/
|
||||
default void executeAsync() {
|
||||
executeAsync(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
*/
|
||||
default void executeAsync(@Nullable SQLHandler<T> success) {
|
||||
executeAsync(success, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
* @param failure 异常处理器 默认为 {@link SQLAction#defaultExceptionHandler()}
|
||||
*/
|
||||
void executeAsync(@Nullable SQLHandler<T> success,
|
||||
@Nullable SQLExceptionHandler failure);
|
||||
|
||||
default void handleException(@Nullable SQLExceptionHandler handler, SQLException exception) {
|
||||
if (handler == null) handler = defaultExceptionHandler();
|
||||
handler.accept(exception, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取管理器提供的默认异常处理器。
|
||||
* 若未使用过 {@link #setExceptionHandler(SQLExceptionHandler)} 方法,
|
||||
* 则默认返回 {@link SQLExceptionHandler#detailed(Logger)} 。
|
||||
*
|
||||
* @return {@link SQLExceptionHandler}
|
||||
*/
|
||||
default SQLExceptionHandler defaultExceptionHandler() {
|
||||
return getManager().getExceptionHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定通用的异常处理器。
|
||||
* <br> 在使用 {@link #execute(SQLExceptionHandler)} 等相关方法时,若传入的处理器为null,则会采用此处理器。
|
||||
* <br> 若该方法传入参数为 null,则会使用 {@link #defaultExceptionHandler()} 。
|
||||
*
|
||||
* @param handler 异常处理器
|
||||
*/
|
||||
default void setExceptionHandler(@Nullable SQLExceptionHandler handler) {
|
||||
getManager().setExceptionHandler(handler);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* SQLBuilder 是用于构建SQL语句以生成SQLAction执行操作的中间类。
|
||||
* <br>其连接了{@link SQLManager} 与 {@link SQLAction} ,避免大量的代码堆积
|
||||
* <br>也是本接口的核心功能所在
|
||||
*
|
||||
* @author CarmJos
|
||||
*/
|
||||
public interface SQLBuilder {
|
||||
|
||||
static @NotNull String withBackQuote(@NotNull String str) {
|
||||
str = str.trim();
|
||||
return !str.isEmpty() && str.charAt(0) == '`' && str.charAt(str.length() - 1) == '`' ? str : "`" + str + "`";
|
||||
}
|
||||
|
||||
static @NotNull String withQuote(@NotNull String str) {
|
||||
str = str.trim();
|
||||
return !str.isEmpty() && str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'' ? str : "'" + str + "'";
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到承载该Builder的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
@NotNull SQLManager getManager();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.builder.*;
|
||||
import cc.carm.lib.easysql.api.function.SQLDebugHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* SQLManager 是EasySQL的核心类,用于管理数据库连接,提供数据库操作的方法。
|
||||
*
|
||||
* @author CarmJos
|
||||
*/
|
||||
public interface SQLManager {
|
||||
|
||||
Logger getLogger();
|
||||
|
||||
boolean isDebugMode();
|
||||
|
||||
/**
|
||||
* 设定是否启用调试模式。
|
||||
* 启用调试模式后,会在每次执行SQL语句时,调用 {@link #getDebugHandler()} 来输出调试信息。
|
||||
*
|
||||
* @param debugMode 是否启用调试模式
|
||||
*/
|
||||
void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode);
|
||||
|
||||
/**
|
||||
* 设定是否启用调试模式。
|
||||
* 启用调试模式后,会在每次执行SQL语句时,调用 {@link #getDebugHandler()} 来输出调试信息。
|
||||
*
|
||||
* @param enable 是否启用调试模式
|
||||
*/
|
||||
default void setDebugMode(boolean enable) {
|
||||
setDebugMode(() -> enable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取调试处理器,用于处理调试信息。
|
||||
*
|
||||
* @return {@link SQLDebugHandler}
|
||||
*/
|
||||
@NotNull SQLDebugHandler getDebugHandler();
|
||||
|
||||
/**
|
||||
* 设定调试处理器,默认为 {@link SQLDebugHandler#defaultHandler(Logger)} 。
|
||||
*
|
||||
* @param debugHandler {@link SQLDebugHandler}
|
||||
*/
|
||||
void setDebugHandler(@NotNull SQLDebugHandler debugHandler);
|
||||
|
||||
/**
|
||||
* 得到连接池源
|
||||
*
|
||||
* @return DataSource
|
||||
*/
|
||||
@NotNull DataSource getDataSource();
|
||||
|
||||
/**
|
||||
* 得到一个数据库连接实例
|
||||
*
|
||||
* @return Connection
|
||||
* @throws SQLException 见 {@link DataSource#getConnection()}
|
||||
*/
|
||||
@NotNull Connection getConnection() throws SQLException;
|
||||
|
||||
/**
|
||||
* 得到正使用的查询。
|
||||
*
|
||||
* @return 查询列表
|
||||
*/
|
||||
@NotNull Map<UUID, SQLQuery> getActiveQuery();
|
||||
|
||||
/**
|
||||
* 获取改管理器提供的默认异常处理器。
|
||||
* 若未使用过 {@link #setExceptionHandler(SQLExceptionHandler)} 方法,
|
||||
* 则默认返回 {@link SQLExceptionHandler#detailed(Logger)} 。
|
||||
*
|
||||
* @return {@link SQLExceptionHandler}
|
||||
*/
|
||||
@NotNull SQLExceptionHandler getExceptionHandler();
|
||||
|
||||
/**
|
||||
* 设定通用的异常处理器。
|
||||
* <br> 在使用 {@link SQLAction#execute(SQLExceptionHandler)} 等相关方法时,若传入的处理器为null,则会采用此处理器。
|
||||
* <br> 若该方法传入参数为 null,则会使用 {@link SQLExceptionHandler#detailed(Logger)} 。
|
||||
*
|
||||
* @param handler 异常处理器
|
||||
*/
|
||||
void setExceptionHandler(@Nullable SQLExceptionHandler handler);
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的SQL语句(多用于UPDATE、REPLACE、DELETE方法)
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @return 更新的行数
|
||||
* @see SQLUpdateAction
|
||||
*/
|
||||
@Nullable Long executeSQL(String sql);
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的预处理SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param params SQL语句中 ? 的对应参数
|
||||
* @return 更新的行数
|
||||
* @see PreparedSQLUpdateAction
|
||||
*/
|
||||
@Nullable Long executeSQL(String sql, Object[] params);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param paramsBatch SQL语句中对应?的参数组
|
||||
* @return 对应参数返回的行数
|
||||
* @see PreparedSQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Long> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch);
|
||||
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param moreSQL 更多SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
* @see SQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
*
|
||||
* @param sqlBatch SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch);
|
||||
|
||||
/**
|
||||
* 在库中创建一个表
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder createTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 对库中的某个表执行更改
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
TableAlterBuilder alterTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 新建一个查询
|
||||
*
|
||||
* @return {@link QueryBuilder}
|
||||
*/
|
||||
QueryBuilder createQuery();
|
||||
|
||||
/**
|
||||
* 创建一条插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建一条替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建更新操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link UpdateBuilder}
|
||||
*/
|
||||
UpdateBuilder createUpdate(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建删除操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link DeleteBuilder}
|
||||
*/
|
||||
DeleteBuilder createDelete(@NotNull String tableName);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.api.action.query.QueryAction;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* SQLQuery 是一个查询中间接口,用于查询操作的封装。
|
||||
*
|
||||
* @author CarmJos
|
||||
*/
|
||||
public interface SQLQuery extends AutoCloseable {
|
||||
|
||||
/**
|
||||
* 获取该查询创建的时间
|
||||
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
default long getExecuteTime() {
|
||||
return getExecuteTime(TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取该查询创建的时间
|
||||
* <br>注意,此处获得的时间非时间戳毫秒数,仅用于计算耗时。
|
||||
*
|
||||
* @param timeUnit 时间单位
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getExecuteTime(TimeUnit timeUnit);
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link QueryAction}
|
||||
*
|
||||
* @return {@link QueryAction} 或 {@link PreparedQueryAction}
|
||||
*/
|
||||
QueryAction getAction();
|
||||
|
||||
ResultSet getResultSet();
|
||||
|
||||
/**
|
||||
* 得到设定的SQL语句
|
||||
*
|
||||
* @return SQL语句
|
||||
*/
|
||||
String getSQLContent();
|
||||
|
||||
/**
|
||||
* 关闭所有内容
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
|
||||
Statement getStatement();
|
||||
|
||||
Connection getConnection();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.builder.*;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* SQLTable 基于 {@link TableCreateBuilder} 构建表,用于快速创建与该表相关的操作。
|
||||
* <ul>
|
||||
* <li>1. 调用 {@link SQLTable#of(String, String[])} 方法创建一个 SQLTable 对象;</li>
|
||||
* <li>2. 在应用初始化阶段调用 {@link SQLTable#create(SQLManager)} 方法初始化 SQLTable 对象;</li>
|
||||
* <li>3. 获取已创建的{@link SQLTable} 实例,直接调用对应方法进行关于表的相关操作。</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author CarmJos
|
||||
* @since 0.3.10
|
||||
*/
|
||||
public abstract class SQLTable {
|
||||
|
||||
public static @NotNull SQLTable of(@NotNull String tableName, @Nullable SQLHandler<TableCreateBuilder> table) {
|
||||
return new SQLTable(tableName) {
|
||||
@Override
|
||||
public boolean create(SQLManager sqlManager) throws SQLException {
|
||||
if (this.manager == null) this.manager = sqlManager;
|
||||
TableCreateBuilder tableBuilder = sqlManager.createTable(getTableName());
|
||||
if (table != null) table.accept(tableBuilder);
|
||||
return tableBuilder.build().executeFunction(l -> l > 0, false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static @NotNull SQLTable of(@NotNull String tableName, @NotNull String[] columns) {
|
||||
return of(tableName, columns, null);
|
||||
}
|
||||
|
||||
public static @NotNull SQLTable of(@NotNull String tableName,
|
||||
@NotNull String[] columns, @Nullable String tableSettings) {
|
||||
return of(tableName, builder -> {
|
||||
builder.setColumns(columns);
|
||||
if (tableSettings != null) builder.setTableSettings(tableSettings);
|
||||
});
|
||||
}
|
||||
|
||||
private final @NotNull String tableName;
|
||||
|
||||
protected SQLManager manager;
|
||||
|
||||
/**
|
||||
* 请调用 {@link SQLTable} 下的静态方法进行对象的初始化。
|
||||
*
|
||||
* @param tableName 该表的名称
|
||||
*/
|
||||
private SQLTable(@NotNull String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public @NotNull String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用指定 SQLManager 进行本示例的初始化。
|
||||
*
|
||||
* @param sqlManager {@link SQLManager}
|
||||
* @return 本表是否为首次创建
|
||||
* @throws SQLException 出现任何错误时抛出
|
||||
*/
|
||||
public abstract boolean create(SQLManager sqlManager) throws SQLException;
|
||||
|
||||
public @NotNull TableQueryBuilder createQuery(@NotNull SQLManager sqlManager) {
|
||||
return sqlManager.createQuery().inTable(getTableName());
|
||||
}
|
||||
|
||||
public @NotNull TableQueryBuilder createQuery() {
|
||||
return createQuery(this.manager);
|
||||
}
|
||||
|
||||
public @NotNull DeleteBuilder createDelete() {
|
||||
return createDelete(this.manager);
|
||||
}
|
||||
|
||||
public @NotNull DeleteBuilder createDelete(@NotNull SQLManager sqlManager) {
|
||||
return sqlManager.createDelete(getTableName());
|
||||
}
|
||||
|
||||
public @NotNull UpdateBuilder createUpdate() {
|
||||
return createUpdate(this.manager);
|
||||
}
|
||||
|
||||
public @NotNull UpdateBuilder createUpdate(@NotNull SQLManager sqlManager) {
|
||||
return sqlManager.createUpdate(getTableName());
|
||||
}
|
||||
|
||||
|
||||
public @NotNull InsertBuilder<PreparedSQLUpdateAction> createInsert() {
|
||||
return createInsert(this.manager);
|
||||
}
|
||||
|
||||
public @NotNull InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull SQLManager sqlManager) {
|
||||
return sqlManager.createInsert(getTableName());
|
||||
}
|
||||
|
||||
|
||||
public @NotNull InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch() {
|
||||
return createInsertBatch(this.manager);
|
||||
}
|
||||
|
||||
public @NotNull InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull SQLManager sqlManager) {
|
||||
return sqlManager.createInsertBatch(getTableName());
|
||||
}
|
||||
|
||||
|
||||
public @NotNull ReplaceBuilder<PreparedSQLUpdateAction> createReplace() {
|
||||
return createReplace(this.manager);
|
||||
}
|
||||
|
||||
public @NotNull ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull SQLManager sqlManager) {
|
||||
return sqlManager.createReplace(getTableName());
|
||||
}
|
||||
|
||||
|
||||
public @NotNull ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch() {
|
||||
return createReplaceBatch(this.manager);
|
||||
}
|
||||
|
||||
public @NotNull ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull SQLManager sqlManager) {
|
||||
return sqlManager.createReplaceBatch(getTableName());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Long>> {
|
||||
|
||||
/**
|
||||
* 设定多组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param allParams 所有参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams);
|
||||
|
||||
/**
|
||||
* 添加一组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param params 参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction addParamsBatch(Object... params);
|
||||
|
||||
/**
|
||||
* 设定自增主键的序列
|
||||
*
|
||||
* @param keyColumnIndex 自增主键的序列
|
||||
* <br>若该值 > 0,则 {@link #execute()} 返回自增主键数值
|
||||
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
* @see #setReturnGeneratedKeys(boolean)
|
||||
*/
|
||||
@Deprecated
|
||||
default PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex) {
|
||||
return setReturnGeneratedKeys(keyColumnIndex > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作返回自增键序列。
|
||||
*
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
default PreparedSQLUpdateBatchAction returnGeneratedKeys() {
|
||||
return setReturnGeneratedKeys(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作是否返回自增键序列。
|
||||
*
|
||||
* @param returnGeneratedKey 是否返回自增键序列
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey);
|
||||
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@ package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
public interface SQLUpdateAction extends SQLAction<Integer> {
|
||||
public interface SQLUpdateAction extends SQLAction<Long> {
|
||||
|
||||
/**
|
||||
* 设定自增主键的序列
|
||||
@@ -0,0 +1,27 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
|
||||
|
||||
/**
|
||||
* 添加一条批量执行的SQL语句
|
||||
*
|
||||
* @param sql SQL语句
|
||||
* @return {@link SQLUpdateBatchAction}
|
||||
*/
|
||||
SQLUpdateBatchAction addBatch(@NotNull String sql);
|
||||
|
||||
@Override
|
||||
default @NotNull String getSQLContent() {
|
||||
return getSQLContents().get(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull List<String> getSQLContents();
|
||||
|
||||
}
|
||||
+9
-11
@@ -32,16 +32,14 @@ import java.sql.SQLException;
|
||||
*/
|
||||
public interface QueryAction extends SQLAction<SQLQuery> {
|
||||
|
||||
@Override
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> @Nullable R executeFunction(@NotNull SQLFunction<@NotNull SQLQuery, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try (SQLQuery value = execute()) {
|
||||
R result = function.apply(value);
|
||||
return result == null ? defaultResult : result;
|
||||
} catch (SQLException exception) {
|
||||
throw new SQLException(exception);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> @Nullable R executeFunction(@NotNull SQLFunction<@NotNull SQLQuery, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try (SQLQuery value = execute()) {
|
||||
R result = function.apply(value);
|
||||
return result == null ? defaultResult : result;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+1
-3
@@ -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);
|
||||
|
||||
default B addCondition(@NotNull String columnName, @Nullable Object queryValue) {
|
||||
return addCondition(columnName, "=", queryValue);
|
||||
}
|
||||
B addCondition(@NotNull String columnName, @Nullable Object queryValue);
|
||||
|
||||
B addCondition(@NotNull String[] columnNames, @Nullable Object[] queryValues);
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
public interface DeleteBuilder extends ConditionalBuilder<DeleteBuilder, SQLAction<Integer>> {
|
||||
public interface DeleteBuilder extends ConditionalBuilder<DeleteBuilder, SQLAction<Long>> {
|
||||
|
||||
String getTableName();
|
||||
String getTableName();
|
||||
|
||||
}
|
||||
+5
-5
@@ -14,12 +14,12 @@ import java.util.List;
|
||||
*/
|
||||
public interface ReplaceBuilder<T extends SQLAction<?>> {
|
||||
|
||||
String getTableName();
|
||||
String getTableName();
|
||||
|
||||
T setColumnNames(List<String> columnNames);
|
||||
T setColumnNames(List<String> columnNames);
|
||||
|
||||
default T setColumnNames(String... columnNames) {
|
||||
return setColumnNames(columnNames == null ? null : Arrays.asList(columnNames));
|
||||
}
|
||||
default T setColumnNames(String... columnNames) {
|
||||
return setColumnNames(columnNames == null ? null : Arrays.asList(columnNames));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface TableAlterBuilder extends SQLBuilder {
|
||||
|
||||
SQLAction<Long> renameTo(@NotNull String newTableName);
|
||||
|
||||
SQLAction<Long> changeComment(@NotNull String newTableComment);
|
||||
|
||||
SQLAction<Long> setAutoIncrementIndex(int index);
|
||||
|
||||
SQLAction<Long> addIndex(@NotNull IndexType indexType, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
/**
|
||||
* 为该表移除一个索引
|
||||
*
|
||||
* @param indexName 索引名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Long> dropIndex(@NotNull String indexName);
|
||||
|
||||
/**
|
||||
* 为该表移除一个外键
|
||||
*
|
||||
* @param keySymbol 外键名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Long> dropForeignKey(@NotNull String keySymbol);
|
||||
|
||||
/**
|
||||
* 为该表移除主键(须添加新主键)
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Long> dropPrimaryKey();
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
default SQLAction<Long> addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return addColumn(columnName, settings, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @param afterColumn 该列增添到哪个列的后面,
|
||||
* <p> 该参数若省缺则放于最后一行
|
||||
* <p> 若为 "" 则置于首行。
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Long> addColumn(@NotNull String columnName, @NotNull String settings, @Nullable String afterColumn);
|
||||
|
||||
SQLAction<Long> renameColumn(@NotNull String columnName, @NotNull String newName);
|
||||
|
||||
SQLAction<Long> modifyColumn(@NotNull String columnName, @NotNull String settings);
|
||||
|
||||
default SQLAction<Long> modifyColumn(@NotNull String columnName, @NotNull String columnSettings, @NotNull String afterColumn) {
|
||||
return modifyColumn(columnName, columnSettings + " AFTER `" + afterColumn + "`");
|
||||
}
|
||||
|
||||
SQLAction<Long> removeColumn(@NotNull String columnName);
|
||||
|
||||
SQLAction<Long> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue);
|
||||
|
||||
SQLAction<Long> removeColumnDefault(@NotNull String columnName);
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param primary 是否为主键,若否则只为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default SQLAction<Long> addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean primary, boolean unsigned) {
|
||||
return addColumn(columnName,
|
||||
(numberType == null ? NumberType.INT : numberType).name()
|
||||
+ (unsigned ? " UNSIGNED " : " ")
|
||||
+ "NOT NULL AUTO_INCREMENT " + (primary ? "PRIMARY KEY" : "UNIQUE KEY"),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Long> addAutoIncrementColumn(@NotNull String columnName, @NotNull NumberType numberType) {
|
||||
return addAutoIncrementColumn(columnName, numberType, false, true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Long> addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withQuote;
|
||||
|
||||
|
||||
public interface TableCreateBuilder extends SQLBuilder {
|
||||
|
||||
/**
|
||||
* 将现有条件构建完整的SQL语句用于执行。
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLUpdateAction build();
|
||||
|
||||
@NotNull String getTableName();
|
||||
|
||||
/**
|
||||
* 得到表的设定。
|
||||
* <p> 若未使用 {@link #setTableSettings(String)} 方法则会采用 {@link #defaultTablesSettings()} 。
|
||||
*
|
||||
* @return TableSettings
|
||||
*/
|
||||
@NotNull String getTableSettings();
|
||||
|
||||
TableCreateBuilder setTableSettings(@NotNull String settings);
|
||||
|
||||
/**
|
||||
* 设定表的标注,一般用于解释该表的作用。
|
||||
*
|
||||
* @param comment 表标注
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setTableComment(@Nullable String comment);
|
||||
|
||||
/**
|
||||
* 直接设定表的所有列信息
|
||||
*
|
||||
* @param columns 列的相关信息 (包括列设定)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setColumns(@NotNull String... columns);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param column 列的相关信息
|
||||
* <br>如 `uuid` VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addColumn(@NotNull String column);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
Objects.requireNonNull(columnName, "columnName could not be null");
|
||||
return addColumn(withBackQuote(columnName) + " " + settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @param comments 列的注解,用于解释该列数据的作用
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings, @NotNull String comments) {
|
||||
return addColumn(columnName, settings + " COMMENT " + withQuote(comments));
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean asPrimaryKey, boolean unsigned);
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName,
|
||||
boolean asPrimaryKey, boolean unsigned) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT, asPrimaryKey, unsigned);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, boolean asPrimaryKey) {
|
||||
return addAutoIncrementColumn(columnName, asPrimaryKey, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param columnName 索引包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder setIndex(@NotNull String columnName,
|
||||
@NotNull IndexType type) {
|
||||
return setIndex(type, null, columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param indexName 索引名称,缺省时将根据第一个索引列赋一个名称
|
||||
* @param columnName 索引包含的列
|
||||
* @param moreColumns 联合索引需要包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setIndex(@NotNull IndexType type, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定自参照外键(即自参照完整性)。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignColumn 外键关联表中对应的关联列,必须为目标表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, getTableName(), foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, null, foreignTable, foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, constraintName, foreignTable, foreignColumn, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @param updateRule 在外键被更新时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @param deleteRule 在外键被删除时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn,
|
||||
@Nullable ForeignKeyRule updateRule, @Nullable ForeignKeyRule deleteRule);
|
||||
|
||||
default String defaultTablesSettings() {
|
||||
return "ENGINE=InnoDB DEFAULT CHARSET=utf8";
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, SQLAction<Integer>> {
|
||||
public interface UpdateBuilder extends ConditionalBuilder<UpdateBuilder, SQLAction<Long>> {
|
||||
|
||||
String getTableName();
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum ForeignKeyRule {
|
||||
|
||||
/**
|
||||
* 啥也不做
|
||||
* <p>注意: 在Mysql中该选项实际上等同于采用默认的 {@link #RESTRICT} 设定!
|
||||
*/
|
||||
NO_ACTION("NO ACTION"),
|
||||
|
||||
/**
|
||||
* 拒绝删除要求,直到使用删除键值的辅助表被手工删除,并且没有参照时(这是默认设置,也是最安全的设置)
|
||||
*/
|
||||
RESTRICT("RESTRICT"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用NULL值替换(只能用于已标记为NOT NULL的字段)
|
||||
*/
|
||||
SET_NULL("SET NULL"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用默认值替换(只能用于设定了DEFAULT的字段)
|
||||
*/
|
||||
SET_DEFAULT("SET DEFAULT"),
|
||||
|
||||
/**
|
||||
* <b>级联删除</b>,删除包含与已删除键值有参照关系的所有记录
|
||||
*/
|
||||
CASCADE("CASCADE");
|
||||
|
||||
final String ruleName;
|
||||
|
||||
ForeignKeyRule(String ruleName) {
|
||||
this.ruleName = ruleName;
|
||||
}
|
||||
|
||||
public String getRuleName() {
|
||||
return ruleName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum IndexType {
|
||||
|
||||
|
||||
/**
|
||||
* <b>普通索引</b>(由关键字KEY或INDEX定义的索引)的唯一任务是加快对数据的访问速度。
|
||||
* <br> 因此,应该只为那些最经常出现在查询条件(WHERE column=)或排序条件(ORDER BY column)中的数据列创建索引。
|
||||
* <br> 只要有可能,就应该选择一个数据最整齐、最紧凑的数据列(如一个整数类型的数据列)来创建索引。
|
||||
*/
|
||||
INDEX("INDEX"),
|
||||
|
||||
|
||||
/**
|
||||
* <b>唯一索引</b> 是在表上一个或者多个字段组合建立的索引,这个或者这些字段的值组合起来在表中不可以重复,用于保证数据的唯一性。
|
||||
*/
|
||||
UNIQUE_KEY("UNIQUE KEY"),
|
||||
|
||||
/**
|
||||
* <b>主键索引</b> 是唯一索引的特定类型。表中创建主键时自动创建的索引 。一个表只能建立一个主索引。
|
||||
*/
|
||||
PRIMARY_KEY("PRIMARY KEY"),
|
||||
|
||||
/**
|
||||
* <b>全文索引</b> 主要用来查找文本中的关键字,而不是直接与索引中的值相比较。
|
||||
* <br> 请搭配 MATCH 等语句使用,而不是使用 WHERE - LIKE 。
|
||||
* <br> 全文索引只可用于 CHAR、 VARCHAR 与 TEXT 系列类型。
|
||||
*/
|
||||
FULLTEXT_INDEX("FULLTEXT");
|
||||
|
||||
|
||||
final String name;
|
||||
|
||||
IndexType(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -2,10 +2,10 @@ package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum NumberType {
|
||||
|
||||
TINYINT,
|
||||
SMALLINT,
|
||||
MEDIUMINT,
|
||||
INT,
|
||||
BIGINT
|
||||
TINYINT,
|
||||
SMALLINT,
|
||||
MEDIUMINT,
|
||||
INT,
|
||||
BIGINT
|
||||
|
||||
}
|
||||
@@ -0,0 +1,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("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/**
|
||||
* 异常处理器。
|
||||
* <br> 在使用 {@link SQLAction#execute(SQLExceptionHandler)} 等相关方法时,
|
||||
* 如果发生异常,则会调用错误处理器进行错误内容的输出提示。
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface SQLExceptionHandler extends BiConsumer<SQLException, SQLAction<?>> {
|
||||
|
||||
/**
|
||||
* 默认的异常处理器,将详细的输出相关错误与错误来源。
|
||||
*
|
||||
* @param logger 用于输出错误信息的Logger。
|
||||
* @return 输出详细信息的错误处理器。
|
||||
*/
|
||||
static SQLExceptionHandler detailed(Logger logger) {
|
||||
return (exception, sqlAction) -> {
|
||||
logger.error("Error occurred while executing SQL: ");
|
||||
int i = 1;
|
||||
for (String content : sqlAction.getSQLContents()) {
|
||||
logger.error(String.format("#%d {%s}", i, content));
|
||||
i++;
|
||||
}
|
||||
exception.printStackTrace();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* “安静“ 的错误处理器,发生错误什么都不做。
|
||||
* 强烈不建议把此处理器作为默认处理器使用!
|
||||
*
|
||||
* @return 无输出的处理器。
|
||||
*/
|
||||
static SQLExceptionHandler silent() {
|
||||
return (exception, sqlAction) -> {
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -8,7 +8,7 @@ import java.sql.SQLException;
|
||||
@FunctionalInterface
|
||||
public interface SQLFunction<T, R> {
|
||||
|
||||
@Nullable
|
||||
R apply(@NotNull T t) throws SQLException;
|
||||
@Nullable
|
||||
R apply(@NotNull T t) throws SQLException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Objects;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface SQLHandler<T> {
|
||||
|
||||
void accept(@NotNull T t) throws SQLException;
|
||||
|
||||
@NotNull
|
||||
@Contract(pure = true)
|
||||
default SQLHandler<T> andThen(@NotNull SQLHandler<? super T> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (T t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public class TimeDateUtils {
|
||||
public static DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
public static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
public TimeDateUtils() {
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cc.carm.lib.easysql.api.util;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class UUIDUtil {
|
||||
|
||||
private static final Pattern COMPILE = Pattern.compile("-", Pattern.LITERAL);
|
||||
|
||||
public static UUID random() {
|
||||
return UUID.randomUUID();
|
||||
}
|
||||
|
||||
public static String toString(UUID uuid, boolean withDash) {
|
||||
if (withDash) return uuid.toString();
|
||||
else return COMPILE.matcher(uuid.toString()).replaceAll(Matcher.quoteReplacement(""));
|
||||
}
|
||||
|
||||
public static UUID toUUID(String s) {
|
||||
if (s.length() == 36) {
|
||||
return UUID.fromString(s);
|
||||
} else {
|
||||
return UUID.fromString(s.substring(0, 8) + '-' + s.substring(8, 12) + '-' + s.substring(12, 16) + '-' + s.substring(16, 20) + '-' + s.substring(20));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,18 +5,19 @@
|
||||
<parent>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<version>0.3.7</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
<version>0.3.18</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<maven.compiler.source>${jdk.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${jdk.version}</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
<maven.javadoc.skip>true</maven.javadoc.skip>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
|
||||
<log4j.version>2.17.2</log4j.version>
|
||||
</properties>
|
||||
|
||||
<artifactId>easysql-demo</artifactId>
|
||||
@@ -64,6 +65,43 @@
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<!--项目地址 https://github.com/brettwooldridge/HikariCP/ -->
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>4.0.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>2.1.212</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -76,6 +114,10 @@
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+31
-4
@@ -1,5 +1,6 @@
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.api.SQLTable;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
@@ -43,6 +44,33 @@ public class EasySQLDemo {
|
||||
.build().execute(null /* 不处理错误 */);
|
||||
}
|
||||
|
||||
public void useSQLTable(SQLManager sqlManager) {
|
||||
SQLTable tags = SQLTable.of("servers", table -> {
|
||||
table.addAutoIncrementColumn("id", true);
|
||||
table.addColumn("user", "INT UNSIGNED NOT NULL");
|
||||
table.addColumn("content", "TEXT NOT NULL");
|
||||
table.addColumn("time", "DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
|
||||
|
||||
table.addForeignKey(
|
||||
"user", "fk_user_tags",
|
||||
"users", "id",
|
||||
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
|
||||
);
|
||||
|
||||
});
|
||||
|
||||
try {
|
||||
tags.create(sqlManager);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
tags.createQuery().addCondition("id", 5).build()
|
||||
.executeAsync(success -> {
|
||||
System.out.println("success!");
|
||||
});
|
||||
}
|
||||
|
||||
public void alertTable(SQLManager sqlManager) {
|
||||
// 同步更新表
|
||||
sqlManager.alterTable("users")
|
||||
@@ -106,7 +134,7 @@ public class EasySQLDemo {
|
||||
|
||||
public void sqlInsert(SQLManager sqlManager) {
|
||||
// 同步SQL插入 (不使用try-catch的情况下,返回的数值可能为空。)
|
||||
Integer id = sqlManager.createInsert("users")
|
||||
Long id = sqlManager.createInsert("users")
|
||||
.setColumnNames("username", "phone", "email", "registerTime")
|
||||
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
|
||||
.setReturnGeneratedKey(true)// 设定在后续返回自增主键
|
||||
@@ -117,11 +145,10 @@ public class EasySQLDemo {
|
||||
});
|
||||
|
||||
try {
|
||||
Integer userID = sqlManager.createInsert("users")
|
||||
Long userID = sqlManager.createInsert("users")
|
||||
.setColumnNames("username", "phone", "email", "registerTime")
|
||||
.setParams("CarmJos", "18888888888", "carm@carm.cc", TimeDateUtils.getCurrentTime())
|
||||
.setReturnGeneratedKey(true)
|
||||
.execute();
|
||||
.returnGeneratedKey().execute();
|
||||
|
||||
System.out.println("新用户的ID为 " + userID);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package cc.carm.lib.easysql;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.tests.*;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class EasySQLTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void onTest() {
|
||||
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setDriverClassName("org.h2.Driver");
|
||||
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=MYSQL;");
|
||||
|
||||
SQLManager sqlManager = new SQLManagerImpl(new HikariDataSource(config), "test");
|
||||
sqlManager.setDebugMode(true);
|
||||
|
||||
print("加载测试类...");
|
||||
Set<TestHandler> tests = new LinkedHashSet<>();
|
||||
tests.add(new TableCreateTest());
|
||||
// tests.add(new TableAlterTest());
|
||||
// tests.add(new TableRenameTest());
|
||||
// tests.add(new QueryNotCloseTest());
|
||||
tests.add(new QueryCloseTest());
|
||||
tests.add(new SQLUpdateBatchTests());
|
||||
tests.add(new SQLUpdateReturnKeysTest());
|
||||
tests.add(new QueryFunctionTest());
|
||||
// tests.add(new DeleteTest());
|
||||
|
||||
print("准备进行测试...");
|
||||
|
||||
int index = 1;
|
||||
int success = 0;
|
||||
|
||||
for (TestHandler currentTest : tests) {
|
||||
print("-------------------------------------------------");
|
||||
if (currentTest.executeTest(index, sqlManager)) {
|
||||
success++;
|
||||
}
|
||||
|
||||
index++;
|
||||
try {
|
||||
Thread.sleep(1000L);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
print(" ");
|
||||
print("全部测试执行完毕,成功 %s 个,失败 %s 个。",
|
||||
success, (tests.size() - success)
|
||||
);
|
||||
|
||||
if (sqlManager.getDataSource() instanceof HikariDataSource) {
|
||||
//Close bee connection pool
|
||||
((HikariDataSource) sqlManager.getDataSource()).close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static void print(@NotNull String format, Object... params) {
|
||||
System.out.printf((format) + "%n", params);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package cc.carm.lib.easysql;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public abstract class TestHandler {
|
||||
|
||||
protected static void print(@NotNull String format, Object... params) {
|
||||
EasySQLTest.print(format, params);
|
||||
}
|
||||
|
||||
@ApiStatus.OverrideOnly
|
||||
public abstract void onTest(SQLManager sqlManager) throws SQLException;
|
||||
|
||||
public boolean executeTest(int index, SQLManager sqlManager) {
|
||||
String testName = getClass().getSimpleName();
|
||||
|
||||
print(" #%s 测试 @%s 开始", index, testName);
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
onTest(sqlManager);
|
||||
print(" #%s 测试 @%s 成功,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
print(" #%s 测试 @%s 失败,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
exception.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class DeleteTest extends TestHandler {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
|
||||
System.out.println("change(s): " + sqlManager.createDelete("test_user_table")
|
||||
.addCondition("id", ">", 5)
|
||||
.addNotNullCondition("username")
|
||||
.build().execute());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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.SQLQuery;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryCloseTest extends TestHandler {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
try (SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute()) {
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.printf(
|
||||
"id: %d username: %s%n",
|
||||
resultSet.getInt("id"),
|
||||
resultSet.getString("username")
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(500L);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryFunctionTest extends TestHandler {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
Integer id_1 = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(1)
|
||||
.build().executeFunction(query -> {
|
||||
try {
|
||||
Thread.sleep(1000L);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
if (!query.getResultSet().next()) return -1;
|
||||
else return query.getResultSet().getInt("id");
|
||||
});
|
||||
|
||||
System.out.println("id (ps): " + id_1);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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.SQLQuery;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
public class QueryNotCloseTest extends TestHandler {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute();
|
||||
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.printf("id: %d username: %s%n", resultSet.getInt("id"), resultSet.getString("username"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SQLUpdateBatchTests extends TestHandler {
|
||||
|
||||
|
||||
protected static List<Object[]> generateParams() {
|
||||
return IntStream.range(0, 5).mapToObj(i -> generateParam()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected static Object[] generateParam() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
return new Object[]{uuid, uuid.toString().substring(0, 5), (int) (Math.random() * 50)};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
List<Long> updates = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.execute();
|
||||
|
||||
System.out.println("changes " + Arrays.toString(updates.toArray()));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLUpdateReturnKeysTest extends SQLUpdateBatchTests {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
List<Long> generatedKeys = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.returnGeneratedKeys()
|
||||
.execute();
|
||||
|
||||
System.out.println("generated " + Arrays.toString(generatedKeys.toArray()));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableAlterTest extends TestHandler {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 修改 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test", "VARCHAR(16) NOT NULL")
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test2", "VARCHAR(16) NOT NULL", "username")
|
||||
.execute();
|
||||
|
||||
|
||||
print(" 修改 test_user_info");
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addAutoIncrementColumn("num", NumberType.BIGINT, false, true)
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addColumn("a", "VARCHAR(16) NOT NULL", "")
|
||||
.execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableCreateTest extends TestHandler {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 创建 test_user_table");
|
||||
sqlManager.createTable("test_user_table")
|
||||
.addAutoIncrementColumn("id")
|
||||
.addColumn("uuid", "VARCHAR(36) NOT NULL", "用户UUID")
|
||||
.addColumn("username", "VARCHAR(16) NOT NULL", "用户名")
|
||||
.addColumn("age", "TINYINT DEFAULT 0 NOT NULL", "年龄")
|
||||
|
||||
.setIndex("uuid", IndexType.UNIQUE_KEY)
|
||||
.build().execute();
|
||||
|
||||
print(" 创建 test_user_info");
|
||||
sqlManager.createTable("test_user_info")
|
||||
.addColumn("uid", "INT UNSIGNED NOT NULL")
|
||||
.addColumn("info", "TEXT", "相关信息")
|
||||
.addForeignKey("uid", "user",
|
||||
"test_user_table", "id",
|
||||
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
|
||||
)
|
||||
.build().execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package cc.carm.lib.easysql.tests;
|
||||
|
||||
import cc.carm.lib.easysql.TestHandler;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableRenameTest extends TestHandler {
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
print(" 重命名 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.renameTo("test_user_table2")
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN" packages="cc.carm.lib.easysql">
|
||||
<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%n"/>
|
||||
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg{nolookups}%n"/>
|
||||
<Policies>
|
||||
<TimeBasedTriggeringPolicy/>
|
||||
<OnStartupTriggeringPolicy/>
|
||||
@@ -13,14 +13,14 @@
|
||||
</RollingRandomAccessFile>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<root level="info">
|
||||
<Root level="info">
|
||||
<filters>
|
||||
<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY" onMismatch="NEUTRAL"/>
|
||||
<RegexFilter regex=".*\$\{[^}]*\}.*" onMatch="DENY" onMismatch="NEUTRAL"/>
|
||||
</filters>
|
||||
<!-- <AppenderRef ref="WINDOWS_COMPAT" level="info"/>-->
|
||||
<AppenderRef ref="File"/>
|
||||
<appender-ref ref="Console"/>
|
||||
</root>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
|
||||
@@ -1,212 +0,0 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLFunction;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.api.function.defaults.DefaultSQLExceptionHandler;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* SQLAction 是用于承载SQL语句并进行处理、返回的基本类。
|
||||
*
|
||||
* <ul>
|
||||
* <li>同步执行 {@link #execute()}, {@link #execute(SQLFunction, SQLExceptionHandler)}
|
||||
* <br>同步执行方法中有会抛出异常的方法与不抛出异常的方法,
|
||||
* <br>若选择不抛出异常,则返回值可能为空,需要特殊处理。</li>
|
||||
*
|
||||
* <li>异步执行 {@link #executeAsync(SQLHandler, SQLExceptionHandler)}
|
||||
* <br>异步执行时将提供成功与异常两种处理方式
|
||||
* <br>可自行选择是否对数据或异常进行处理
|
||||
* <br>默认的异常处理器为 {@link #defaultExceptionHandler()}
|
||||
* <br>若有特殊需要,可通过{@link #setExceptionHandler(SQLExceptionHandler)} 方法修改默认的处理器</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param <T> 需要返回的类型
|
||||
* @author CarmJos
|
||||
* @since 0.0.1
|
||||
*/
|
||||
public interface SQLAction<T> {
|
||||
|
||||
/**
|
||||
* 得到该Action的UUID
|
||||
*
|
||||
* @return UUID
|
||||
*/
|
||||
@NotNull UUID getActionUUID();
|
||||
|
||||
/**
|
||||
* 得到短八位格式的UUID
|
||||
*
|
||||
* @return UUID(8)
|
||||
*/
|
||||
@NotNull String getShortID();
|
||||
|
||||
/**
|
||||
* 得到该Action的创建时间
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getCreateTime();
|
||||
|
||||
/**
|
||||
* 得到该Action所要执行的源SQL语句
|
||||
*
|
||||
* @return 源SQL语句
|
||||
*/
|
||||
@NotNull String getSQLContent();
|
||||
|
||||
/**
|
||||
* 得到承载该Action的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
@NotNull SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 执行该Action对应的SQL语句
|
||||
*
|
||||
* @return 指定数据类型
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@NotNull T execute() throws SQLException;
|
||||
|
||||
|
||||
/**
|
||||
* 执行语句并返回值
|
||||
*
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default T execute(@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(t -> t, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
return execute(function, null, exceptionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param exceptionHandler 异常处理器 默认为 {@link #defaultExceptionHandler()}
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null,_ -> !null")
|
||||
default <R> R execute(@NotNull SQLFunction<T, R> function,
|
||||
@Nullable R defaultResult,
|
||||
@Nullable SQLExceptionHandler exceptionHandler) {
|
||||
try {
|
||||
return executeFunction(function, defaultResult);
|
||||
} catch (SQLException exception) {
|
||||
handleException(exceptionHandler, exception);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function) throws SQLException {
|
||||
return executeFunction(function, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行语句并处理返回值
|
||||
*
|
||||
* @param function 处理方法
|
||||
* @param defaultResult 默认结果,若处理后的结果为null,则返回该值
|
||||
* @param <R> 需要返回的内容
|
||||
* @return 指定类型数据
|
||||
* @throws SQLException 当SQL操作出现问题时抛出
|
||||
*/
|
||||
@Nullable
|
||||
@Contract("_,!null -> !null")
|
||||
default <R> R executeFunction(@NotNull SQLFunction<@NotNull T, R> function,
|
||||
@Nullable R defaultResult) throws SQLException {
|
||||
try {
|
||||
R result = function.apply(execute());
|
||||
return result == null ? defaultResult : result;
|
||||
} catch (SQLException exception) {
|
||||
throw new SQLException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句,采用默认异常处理,无需返回值。
|
||||
*/
|
||||
default void executeAsync() {
|
||||
executeAsync(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
*/
|
||||
default void executeAsync(@Nullable SQLHandler<T> success) {
|
||||
executeAsync(success, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行SQL语句
|
||||
*
|
||||
* @param success 成功时的操作
|
||||
* @param failure 异常处理器 默认为 {@link SQLAction#defaultExceptionHandler()}
|
||||
*/
|
||||
void executeAsync(@Nullable SQLHandler<T> success,
|
||||
@Nullable SQLExceptionHandler failure);
|
||||
|
||||
default void handleException(@Nullable SQLExceptionHandler handler, SQLException exception) {
|
||||
if (handler == null) handler = defaultExceptionHandler();
|
||||
handler.accept(exception, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认的异常处理器
|
||||
*
|
||||
* @return {@link DefaultSQLExceptionHandler#get(Logger)}
|
||||
* @see DefaultSQLExceptionHandler
|
||||
*/
|
||||
default SQLExceptionHandler defaultExceptionHandler() {
|
||||
return DefaultSQLExceptionHandler.get(getManager().getLogger());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定通用的异常处理器。
|
||||
* <br> 在使用 {@link #execute(SQLExceptionHandler)} 等相关方法时,若传入的处理器为null,则会采用此处理器。
|
||||
* <br> 若该方法传入参数为 null,则会使用 {@link #defaultExceptionHandler()} 。
|
||||
*
|
||||
* @param handler 异常处理器
|
||||
*/
|
||||
default void setExceptionHandler(@Nullable SQLExceptionHandler handler) {
|
||||
DefaultSQLExceptionHandler.setCustomHandler(handler);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* SQLBuilder 是用于构建SQL语句以生成SQLAction执行操作的中间类。
|
||||
* <br>其连接了{@link SQLManager} 与 {@link SQLAction} ,避免大量的代码堆积
|
||||
* <br>也是本接口的核心功能所在
|
||||
*
|
||||
* @author CarmJos
|
||||
*/
|
||||
public interface SQLBuilder {
|
||||
|
||||
/**
|
||||
* 得到承载该Builder的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
@NotNull SQLManager getManager();
|
||||
|
||||
|
||||
static @NotNull String withBackQuote(@NotNull String str) {
|
||||
str = str.trim();
|
||||
return str.startsWith("`") && str.endsWith("`") ? str : "`" + str + "`";
|
||||
}
|
||||
|
||||
static @NotNull String withQuote(@NotNull String str) {
|
||||
str = str.trim();
|
||||
return str.startsWith("'") && str.endsWith("'") ? str : "'" + str + "'";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.builder.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public interface SQLManager {
|
||||
|
||||
Logger getLogger();
|
||||
|
||||
boolean isDebugMode();
|
||||
|
||||
void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode);
|
||||
|
||||
default void setDebugMode(boolean enable) {
|
||||
setDebugMode(() -> enable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到连接池源
|
||||
*
|
||||
* @return DataSource
|
||||
*/
|
||||
@NotNull DataSource getDataSource();
|
||||
|
||||
/**
|
||||
* 得到一个数据库连接实例
|
||||
*
|
||||
* @return Connection
|
||||
* @throws SQLException 见 {@link DataSource#getConnection()}
|
||||
*/
|
||||
@NotNull Connection getConnection() throws SQLException;
|
||||
|
||||
/**
|
||||
* 得到正使用的查询。
|
||||
*
|
||||
* @return 查询列表
|
||||
*/
|
||||
@NotNull Map<UUID, SQLQuery> getActiveQuery();
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的SQL语句(多用于UPDATE、REPLACE、DELETE方法)
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @return 更新的行数
|
||||
* @see SQLUpdateAction
|
||||
*/
|
||||
@Nullable Integer executeSQL(String sql);
|
||||
|
||||
/**
|
||||
* 执行一条不需要返回结果的预处理SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param params SQL语句中 ? 的对应参数
|
||||
* @return 更新的行数
|
||||
* @see PreparedSQLUpdateAction
|
||||
*/
|
||||
@Nullable Integer executeSQL(String sql, Object[] params);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL更改(UPDATE、REPLACE、DELETE)
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param paramsBatch SQL语句中对应?的参数组
|
||||
* @return 对应参数返回的行数
|
||||
* @see PreparedSQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch);
|
||||
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
* 该方法使用 Statement 实现,请注意SQL注入风险!
|
||||
*
|
||||
* @param sql SQL语句内容
|
||||
* @param moreSQL 更多SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
* @see SQLUpdateBatchAction
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL);
|
||||
|
||||
/**
|
||||
* 执行多条不需要返回结果的SQL。
|
||||
*
|
||||
* @param sqlBatch SQL语句内容
|
||||
* @return 对应参数返回的行数
|
||||
*/
|
||||
@Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch);
|
||||
|
||||
/**
|
||||
* 在库中创建一个表
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder createTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 对库中的某个表执行更改
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
TableAlterBuilder alterTable(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 新建一个查询
|
||||
*
|
||||
* @return {@link QueryBuilder}
|
||||
*/
|
||||
QueryBuilder createQuery();
|
||||
|
||||
/**
|
||||
* 创建一条插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的插入操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link InsertBuilder}
|
||||
*/
|
||||
InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建一条替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建支持多组数据的替换操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link ReplaceBuilder}
|
||||
*/
|
||||
ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建更新操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link UpdateBuilder}
|
||||
*/
|
||||
UpdateBuilder createUpdate(@NotNull String tableName);
|
||||
|
||||
/**
|
||||
* 创建删除操作
|
||||
*
|
||||
* @param tableName 目标表名
|
||||
* @return {@link DeleteBuilder}
|
||||
*/
|
||||
DeleteBuilder createDelete(@NotNull String tableName);
|
||||
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package cc.carm.lib.easysql.api;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.api.action.query.QueryAction;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
public interface SQLQuery extends AutoCloseable {
|
||||
|
||||
/**
|
||||
* 获取该查询创建的时间
|
||||
*
|
||||
* @return 创建时间
|
||||
*/
|
||||
long getExecuteTime();
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link SQLManager}
|
||||
*
|
||||
* @return {@link SQLManager}
|
||||
*/
|
||||
SQLManager getManager();
|
||||
|
||||
/**
|
||||
* 得到承载该SQLQuery的对应{@link QueryAction}
|
||||
*
|
||||
* @return {@link QueryAction} 或 {@link PreparedQueryAction}
|
||||
*/
|
||||
QueryAction getAction();
|
||||
|
||||
ResultSet getResultSet();
|
||||
|
||||
/**
|
||||
* 得到设定的SQL语句
|
||||
*
|
||||
* @return SQL语句
|
||||
*/
|
||||
String getSQLContent();
|
||||
|
||||
/**
|
||||
* 关闭所有内容
|
||||
*/
|
||||
@Override
|
||||
void close();
|
||||
|
||||
Statement getStatement();
|
||||
|
||||
Connection getConnection();
|
||||
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PreparedSQLUpdateBatchAction extends SQLAction<List<Integer>> {
|
||||
|
||||
/**
|
||||
* 设定多组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param allParams 所有参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams);
|
||||
|
||||
/**
|
||||
* 添加一组SQL语句中所有 ? 对应的参数
|
||||
*
|
||||
* @param params 参数内容
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction addParamsBatch(Object... params);
|
||||
|
||||
/**
|
||||
* 设定自增主键的序列
|
||||
*
|
||||
* @param keyColumnIndex 自增主键的序列
|
||||
* <br>若该值 > 0,则 {@link #execute()} 返回自增主键数值
|
||||
* <br>若该值 ≤ 0,则 {@link #execute()} 返回变更的行数
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
* @see #setReturnGeneratedKeys(boolean)
|
||||
*/
|
||||
@Deprecated
|
||||
default PreparedSQLUpdateBatchAction setKeyIndex(int keyColumnIndex) {
|
||||
return setReturnGeneratedKeys(keyColumnIndex > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作返回自增键序列。
|
||||
*
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
default PreparedSQLUpdateBatchAction returnGeneratedKeys() {
|
||||
return setReturnGeneratedKeys(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定该操作是否返回自增键序列。
|
||||
*
|
||||
* @param returnGeneratedKey 是否返回自增键序列
|
||||
* @return {@link PreparedSQLUpdateBatchAction}
|
||||
*/
|
||||
PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey);
|
||||
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
|
||||
|
||||
/**
|
||||
* 添加一条批量执行的SQL语句
|
||||
*
|
||||
* @param sql SQL语句
|
||||
* @return {@link SQLUpdateBatchAction}
|
||||
*/
|
||||
SQLUpdateBatchAction addBatch(@NotNull String sql);
|
||||
|
||||
@Override
|
||||
default @NotNull String getSQLContent() {
|
||||
return getSQLContents().get(0);
|
||||
}
|
||||
|
||||
List<String> getSQLContents();
|
||||
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface TableAlterBuilder extends SQLBuilder {
|
||||
|
||||
SQLAction<Integer> renameTo(@NotNull String newTableName);
|
||||
|
||||
SQLAction<Integer> changeComment(@NotNull String newTableComment);
|
||||
|
||||
SQLAction<Integer> setAutoIncrementIndex(int index);
|
||||
|
||||
SQLAction<Integer> addIndex(@NotNull IndexType indexType, @NotNull String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
/**
|
||||
* 为该表移除一个索引
|
||||
*
|
||||
* @param indexName 索引名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropIndex(@NotNull String indexName);
|
||||
|
||||
/**
|
||||
* 为该表移除一个外键
|
||||
*
|
||||
* @param keySymbol 外键名
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropForeignKey(@NotNull String keySymbol);
|
||||
|
||||
/**
|
||||
* 为该表移除主键(须添加新主键)
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> dropPrimaryKey();
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
default SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return addColumn(columnName, settings, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为表添加一列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的相关设定
|
||||
* @param afterColumn 该列增添到哪个列的后面,
|
||||
* <p> 该参数若省缺则放于最后一行
|
||||
* <p> 若为 "" 则置于首行。
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings, @Nullable String afterColumn);
|
||||
|
||||
SQLAction<Integer> renameColumn(@NotNull String columnName, @NotNull String newName);
|
||||
|
||||
SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String settings);
|
||||
|
||||
default SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String columnSettings, @NotNull String afterColumn) {
|
||||
return modifyColumn(columnName, columnSettings + " AFTER `" + afterColumn + "`");
|
||||
}
|
||||
|
||||
SQLAction<Integer> removeColumn(@NotNull String columnName);
|
||||
|
||||
SQLAction<Integer> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue);
|
||||
|
||||
SQLAction<Integer> removeColumnDefault(@NotNull String columnName);
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param primary 是否为主键,若否则只为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean primary, boolean unsigned) {
|
||||
return addColumn(columnName,
|
||||
(numberType == null ? NumberType.INT : numberType).name()
|
||||
+ (unsigned ? " UNSIGNED " : " ")
|
||||
+ "NOT NULL AUTO_INCREMENT " + (primary ? "PRIMARY KEY" : "UNIQUE KEY"),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName, @NotNull NumberType numberType) {
|
||||
return addAutoIncrementColumn(columnName, numberType, false, true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <br> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableAlterBuilder}
|
||||
*/
|
||||
default SQLAction<Integer> addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.builder;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLBuilder;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withQuote;
|
||||
|
||||
|
||||
public interface TableCreateBuilder extends SQLBuilder {
|
||||
|
||||
/**
|
||||
* 将现有条件构建完整的SQL语句用于执行。
|
||||
*
|
||||
* @return {@link SQLUpdateAction}
|
||||
*/
|
||||
SQLUpdateAction build();
|
||||
|
||||
@NotNull String getTableName();
|
||||
|
||||
/**
|
||||
* 得到表的设定。
|
||||
* <p> 若未使用 {@link #setTableSettings(String)} 方法则会采用 {@link #defaultTablesSettings()} 。
|
||||
*
|
||||
* @return TableSettings
|
||||
*/
|
||||
@NotNull String getTableSettings();
|
||||
|
||||
TableCreateBuilder setTableSettings(@NotNull String settings);
|
||||
|
||||
/**
|
||||
* 设定表的标注,一般用于解释该表的作用。
|
||||
*
|
||||
* @param comment 表标注
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setTableComment(@Nullable String comment);
|
||||
|
||||
/**
|
||||
* 直接设定表的所有列信息
|
||||
*
|
||||
* @param columns 列的相关信息 (包括列设定)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setColumns(@NotNull String... columns);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param column 列的相关信息
|
||||
* <br>如 `uuid` VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addColumn(@NotNull String column);
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return addColumn(withBackQuote(columnName) + " " + settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个列
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param settings 列的设定
|
||||
* <br>如 VARCHAR(36) NOT NULL UNIQUE KEY
|
||||
* @param comments 列的注解,用于解释该列数据的作用
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addColumn(@NotNull String columnName, @NotNull String settings, @NotNull String comments) {
|
||||
return addColumn(columnName, settings + " COMMENT " + withQuote(comments));
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param numberType 数字类型,若省缺则为 {@link NumberType#INT}
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean asPrimaryKey, boolean unsigned);
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @param unsigned 是否采用 UNSIGNED (即无负数,可以增加自增键的最高数,建议为true)
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName,
|
||||
boolean asPrimaryKey, boolean unsigned) {
|
||||
return addAutoIncrementColumn(columnName, NumberType.INT, asPrimaryKey, unsigned);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @param asPrimaryKey 是否为主键,若为false则设定为唯一键
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, boolean asPrimaryKey) {
|
||||
return addAutoIncrementColumn(columnName, asPrimaryKey, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为该表添加一个INT类型的自增主键列
|
||||
* <p> 自增列强制要求为数字类型,非空,且为UNIQUE。
|
||||
* <p> 注意:一个表只允许有一个自增列!
|
||||
*
|
||||
* @param columnName 列名
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName) {
|
||||
return addAutoIncrementColumn(columnName, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param columnName 索引包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder setIndex(@NotNull String columnName,
|
||||
@NotNull IndexType type) {
|
||||
return setIndex(type, null, columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设定表中的某列为索引或键。
|
||||
*
|
||||
* <p>创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。
|
||||
* <br>虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行INSERT、UPDATE 和DELETE。
|
||||
* <br>因此,请合理的设计索引。
|
||||
*
|
||||
* @param type 索引类型
|
||||
* @param indexName 索引名称,缺省时将根据第一个索引列赋一个名称
|
||||
* @param columnName 索引包含的列
|
||||
* @param moreColumns 联合索引需要包含的列
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder setIndex(@NotNull IndexType type, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns);
|
||||
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定自参照外键(即自参照完整性)。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignColumn 外键关联表中对应的关联列,必须为目标表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, getTableName(), foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, null, foreignTable, foreignColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
default TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn) {
|
||||
return addForeignKey(tableColumn, constraintName, foreignTable, foreignColumn, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以本表位从表,为表中某列设定外键。
|
||||
*
|
||||
* <p>外键约束(FOREIGN KEY)是表的一个特殊字段,经常与主键约束一起使用。
|
||||
* <br>外键用来建立主表与从表的关联关系,为两个表的数据建立连接,约束两个表中数据的一致性和完整性。
|
||||
* <br>主表删除某条记录时,从表中与之对应的记录也必须有相应的改变。
|
||||
*
|
||||
* @param tableColumn 本表中的列
|
||||
* @param constraintName 约束名,缺省时将使用参数自动生成,如 <i>fk_[tableColumn]_[foreignTable]</i>
|
||||
* @param foreignTable 外键关联主表,必须为已存在的表或本表,且必须有主键。
|
||||
* @param foreignColumn 外键关联主表中对应的关联列,须满足
|
||||
* <p> 1. 为主表的主键,即 {@link IndexType#PRIMARY_KEY}
|
||||
* <p> 2. 数据类型必须和所要建立主键的列的数据类型相同。
|
||||
* @param updateRule 在外键被更新时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @param deleteRule 在外键被删除时采用的规则,缺省时默认为{@link ForeignKeyRule#RESTRICT}
|
||||
* @return {@link TableCreateBuilder}
|
||||
*/
|
||||
TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn,
|
||||
@Nullable ForeignKeyRule updateRule, @Nullable ForeignKeyRule deleteRule);
|
||||
|
||||
default String defaultTablesSettings() {
|
||||
return "ENGINE=InnoDB DEFAULT CHARSET=utf8";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum ForeignKeyRule {
|
||||
|
||||
/**
|
||||
* 啥也不做
|
||||
* <p>注意: 在Mysql中该选项实际上等同于采用默认的 {@link #RESTRICT} 设定!
|
||||
*/
|
||||
NO_ACTION("NO ACTION"),
|
||||
|
||||
/**
|
||||
* 拒绝删除要求,直到使用删除键值的辅助表被手工删除,并且没有参照时(这是默认设置,也是最安全的设置)
|
||||
*/
|
||||
RESTRICT("RESTRICT"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用NULL值替换(只能用于已标记为NOT NULL的字段)
|
||||
*/
|
||||
SET_NULL("SET NULL"),
|
||||
|
||||
/**
|
||||
* 修改包含与已删除键值有参照关系的所有记录,使用默认值替换(只能用于设定了DEFAULT的字段)
|
||||
*/
|
||||
SET_DEFAULT("SET DEFAULT"),
|
||||
|
||||
/**
|
||||
* <b>级联删除</b>,删除包含与已删除键值有参照关系的所有记录
|
||||
*/
|
||||
CASCADE("CASCADE");
|
||||
|
||||
final String ruleName;
|
||||
|
||||
ForeignKeyRule(String ruleName) {
|
||||
this.ruleName = ruleName;
|
||||
}
|
||||
|
||||
public String getRuleName() {
|
||||
return ruleName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.enums;
|
||||
|
||||
public enum IndexType {
|
||||
|
||||
|
||||
/**
|
||||
* <b>普通索引</b>(由关键字KEY或INDEX定义的索引)的唯一任务是加快对数据的访问速度。
|
||||
* <br> 因此,应该只为那些最经常出现在查询条件(WHERE column=)或排序条件(ORDER BY column)中的数据列创建索引。
|
||||
* <br> 只要有可能,就应该选择一个数据最整齐、最紧凑的数据列(如一个整数类型的数据列)来创建索引。
|
||||
*/
|
||||
INDEX("INDEX"),
|
||||
|
||||
|
||||
/**
|
||||
* <b>唯一索引</b> 是在表上一个或者多个字段组合建立的索引,这个或者这些字段的值组合起来在表中不可以重复,用于保证数据的唯一性。
|
||||
*/
|
||||
UNIQUE_KEY("UNIQUE KEY"),
|
||||
|
||||
/**
|
||||
* <b>主键索引</b> 是唯一索引的特定类型。表中创建主键时自动创建的索引 。一个表只能建立一个主索引。
|
||||
*/
|
||||
PRIMARY_KEY("PRIMARY KEY"),
|
||||
|
||||
/**
|
||||
* <b>全文索引</b> 主要用来查找文本中的关键字,而不是直接与索引中的值相比较。
|
||||
* <br> 请搭配 MATCH 等语句使用,而不是使用 WHERE - LIKE 。
|
||||
* <br> 全文索引只可用于 CHAR、 VARCHAR 与 TEXT 系列类型。
|
||||
*/
|
||||
FULLTEXT_INDEX("FULLTEXT");
|
||||
|
||||
|
||||
final String name;
|
||||
|
||||
IndexType(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface SQLExceptionHandler extends BiConsumer<SQLException, SQLAction<?>> {
|
||||
|
||||
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.function;
|
||||
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Objects;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface SQLHandler<T> {
|
||||
|
||||
void accept(@NotNull T t) throws SQLException;
|
||||
|
||||
@NotNull
|
||||
@Contract(pure = true)
|
||||
default SQLHandler<T> andThen(@NotNull SQLHandler<? super T> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (T t) -> {
|
||||
accept(t);
|
||||
after.accept(t);
|
||||
};
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.function.defaults;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class DefaultSQLExceptionHandler implements SQLExceptionHandler {
|
||||
|
||||
private static @Nullable SQLExceptionHandler customDefaultHandler = null;
|
||||
|
||||
public static void setCustomHandler(@Nullable SQLExceptionHandler handler) {
|
||||
DefaultSQLExceptionHandler.customDefaultHandler = handler;
|
||||
}
|
||||
|
||||
public static @Nullable SQLExceptionHandler getCustomHandler() {
|
||||
return customDefaultHandler;
|
||||
}
|
||||
|
||||
public static @NotNull SQLExceptionHandler get(Logger logger) {
|
||||
if (getCustomHandler() != null) return getCustomHandler();
|
||||
else return new DefaultSQLExceptionHandler(logger);
|
||||
}
|
||||
|
||||
private final Logger logger;
|
||||
|
||||
public DefaultSQLExceptionHandler(Logger logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
protected Logger getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(SQLException exception, SQLAction<?> sqlAction) {
|
||||
if (sqlAction instanceof SQLUpdateBatchAction) {
|
||||
|
||||
getLogger().severe("Error when execute SQLs : ");
|
||||
int i = 1;
|
||||
for (String content : ((SQLUpdateBatchAction) sqlAction).getSQLContents()) {
|
||||
getLogger().severe("#" + i + " {" + content + "}");
|
||||
i++;
|
||||
}
|
||||
|
||||
} else {
|
||||
getLogger().severe("Error when execute { " + sqlAction.getSQLContent() + " }");
|
||||
}
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package cc.carm.lib.easysql.api.util;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDUtil {
|
||||
|
||||
public static UUID toUUID(String s) {
|
||||
if (s.length() == 36) {
|
||||
return UUID.fromString(s);
|
||||
} else {
|
||||
return UUID.fromString(s.substring(0, 8) + '-' + s.substring(8, 12) + '-' + s.substring(12, 16) + '-' + s.substring(16, 20) + '-' + s.substring(20));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class AbstractSQLAction<T> implements SQLAction<T> {
|
||||
|
||||
private final @NotNull SQLManagerImpl sqlManager;
|
||||
|
||||
private final @NotNull UUID uuid;
|
||||
private final long createTime;
|
||||
|
||||
protected @NotNull String sqlContent;
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
this(manager, sql, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, @NotNull UUID uuid) {
|
||||
this(manager, sql, uuid, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, long createTime) {
|
||||
this(manager, sql, UUID.randomUUID(), createTime);
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@NotNull UUID uuid, long createTime) {
|
||||
this.sqlManager = manager;
|
||||
this.sqlContent = sql;
|
||||
this.uuid = uuid;
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public @NotNull UUID getActionUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getShortID() {
|
||||
return getActionUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCreateTime() {
|
||||
return this.createTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getSQLContent() {
|
||||
return this.sqlContent.trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull SQLManagerImpl getManager() {
|
||||
return this.sqlManager;
|
||||
}
|
||||
|
||||
protected void outputDebugMessage() {
|
||||
getManager().debug("# " + getShortID() + " -> { " + getSQLContent() + " }");
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("FutureReturnValueIgnored")
|
||||
public void executeAsync(SQLHandler<T> success, SQLExceptionHandler failure) {
|
||||
getManager().getExecutorPool().submit(() -> {
|
||||
try {
|
||||
T returnedValue = execute();
|
||||
if (success != null) success.accept(returnedValue);
|
||||
} catch (SQLException e) {
|
||||
handleException(failure, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class PreparedSQLBatchUpdateActionImpl
|
||||
extends AbstractSQLAction<List<Integer>>
|
||||
implements PreparedSQLUpdateBatchAction {
|
||||
|
||||
boolean returnKeys = false;
|
||||
List<Object[]> allParams;
|
||||
|
||||
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
this.allParams = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams) {
|
||||
List<Object[]> paramsList = new ArrayList<>();
|
||||
allParams.forEach(paramsList::add);
|
||||
this.allParams = paramsList;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction addParamsBatch(Object... params) {
|
||||
this.allParams.add(params);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey) {
|
||||
this.returnKeys = returnGeneratedKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<Integer> execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
|
||||
connection, getSQLContent(), allParams, returnKeys
|
||||
)) {
|
||||
|
||||
outputDebugMessage();
|
||||
int[] executed = statement.executeBatch();
|
||||
|
||||
if (!returnKeys) return Arrays.stream(executed).boxed().collect(Collectors.toList());
|
||||
else {
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
List<Integer> generatedKeys = new ArrayList<>();
|
||||
while (resultSet.next()) {
|
||||
generatedKeys.add(resultSet.getInt(1));
|
||||
}
|
||||
return generatedKeys;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PreparedSQLUpdateActionImpl
|
||||
extends SQLUpdateActionImpl
|
||||
implements PreparedSQLUpdateAction {
|
||||
|
||||
Object[] params;
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
this(manager, sql, (Object[]) null);
|
||||
}
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@Nullable List<Object> params) {
|
||||
this(manager, sql, params == null ? null : params.toArray());
|
||||
}
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@Nullable Object[] params) {
|
||||
super(manager, sql);
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateActionImpl setParams(Object... params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateAction setParams(@Nullable Iterable<Object> params) {
|
||||
if (params == null) {
|
||||
return setParams((Object[]) null);
|
||||
} else {
|
||||
List<Object> paramsList = new ArrayList<>();
|
||||
params.forEach(paramsList::add);
|
||||
return setParams(paramsList.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Integer execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
|
||||
try (PreparedStatement statement = StatementUtil.createPrepareStatement(
|
||||
connection, getSQLContent(), params, returnGeneratedKeys
|
||||
)) {
|
||||
|
||||
outputDebugMessage();
|
||||
|
||||
int changes = statement.executeUpdate();
|
||||
if (!returnGeneratedKeys) return changes;
|
||||
else {
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
return resultSet.next() ? resultSet.getInt(1) : -1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class SQLUpdateActionImpl
|
||||
extends AbstractSQLAction<Integer>
|
||||
implements SQLUpdateAction {
|
||||
|
||||
boolean returnGeneratedKeys = false;
|
||||
|
||||
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Integer execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
outputDebugMessage();
|
||||
|
||||
if (!returnGeneratedKeys) {
|
||||
return statement.executeUpdate(getSQLContent());
|
||||
} else {
|
||||
statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS);
|
||||
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
return resultSet.next() ? resultSet.getInt(1) : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey) {
|
||||
this.returnGeneratedKeys = returnGeneratedKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class SQLUpdateBatchActionImpl
|
||||
extends AbstractSQLAction<List<Integer>>
|
||||
implements SQLUpdateBatchAction {
|
||||
|
||||
List<String> sqlContents = new ArrayList<>();
|
||||
|
||||
public SQLUpdateBatchActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
this.sqlContents.add(sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<String> getSQLContents() {
|
||||
return this.sqlContents;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLUpdateBatchAction addBatch(@NotNull String sql) {
|
||||
this.sqlContents.add(sql);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<Integer> execute() throws SQLException {
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
outputDebugMessage();
|
||||
|
||||
for (String content : this.sqlContents) {
|
||||
statement.addBatch(content);
|
||||
}
|
||||
|
||||
int[] executed = statement.executeBatch();
|
||||
|
||||
return Arrays.stream(executed).boxed().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void outputDebugMessage() {
|
||||
getManager().debug("# " + getShortID() + " -> [");
|
||||
for (String content : getSQLContents()) getManager().debug(" { " + content + " }");
|
||||
getManager().debug("]");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package cc.carm.lib.easysql.action.query;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.query.SQLQueryImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class PreparedQueryActionImpl extends QueryActionImpl implements PreparedQueryAction {
|
||||
|
||||
Consumer<PreparedStatement> handler;
|
||||
Object[] params;
|
||||
|
||||
public PreparedQueryActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl setParams(@Nullable Object... params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl setParams(@Nullable Iterable<Object> params) {
|
||||
if (params == null) {
|
||||
return setParams((Object[]) null);
|
||||
} else {
|
||||
List<Object> paramsList = new ArrayList<>();
|
||||
params.forEach(paramsList::add);
|
||||
return setParams(paramsList.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl handleStatement(@Nullable Consumer<PreparedStatement> statement) {
|
||||
this.handler = statement;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public @NotNull SQLQueryImpl execute() throws SQLException {
|
||||
outputDebugMessage();
|
||||
|
||||
Connection connection = getManager().getConnection();
|
||||
PreparedStatement preparedStatement;
|
||||
try {
|
||||
if (handler == null) {
|
||||
preparedStatement = StatementUtil.createPrepareStatement(connection, getSQLContent(), this.params);
|
||||
} else {
|
||||
preparedStatement = connection.prepareStatement(getSQLContent());
|
||||
handler.accept(preparedStatement);
|
||||
}
|
||||
} catch (SQLException exception) {
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
|
||||
try {
|
||||
long executeTime = System.currentTimeMillis();
|
||||
SQLQueryImpl query = new SQLQueryImpl(
|
||||
getManager(), this,
|
||||
connection, preparedStatement,
|
||||
preparedStatement.executeQuery(),
|
||||
executeTime
|
||||
);
|
||||
getManager().getActiveQuery().put(getActionUUID(), query);
|
||||
|
||||
return query;
|
||||
} catch (SQLException exception) {
|
||||
preparedStatement.close();
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package cc.carm.lib.easysql.action.query;
|
||||
|
||||
import cc.carm.lib.easysql.action.AbstractSQLAction;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.api.action.query.QueryAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.query.SQLQueryImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements QueryAction {
|
||||
|
||||
public QueryActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull SQLQueryImpl execute() throws SQLException {
|
||||
|
||||
Connection connection = getManager().getConnection();
|
||||
Statement statement;
|
||||
|
||||
try {
|
||||
statement = connection.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
connection.close();
|
||||
throw ex;
|
||||
}
|
||||
|
||||
outputDebugMessage();
|
||||
try {
|
||||
long executeTime = System.currentTimeMillis();
|
||||
SQLQueryImpl query = new SQLQueryImpl(
|
||||
getManager(), this,
|
||||
connection, statement,
|
||||
statement.executeQuery(getSQLContent()),
|
||||
executeTime
|
||||
);
|
||||
getManager().getActiveQuery().put(getActionUUID(), query);
|
||||
|
||||
return query;
|
||||
} catch (SQLException exception) {
|
||||
statement.close();
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void executeAsync(SQLHandler<SQLQuery> success, SQLExceptionHandler failure) {
|
||||
try (SQLQueryImpl query = execute()) {
|
||||
if (success != null) success.accept(query);
|
||||
} catch (SQLException exception) {
|
||||
handleException(failure, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.ConditionalBuilder;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
|
||||
public abstract class AbstractConditionalBuilder<B extends ConditionalBuilder<B, T>, T extends SQLAction<?>>
|
||||
extends AbstractSQLBuilder implements ConditionalBuilder<B, T> {
|
||||
|
||||
ArrayList<String> conditionSQLs = new ArrayList<>();
|
||||
ArrayList<Object> conditionParams = new ArrayList<>();
|
||||
int limit = -1;
|
||||
|
||||
public AbstractConditionalBuilder(@NotNull SQLManagerImpl manager) {
|
||||
super(manager);
|
||||
}
|
||||
|
||||
protected abstract B getThis();
|
||||
|
||||
@Override
|
||||
public B setConditions(@Nullable String condition) {
|
||||
this.conditionSQLs = new ArrayList<>();
|
||||
this.conditionParams = new ArrayList<>();
|
||||
if (condition != null) this.conditionSQLs.add(condition);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B setConditions(
|
||||
LinkedHashMap<@NotNull String, @Nullable Object> conditions
|
||||
) {
|
||||
conditions.forEach(this::addCondition);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B addCondition(@Nullable String condition) {
|
||||
this.conditionSQLs.add(condition);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B addCondition(
|
||||
@NotNull String columnName, @NotNull String operator, @Nullable Object queryValue
|
||||
) {
|
||||
addCondition(withBackQuote(columnName) + " " + operator + " ?");
|
||||
this.conditionParams.add(queryValue);
|
||||
return getThis();
|
||||
}
|
||||
|
||||
@Override
|
||||
public B addCondition(
|
||||
@NotNull String[] columnNames, @Nullable Object[] queryValues
|
||||
) {
|
||||
if (queryValues == null || columnNames.length != queryValues.length) {
|
||||
throw new RuntimeException("queryNames are not match with queryValues");
|
||||
}
|
||||
for (int i = 0; i < columnNames.length; i++) {
|
||||
addCondition(columnNames[i], queryValues[i]);
|
||||
}
|
||||
return getThis();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public B addNotNullCondition(@NotNull String columnName) {
|
||||
return addCondition(withBackQuote(columnName) + " IS NOT NULL");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public B addTimeCondition(
|
||||
@NotNull String columnName, @Nullable Date startDate, @Nullable Date endDate
|
||||
) {
|
||||
if (startDate == null && endDate == null) return getThis(); // 都不限定时间,不用判断了
|
||||
if (startDate != null) {
|
||||
addCondition(withBackQuote(columnName) + " BETWEEN ? AND ?");
|
||||
this.conditionParams.add(startDate);
|
||||
if (endDate != null) {
|
||||
this.conditionParams.add(endDate);
|
||||
} else {
|
||||
if (startDate instanceof java.sql.Date) {
|
||||
this.conditionParams.add(new java.sql.Date(System.currentTimeMillis()));
|
||||
} else if (startDate instanceof Time) {
|
||||
this.conditionParams.add(new Time(System.currentTimeMillis()));
|
||||
} else {
|
||||
this.conditionParams.add(new Timestamp(System.currentTimeMillis()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
addCondition(columnName, "<=", endDate);
|
||||
}
|
||||
return getThis();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public B setLimit(int limit) {
|
||||
this.limit = limit;
|
||||
return getThis();
|
||||
}
|
||||
|
||||
protected String buildConditionSQL() {
|
||||
|
||||
if (!conditionSQLs.isEmpty()) {
|
||||
StringBuilder conditionBuilder = new StringBuilder();
|
||||
conditionBuilder.append("WHERE").append(" ");
|
||||
Iterator<String> iterator = conditionSQLs.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
conditionBuilder.append(iterator.next());
|
||||
if (iterator.hasNext()) conditionBuilder.append(" AND ");
|
||||
}
|
||||
return conditionBuilder.toString().trim();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected String buildLimitSQL() {
|
||||
return limit > 0 ? "LIMIT " + limit : "";
|
||||
}
|
||||
|
||||
protected ArrayList<Object> getConditionParams() {
|
||||
return conditionParams;
|
||||
}
|
||||
|
||||
protected boolean hasConditions() {
|
||||
return this.conditionSQLs != null && !this.conditionSQLs.isEmpty();
|
||||
}
|
||||
|
||||
protected boolean hasConditionParams() {
|
||||
return hasConditions() && getConditionParams() != null && !getConditionParams().isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.PreparedSQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.builder.DeleteBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
|
||||
public class DeleteBuilderImpl
|
||||
extends AbstractConditionalBuilder<DeleteBuilder, SQLAction<Integer>>
|
||||
implements DeleteBuilder {
|
||||
|
||||
String tableName;
|
||||
|
||||
public DeleteBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateAction build() {
|
||||
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
|
||||
sqlBuilder.append("DELETE FROM ").append(withBackQuote(getTableName()));
|
||||
|
||||
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
|
||||
if (limit > 0) sqlBuilder.append(" ").append(buildLimitSQL());
|
||||
|
||||
return new PreparedSQLUpdateActionImpl(
|
||||
getManager(), sqlBuilder.toString(),
|
||||
hasConditionParams() ? getConditionParams() : null
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected DeleteBuilderImpl getThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.InsertBuilder;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
|
||||
public abstract class InsertBuilderImpl<T extends SQLAction<?>>
|
||||
extends AbstractSQLBuilder implements InsertBuilder<T> {
|
||||
|
||||
String tableName;
|
||||
|
||||
public InsertBuilderImpl(@NotNull SQLManagerImpl manager, String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
protected static String buildSQL(String tableName, List<String> columnNames) {
|
||||
int valueLength = columnNames.size();
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
|
||||
sqlBuilder.append("INSERT IGNORE INTO ").append(withBackQuote(tableName)).append("(");
|
||||
Iterator<String> iterator = columnNames.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
sqlBuilder.append(withBackQuote(iterator.next()));
|
||||
if (iterator.hasNext()) sqlBuilder.append(", ");
|
||||
}
|
||||
|
||||
sqlBuilder.append(") VALUES (");
|
||||
|
||||
for (int i = 0; i < valueLength; i++) {
|
||||
sqlBuilder.append("?");
|
||||
if (i != valueLength - 1) {
|
||||
sqlBuilder.append(", ");
|
||||
}
|
||||
}
|
||||
sqlBuilder.append(")");
|
||||
return sqlBuilder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.ReplaceBuilder;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
|
||||
public abstract class ReplaceBuilderImpl<T extends SQLAction<?>>
|
||||
extends AbstractSQLBuilder implements ReplaceBuilder<T> {
|
||||
|
||||
String tableName;
|
||||
|
||||
public ReplaceBuilderImpl(@NotNull SQLManagerImpl manager, String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
protected static String buildSQL(String tableName, List<String> columnNames) {
|
||||
int valueLength = columnNames.size();
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
|
||||
sqlBuilder.append("REPLACE INTO ").append(withBackQuote(tableName)).append("(");
|
||||
Iterator<String> iterator = columnNames.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
sqlBuilder.append(withBackQuote(iterator.next()));
|
||||
if (iterator.hasNext()) sqlBuilder.append(", ");
|
||||
}
|
||||
|
||||
sqlBuilder.append(") VALUES (");
|
||||
|
||||
for (int i = 0; i < valueLength; i++) {
|
||||
sqlBuilder.append("?");
|
||||
if (i != valueLength - 1) {
|
||||
sqlBuilder.append(", ");
|
||||
}
|
||||
}
|
||||
sqlBuilder.append(")");
|
||||
return sqlBuilder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
}
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.SQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.builder.TableAlterBuilder;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withQuote;
|
||||
|
||||
public class TableAlterBuilderImpl extends AbstractSQLBuilder implements TableAlterBuilder {
|
||||
|
||||
protected final @NotNull String tableName;
|
||||
|
||||
public TableAlterBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public @NotNull String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> renameTo(@NotNull String newTableName) {
|
||||
return new SQLUpdateActionImpl(getManager(),
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " RENAME TO " + withBackQuote(newTableName) + ""
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> changeComment(@NotNull String newTableComment) {
|
||||
return new SQLUpdateActionImpl(getManager(),
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " COMMENT " + withQuote(newTableComment)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> setAutoIncrementIndex(int index) {
|
||||
return new SQLUpdateActionImpl(getManager(),
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " AUTO_INCREMENT=" + index
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> addIndex(@NotNull IndexType indexType, @NotNull String indexName, @NotNull String columnName, @NotNull String... moreColumns) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " ADD "
|
||||
+ TableCreateBuilderImpl.buildIndexSettings(indexType, indexName, columnName, moreColumns)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> dropIndex(@NotNull String indexName) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " DROP INDEX " + withBackQuote(indexName)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> dropForeignKey(@NotNull String keySymbol) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " DROP FOREIGN KEY " + withBackQuote(keySymbol)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> dropPrimaryKey() {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " DROP PRIMARY KEY"
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> addColumn(@NotNull String columnName, @NotNull String settings, @Nullable String afterColumn) {
|
||||
String orderSettings = null;
|
||||
if (afterColumn != null) {
|
||||
if (afterColumn.length() > 0) {
|
||||
orderSettings = "AFTER " + withBackQuote(afterColumn);
|
||||
} else {
|
||||
orderSettings = "FIRST";
|
||||
}
|
||||
}
|
||||
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " ADD " + withBackQuote(columnName) + " " + settings
|
||||
+ (orderSettings != null ? " " + orderSettings : "")
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> renameColumn(@NotNull String columnName, @NotNull String newName) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " RENAME COLUMN " + withBackQuote(columnName) + " TO " + withBackQuote(newName)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> modifyColumn(@NotNull String columnName, @NotNull String settings) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " MODIFY COLUMN " + withBackQuote(columnName) + " " + settings
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> removeColumn(@NotNull String columnName) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " DROP " + withBackQuote(columnName)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> setColumnDefault(@NotNull String columnName, @NotNull String defaultValue) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " ALTER " + withBackQuote(columnName) + " SET DEFAULT " + defaultValue
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLAction<Integer> removeColumnDefault(@NotNull String columnName) {
|
||||
return createAction(
|
||||
"ALTER TABLE " + withBackQuote(getTableName()) + " ALTER " + withBackQuote(columnName) + " DROP DEFAULT"
|
||||
);
|
||||
}
|
||||
|
||||
private SQLUpdateActionImpl createAction(@NotNull String sql) {
|
||||
return new SQLUpdateActionImpl(getManager(), sql);
|
||||
}
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.SQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.builder.TableCreateBuilder;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withQuote;
|
||||
|
||||
public class TableCreateBuilderImpl extends AbstractSQLBuilder implements TableCreateBuilder {
|
||||
|
||||
protected final @NotNull String tableName;
|
||||
|
||||
@NotNull List<String> columns = new ArrayList<>();
|
||||
@NotNull List<String> indexes = new ArrayList<>();
|
||||
@NotNull List<String> foreignKeys = new ArrayList<>();
|
||||
|
||||
@NotNull String tableSettings = defaultTablesSettings();
|
||||
@Nullable String tableComment;
|
||||
|
||||
public TableCreateBuilderImpl(SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getTableName() {
|
||||
return this.tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getTableSettings() {
|
||||
return this.tableSettings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLUpdateAction build() {
|
||||
StringBuilder createSQL = new StringBuilder();
|
||||
createSQL.append("CREATE TABLE IF NOT EXISTS ").append(withBackQuote(tableName));
|
||||
createSQL.append("(");
|
||||
createSQL.append(String.join(", ", columns));
|
||||
if (indexes.size() > 0) {
|
||||
createSQL.append(", ");
|
||||
createSQL.append(String.join(", ", indexes));
|
||||
}
|
||||
if (foreignKeys.size() > 0) {
|
||||
createSQL.append(", ");
|
||||
createSQL.append(String.join(", ", foreignKeys));
|
||||
}
|
||||
createSQL.append(") ").append(getTableSettings());
|
||||
|
||||
if (tableComment != null) {
|
||||
createSQL.append(" COMMENT ").append(withQuote(tableComment));
|
||||
}
|
||||
|
||||
return new SQLUpdateActionImpl(getManager(), createSQL.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder addColumn(@NotNull String column) {
|
||||
this.columns.add(column);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder addAutoIncrementColumn(@NotNull String columnName, @Nullable NumberType numberType,
|
||||
boolean asPrimaryKey, boolean unsigned) {
|
||||
return addColumn(columnName,
|
||||
(numberType == null ? NumberType.INT : numberType).name()
|
||||
+ (unsigned ? " UNSIGNED " : " ")
|
||||
+ "NOT NULL AUTO_INCREMENT " + (asPrimaryKey ? "PRIMARY KEY" : "UNIQUE KEY")
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setIndex(@NotNull IndexType type, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns) {
|
||||
this.indexes.add(buildIndexSettings(type, indexName, columnName, moreColumns));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder addForeignKey(@NotNull String tableColumn, @Nullable String constraintName,
|
||||
@NotNull String foreignTable, @NotNull String foreignColumn,
|
||||
@Nullable ForeignKeyRule updateRule, @Nullable ForeignKeyRule deleteRule) {
|
||||
StringBuilder keyBuilder = new StringBuilder();
|
||||
|
||||
keyBuilder.append("CONSTRAINT ");
|
||||
if (constraintName == null) {
|
||||
keyBuilder.append(withBackQuote("fk_" + tableColumn + "_" + foreignTable));
|
||||
} else {
|
||||
keyBuilder.append(withBackQuote(constraintName));
|
||||
}
|
||||
keyBuilder.append(" ");
|
||||
keyBuilder.append("FOREIGN KEY (").append(withBackQuote(tableColumn)).append(") ");
|
||||
keyBuilder.append("REFERENCES ").append(withBackQuote(foreignTable)).append("(").append(withBackQuote(foreignColumn)).append(")");
|
||||
|
||||
if (updateRule != null) keyBuilder.append(" ON UPDATE ").append(updateRule.getRuleName());
|
||||
if (deleteRule != null) keyBuilder.append(" ON DELETE ").append(deleteRule.getRuleName());
|
||||
|
||||
this.foreignKeys.add(keyBuilder.toString());
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setColumns(@NotNull String... columns) {
|
||||
this.columns = Arrays.asList(columns);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setTableSettings(@NotNull String settings) {
|
||||
this.tableSettings = settings;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder setTableComment(@Nullable String comment) {
|
||||
this.tableComment = comment;
|
||||
return this;
|
||||
}
|
||||
|
||||
protected static String buildIndexSettings(@NotNull IndexType indexType, @Nullable String indexName,
|
||||
@NotNull String columnName, @NotNull String... moreColumns) {
|
||||
|
||||
StringBuilder indexBuilder = new StringBuilder();
|
||||
|
||||
indexBuilder.append(indexType.getName()).append(" ");
|
||||
if (indexName != null) {
|
||||
indexBuilder.append(withBackQuote(indexName));
|
||||
}
|
||||
indexBuilder.append("(");
|
||||
indexBuilder.append(withBackQuote(columnName));
|
||||
|
||||
if (moreColumns.length > 0) {
|
||||
indexBuilder.append(", ");
|
||||
|
||||
for (int i = 0; i < moreColumns.length; i++) {
|
||||
indexBuilder.append(withBackQuote(moreColumns[i]));
|
||||
if (i != moreColumns.length - 1) indexBuilder.append(", ");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
indexBuilder.append(")");
|
||||
|
||||
return indexBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
package cc.carm.lib.easysql.builder.impl;
|
||||
|
||||
import cc.carm.lib.easysql.action.query.PreparedQueryActionImpl;
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.api.builder.TableQueryBuilder;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import static cc.carm.lib.easysql.api.SQLBuilder.withBackQuote;
|
||||
|
||||
public class TableQueryBuilderImpl
|
||||
extends AbstractConditionalBuilder<TableQueryBuilder, PreparedQueryAction>
|
||||
implements TableQueryBuilder {
|
||||
|
||||
@NotNull String tableName;
|
||||
|
||||
String[] columns;
|
||||
|
||||
@Nullable String orderBy;
|
||||
|
||||
int[] pageLimit;
|
||||
|
||||
public TableQueryBuilderImpl(@NotNull SQLManagerImpl manager, @NotNull String tableName) {
|
||||
super(manager);
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl build() {
|
||||
StringBuilder sqlBuilder = new StringBuilder();
|
||||
sqlBuilder.append("SELECT").append(" ");
|
||||
if (columns == null || columns.length < 1) {
|
||||
sqlBuilder.append("*");
|
||||
} else {
|
||||
for (int i = 0; i < columns.length; i++) {
|
||||
String name = columns[i];
|
||||
sqlBuilder.append(withBackQuote(name));
|
||||
if (i != columns.length - 1) {
|
||||
sqlBuilder.append(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlBuilder.append(" ").append("FROM").append(" ").append(withBackQuote(tableName));
|
||||
|
||||
if (hasConditions()) sqlBuilder.append(" ").append(buildConditionSQL());
|
||||
|
||||
if (orderBy != null) sqlBuilder.append(" ").append(orderBy);
|
||||
|
||||
if (pageLimit != null && pageLimit.length == 2) {
|
||||
sqlBuilder.append(" LIMIT ").append(pageLimit[0]).append(",").append(pageLimit[1]);
|
||||
} else if (limit > 0) {
|
||||
sqlBuilder.append(" ").append(buildLimitSQL());
|
||||
}
|
||||
|
||||
|
||||
return new PreparedQueryActionImpl(getManager(), sqlBuilder.toString())
|
||||
.setParams(hasConditionParams() ? getConditionParams() : null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableQueryBuilderImpl selectColumns(@NotNull String... columnNames) {
|
||||
this.columns = columnNames;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableQueryBuilder orderBy(@NotNull String columnName, boolean asc) {
|
||||
this.orderBy = "ORDER BY " + withBackQuote(columnName) + " " + (asc ? "ASC" : "DESC");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableQueryBuilder setPageLimit(int start, int end) {
|
||||
this.pageLimit = new int[]{start, end};
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TableQueryBuilderImpl getThis() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
package cc.carm.lib.easysql.manager;
|
||||
|
||||
import cc.carm.lib.easysql.action.PreparedSQLBatchUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.action.PreparedSQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.action.SQLUpdateActionImpl;
|
||||
import cc.carm.lib.easysql.action.SQLUpdateBatchActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.api.builder.*;
|
||||
import cc.carm.lib.easysql.builder.impl.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class SQLManagerImpl implements SQLManager {
|
||||
|
||||
private final Logger LOGGER;
|
||||
private final DataSource dataSource;
|
||||
protected ExecutorService executorPool;
|
||||
ConcurrentHashMap<UUID, SQLQuery> activeQuery = new ConcurrentHashMap<>();
|
||||
|
||||
@NotNull Supplier<Boolean> debugMode = () -> false;
|
||||
|
||||
public SQLManagerImpl(@NotNull DataSource dataSource) {
|
||||
this(dataSource, null);
|
||||
}
|
||||
|
||||
public SQLManagerImpl(@NotNull DataSource dataSource, @Nullable String name) {
|
||||
String managerName = "SQLManager" + (name != null ? "#" + name : "");
|
||||
this.LOGGER = Logger.getLogger(managerName);
|
||||
this.dataSource = dataSource;
|
||||
this.executorPool = Executors.newFixedThreadPool(3, r -> {
|
||||
Thread thread = new Thread(r, managerName);
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugMode() {
|
||||
return this.debugMode.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDebugMode(@NotNull Supplier<@NotNull Boolean> debugMode) {
|
||||
this.debugMode = debugMode;
|
||||
}
|
||||
|
||||
public void debug(String msg) {
|
||||
if (isDebugMode()) getLogger().info("[DEBUG] " + msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Logger getLogger() {
|
||||
return LOGGER;
|
||||
}
|
||||
|
||||
public ExecutorService getExecutorPool() {
|
||||
return executorPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull DataSource getDataSource() {
|
||||
return this.dataSource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Connection getConnection() throws SQLException {
|
||||
return getDataSource().getConnection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Map<UUID, SQLQuery> getActiveQuery() {
|
||||
return this.activeQuery;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer executeSQL(String sql) {
|
||||
return new SQLUpdateActionImpl(this, sql).execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer executeSQL(String sql, Object[] params) {
|
||||
return new PreparedSQLUpdateActionImpl(this, sql, params).execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Integer> executeSQLBatch(String sql, Iterable<Object[]> paramsBatch) {
|
||||
return new PreparedSQLBatchUpdateActionImpl(this, sql)
|
||||
.setAllParams(paramsBatch)
|
||||
.execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Integer> executeSQLBatch(@NotNull String sql, String... moreSQL) {
|
||||
SQLUpdateBatchAction action = new SQLUpdateBatchActionImpl(this, sql);
|
||||
if (moreSQL != null && moreSQL.length > 0) {
|
||||
Arrays.stream(moreSQL).forEach(action::addBatch);
|
||||
}
|
||||
return action.execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable List<Integer> executeSQLBatch(@NotNull Iterable<String> sqlBatch) {
|
||||
Iterator<String> iterator = sqlBatch.iterator();
|
||||
if (!iterator.hasNext()) return null; // PLEASE GIVE IT SOMETHING
|
||||
|
||||
SQLUpdateBatchAction action = new SQLUpdateBatchActionImpl(this, iterator.next());
|
||||
while (iterator.hasNext()) {
|
||||
action.addBatch(iterator.next());
|
||||
}
|
||||
|
||||
return action.execute(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableCreateBuilder createTable(@NotNull String tableName) {
|
||||
return new TableCreateBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableAlterBuilder alterTable(@NotNull String tableName) {
|
||||
return new TableAlterBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public QueryBuilder createQuery() {
|
||||
return new QueryBuilderImpl(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InsertBuilder<PreparedSQLUpdateBatchAction> createInsertBatch(@NotNull String tableName) {
|
||||
return new InsertBuilderImpl<PreparedSQLUpdateBatchAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLBatchUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public InsertBuilder<PreparedSQLUpdateAction> createInsert(@NotNull String tableName) {
|
||||
return new InsertBuilderImpl<PreparedSQLUpdateAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReplaceBuilder<PreparedSQLUpdateBatchAction> createReplaceBatch(@NotNull String tableName) {
|
||||
return new ReplaceBuilderImpl<PreparedSQLUpdateBatchAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLBatchUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReplaceBuilder<PreparedSQLUpdateAction> createReplace(@NotNull String tableName) {
|
||||
return new ReplaceBuilderImpl<PreparedSQLUpdateAction>(this, tableName) {
|
||||
@Override
|
||||
public PreparedSQLUpdateAction setColumnNames(List<String> columnNames) {
|
||||
return new PreparedSQLUpdateActionImpl(getManager(), buildSQL(getTableName(), columnNames));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateBuilder createUpdate(@NotNull String tableName) {
|
||||
return new UpdateBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteBuilder createDelete(@NotNull String tableName) {
|
||||
return new DeleteBuilderImpl(this, tableName);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
package cc.carm.lib.easysql.query;
|
||||
|
||||
import cc.carm.lib.easysql.action.query.QueryActionImpl;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class SQLQueryImpl implements SQLQuery {
|
||||
|
||||
protected final long executeTime;
|
||||
|
||||
protected SQLManagerImpl sqlManager;
|
||||
protected QueryActionImpl queryAction;
|
||||
|
||||
Connection connection;
|
||||
Statement statement;
|
||||
|
||||
ResultSet resultSet;
|
||||
|
||||
public SQLQueryImpl(
|
||||
SQLManagerImpl sqlManager, QueryActionImpl queryAction,
|
||||
Connection connection, Statement statement, ResultSet resultSet
|
||||
) {
|
||||
this(sqlManager, queryAction, connection, statement, resultSet, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public SQLQueryImpl(
|
||||
SQLManagerImpl sqlManager, QueryActionImpl queryAction,
|
||||
Connection connection, Statement statement, ResultSet resultSet,
|
||||
long executeTime
|
||||
) {
|
||||
this.executeTime = executeTime;
|
||||
this.sqlManager = sqlManager;
|
||||
this.queryAction = queryAction;
|
||||
this.connection = connection;
|
||||
this.statement = statement;
|
||||
this.resultSet = resultSet;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getExecuteTime() {
|
||||
return this.executeTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLManagerImpl getManager() {
|
||||
return this.sqlManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public QueryActionImpl getAction() {
|
||||
return this.queryAction;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultSet getResultSet() {
|
||||
return this.resultSet;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSQLContent() {
|
||||
return getAction().getSQLContent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
if (getResultSet() != null) getResultSet().close();
|
||||
if (getStatement() != null) getStatement().close();
|
||||
if (getConnection() != null) getConnection().close();
|
||||
|
||||
getManager().debug("#" + getAction().getShortID() +
|
||||
" -> finished after " + (System.currentTimeMillis() - getExecuteTime()) + " ms."
|
||||
);
|
||||
getManager().getActiveQuery().remove(getAction().getActionUUID());
|
||||
} catch (SQLException e) {
|
||||
getAction().handleException(getAction().defaultExceptionHandler(), e);
|
||||
}
|
||||
this.queryAction = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement getStatement() {
|
||||
return this.statement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection getConnection() {
|
||||
return this.connection;
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
package cc.carm.lib.easysql.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.sql.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public class StatementUtil {
|
||||
|
||||
/**
|
||||
* 创建一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param params "?"所代表的对应参数列表
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatement(
|
||||
Connection connection, String sql, Object[] params
|
||||
) throws SQLException {
|
||||
return createPrepareStatement(connection, sql, params, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param params "?"所代表的对应参数列表
|
||||
* @param returnGeneratedKey 是否会返回自增主键
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatement(
|
||||
Connection connection, String sql, Object[] params, boolean returnGeneratedKey
|
||||
) throws SQLException {
|
||||
sql = sql.trim();
|
||||
PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
|
||||
Map<Integer, Integer> nullTypeMap = new HashMap<>();
|
||||
if (params != null) fillParams(statement, Arrays.asList(params), nullTypeMap);
|
||||
statement.addBatch();
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建批量操作的一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param paramsBatch "?"所代表的对应参数列表
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatementBatch(
|
||||
Connection connection, String sql, Iterable<Object[]> paramsBatch
|
||||
) throws SQLException {
|
||||
return createPrepareStatementBatch(connection, sql, paramsBatch, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建批量操作的一个 {@link PreparedStatement} 。
|
||||
*
|
||||
* @param connection 数据库连接
|
||||
* @param sql SQL语句,使用"?"做为占位符
|
||||
* @param paramsBatch "?"所代表的对应参数列表
|
||||
* @param returnGeneratedKey 是否会返回自增主键
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement createPrepareStatementBatch(
|
||||
Connection connection, String sql, Iterable<Object[]> paramsBatch, boolean returnGeneratedKey
|
||||
) throws SQLException {
|
||||
|
||||
sql = sql.trim();
|
||||
PreparedStatement statement = connection.prepareStatement(sql, returnGeneratedKey ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
|
||||
Map<Integer, Integer> nullTypeMap = new HashMap<>();
|
||||
for (Object[] params : paramsBatch) {
|
||||
fillParams(statement, Arrays.asList(params), nullTypeMap);
|
||||
statement.addBatch();
|
||||
}
|
||||
|
||||
return statement;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 填充PreparedStatement的参数。
|
||||
*
|
||||
* @param statement PreparedStatement
|
||||
* @param params SQL参数
|
||||
* @return {@link PreparedStatement} 填充参数后的PreparedStatement
|
||||
* @throws SQLException SQL执行异常
|
||||
*/
|
||||
public static PreparedStatement fillParams(
|
||||
PreparedStatement statement, Iterable<?> params
|
||||
) throws SQLException {
|
||||
return fillParams(statement, params, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 填充PreparedStatement的参数。
|
||||
*
|
||||
* @param statement PreparedStatement
|
||||
* @param params SQL参数
|
||||
* @param nullCache null参数的类型缓存,避免循环中重复获取类型
|
||||
* @return 完成参数填充的 {@link PreparedStatement}
|
||||
*/
|
||||
public static PreparedStatement fillParams(
|
||||
PreparedStatement statement, Iterable<?> params, Map<Integer, Integer> nullCache
|
||||
) throws SQLException {
|
||||
if (null == params) {
|
||||
return statement;// 无参数
|
||||
}
|
||||
|
||||
int paramIndex = 1;//第一个参数从1计数
|
||||
for (Object param : params) {
|
||||
setParam(statement, paramIndex++, param, nullCache);
|
||||
}
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取null字段对应位置的数据类型
|
||||
* 如果类型获取失败将使用默认的 {@link Types#VARCHAR}
|
||||
*
|
||||
* @param statement {@link PreparedStatement}
|
||||
* @param paramIndex 参数序列,第一位从1开始
|
||||
* @return 数据类型,默认为 {@link Types#VARCHAR}
|
||||
*/
|
||||
public static int getNullType(PreparedStatement statement, int paramIndex) {
|
||||
try {
|
||||
ParameterMetaData pmd = statement.getParameterMetaData();
|
||||
return pmd.getParameterType(paramIndex);
|
||||
} catch (SQLException ignore) {
|
||||
return Types.VARCHAR;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为 {@link PreparedStatement} 设置单个参数
|
||||
*
|
||||
* @param preparedStatement {@link PreparedStatement}
|
||||
* @param paramIndex 参数序列,从1开始
|
||||
* @param param 参数,不能为{@code null}
|
||||
* @param nullCache 用于缓存参数为null位置的类型,避免重复获取
|
||||
*/
|
||||
private static void setParam(
|
||||
PreparedStatement preparedStatement, int paramIndex, Object param,
|
||||
Map<Integer, Integer> nullCache
|
||||
) throws SQLException {
|
||||
|
||||
if (param == null) {
|
||||
Integer type = (null == nullCache) ? null : nullCache.get(paramIndex);
|
||||
if (null == type) {
|
||||
type = getNullType(preparedStatement, paramIndex);
|
||||
if (null != nullCache) {
|
||||
nullCache.put(paramIndex, type);
|
||||
}
|
||||
}
|
||||
preparedStatement.setNull(paramIndex, type);
|
||||
}
|
||||
|
||||
// 针对UUID特殊处理,避免元数据直接传入
|
||||
if (param instanceof UUID) {
|
||||
preparedStatement.setString(paramIndex, param.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
// 针对StringBuilder或StringBuffer进行处理,避免元数据传入
|
||||
if (param instanceof StringBuilder || param instanceof StringBuffer) {
|
||||
preparedStatement.setString(paramIndex, param.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
// 日期特殊处理,默认按照时间戳传入,避免精度丢失
|
||||
if (param instanceof java.util.Date) {
|
||||
if (param instanceof Date) {
|
||||
preparedStatement.setDate(paramIndex, (Date) param);
|
||||
} else if (param instanceof Time) {
|
||||
preparedStatement.setTime(paramIndex, (Time) param);
|
||||
} else {
|
||||
preparedStatement.setTimestamp(paramIndex, new Timestamp(((java.util.Date) param).getTime()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 针对大数字类型的特殊处理
|
||||
if (param instanceof Number) {
|
||||
if (param instanceof BigDecimal) {
|
||||
// BigDecimal的转换交给JDBC驱动处理
|
||||
preparedStatement.setBigDecimal(paramIndex, (BigDecimal) param);
|
||||
return;
|
||||
} else if (param instanceof BigInteger) {
|
||||
preparedStatement.setBigDecimal(paramIndex, new BigDecimal((BigInteger) param));
|
||||
return;
|
||||
}
|
||||
// 其它数字类型按照默认类型传入
|
||||
}
|
||||
|
||||
if (param instanceof Enum) {
|
||||
//枚举类采用 name()
|
||||
preparedStatement.setString(paramIndex, ((Enum<?>) param).name());
|
||||
return;
|
||||
}
|
||||
|
||||
// 其它参数类型直接传入
|
||||
preparedStatement.setObject(paramIndex, param);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<version>0.3.7</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
<maven.javadoc.skip>true</maven.javadoc.skip>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
</properties>
|
||||
|
||||
<artifactId>easysql-test</artifactId>
|
||||
|
||||
<name>EasySQL-Test</name>
|
||||
<description>EasySQL的测试代码</description>
|
||||
<url>https://github.com/CarmJos/EasySQL</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>${project.parent.groupId}</groupId>
|
||||
<artifactId>easysql-beecp</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>8.0.28</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.36</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<version>2.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
<excludes>
|
||||
<exclude>META-INF/MANIFEST.MF</exclude>
|
||||
</excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
<!-- when downloading via Maven we can pull depends individually -->
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<descriptorRefs>
|
||||
<descriptRef>jar-with-dependencies</descriptRef>
|
||||
</descriptorRefs>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>cc.carm.lib.easysql.testrunner.Main</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>assembly</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -1,36 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public abstract class EasySQLTest {
|
||||
|
||||
@ApiStatus.OverrideOnly
|
||||
public abstract void onTest(SQLManager sqlManager) throws SQLException;
|
||||
|
||||
public boolean executeTest(int index, SQLManager sqlManager) {
|
||||
String testName = getClass().getSimpleName();
|
||||
|
||||
print(" #%s 测试 @%s 开始", index, testName);
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
onTest(sqlManager);
|
||||
print(" #%s 测试 @%s 成功,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
print(" #%s 测试 @%s 失败,耗时 %s ms。", index, testName, (System.currentTimeMillis() - start));
|
||||
exception.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected static void print(@NotNull String format, Object... params) {
|
||||
Main.print(format, params);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner;
|
||||
|
||||
import cc.carm.lib.easysql.EasySQL;
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.tests.DeleteTest;
|
||||
import cc.carm.lib.easysql.testrunner.tests.QueryCloseTest;
|
||||
import cc.carm.lib.easysql.testrunner.tests.QueryFunctionTest;
|
||||
import cc.carm.lib.easysql.testrunner.tests.TableCreateTest;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Scanner;
|
||||
import java.util.Set;
|
||||
|
||||
@TestOnly
|
||||
@SuppressWarnings("all")
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length < 4) {
|
||||
print("请提供以下参数:<数据库驱动> <数据库地址(JDBC)> <数据库用户> <数据库密码> [是否采用DEBUG(y/n)]");
|
||||
return;
|
||||
}
|
||||
|
||||
SQLManager sqlManager;
|
||||
try {
|
||||
print("初始化 SQLManager...");
|
||||
print("数据库驱动 %s", args[0]);
|
||||
print("数据库地址 %s", args[1]);
|
||||
print("数据库用户 %s", args[2]);
|
||||
print("数据库密码 %s", args[3]);
|
||||
sqlManager = EasySQL.createManager(args[0], args[1], args[2], args[3]);
|
||||
sqlManager.setDebugMode(args.length > 4);
|
||||
print("SQLManager 初始化完成!");
|
||||
} catch (Exception exception) {
|
||||
print("SQLManager 初始化失败,请检查数据库配置。");
|
||||
exception.printStackTrace();
|
||||
return;
|
||||
}
|
||||
|
||||
print("加载测试类...");
|
||||
Set<EasySQLTest> tests = new LinkedHashSet<>();
|
||||
tests.add(new TableCreateTest());
|
||||
// tests.add(new TableAlterTest());
|
||||
// tests.add(new TableRenameTest());
|
||||
// tests.add(new QueryNotCloseTest());
|
||||
tests.add(new QueryCloseTest());
|
||||
// tests.add(new SQLUpdateBatchTests());
|
||||
// tests.add(new SQLUpdateReturnKeysTest());
|
||||
tests.add(new QueryFunctionTest());
|
||||
tests.add(new DeleteTest());
|
||||
|
||||
print("准备进行测试...");
|
||||
|
||||
int index = 1;
|
||||
int success = 0;
|
||||
|
||||
Iterator<EasySQLTest> testIterator = tests.iterator();
|
||||
|
||||
print("准备完成,请按回车键开始执行测试。");
|
||||
|
||||
while (testIterator.hasNext()) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
if (scanner.nextLine() != null) {
|
||||
|
||||
EasySQLTest currentTest = testIterator.next();
|
||||
|
||||
if (currentTest.executeTest(index, sqlManager)) {
|
||||
success++;
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
print(" ");
|
||||
print("全部测试执行完毕,成功 %s 个,失败 %s 个。",
|
||||
success, (tests.size() - success)
|
||||
);
|
||||
|
||||
EasySQL.shutdownManager(sqlManager);
|
||||
|
||||
}
|
||||
|
||||
public static void print(@NotNull String format, Object... params) {
|
||||
System.out.printf((format) + "%n", params);
|
||||
}
|
||||
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class DeleteTest extends EasySQLTest {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
Integer changes = sqlManager.createDelete("test_user_table")
|
||||
.addCondition("id", ">", 5)
|
||||
.addNotNullCondition("username")
|
||||
.build().execute();
|
||||
|
||||
System.out.println("change(s): " + changes);
|
||||
|
||||
}
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryCloseTest extends EasySQLTest {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
try (SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute()) {
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.println("id: " + resultSet.getInt("id") + " username: " + resultSet.getString("username"));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryFunctionTest extends EasySQLTest {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
Integer id_1 = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(1)
|
||||
.build().executeFunction(query -> {
|
||||
if (!query.getResultSet().next()) return -1;
|
||||
else return query.getResultSet().getInt("id");
|
||||
});
|
||||
|
||||
System.out.println("id (ps): " + id_1);
|
||||
|
||||
Integer id_2 = sqlManager.createQuery().withSQL("SELECT id FROM test_user_table ORDER BY id DESC LIMIT 1")
|
||||
.executeFunction(query -> {
|
||||
if (!query.getResultSet().next()) return -1;
|
||||
else return query.getResultSet().getInt("id");
|
||||
});
|
||||
|
||||
System.out.println("id (s): " + id_2);
|
||||
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.SQLQuery;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class QueryNotCloseTest extends EasySQLTest {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
SQLQuery query = sqlManager.createQuery()
|
||||
.inTable("test_user_table")
|
||||
.orderBy("id", false)
|
||||
.setLimit(5)
|
||||
.build().execute();
|
||||
|
||||
ResultSet resultSet = query.getResultSet();
|
||||
|
||||
while (resultSet.next()) {
|
||||
|
||||
System.out.println("id: " + resultSet.getInt("id") + " username: " + resultSet.getString("username"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class SQLUpdateBatchTests extends EasySQLTest {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
List<Integer> updates = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.execute();
|
||||
|
||||
System.out.println("changes " + Arrays.toString(updates.toArray()));
|
||||
|
||||
}
|
||||
|
||||
protected List<Object[]> generateParams() {
|
||||
return IntStream.range(0, 5).mapToObj(i -> generateParam()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected Object[] generateParam() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
return new Object[]{uuid, uuid.toString().substring(0, 5), (int) (Math.random() * 50)};
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLUpdateReturnKeysTest extends SQLUpdateBatchTests {
|
||||
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
List<Integer> generatedKeys = sqlManager.createInsertBatch("test_user_table")
|
||||
.setColumnNames("uuid", "username", "age")
|
||||
.setAllParams(generateParams())
|
||||
.returnGeneratedKeys()
|
||||
.execute();
|
||||
|
||||
System.out.println("generated " + Arrays.toString(generatedKeys.toArray()));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.NumberType;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableAlterTest extends EasySQLTest {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 修改 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test", "VARCHAR(16) NOT NULL")
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.addColumn("test2", "VARCHAR(16) NOT NULL", "username")
|
||||
.execute();
|
||||
|
||||
|
||||
print(" 修改 test_user_info");
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addAutoIncrementColumn("num", NumberType.BIGINT, false, true)
|
||||
.execute();
|
||||
|
||||
sqlManager.alterTable("test_user_info")
|
||||
.addColumn("a", "VARCHAR(16) NOT NULL", "")
|
||||
.execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.api.enums.ForeignKeyRule;
|
||||
import cc.carm.lib.easysql.api.enums.IndexType;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableCreateTest extends EasySQLTest {
|
||||
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
|
||||
print(" 创建 test_user_table");
|
||||
sqlManager.createTable("test_user_table")
|
||||
.addAutoIncrementColumn("id")
|
||||
.addColumn("uuid", "VARCHAR(36) NOT NULL", "用户UUID")
|
||||
.addColumn("username", "VARCHAR(16) NOT NULL", "用户名")
|
||||
.addColumn("age", "TINYINT DEFAULT 0 NOT NULL", "年龄")
|
||||
|
||||
.setIndex("uuid", IndexType.UNIQUE_KEY)
|
||||
.build().execute();
|
||||
|
||||
print(" 创建 test_user_info");
|
||||
sqlManager.createTable("test_user_info")
|
||||
.addColumn("uid", "INT UNSIGNED NOT NULL")
|
||||
.addColumn("info", "TEXT", "相关信息")
|
||||
.addForeignKey("uid", "user",
|
||||
"test_user_table", "id",
|
||||
ForeignKeyRule.CASCADE, ForeignKeyRule.CASCADE
|
||||
)
|
||||
.setIndex(IndexType.FULLTEXT_INDEX, "sign", "info")
|
||||
.build().execute();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package cc.carm.lib.easysql.testrunner.tests;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLManager;
|
||||
import cc.carm.lib.easysql.testrunner.EasySQLTest;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TableRenameTest extends EasySQLTest {
|
||||
@Override
|
||||
public void onTest(SQLManager sqlManager) throws SQLException {
|
||||
print(" 重命名 test_user_table");
|
||||
sqlManager.alterTable("test_user_table")
|
||||
.renameTo("test_user_table2")
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,13 @@
|
||||
<parent>
|
||||
<artifactId>easysql-parent</artifactId>
|
||||
<groupId>cc.carm.lib</groupId>
|
||||
<version>0.3.7</version>
|
||||
<version>0.3.18</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<maven.compiler.source>${jdk.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${jdk.version}</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
|
||||
</properties>
|
||||
@@ -81,10 +81,6 @@
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.SQLAction;
|
||||
import cc.carm.lib.easysql.api.function.SQLExceptionHandler;
|
||||
import cc.carm.lib.easysql.api.function.SQLHandler;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public abstract class AbstractSQLAction<T> implements SQLAction<T> {
|
||||
|
||||
protected final @NotNull String sqlContent;
|
||||
private final @NotNull SQLManagerImpl sqlManager;
|
||||
private final @NotNull UUID uuid;
|
||||
private final long createNanoTime;
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
this(manager, sql, System.nanoTime());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, @NotNull UUID uuid) {
|
||||
this(manager, sql, uuid, System.nanoTime());
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql, long createNanoTime) {
|
||||
this(manager, sql, UUID.randomUUID(), createNanoTime);
|
||||
}
|
||||
|
||||
public AbstractSQLAction(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@NotNull UUID uuid, long createNanoTime) {
|
||||
Objects.requireNonNull(manager);
|
||||
Objects.requireNonNull(sql);
|
||||
Objects.requireNonNull(uuid);
|
||||
this.sqlManager = manager;
|
||||
this.sqlContent = sql;
|
||||
this.uuid = uuid;
|
||||
this.createNanoTime = createNanoTime;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public @NotNull UUID getActionUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getShortID() {
|
||||
return getActionUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCreateTime(TimeUnit unit) {
|
||||
return unit.convert(createNanoTime, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getSQLContent() {
|
||||
return this.sqlContent.trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull SQLManagerImpl getManager() {
|
||||
return this.sqlManager;
|
||||
}
|
||||
|
||||
protected void debugMessage(List<Object[]> params) {
|
||||
if (getManager().isDebugMode()) {
|
||||
try {
|
||||
getManager().getDebugHandler().beforeExecute(this, params);
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("FutureReturnValueIgnored")
|
||||
public void executeAsync(SQLHandler<T> success, SQLExceptionHandler failure) {
|
||||
getManager().getExecutorPool().submit(() -> {
|
||||
try {
|
||||
T returnedValue = execute();
|
||||
if (success != null) success.accept(returnedValue);
|
||||
} catch (SQLException e) {
|
||||
handleException(failure, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class PreparedSQLBatchUpdateActionImpl
|
||||
extends AbstractSQLAction<List<Long>>
|
||||
implements PreparedSQLUpdateBatchAction {
|
||||
|
||||
boolean returnKeys = false;
|
||||
@NotNull List<Object[]> allParams;
|
||||
|
||||
public PreparedSQLBatchUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
this.allParams = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setAllParams(Iterable<Object[]> allParams) {
|
||||
List<Object[]> paramsList = new ArrayList<>();
|
||||
allParams.forEach(paramsList::add);
|
||||
this.allParams = paramsList;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction addParamsBatch(Object... params) {
|
||||
this.allParams.add(params);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateBatchAction setReturnGeneratedKeys(boolean returnGeneratedKey) {
|
||||
this.returnKeys = returnGeneratedKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<Long> execute() throws SQLException {
|
||||
debugMessage(allParams);
|
||||
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
|
||||
connection, getSQLContent(), allParams, returnKeys
|
||||
)) {
|
||||
|
||||
int[] executed = statement.executeBatch();
|
||||
|
||||
if (!returnKeys) {
|
||||
return Arrays.stream(executed).mapToLong(Long::valueOf).boxed().collect(Collectors.toList());
|
||||
} else {
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
List<Long> generatedKeys = new ArrayList<>();
|
||||
while (resultSet.next()) {
|
||||
generatedKeys.add(resultSet.getLong(1));
|
||||
}
|
||||
return generatedKeys;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class PreparedSQLUpdateActionImpl
|
||||
extends SQLUpdateActionImpl
|
||||
implements PreparedSQLUpdateAction {
|
||||
|
||||
Object[] params;
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
this(manager, sql, (Object[]) null);
|
||||
}
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@Nullable List<Object> params) {
|
||||
this(manager, sql, params == null ? null : params.toArray());
|
||||
}
|
||||
|
||||
public PreparedSQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql,
|
||||
@Nullable Object[] params) {
|
||||
super(manager, sql);
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateActionImpl setParams(Object... params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedSQLUpdateAction setParams(@Nullable Iterable<Object> params) {
|
||||
if (params == null) {
|
||||
return setParams((Object[]) null);
|
||||
} else {
|
||||
List<Object> paramsList = new ArrayList<>();
|
||||
params.forEach(paramsList::add);
|
||||
return setParams(paramsList.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Long execute() throws SQLException {
|
||||
debugMessage(Collections.singletonList(params));
|
||||
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
|
||||
try (PreparedStatement statement = StatementUtil.createPrepareStatement(
|
||||
connection, getSQLContent(), params, returnGeneratedKeys
|
||||
)) {
|
||||
|
||||
int changes = statement.executeUpdate();
|
||||
if (!returnGeneratedKeys) return (long) changes;
|
||||
else {
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
return resultSet.next() ? resultSet.getLong(1) : -1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class SQLUpdateActionImpl
|
||||
extends AbstractSQLAction<Long>
|
||||
implements SQLUpdateAction {
|
||||
|
||||
boolean returnGeneratedKeys = false;
|
||||
|
||||
public SQLUpdateActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Long execute() throws SQLException {
|
||||
debugMessage(new ArrayList<>());
|
||||
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
|
||||
if (!returnGeneratedKeys) {
|
||||
return (long) statement.executeUpdate(getSQLContent());
|
||||
} else {
|
||||
statement.executeUpdate(getSQLContent(), Statement.RETURN_GENERATED_KEYS);
|
||||
|
||||
try (ResultSet resultSet = statement.getGeneratedKeys()) {
|
||||
return resultSet.next() ? resultSet.getLong(1) : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public SQLUpdateAction setReturnGeneratedKey(boolean returnGeneratedKey) {
|
||||
this.returnGeneratedKeys = returnGeneratedKey;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cc.carm.lib.easysql.action;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class SQLUpdateBatchActionImpl
|
||||
extends AbstractSQLAction<List<Integer>>
|
||||
implements SQLUpdateBatchAction {
|
||||
|
||||
protected final List<String> sqlContents = new ArrayList<>();
|
||||
|
||||
public SQLUpdateBatchActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
this.sqlContents.add(sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<String> getSQLContents() {
|
||||
return this.sqlContents;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SQLUpdateBatchAction addBatch(@NotNull String sql) {
|
||||
Objects.requireNonNull(sql, "sql could not be null");
|
||||
this.sqlContents.add(sql);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull List<Integer> execute() throws SQLException {
|
||||
debugMessage(new ArrayList<>());
|
||||
|
||||
try (Connection connection = getManager().getConnection()) {
|
||||
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
|
||||
for (String content : this.sqlContents) {
|
||||
statement.addBatch(content);
|
||||
}
|
||||
|
||||
int[] executed = statement.executeBatch();
|
||||
|
||||
return Arrays.stream(executed).boxed().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package cc.carm.lib.easysql.action.query;
|
||||
|
||||
import cc.carm.lib.easysql.api.action.query.PreparedQueryAction;
|
||||
import cc.carm.lib.easysql.manager.SQLManagerImpl;
|
||||
import cc.carm.lib.easysql.query.SQLQueryImpl;
|
||||
import cc.carm.lib.easysql.util.StatementUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class PreparedQueryActionImpl extends QueryActionImpl implements PreparedQueryAction {
|
||||
|
||||
Consumer<PreparedStatement> handler;
|
||||
Object[] params;
|
||||
|
||||
public PreparedQueryActionImpl(@NotNull SQLManagerImpl manager, @NotNull String sql) {
|
||||
super(manager, sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl setParams(@Nullable Object... params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl setParams(@Nullable Iterable<Object> params) {
|
||||
if (params == null) {
|
||||
return setParams((Object[]) null);
|
||||
} else {
|
||||
List<Object> paramsList = new ArrayList<>();
|
||||
params.forEach(paramsList::add);
|
||||
return setParams(paramsList.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreparedQueryActionImpl handleStatement(@Nullable Consumer<PreparedStatement> statement) {
|
||||
this.handler = statement;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public @NotNull SQLQueryImpl execute() throws SQLException {
|
||||
debugMessage(Collections.singletonList(params));
|
||||
|
||||
Connection connection = getManager().getConnection();
|
||||
PreparedStatement preparedStatement;
|
||||
try {
|
||||
if (handler == null) {
|
||||
preparedStatement = StatementUtil.createPrepareStatement(connection, getSQLContent(), this.params);
|
||||
} else {
|
||||
preparedStatement = connection.prepareStatement(getSQLContent());
|
||||
handler.accept(preparedStatement);
|
||||
}
|
||||
} catch (SQLException exception) {
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
|
||||
try {
|
||||
SQLQueryImpl query = new SQLQueryImpl(
|
||||
getManager(), this,
|
||||
connection, preparedStatement,
|
||||
preparedStatement.executeQuery()
|
||||
);
|
||||
getManager().getActiveQuery().put(getActionUUID(), query);
|
||||
return query;
|
||||
} catch (SQLException exception) {
|
||||
preparedStatement.close();
|
||||
connection.close();
|
||||
throw exception;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user