1
mirror of https://github.com/CarmJos/EasySQL.git synced 2024-09-19 21:35:47 +00:00

[0.3.12] 版本更新 (破坏性)

- `[R]` 采用 slf4j-api 替代Java原生的Logger库。
- `[A]` 新增 SQLDebugHandler 用于更好的处理调试消息。
This commit is contained in:
Carm Jos 2022-04-13 06:30:20 +08:00
parent 03e157d3d9
commit 18dd618c21
21 changed files with 187 additions and 44 deletions

View File

@ -5,7 +5,7 @@
<parent>
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId>
<version>0.3.11</version>
<version>0.3.12</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -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>

View File

@ -6,10 +6,12 @@ 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.logging.Logger;
/**
* SQLAction 是用于承载SQL语句并进行处理返回的基本类
@ -60,6 +62,15 @@ public interface SQLAction<T> {
*/
@NotNull String getSQLContent();
/**
* 得到该Action所要执行的源SQL语句列表
*
* @return 源SQL语句列表
*/
default @NotNull List<String> getSQLContents() {
return Collections.singletonList(getSQLContent());
}
/**
* 得到承载该Action的对应{@link SQLManager}
*

View File

@ -5,9 +5,11 @@ import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.SQLUpdateAction;
import cc.carm.lib.easysql.api.action.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;
@ -16,7 +18,6 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.logging.Logger;
/**
* SQLManager 是EasySQL的核心类用于管理数据库连接提供数据库操作的方法
@ -29,12 +30,38 @@ public interface SQLManager {
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);
/**
* 得到连接池源
*

View File

@ -21,6 +21,7 @@ public interface SQLUpdateBatchAction extends SQLAction<List<Integer>> {
return getSQLContents().get(0);
}
List<String> getSQLContents();
@Override
@NotNull List<String> getSQLContents();
}

View File

@ -0,0 +1,80 @@
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.slf4j.Logger;
import java.util.Arrays;
import java.util.List;
/**
* 异常处理器
* <br> 在使用 {@link SQLAction#execute(SQLExceptionHandler)} 等相关方法时
* 如果发生异常则会调用错误处理器进行错误内容的输出提示
*/
public interface SQLDebugHandler {
/**
* 该方法将在 {@link SQLAction#execute()} 执行前调用
*
* @param action {@link SQLAction} 对象
* @param params 执行传入的参数列表
* 实际上仅有 {@link PreparedSQLUpdateAction} {@link PreparedSQLUpdateBatchAction} 才会有传入参数
*/
void beforeExecute(@NotNull SQLAction<?> action, @NotNull List<Object[]> params);
/**
* 该方法将在 {@link SQLQuery#close()} 执行后调用
*
* @param query {@link SQLQuery} 对象
* @param executeTime 该次查询开始执行的时间
* @param closeTime 该次查询彻底关闭的时间
*/
void afterQuery(@NotNull SQLQuery query, long executeTime, long closeTime);
@SuppressWarnings("DuplicatedCode")
static SQLDebugHandler defaultHandler(Logger logger) {
return new SQLDebugHandler() {
@Override
public void beforeExecute(@NotNull SQLAction<?> action, @NotNull List<Object[]> params) {
logger.info("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
logger.info("┣# ActionUUID: {}", action.getActionUUID());
logger.info("┣# ActionType: {}", action.getClass().getName());
if (action.getSQLContents().size() == 1) {
logger.info("┣# SQLContent: {}", action.getSQLContents().get(0));
} else {
logger.info("┣# SQLContents: ");
int i = 0;
for (String sqlContent : action.getSQLContents()) {
logger.info("┃ [{}] {}", ++i, sqlContent);
}
}
if (params.size() == 1) {
Object[] param = params.get(0);
logger.info("┣# SQLParams({}): {}", param.length, Arrays.stream(param).map(Object::toString).reduce((a, b) -> a + ", " + b).orElse(""));
} else if (params.size() > 1) {
logger.info("┣# SQLParams: ");
int i = 0;
for (Object[] param : params) {
logger.info("┃ [{}] {}", ++i, Arrays.stream(param).map(Object::toString).reduce((a, b) -> a + ", " + b).orElse(""));
}
}
logger.info("┣# createTime: {}", action.getCreateTime());
logger.info("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
@Override
public void afterQuery(@NotNull SQLQuery query, long executeTime, long closeTime) {
logger.info("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
logger.info("┣# ActionUUID: {}", query.getAction().getActionUUID());
logger.info("┣# SQLContent: {}", query.getSQLContent());
logger.info("┣# executeCote: {} ms", (closeTime - executeTime));
logger.info("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
}
};
}
}

View File

@ -1,11 +1,10 @@
package cc.carm.lib.easysql.api.function;
import cc.carm.lib.easysql.api.SQLAction;
import cc.carm.lib.easysql.api.action.SQLUpdateBatchAction;
import org.slf4j.Logger;
import java.sql.SQLException;
import java.util.function.BiConsumer;
import java.util.logging.Logger;
/**
* 异常处理器
@ -23,15 +22,11 @@ public interface SQLExceptionHandler extends BiConsumer<SQLException, SQLAction<
*/
static SQLExceptionHandler detailed(Logger logger) {
return (exception, sqlAction) -> {
if (sqlAction instanceof SQLUpdateBatchAction) {
logger.severe("Error when execute SQLs : ");
int i = 1;
for (String content : ((SQLUpdateBatchAction) sqlAction).getSQLContents()) {
logger.severe(String.format("#%d {%s}", i, content));
i++;
}
} else {
logger.severe("Error when execute { " + sqlAction.getSQLContent() + " }");
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();
};

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.11</version>
<version>0.3.12</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.11</version>
<version>0.3.12</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -7,6 +7,7 @@ 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;
@ -66,8 +67,10 @@ public abstract class AbstractSQLAction<T> implements SQLAction<T> {
return this.sqlManager;
}
protected void outputDebugMessage() {
getManager().debug("# " + getShortID() + " -> { " + getSQLContent() + " }");
protected void debugMessage(List<Object[]> params) {
if (getManager().isDebugMode()) {
getManager().getDebugHandler().beforeExecute(this, params);
}
}
@Override

View File

@ -48,12 +48,13 @@ public class PreparedSQLBatchUpdateActionImpl
@Override
public @NotNull List<Long> execute() throws SQLException {
debugMessage(allParams);
try (Connection connection = getManager().getConnection()) {
try (PreparedStatement statement = StatementUtil.createPrepareStatementBatch(
connection, getSQLContent(), allParams, returnKeys
)) {
outputDebugMessage();
int[] executed = statement.executeBatch();
if (!returnKeys) {

View File

@ -11,6 +11,7 @@ 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
@ -53,14 +54,14 @@ public class PreparedSQLUpdateActionImpl
@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
)) {
outputDebugMessage();
int changes = statement.executeUpdate();
if (!returnGeneratedKeys) return (long) changes;
else {

View File

@ -8,6 +8,7 @@ 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>
@ -21,9 +22,10 @@ public class SQLUpdateActionImpl
@Override
public @NotNull Long execute() throws SQLException {
debugMessage(new ArrayList<>());
try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) {
outputDebugMessage();
if (!returnGeneratedKeys) {
return (long) statement.executeUpdate(getSQLContent());

View File

@ -38,10 +38,11 @@ public class SQLUpdateBatchActionImpl
@Override
public @NotNull List<Integer> execute() throws SQLException {
debugMessage(new ArrayList<>());
try (Connection connection = getManager().getConnection()) {
try (Statement statement = connection.createStatement()) {
outputDebugMessage();
for (String content : this.sqlContents) {
statement.addBatch(content);
@ -55,12 +56,4 @@ public class SQLUpdateBatchActionImpl
}
}
@Override
protected void outputDebugMessage() {
getManager().debug("# " + getShortID() + " -> [");
for (String content : getSQLContents()) getManager().debug(String.format(" { %s }", content));
getManager().debug("]");
}
}

View File

@ -11,6 +11,7 @@ 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;
@ -49,8 +50,8 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
@Override
public @NotNull SQLQueryImpl execute() throws SQLException {
outputDebugMessage();
debugMessage(Collections.singletonList(params));
Connection connection = getManager().getConnection();
PreparedStatement preparedStatement;
try {
@ -74,7 +75,6 @@ public class PreparedQueryActionImpl extends QueryActionImpl implements Prepared
executeTime
);
getManager().getActiveQuery().put(getActionUUID(), query);
return query;
} catch (SQLException exception) {
preparedStatement.close();

View File

@ -12,6 +12,7 @@ import org.jetbrains.annotations.NotNull;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements QueryAction {
@ -21,6 +22,7 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
@Override
public @NotNull SQLQueryImpl execute() throws SQLException {
debugMessage(new ArrayList<>());
Connection connection = getManager().getConnection();
Statement statement;
@ -32,7 +34,6 @@ public class QueryActionImpl extends AbstractSQLAction<SQLQuery> implements Quer
throw ex;
}
outputDebugMessage();
try {
long executeTime = System.currentTimeMillis();
SQLQueryImpl query = new SQLQueryImpl(

View File

@ -10,6 +10,8 @@ import cc.carm.lib.easysql.builder.AbstractSQLBuilder;
import cc.carm.lib.easysql.manager.SQLManagerImpl;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
public class QueryBuilderImpl extends AbstractSQLBuilder implements QueryBuilder {

View File

@ -10,10 +10,13 @@ import cc.carm.lib.easysql.api.action.PreparedSQLUpdateAction;
import cc.carm.lib.easysql.api.action.PreparedSQLUpdateBatchAction;
import cc.carm.lib.easysql.api.action.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 cc.carm.lib.easysql.builder.impl.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
@ -23,7 +26,6 @@ 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 {
@ -34,14 +36,19 @@ public class SQLManagerImpl implements SQLManager {
@NotNull Supplier<Boolean> debugMode = () -> Boolean.FALSE;
@NotNull SQLExceptionHandler exceptionHandler;
@NotNull SQLDebugHandler debugHandler;
public SQLManagerImpl(@NotNull DataSource dataSource) {
this(dataSource, null);
}
public SQLManagerImpl(@NotNull DataSource dataSource, @Nullable String name) {
this(dataSource, LoggerFactory.getLogger(SQLManagerImpl.class), name);
}
public SQLManagerImpl(@NotNull DataSource dataSource, @NotNull Logger logger, @Nullable String name) {
String managerName = "SQLManager" + (name != null ? "#" + name : "");
this.LOGGER = Logger.getLogger(managerName);
this.LOGGER = logger;
this.dataSource = dataSource;
this.executorPool = Executors.newFixedThreadPool(3, r -> {
Thread thread = new Thread(r, managerName);
@ -50,6 +57,7 @@ public class SQLManagerImpl implements SQLManager {
});
this.exceptionHandler = SQLExceptionHandler.detailed(getLogger());
this.debugHandler = SQLDebugHandler.defaultHandler(getLogger());
}
@Override
@ -62,6 +70,16 @@ public class SQLManagerImpl implements SQLManager {
this.debugMode = debugMode;
}
@Override
public @NotNull SQLDebugHandler getDebugHandler() {
return this.debugHandler;
}
@Override
public void setDebugHandler(@NotNull SQLDebugHandler debugHandler) {
this.debugHandler = debugHandler;
}
public void debug(String msg) {
if (isDebugMode()) getLogger().info("[DEBUG] " + msg);
}

View File

@ -71,9 +71,9 @@ public class SQLQueryImpl implements SQLQuery {
if (getStatement() != null && !getStatement().isClosed()) getStatement().close();
if (getConnection() != null && !getConnection().isClosed()) getConnection().close();
getManager().debug("#" + getAction().getShortID() +
" -> finished after " + (System.currentTimeMillis() - getExecuteTime()) + " ms."
);
if (getManager().isDebugMode()) {
getManager().getDebugHandler().afterQuery(this, getExecuteTime(), System.currentTimeMillis());
}
getManager().getActiveQuery().remove(getAction().getActionUUID());
} catch (SQLException e) {
getAction().handleException(getAction().defaultExceptionHandler(), e);

View File

@ -17,7 +17,7 @@
<groupId>cc.carm.lib</groupId>
<artifactId>easysql-parent</artifactId>
<packaging>pom</packaging>
<version>0.3.11</version>
<version>0.3.12</version>
<modules>
<module>api</module>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.11</version>
<version>0.3.12</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>easysql-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>0.3.11</version>
<version>0.3.12</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>