Browse Source

REPORT-69942 更新Druid到1.2.9

bugfix/KERNEL-11409-jackson
rinoux 3 years ago
parent
commit
086e32eaba
  1. 13
      fine-druid/readme.MD
  2. 5
      fine-druid/src/main/java/com/fr/third/alibaba/druid/DbType.java
  3. 1
      fine-druid/src/main/java/com/fr/third/alibaba/druid/filter/FilterManager.java
  4. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/mock/handler/MySqlMockExecuteHandlerImpl.java
  5. 79
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidAbstractDataSource.java
  6. 21
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidConnectionHolder.java
  7. 393
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidDataSource.java
  8. 224
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidDataSourceFactory.java
  9. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidPooledStatement.java
  10. 8
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/vendor/MSSQLValidConnectionChecker.java
  11. 6
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/vendor/MySqlValidConnectionChecker.java
  12. 62
      fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/vendor/OceanBaseValidConnectionChecker.java
  13. 14
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/PagerUtils.java
  14. 20
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/SQLTransformUtils.java
  15. 13
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/SQLUtils.java
  16. 16
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/SQLOrderBy.java
  17. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLBinaryOpExpr.java
  18. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLBinaryOpExprGroup.java
  19. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLDateExpr.java
  20. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLDateTimeExpr.java
  21. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLIntegerExpr.java
  22. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLTimeExpr.java
  23. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLAnalyzeTableStatement.java
  24. 8
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLCreateTableStatement.java
  25. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLDeleteStatement.java
  26. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLInsertInto.java
  27. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLSelect.java
  28. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java
  29. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLShowGrantsStatement.java
  30. 6
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLUnionQuery.java
  31. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLUpdateStatement.java
  32. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/builder/impl/SQLDeleteBuilderImpl.java
  33. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/builder/impl/SQLSelectBuilderImpl.java
  34. 3
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/builder/impl/SQLUpdateBuilderImpl.java
  35. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/db2/parser/DB2StatementParser.java
  36. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/h2/visitor/H2OutputVisitor.java
  37. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlCreateTableSpaceStatement.java
  38. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlKillStatement.java
  39. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/parser/MySqlStatementParser.java
  40. 16
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java
  41. 0
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/oracle/ast/expr/OracleIntervalExpr.java
  42. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/oracle/parser/OracleStatementParser.java
  43. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/postgresql/ast/stmt/PGInsertStatement.java
  44. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/postgresql/parser/PGSQLStatementParser.java
  45. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/postgresql/visitor/PGOutputVisitor.java
  46. 56
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/ast/stmt/PrestoSelectStatement.java
  47. 10
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/parser/PrestoExprParser.java
  48. 202
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/parser/PrestoSelectParser.java
  49. 15
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/parser/PrestoStatementParser.java
  50. 47
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/visitor/PrestoOutputVisitor.java
  51. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerOutputVisitor.java
  52. 8
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/parser/SQLExprParser.java
  53. 8
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/parser/SQLSelectParser.java
  54. 1
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/repository/SchemaRepository.java
  55. 1
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/transform/SQLRefactorVisitor.java
  56. 3
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/ExportParameterVisitorUtils.java
  57. 7
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/ParameterizedOutputVisitorUtils.java
  58. 24
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java
  59. 4
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SQLDataTypeValidator.java
  60. 6
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SQLEvalVisitorUtils.java
  61. 9
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SchemaStatVisitor.java
  62. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/Ascii.java
  63. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/Char.java
  64. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/If.java
  65. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/Isnull.java
  66. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/OneParamFunctions.java
  67. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/ToDate.java
  68. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/calcite/CalciteMySqlNodeVisitor.java
  69. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/console/DruidStat.java
  70. 18
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/hibernate/DruidConnectionProvider.java
  71. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/http/ResourceServlet.java
  72. 35
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/logging/LogFactory.java
  73. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/monitor/dao/MonitorDaoJdbcImpl.java
  74. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/opds/udf/ExportConditions.java
  75. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/support/opds/udf/SqlTypeUDF.java
  76. 30
      fine-druid/src/main/java/com/fr/third/alibaba/druid/util/ClassLoaderFactory.java
  77. 7
      fine-druid/src/main/java/com/fr/third/alibaba/druid/util/ClassLoaderHelper.java
  78. 13
      fine-druid/src/main/java/com/fr/third/alibaba/druid/util/JdbcConstants.java
  79. 36
      fine-druid/src/main/java/com/fr/third/alibaba/druid/util/JdbcUtils.java
  80. 146
      fine-druid/src/main/java/com/fr/third/alibaba/druid/util/MySqlUtils.java
  81. 24
      fine-druid/src/main/java/com/fr/third/alibaba/druid/util/Utils.java
  82. 1
      fine-druid/src/main/java/com/fr/third/alibaba/druid/wall/WallFilter.java
  83. 2
      fine-druid/src/main/java/com/fr/third/alibaba/druid/wall/spi/ClickhouseWallProvider.java

13
fine-druid/readme.MD

@ -0,0 +1,13 @@
# Alibaba Druid
- FineReport更新时间 `2022-04-27`
- Druid版本 1.2.9
- [github地址](https://github.com/alibaba/druid)
## 变动列表
| 版本 |日期| FineReport变动 |
|-------|---|-------------------------------------------------------------------------------------|
| 1.2.9 | 2022-04-27 | DruidAbstractDataSource.testConnectionInternal()判断timeBetweenEvictionRunsMillis > 0 |
| 1.2.9 |2022-04-27| MysqlUtils.getLastPacketReceivedTimeMs添加驱动判断 |

5
fine-druid/src/main/java/com/fr/third/alibaba/druid/DbType.java

@ -58,6 +58,11 @@ public enum DbType {
trino (1 << 39), trino (1 << 39),
oscar (1 << 40),
tidb ( 1 << 41),
tydb ( 1 << 42),
ingres (0), ingres (0),
cloudscape (0), cloudscape (0),

1
fine-druid/src/main/java/com/fr/third/alibaba/druid/filter/FilterManager.java

@ -71,7 +71,6 @@ public class FilterManager {
loadFilterConfig(filterProperties, ClassLoader.getSystemClassLoader()); loadFilterConfig(filterProperties, ClassLoader.getSystemClassLoader());
loadFilterConfig(filterProperties, FilterManager.class.getClassLoader()); loadFilterConfig(filterProperties, FilterManager.class.getClassLoader());
loadFilterConfig(filterProperties, Thread.currentThread().getContextClassLoader()); loadFilterConfig(filterProperties, Thread.currentThread().getContextClassLoader());
loadFilterConfig(filterProperties, FilterManager.class.getClassLoader());
return filterProperties; return filterProperties;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/mock/handler/MySqlMockExecuteHandlerImpl.java

@ -60,7 +60,7 @@ public class MySqlMockExecuteHandlerImpl implements MockExecuteHandler {
throw new SQLException("not support multi-statment. " + sql); throw new SQLException("not support multi-statment. " + sql);
} }
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
throw new SQLException("executeQueryError : " + sql); throw new SQLException("executeQueryError : " + sql);
} }

79
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidAbstractDataSource.java

@ -15,6 +15,34 @@
*/ */
package com.fr.third.alibaba.druid.pool; package com.fr.third.alibaba.druid.pool;
import com.fr.third.alibaba.druid.DbType;
import com.fr.third.alibaba.druid.DruidRuntimeException;
import com.fr.third.alibaba.druid.VERSION;
import com.fr.third.alibaba.druid.filter.Filter;
import com.fr.third.alibaba.druid.filter.FilterChainImpl;
import com.fr.third.alibaba.druid.filter.FilterManager;
import com.fr.third.alibaba.druid.pool.vendor.NullExceptionSorter;
import com.fr.third.alibaba.druid.proxy.jdbc.DataSourceProxy;
import com.fr.third.alibaba.druid.proxy.jdbc.TransactionInfo;
import com.fr.third.alibaba.druid.stat.JdbcDataSourceStat;
import com.fr.third.alibaba.druid.stat.JdbcSqlStat;
import com.fr.third.alibaba.druid.stat.JdbcStatManager;
import com.fr.third.alibaba.druid.support.logging.Log;
import com.fr.third.alibaba.druid.support.logging.LogFactory;
import com.fr.third.alibaba.druid.util.DruidPasswordCallback;
import com.fr.third.alibaba.druid.util.Histogram;
import com.fr.third.alibaba.druid.util.JdbcConstants;
import com.fr.third.alibaba.druid.util.JdbcUtils;
import com.fr.third.alibaba.druid.util.MySqlUtils;
import com.fr.third.alibaba.druid.util.StringUtils;
import com.fr.third.alibaba.druid.util.Utils;
import javax.management.JMException;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.sql.DataSource;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Connection; import java.sql.Connection;
@ -43,35 +71,6 @@ import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.management.JMException;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.sql.DataSource;
import com.fr.third.alibaba.druid.DbType;
import com.fr.third.alibaba.druid.DruidRuntimeException;
import com.fr.third.alibaba.druid.VERSION;
import com.fr.third.alibaba.druid.filter.Filter;
import com.fr.third.alibaba.druid.filter.FilterChainImpl;
import com.fr.third.alibaba.druid.filter.FilterManager;
import com.fr.third.alibaba.druid.pool.vendor.NullExceptionSorter;
import com.fr.third.alibaba.druid.proxy.jdbc.DataSourceProxy;
import com.fr.third.alibaba.druid.proxy.jdbc.TransactionInfo;
import com.fr.third.alibaba.druid.stat.JdbcDataSourceStat;
import com.fr.third.alibaba.druid.stat.JdbcSqlStat;
import com.fr.third.alibaba.druid.stat.JdbcStatManager;
import com.fr.third.alibaba.druid.support.logging.Log;
import com.fr.third.alibaba.druid.support.logging.LogFactory;
import com.fr.third.alibaba.druid.util.DruidPasswordCallback;
import com.fr.third.alibaba.druid.util.Histogram;
import com.fr.third.alibaba.druid.util.JdbcConstants;
import com.fr.third.alibaba.druid.util.JdbcUtils;
import com.fr.third.alibaba.druid.util.MySqlUtils;
import com.fr.third.alibaba.druid.util.StringUtils;
import com.fr.third.alibaba.druid.util.Utils;
/** /**
* @author wenshao [szujobs@hotmail.com] * @author wenshao [szujobs@hotmail.com]
* @author ljw [ljw2083@alibaba-inc.com] * @author ljw [ljw2083@alibaba-inc.com]
@ -171,6 +170,8 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
protected volatile ValidConnectionChecker validConnectionChecker = null; protected volatile ValidConnectionChecker validConnectionChecker = null;
protected volatile boolean usePingMethod = false;
protected final Map<DruidPooledConnection, Object> activeConnections = new IdentityHashMap<DruidPooledConnection, Object>(); protected final Map<DruidPooledConnection, Object> activeConnections = new IdentityHashMap<DruidPooledConnection, Object>();
protected final static Object PRESENT = new Object(); protected final static Object PRESENT = new Object();
@ -641,6 +642,14 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
this.validConnectionChecker = validConnectionChecker; this.validConnectionChecker = validConnectionChecker;
} }
public boolean isUsePingMethod() {
return usePingMethod;
}
public void setUsePingMethod(boolean usePingMethod) {
this.usePingMethod = usePingMethod;
}
public String getValidConnectionCheckerClassName() { public String getValidConnectionCheckerClassName() {
if (validConnectionChecker == null) { if (validConnectionChecker == null) {
return null; return null;
@ -1483,8 +1492,8 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
long lastPacketReceivedTimeMs = MySqlUtils.getLastPacketReceivedTimeMs(conn); long lastPacketReceivedTimeMs = MySqlUtils.getLastPacketReceivedTimeMs(conn);
if (lastPacketReceivedTimeMs > 0) { if (lastPacketReceivedTimeMs > 0) {
long mysqlIdleMillis = currentTimeMillis - lastPacketReceivedTimeMs; long mysqlIdleMillis = currentTimeMillis - lastPacketReceivedTimeMs;
if (lastPacketReceivedTimeMs > 0 if (lastPacketReceivedTimeMs > 0 //
&& timeBetweenEvictionRunsMillis > 0 && this.timeBetweenEvictionRunsMillis > 0L
&& mysqlIdleMillis >= timeBetweenEvictionRunsMillis) { && mysqlIdleMillis >= timeBetweenEvictionRunsMillis) {
discardConnection(holder); discardConnection(holder);
String errorMsg = "discard long time none received connection. " String errorMsg = "discard long time none received connection. "
@ -1548,7 +1557,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
return true; return true;
} catch (Throwable ex) { } catch (Throwable ex) {
LOG.debug(ex.getMessage(), ex); // skip
return false; return false;
} finally { } finally {
if (sqlFile != null) { if (sqlFile != null) {
@ -1653,7 +1662,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
public Connection createPhysicalConnection(String url, Properties info) throws SQLException { public Connection createPhysicalConnection(String url, Properties info) throws SQLException {
Connection conn; Connection conn;
if (getProxyFilters().size() == 0) { if (getProxyFilters().isEmpty()) {
conn = getDriver().connect(url, info); conn = getDriver().connect(url, info);
} else { } else {
conn = new FilterChainImpl(this).connection_connect(info); conn = new FilterChainImpl(this).connection_connect(info);
@ -1837,7 +1846,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
} }
Collection<String> initSqls = getConnectionInitSqls(); Collection<String> initSqls = getConnectionInitSqls();
if (initSqls.size() == 0 if (initSqls.isEmpty()
&& variables == null && variables == null
&& globalVariables == null) { && globalVariables == null) {
return; return;
@ -1856,7 +1865,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
} }
DbType dbType = DbType.of(this.dbTypeName); DbType dbType = DbType.of(this.dbTypeName);
if (dbType == DbType.mysql || dbType == DbType.ads) { if (JdbcUtils.isMysqlDbType(dbType)) {
if (variables != null) { if (variables != null) {
ResultSet rs = null; ResultSet rs = null;
try { try {

21
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidConnectionHolder.java

@ -77,22 +77,22 @@ public final class DruidConnectionHolder {
protected String initSchema; protected String initSchema;
public DruidConnectionHolder(DruidAbstractDataSource dataSource, PhysicalConnectionInfo pyConnectInfo) public DruidConnectionHolder(DruidAbstractDataSource dataSource, PhysicalConnectionInfo pyConnectInfo)
throws SQLException{ throws SQLException{
this(dataSource, this(dataSource,
pyConnectInfo.getPhysicalConnection(), pyConnectInfo.getPhysicalConnection(),
pyConnectInfo.getConnectNanoSpan(), pyConnectInfo.getConnectNanoSpan(),
pyConnectInfo.getVairiables(), pyConnectInfo.getVairiables(),
pyConnectInfo.getGlobalVairiables()); pyConnectInfo.getGlobalVairiables());
} }
public DruidConnectionHolder(DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan) public DruidConnectionHolder(DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan)
throws SQLException{ throws SQLException{
this(dataSource, conn, connectNanoSpan, null, null); this(dataSource, conn, connectNanoSpan, null, null);
} }
public DruidConnectionHolder(DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan, public DruidConnectionHolder(DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan,
Map<String, Object> variables, Map<String, Object> globleVariables) Map<String, Object> variables, Map<String, Object> globleVariables)
throws SQLException{ throws SQLException{
this.dataSource = dataSource; this.dataSource = dataSource;
this.conn = conn; this.conn = conn;
this.createNanoSpan = connectNanoSpan; this.createNanoSpan = connectNanoSpan;
@ -136,16 +136,11 @@ public final class DruidConnectionHolder {
holdabilityUnsupported = true; holdabilityUnsupported = true;
} }
LOG.warn("getHoldability error", e); LOG.warn("getHoldability error", e);
} catch (AbstractMethodError e){
LOG.warn("getHoldability error", e);
} }
} }
} }
try { this.underlyingReadOnly = conn.isReadOnly();
this.underlyingReadOnly = conn.isReadOnly();
} catch (Throwable e){
}
try { try {
this.underlyingTransactionIsolation = conn.getTransactionIsolation(); this.underlyingTransactionIsolation = conn.getTransactionIsolation();
} catch (SQLException e) { } catch (SQLException e) {

393
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidDataSource.java

@ -99,77 +99,75 @@ import com.fr.third.alibaba.druid.wall.WallProviderStatValue;
*/ */
public class DruidDataSource extends DruidAbstractDataSource implements DruidDataSourceMBean, ManagedDataSource, Referenceable, Closeable, Cloneable, ConnectionPoolDataSource, MBeanRegistration { public class DruidDataSource extends DruidAbstractDataSource implements DruidDataSourceMBean, ManagedDataSource, Referenceable, Closeable, Cloneable, ConnectionPoolDataSource, MBeanRegistration {
private final static Log LOG = LogFactory.getLog(DruidDataSource.class); private final static Log LOG = LogFactory.getLog(DruidDataSource.class);
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// stats // stats
private volatile long recycleErrorCount = 0L; private volatile long recycleErrorCount = 0L;
private long connectCount = 0L; private long connectCount = 0L;
private long closeCount = 0L; private long closeCount = 0L;
private volatile long connectErrorCount = 0L; private volatile long connectErrorCount = 0L;
private long recycleCount = 0L; private long recycleCount = 0L;
private long removeAbandonedCount = 0L; private long removeAbandonedCount = 0L;
private long notEmptyWaitCount = 0L; private long notEmptyWaitCount = 0L;
private long notEmptySignalCount = 0L; private long notEmptySignalCount = 0L;
private long notEmptyWaitNanos = 0L; private long notEmptyWaitNanos = 0L;
private int keepAliveCheckCount = 0; private int keepAliveCheckCount = 0;
private int activePeak = 0; private int activePeak = 0;
private long activePeakTime = 0; private long activePeakTime = 0;
private int poolingPeak = 0; private int poolingPeak = 0;
private long poolingPeakTime = 0; private long poolingPeakTime = 0;
// store // store
private volatile DruidConnectionHolder[] connections; private volatile DruidConnectionHolder[] connections;
private int poolingCount = 0; private int poolingCount = 0;
private int activeCount = 0; private int activeCount = 0;
private volatile long discardCount = 0; private volatile long discardCount = 0;
private int notEmptyWaitThreadCount = 0; private int notEmptyWaitThreadCount = 0;
private int notEmptyWaitThreadPeak = 0; private int notEmptyWaitThreadPeak = 0;
// //
private DruidConnectionHolder[] evictConnections; private DruidConnectionHolder[] evictConnections;
private DruidConnectionHolder[] keepAliveConnections; private DruidConnectionHolder[] keepAliveConnections;
// threads // threads
private volatile ScheduledFuture<?> destroySchedulerFuture; private volatile ScheduledFuture<?> destroySchedulerFuture;
private DestroyTask destroyTask; private DestroyTask destroyTask;
private volatile Future<?> createSchedulerFuture; private volatile Future<?> createSchedulerFuture;
private CreateConnectionThread createConnectionThread; private CreateConnectionThread createConnectionThread;
private PeriodDetectionThread periodDetectionThread; private DestroyConnectionThread destroyConnectionThread;
private DestroyConnectionThread destroyConnectionThread; private LogStatsThread logStatsThread;
private LogStatsThread logStatsThread; private int createTaskCount;
private int createTaskCount;
private volatile long createTaskIdSeed = 1L; private volatile long createTaskIdSeed = 1L;
private long[] createTasks; private long[] createTasks;
private CountDownLatch initedLatch = new CountDownLatch(2); private final CountDownLatch initedLatch = new CountDownLatch(2);
private volatile boolean enable = true; private volatile boolean enable = true;
private boolean resetStatEnable = true; private boolean resetStatEnable = true;
private volatile long resetCount = 0L; private volatile long resetCount = 0L;
private String initStackTrace; private String initStackTrace;
private volatile boolean closing = false; private volatile boolean closing = false;
private volatile boolean closed = false; private volatile boolean closed = false;
private long closeTimeMillis = -1L; private long closeTimeMillis = -1L;
protected JdbcDataSourceStat dataSourceStat; protected JdbcDataSourceStat dataSourceStat;
private boolean useGlobalDataSourceStat = false; private boolean useGlobalDataSourceStat = false;
private boolean mbeanRegistered = false; private boolean mbeanRegistered = false;
public static ThreadLocal<Long> waitNanosLocal = new ThreadLocal<Long>(); public static ThreadLocal<Long> waitNanosLocal = new ThreadLocal<Long>();
private boolean logDifferentThread = true; private boolean logDifferentThread = true;
private volatile boolean keepAlive = false; private volatile boolean keepAlive = false;
private SQLException initException = null; private boolean asyncInit = false;
private boolean asyncInit = false; protected boolean killWhenSocketReadTimeout = false;
protected boolean killWhenSocketReadTimeout = false; protected boolean checkExecuteTime = false;
protected boolean checkExecuteTime = false;
private static List<Filter> autoFilters = null; private static List<Filter> autoFilters = null;
private boolean loadSpifilterSkip = false; private boolean loadSpifilterSkip = false;
private volatile DataSourceDisableException disableException = null; private volatile DataSourceDisableException disableException = null;
protected static final AtomicLongFieldUpdater<DruidDataSource> recycleErrorCountUpdater protected static final AtomicLongFieldUpdater<DruidDataSource> recycleErrorCountUpdater
= AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "recycleErrorCount"); = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "recycleErrorCount");
@ -180,11 +178,11 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
protected static final AtomicLongFieldUpdater<DruidDataSource> createTaskIdSeedUpdater protected static final AtomicLongFieldUpdater<DruidDataSource> createTaskIdSeedUpdater
= AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "createTaskIdSeed"); = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "createTaskIdSeed");
public DruidDataSource() { public DruidDataSource(){
this(false); this(false);
} }
public DruidDataSource(boolean fairLock) { public DruidDataSource(boolean fairLock){
super(fairLock); super(fairLock);
configFromPropety(System.getProperties()); configFromPropety(System.getProperties());
@ -528,45 +526,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
} }
private synchronized void doSomethingBeforeCreationThreadBreak() {
String threadName = "Druid-ConnectionPool-Create-" + System.identityHashCode(this) + this.getUrl();
createConnectionThread = new CreateConnectionThread(threadName);
createConnectionThread.setStarted(false);
String destroyName = "Druid-ConnectionPool-Destroy-" + System.identityHashCode(this) + this.getUrl();
if (destroyConnectionThread != null) {
if (!destroyConnectionThread.isInterrupted()) {
destroyConnectionThread.interrupt();
}
}
destroyConnectionThread = new DestroyConnectionThread(destroyName);
destroyConnectionThread.setStarted(false);
initedLatch = new CountDownLatch(2);
}
private void checkThread() throws SQLException {
if (createConnectionThread == null) {
throw new IllegalStateException("createConnectionThread not start!");
}
if (destroyConnectionThread == null) {
throw new IllegalStateException("destroyConnectionThread not start!");
}
if (!createConnectionThread.isStarted() && !destroyConnectionThread.isStarted()) {
synchronized (this) {//线程安全问题,加个双检锁
if (!createConnectionThread.isStarted() && !destroyConnectionThread.isStarted()) {
createConnectionThread.setStarted(true);
createConnectionThread.start();
destroyConnectionThread.setStarted(true);
destroyConnectionThread.start();
try {
initedLatch.await();
} catch (InterruptedException e) {
throw new SQLException(e.getMessage(), e);
}
}
}
}
}
public boolean isKillWhenSocketReadTimeout() { public boolean isKillWhenSocketReadTimeout() {
return killWhenSocketReadTimeout; return killWhenSocketReadTimeout;
} }
@ -839,11 +798,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
public void init() throws SQLException { public void init() throws SQLException {
if (initException != null) {
LOG.error("{dataSource-" + this.getID() + "} init error", initException);
throw initException;
}
if (inited) { if (inited) {
return; return;
} }
@ -889,10 +843,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
DbType dbType = DbType.of(this.dbTypeName); DbType dbType = DbType.of(this.dbTypeName);
if (dbType == DbType.mysql if (JdbcUtils.isMysqlDbType(dbType)) {
|| dbType == DbType.mariadb
|| dbType == DbType.oceanbase
|| dbType == DbType.ads) {
boolean cacheServerConfigurationSet = false; boolean cacheServerConfigurationSet = false;
if (this.connectProperties.containsKey("cacheServerConfiguration")) { if (this.connectProperties.containsKey("cacheServerConfiguration")) {
cacheServerConfigurationSet = true; cacheServerConfigurationSet = true;
@ -993,7 +944,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
createAndLogThread(); createAndLogThread();
createAndStartCreatorThread(); createAndStartCreatorThread();
createAndStartDestroyThread(); createAndStartDestroyThread();
createAndStartDetectThread();
initedLatch.await(); initedLatch.await();
init = true; init = true;
@ -1018,13 +968,16 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} catch (SQLException e) { } catch (SQLException e) {
LOG.error("{dataSource-" + this.getID() + "} init error", e); LOG.error("{dataSource-" + this.getID() + "} init error", e);
initException = e;
throw e; throw e;
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new SQLException(e.getMessage(), e); throw new SQLException(e.getMessage(), e);
} catch (Throwable e) { } catch (RuntimeException e){
initException = new SQLException(e.getMessage()); LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e; throw e;
} catch (Error e){
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} finally { } finally {
inited = true; inited = true;
lock.unlock(); lock.unlock();
@ -1122,7 +1075,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
period = 1000; period = 1000;
} }
destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destroyTask, period, period, destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destroyTask, period, period,
TimeUnit.MILLISECONDS); TimeUnit.MILLISECONDS);
initedLatch.countDown(); initedLatch.countDown();
return; return;
} }
@ -1134,7 +1087,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
protected void createAndStartCreatorThread() { protected void createAndStartCreatorThread() {
if (createScheduler == null) { if (createScheduler == null) {
String threadName = "Druid-ConnectionPool-Create-" + System.identityHashCode(this) + this.getUrl(); String threadName = "Druid-ConnectionPool-Create-" + System.identityHashCode(this);
createConnectionThread = new CreateConnectionThread(threadName); createConnectionThread = new CreateConnectionThread(threadName);
createConnectionThread.start(); createConnectionThread.start();
return; return;
@ -1143,15 +1096,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
initedLatch.countDown(); initedLatch.countDown();
} }
private void createAndStartDetectThread() {
if (createScheduler == null) {
String threadName = "Druid-ConnectionPool-Detection-" + System.identityHashCode(this) + this.getUrl();
periodDetectionThread = new PeriodDetectionThread(threadName);
periodDetectionThread.start();
}
}
/** /**
* load filters from SPI ServiceLoader * load filters from SPI ServiceLoader
* *
@ -1237,21 +1181,21 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
return; return;
} }
String infoMessage = ""; String errorMessage = "";
if (isTestOnBorrow()) { if (testOnBorrow) {
infoMessage += "testOnBorrow is true, "; errorMessage += "testOnBorrow is true, ";
} }
if (isTestOnReturn()) { if (testOnReturn) {
infoMessage += "testOnReturn is true, "; errorMessage += "testOnReturn is true, ";
} }
if (isTestWhileIdle()) { if (testWhileIdle) {
infoMessage += "testWhileIdle is true, "; errorMessage += "testWhileIdle is true, ";
} }
LOG.info(infoMessage + "validationQuery not set"); LOG.error(errorMessage + "validationQuery not set");
} }
protected void resolveDriver() throws SQLException { protected void resolveDriver() throws SQLException {
@ -1289,7 +1233,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (driver.getMajorVersion() < 10) { if (driver.getMajorVersion() < 10) {
throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "." throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "."
+ driver.getMinorVersion()); + driver.getMinorVersion());
} }
if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) { if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) {
@ -1333,7 +1277,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (query instanceof SQLSelectQueryBlock) { if (query instanceof SQLSelectQueryBlock) {
if (((SQLSelectQueryBlock) query).getFrom() == null) { if (((SQLSelectQueryBlock) query).getFrom() == null) {
LOG.error("invalid oracle validationQuery. " + validationQuery + ", may should be : " + validationQuery LOG.error("invalid oracle validationQuery. " + validationQuery + ", may should be : " + validationQuery
+ " FROM DUAL"); + " FROM DUAL");
} }
} }
} }
@ -1362,7 +1306,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (query instanceof SQLSelectQueryBlock) { if (query instanceof SQLSelectQueryBlock) {
if (((SQLSelectQueryBlock) query).getFrom() == null) { if (((SQLSelectQueryBlock) query).getFrom() == null) {
LOG.error("invalid db2 validationQuery. " + validationQuery + ", may should be : " + validationQuery LOG.error("invalid db2 validationQuery. " + validationQuery + ", may should be : " + validationQuery
+ " FROM SYSDUMMY"); + " FROM SYSDUMMY");
} }
} }
} }
@ -1374,22 +1318,27 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
String realDriverClassName = driver.getClass().getName(); String realDriverClassName = driver.getClass().getName();
if (JdbcUtils.isMySqlDriver(realDriverClassName)) { if (JdbcUtils.isMySqlDriver(realDriverClassName)) {
this.validConnectionChecker = new MySqlValidConnectionChecker(); this.validConnectionChecker = new MySqlValidConnectionChecker(usePingMethod);
} else if (realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER) } else if (realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER)
|| realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER2)) { || realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER2)) {
this.validConnectionChecker = new OracleValidConnectionChecker(); this.validConnectionChecker = new OracleValidConnectionChecker();
} else if (realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER) } else if (realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER)
|| realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_SQLJDBC4) || realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_SQLJDBC4)
|| realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_JTDS)) { || realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_JTDS)) {
this.validConnectionChecker = new MSSQLValidConnectionChecker(); this.validConnectionChecker = new MSSQLValidConnectionChecker();
} else if (realDriverClassName.equals(JdbcConstants.POSTGRESQL_DRIVER) } else if (realDriverClassName.equals(JdbcConstants.POSTGRESQL_DRIVER)
|| realDriverClassName.equals(JdbcConstants.ENTERPRISEDB_DRIVER) || realDriverClassName.equals(JdbcConstants.ENTERPRISEDB_DRIVER)
|| realDriverClassName.equals(JdbcConstants.POLARDB_DRIVER)) { || realDriverClassName.equals(JdbcConstants.POLARDB_DRIVER)) {
this.validConnectionChecker = new PGValidConnectionChecker(); this.validConnectionChecker = new PGValidConnectionChecker();
} else if (realDriverClassName.equals(JdbcConstants.OCEANBASE_DRIVER)
|| (realDriverClassName.equals(JdbcConstants.OCEANBASE_DRIVER2))) {
DbType dbType = DbType.of(this.dbTypeName);
this.validConnectionChecker = new OceanBaseValidConnectionChecker(dbType);
} }
} }
private void initExceptionSorter() { private void initExceptionSorter() {
@ -1402,7 +1351,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
for (Class<?> driverClass = driver.getClass(); ; ) { for (Class<?> driverClass = driver.getClass();;) {
String realDriverClassName = driverClass.getName(); String realDriverClassName = driverClass.getName();
if (realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER) // if (realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER) //
|| realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER_6)) { || realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER_6)) {
@ -1453,7 +1402,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException { public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException {
init(); init();
checkThread();
if (filters.size() > 0) { if (filters.size() > 0) {
FilterChainImpl filterChain = new FilterChainImpl(this); FilterChainImpl filterChain = new FilterChainImpl(this);
return filterChain.dataSource_connect(this, maxWaitMillis); return filterChain.dataSource_connect(this, maxWaitMillis);
@ -1474,7 +1422,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException { public DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException {
int notFullTimeoutRetryCnt = 0; int notFullTimeoutRetryCnt = 0;
for (; ; ) { for (;;) {
// handle notFullTimeoutRetry // handle notFullTimeoutRetry
DruidPooledConnection poolableConnection; DruidPooledConnection poolableConnection;
try { try {
@ -1508,10 +1456,10 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (testWhileIdle) { if (testWhileIdle) {
final DruidConnectionHolder holder = poolableConnection.holder; final DruidConnectionHolder holder = poolableConnection.holder;
long currentTimeMillis = System.currentTimeMillis(); long currentTimeMillis = System.currentTimeMillis();
long lastActiveTimeMillis = holder.lastActiveTimeMillis; long lastActiveTimeMillis = holder.lastActiveTimeMillis;
long lastExecTimeMillis = holder.lastExecTimeMillis; long lastExecTimeMillis = holder.lastExecTimeMillis;
long lastKeepTimeMillis = holder.lastKeepTimeMillis; long lastKeepTimeMillis = holder.lastKeepTimeMillis;
if (checkExecuteTime if (checkExecuteTime
&& lastExecTimeMillis != lastActiveTimeMillis) { && lastExecTimeMillis != lastActiveTimeMillis) {
@ -1522,7 +1470,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
lastActiveTimeMillis = lastKeepTimeMillis; lastActiveTimeMillis = lastKeepTimeMillis;
} }
long idleMillis = currentTimeMillis - lastActiveTimeMillis; long idleMillis = currentTimeMillis - lastActiveTimeMillis;
long timeBetweenEvictionRunsMillis = this.timeBetweenEvictionRunsMillis; long timeBetweenEvictionRunsMillis = this.timeBetweenEvictionRunsMillis;
@ -1532,7 +1480,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (idleMillis >= timeBetweenEvictionRunsMillis if (idleMillis >= timeBetweenEvictionRunsMillis
|| idleMillis < 0 // unexcepted branch || idleMillis < 0 // unexcepted branch
) { ) {
boolean validate = testConnectionInternal(poolableConnection.holder, poolableConnection.conn); boolean validate = testConnectionInternal(poolableConnection.holder, poolableConnection.conn);
if (!validate) { if (!validate) {
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
@ -1540,7 +1488,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
discardConnection(poolableConnection.holder); discardConnection(poolableConnection.holder);
continue; continue;
} }
} }
} }
@ -1643,7 +1591,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
DruidConnectionHolder holder; DruidConnectionHolder holder;
for (boolean createDirect = false; ; ) { for (boolean createDirect = false;;) {
if (createDirect) { if (createDirect) {
createStartNanosUpdater.set(this, System.nanoTime()); createStartNanosUpdater.set(this, System.nanoTime());
if (creatingCountUpdater.compareAndSet(this, 0, 1)) { if (creatingCountUpdater.compareAndSet(this, 0, 1)) {
@ -1792,10 +1740,10 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
StringBuilder buf = new StringBuilder(128); StringBuilder buf = new StringBuilder(128);
buf.append("wait millis ")// buf.append("wait millis ")//
.append(waitNanos / (1000 * 1000))// .append(waitNanos / (1000 * 1000))//
.append(", active ").append(activeCount)// .append(", active ").append(activeCount)//
.append(", maxActive ").append(maxActive)// .append(", maxActive ").append(maxActive)//
.append(", creating ").append(creatingCount)// .append(", creating ").append(creatingCount)//
; ;
if (creatingCount > 0 && createStartNanos > 0) { if (creatingCount > 0 && createStartNanos > 0) {
long createElapseMillis = (System.nanoTime() - createStartNanos) / (1000 * 1000); long createElapseMillis = (System.nanoTime() - createStartNanos) / (1000 * 1000);
@ -1808,21 +1756,17 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
buf.append(", createErrorCount ").append(createErrorCount); buf.append(", createErrorCount ").append(createErrorCount);
} }
JdbcDataSourceStat sourceStat = this.getDataSourceStat(); List<JdbcSqlStatValue> sqlList = this.getDataSourceStat().getRuningSqlList();
if (sourceStat != null) { for (int i = 0; i < sqlList.size(); ++i) {
List<JdbcSqlStatValue> sqlList = sourceStat.getRuningSqlList(); if (i != 0) {
for (int i = 0; i < sqlList.size(); ++i) { buf.append('\n');
if (i != 0) { } else {
buf.append('\n'); buf.append(", ");
} else {
buf.append(", ");
}
JdbcSqlStatValue sql = sqlList.get(i);
buf.append("runningSqlCount ");
buf.append(sql.getRunningCount());
buf.append(" : ");
buf.append(sql.getSql());
} }
JdbcSqlStatValue sql = sqlList.get(i);
buf.append("runningSqlCount ").append(sql.getRunningCount());
buf.append(" : ");
buf.append(sql.getSql());
} }
String errorMessage = buf.toString(); String errorMessage = buf.toString();
@ -1914,12 +1858,13 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
lock.unlock(); lock.unlock();
} }
if (onFatalError && holder != null && holder.getDataSource() != null) { if(onFatalError && holder != null && holder.getDataSource() != null) {
ReentrantLock dataSourceLock = holder.getDataSource().lock; ReentrantLock dataSourceLock = holder.getDataSource().lock;
dataSourceLock.lock(); dataSourceLock.lock();
try { try {
emptySignal(); emptySignal();
} finally { }
finally {
dataSourceLock.unlock(); dataSourceLock.unlock();
} }
} }
@ -1956,8 +1901,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
if (logDifferentThread // if (logDifferentThread //
&& (!isAsyncCloseConnectionEnable()) // && (!isAsyncCloseConnectionEnable()) //
&& pooledConnection.ownerThread != Thread.currentThread()// && pooledConnection.ownerThread != Thread.currentThread()//
) { ) {
LOG.warn("get/close not same thread"); LOG.warn("get/close not same thread");
} }
@ -2152,10 +2097,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
destroyConnectionThread.interrupt(); destroyConnectionThread.interrupt();
} }
if (periodDetectionThread != null) {
periodDetectionThread.interrupt();
}
if (createSchedulerFuture != null) { if (createSchedulerFuture != null) {
createSchedulerFuture.cancel(true); createSchedulerFuture.cancel(true);
} }
@ -2213,7 +2154,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
@Override @Override
public Object run() { public Object run() {
ObjectName objectName = DruidDataSourceStatManager.addDataSource(DruidDataSource.this, ObjectName objectName = DruidDataSourceStatManager.addDataSource(DruidDataSource.this,
DruidDataSource.this.name); DruidDataSource.this.name);
DruidDataSource.this.setObjectName(objectName); DruidDataSource.this.setObjectName(objectName);
DruidDataSource.this.mbeanRegistered = true; DruidDataSource.this.mbeanRegistered = true;
@ -2307,7 +2248,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
private DruidConnectionHolder pollLast(long nanos) throws InterruptedException, SQLException { private DruidConnectionHolder pollLast(long nanos) throws InterruptedException, SQLException {
long estimate = nanos; long estimate = nanos;
for (; ; ) { for (;;) {
if (poolingCount == 0) { if (poolingCount == 0) {
emptySignal(); // send signal to CreateThread create connection emptySignal(); // send signal to CreateThread create connection
@ -2328,8 +2269,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try { try {
long startEstimate = estimate; long startEstimate = estimate;
estimate = notEmpty.awaitNanos(estimate); // signal by estimate = notEmpty.awaitNanos(estimate); // signal by
// recycle or // recycle or
// creator // creator
notEmptyWaitCount++; notEmptyWaitCount++;
notEmptyWaitNanos += (startEstimate - estimate); notEmptyWaitNanos += (startEstimate - estimate);
@ -2553,7 +2494,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
value.setCommitCount(commitCountUpdater.getAndSet(this, 0)); value.setCommitCount(commitCountUpdater.getAndSet(this, 0));
value.setRollbackCount(rollbackCountUpdater.getAndSet(this, 0)); value.setRollbackCount(rollbackCountUpdater.getAndSet(this, 0));
value.setPstmtCacheHitCount(cachedPreparedStatementHitCountUpdater.getAndSet(this, 0)); value.setPstmtCacheHitCount(cachedPreparedStatementHitCountUpdater.getAndSet(this,0));
value.setPstmtCacheMissCount(cachedPreparedStatementMissCountUpdater.getAndSet(this, 0)); value.setPstmtCacheMissCount(cachedPreparedStatementMissCountUpdater.getAndSet(this, 0));
value.setStartTransactionCount(startTransactionCountUpdater.getAndSet(this, 0)); value.setStartTransactionCount(startTransactionCountUpdater.getAndSet(this, 0));
@ -2631,7 +2572,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
clearCreateTask(createTaskId); clearCreateTask(createTaskId);
if (poolingCount + createTaskCount < notEmptyWaitThreadCount // if (poolingCount + createTaskCount < notEmptyWaitThreadCount //
&& activeCount + poolingCount + createTaskCount < maxActive) { && activeCount + poolingCount + createTaskCount < maxActive) {
emptySignal(); emptySignal();
} }
} }
@ -2643,7 +2584,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public class CreateConnectionTask implements Runnable { public class CreateConnectionTask implements Runnable {
private int errorCount = 0; private int errorCount = 0;
private boolean initTask = false; private boolean initTask = false;
private final long taskId; private final long taskId;
@ -2662,7 +2603,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
private void runInternal() { private void runInternal() {
for (; ; ) { for (;;) {
// addLast // addLast
lock.lock(); lock.lock();
@ -2828,9 +2769,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
public class CreateConnectionThread extends Thread { public class CreateConnectionThread extends Thread {
private volatile boolean started = true;
public CreateConnectionThread(String name) { public CreateConnectionThread(String name){
super(name); super(name);
this.setDaemon(true); this.setDaemon(true);
} }
@ -2840,7 +2780,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
long lastDiscardCount = 0; long lastDiscardCount = 0;
int errorCount = 0; int errorCount = 0;
for (; ; ) { for (;;) {
// addLast // addLast
try { try {
lock.lockInterruptibly(); lock.lockInterruptibly();
@ -2889,7 +2829,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if ((!closing) && (!closed)) { if ((!closing) && (!closed)) {
LOG.error("create connection Thread Interrupted, url: " + jdbcUrl, e); LOG.error("create connection Thread Interrupted, url: " + jdbcUrl, e);
} }
DruidDataSource.this.doSomethingBeforeCreationThreadBreak();
break; break;
} finally { } finally {
lock.unlock(); lock.unlock();
@ -2899,13 +2838,9 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try { try {
connection = createPhysicalConnection(); connection = createPhysicalConnection();
} catch (SQLException | RuntimeException e) { } catch (SQLException e) {
if (e instanceof SQLException) { LOG.error("create connection SQLException, url: " + jdbcUrl + ", errorCode " + e.getErrorCode()
LOG.error("create connection error, url: " + jdbcUrl + ", errorCode " + ((SQLException) e).getErrorCode() + ", state " + e.getSQLState(), e);
+ ", state " + ((SQLException) e).getSQLState(), e);
} else {
LOG.error("create connection error", e);
}
errorCount++; errorCount++;
if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) { if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) {
@ -2926,16 +2861,17 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try { try {
Thread.sleep(timeBetweenConnectErrorMillis); Thread.sleep(timeBetweenConnectErrorMillis);
} catch (InterruptedException ignore) { } catch (InterruptedException interruptEx) {
break;
} }
DruidDataSource.this.doSomethingBeforeCreationThreadBreak();
break;
} }
} catch (RuntimeException e) {
LOG.error("create connection RuntimeException", e);
setFailContinuous(true);
continue;
} catch (Error e) { } catch (Error e) {
LOG.error("create connection Error", e); LOG.error("create connection Error", e);
setFailContinuous(true); setFailContinuous(true);
DruidDataSource.this.doSomethingBeforeCreationThreadBreak();
break; break;
} }
@ -2956,49 +2892,11 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
} }
} }
public boolean isStarted() {
return started;
}
public void setStarted(boolean started) {
this.started = started;
}
}
//周期性检查生产线程状态,因为在终止生产线程的时候,为了不让生产线程疯狂重试数据库,只是生成了一个生产线程,但是并没有start,需要一个守护线程
//周期性检查线程状态,帮助其启动。
private class PeriodDetectionThread extends Thread {
public PeriodDetectionThread(String name) {
super(name);
this.setDaemon(true);
}
public void run() {
while (true) {
synchronized (DruidDataSource.this) {
//生产线程发生了切换,并且有线程在等待连接,需要主动唤醒生产线程,否则由getConnection方法来唤醒生产线程
if (!createConnectionThread.started && !destroyConnectionThread.started && notEmptyWaitThreadCount > 0) {
createConnectionThread.setStarted(true);
createConnectionThread.start();
destroyConnectionThread.setStarted(true);
destroyConnectionThread.start();
}
}
try {
Thread.sleep(30000);
} catch (InterruptedException ignore) {
break;
}
}
}
} }
public class DestroyConnectionThread extends Thread { public class DestroyConnectionThread extends Thread {
private volatile boolean started = true; public DestroyConnectionThread(String name){
public DestroyConnectionThread(String name) {
super(name); super(name);
this.setDaemon(true); this.setDaemon(true);
} }
@ -3006,7 +2904,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public void run() { public void run() {
initedLatch.countDown(); initedLatch.countDown();
for (; ; ) { for (;;) {
// 从前面开始删除 // 从前面开始删除
try { try {
if (closed || closing) { if (closed || closing) {
@ -3030,13 +2928,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
} }
public boolean isStarted() {
return started;
}
public void setStarted(boolean started) {
this.started = started;
}
} }
public class DestroyTask implements Runnable { public class DestroyTask implements Runnable {
@ -3057,14 +2948,14 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public class LogStatsThread extends Thread { public class LogStatsThread extends Thread {
public LogStatsThread(String name) { public LogStatsThread(String name){
super(name); super(name);
this.setDaemon(true); this.setDaemon(true);
} }
public void run() { public void run() {
try { try {
for (; ; ) { for (;;) {
try { try {
logStats(); logStats();
} catch (Exception e) { } catch (Exception e) {
@ -3090,7 +2981,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try { try {
Iterator<DruidPooledConnection> iter = activeConnections.keySet().iterator(); Iterator<DruidPooledConnection> iter = activeConnections.keySet().iterator();
for (; iter.hasNext(); ) { for (; iter.hasNext();) {
DruidPooledConnection pooledConnection = iter.next(); DruidPooledConnection pooledConnection = iter.next();
if (pooledConnection.isRunning()) { if (pooledConnection.isRunning()) {
@ -3142,7 +3033,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
buf.append("ownerThread current state is " + pooledConnection.getOwnerThread().getState() buf.append("ownerThread current state is " + pooledConnection.getOwnerThread().getState()
+ ", current stackTrace\n"); + ", current stackTrace\n");
trace = pooledConnection.getOwnerThread().getStackTrace(); trace = pooledConnection.getOwnerThread().getStackTrace();
for (int i = 0; i < trace.length; i++) { for (int i = 0; i < trace.length; i++) {
buf.append("\tat "); buf.append("\tat ");
@ -3158,9 +3049,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
return removeCount; return removeCount;
} }
/** /** Instance key */
* Instance key
*/
protected String instanceKey = null; protected String instanceKey = null;
public Reference getReference() throws NamingException { public Reference getReference() throws NamingException {
@ -3241,7 +3130,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
for (int i = 0; i < poolingCount; ++i) { for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder connection = connections[i]; DruidConnectionHolder connection = connections[i];
if ((onFatalError || fatalErrorIncrement > 0) && (lastFatalErrorTimeMillis > connection.connectTimeMillis)) { if ((onFatalError || fatalErrorIncrement > 0) && (lastFatalErrorTimeMillis > connection.connectTimeMillis)) {
keepAliveConnections[keepAliveCount++] = connection; keepAliveConnections[keepAliveCount++] = connection;
continue; continue;
} }
@ -3865,7 +3754,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
if (this.statLogger != null if (this.statLogger != null
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) { && (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
return true; return true;
} }
@ -3881,7 +3770,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
if (this.statLogger != null if (this.statLogger != null
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) { && (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
return (T) statLogger; return (T) statLogger;
} }
@ -3925,7 +3814,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} }
int fillCount = 0; int fillCount = 0;
for (; ; ) { for (;;) {
try { try {
lock.lockInterruptibly(); lock.lockInterruptibly();
} catch (InterruptedException e) { } catch (InterruptedException e) {

224
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidDataSourceFactory.java

@ -39,60 +39,41 @@ public class DruidDataSourceFactory implements ObjectFactory {
static final int UNKNOWN_TRANSACTIONISOLATION = -1; static final int UNKNOWN_TRANSACTIONISOLATION = -1;
private final static String HIBERNATE_PREFIX = "hibernate."; public final static String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
private final static String HIBERNATE_CONN_PREFIX = "connection."; public final static String PROP_DEFAULTREADONLY = "defaultReadOnly";
public final static String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
public final static String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit"; public final static String PROP_DEFAULTCATALOG = "defaultCatalog";
public final static String PROP_DEFAULTREADONLY = "defaultReadOnly"; public final static String PROP_DRIVERCLASSNAME = "driverClassName";
public final static String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation"; public final static String PROP_MAXACTIVE = "maxActive";
public final static String PROP_DEFAULTCATALOG = "defaultCatalog"; public final static String PROP_MAXIDLE = "maxIdle";
public final static String PROP_DRIVERCLASSNAME = "driverClassName"; public final static String PROP_MINIDLE = "minIdle";
public final static String HB_PROP_DRIVERCLASSNAME = HIBERNATE_PREFIX + HIBERNATE_CONN_PREFIX + "driver_class"; public final static String PROP_INITIALSIZE = "initialSize";
public final static String PROP_MAXACTIVE = "maxActive"; public final static String PROP_MAXWAIT = "maxWait";
public final static String HB_PROP_MAXACTIVE = HIBERNATE_PREFIX + "maxActive"; public final static String PROP_TESTONBORROW = "testOnBorrow";
public final static String PROP_MAXIDLE = "maxIdle"; public final static String PROP_TESTONRETURN = "testOnReturn";
public final static String HB_PROP_MAXIDLE = HIBERNATE_PREFIX + "maxIdle"; public final static String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
public final static String PROP_MINIDLE = "minIdle"; public final static String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
public final static String HB_PROP_MINIDLE = HIBERNATE_PREFIX + "minIdle"; public final static String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
public final static String PROP_INITIALSIZE = "initialSize"; public final static String PROP_PHY_TIMEOUT_MILLIS = "phyTimeoutMillis";
public final static String HB_PROP_INITIALSIZE = HIBERNATE_PREFIX + "initialSize"; public final static String PROP_TESTWHILEIDLE = "testWhileIdle";
public final static String PROP_MAXWAIT = "maxWait"; public final static String PROP_PASSWORD = "password";
public final static String HB_PROP_MAXWAIT = HIBERNATE_PREFIX + "maxWait"; public final static String PROP_URL = "url";
public final static String PROP_TESTONBORROW = "testOnBorrow"; public final static String PROP_USERNAME = "username";
public final static String HB_PROP_TESTONBORROW = HIBERNATE_PREFIX + "testOnBorrow"; public final static String PROP_VALIDATIONQUERY = "validationQuery";
public final static String PROP_TESTONRETURN = "testOnReturn"; public final static String PROP_VALIDATIONQUERY_TIMEOUT = "validationQueryTimeout";
public final static String HB_PROP_TESTONRETURN = HIBERNATE_PREFIX + "testOnReturn"; public final static String PROP_INITCONNECTIONSQLS = "initConnectionSqls";
public final static String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
public final static String HB_PROP_TIMEBETWEENEVICTIONRUNSMILLIS = HIBERNATE_PREFIX + "timeBetweenEvictionRunsMillis";
public final static String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
public final static String HB_PROP_NUMTESTSPEREVICTIONRUN = HIBERNATE_PREFIX + "numTestsPerEvictionRun";
public final static String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
public final static String HB_PROP_MINEVICTABLEIDLETIMEMILLIS = HIBERNATE_PREFIX + "minEvictableIdleTimeMillis";
public final static String PROP_PHY_TIMEOUT_MILLIS = "phyTimeoutMillis";
public final static String PROP_TESTWHILEIDLE = "testWhileIdle";
public final static String HB_PROP_TESTWHILEIDLE = HIBERNATE_PREFIX + "testWhileIdle";
public final static String PROP_PASSWORD = "password";
public final static String HB_PROP_PASSWORD = HIBERNATE_PREFIX + HIBERNATE_CONN_PREFIX + "password";
public final static String PROP_URL = "url";
public final static String HB_PROP_URL = HIBERNATE_PREFIX + HIBERNATE_CONN_PREFIX + "url";
public final static String PROP_USERNAME = "username";
public final static String HB_PROP_USERNAME = HIBERNATE_PREFIX + HIBERNATE_CONN_PREFIX + "username";
public final static String PROP_VALIDATIONQUERY = "validationQuery";
public final static String HB_PROP_VALIDATIONQUERY = HIBERNATE_PREFIX + "validationQuery";
public final static String PROP_VALIDATIONQUERY_TIMEOUT = "validationQueryTimeout";
public final static String PROP_INITCONNECTIONSQLS = "initConnectionSqls";
public final static String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed"; public final static String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed";
public final static String PROP_REMOVEABANDONED = "removeAbandoned"; public final static String PROP_REMOVEABANDONED = "removeAbandoned";
public final static String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout"; public final static String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
public final static String PROP_LOGABANDONED = "logAbandoned"; public final static String PROP_LOGABANDONED = "logAbandoned";
public final static String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements"; public final static String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
public final static String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements"; public final static String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
public final static String PROP_CONNECTIONPROPERTIES = "connectionProperties"; public final static String PROP_CONNECTIONPROPERTIES = "connectionProperties";
public final static String PROP_FILTERS = "filters"; public final static String PROP_FILTERS = "filters";
public final static String PROP_EXCEPTION_SORTER = "exceptionSorter"; public final static String PROP_EXCEPTION_SORTER = "exceptionSorter";
public final static String PROP_EXCEPTION_SORTER_CLASS_NAME = "exception-sorter-class-name"; public final static String PROP_EXCEPTION_SORTER_CLASS_NAME = "exception-sorter-class-name";
public final static String PROP_NAME = "name"; public final static String PROP_NAME = "name";
public final static String PROP_INIT = "init"; public final static String PROP_INIT = "init";
private final static String[] ALL_PROPERTIES = { private final static String[] ALL_PROPERTIES = {
PROP_DEFAULTAUTOCOMMIT, PROP_DEFAULTAUTOCOMMIT,
@ -242,161 +223,56 @@ public class DruidDataSourceFactory implements ObjectFactory {
value = (String) properties.get(PROP_DRIVERCLASSNAME); value = (String) properties.get(PROP_DRIVERCLASSNAME);
if (value != null) { if (value != null) {
dataSource.setDriverClassName(value); dataSource.setDriverClassName(value);
} else {
value = (String) properties.get(HB_PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
}
} }
value = (String) properties.get(PROP_MAXACTIVE); value = (String) properties.get(PROP_MAXACTIVE);
if (value != null) { if (value != null) {
dataSource.setMaxActive(Integer.parseInt(value)); dataSource.setMaxActive(Integer.parseInt(value));
} else {
Object o = properties.get(HB_PROP_MAXACTIVE);
if (o != null) {
if (o instanceof Integer) {
dataSource.setMaxActive((Integer) o);
} else {
value = (String) o;
dataSource.setMaxActive(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_MAXIDLE); value = (String) properties.get(PROP_MAXIDLE);
if (value != null) { if (value != null) {
dataSource.setMaxIdle(Integer.parseInt(value)); dataSource.setMaxIdle(Integer.parseInt(value));
} else {
Object o = properties.get(HB_PROP_MAXIDLE);
if (o != null) {
if (o instanceof Integer) {
dataSource.setMaxIdle((Integer) o);
} else {
value = (String) o;
dataSource.setMaxIdle(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_MINIDLE); value = (String) properties.get(PROP_MINIDLE);
if (value != null) { if (value != null) {
dataSource.setMinIdle(Integer.parseInt(value)); dataSource.setMinIdle(Integer.parseInt(value));
} else {
Object o = properties.get(HB_PROP_MINIDLE);
if (o != null) {
if (o instanceof Integer) {
dataSource.setMinIdle((Integer) o);
} else {
value = (String) o;
dataSource.setMinIdle(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_INITIALSIZE); value = (String) properties.get(PROP_INITIALSIZE);
if (value != null) { if (value != null) {
dataSource.setInitialSize(Integer.parseInt(value)); dataSource.setInitialSize(Integer.parseInt(value));
} else {
Object o = properties.get(HB_PROP_INITIALSIZE);
if (o != null) {
if (o instanceof Integer) {
dataSource.setInitialSize((Integer) o);
} else {
value = (String) o;
dataSource.setInitialSize(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_MAXWAIT); value = (String) properties.get(PROP_MAXWAIT);
if (value != null) { if (value != null) {
dataSource.setMaxWait(Long.parseLong(value)); dataSource.setMaxWait(Long.parseLong(value));
} else {
Object o = properties.get(HB_PROP_MAXWAIT);
if (o != null) {
if (o instanceof Integer) {
dataSource.setMaxWait((Integer) o);
} else {
value = (String) o;
dataSource.setMaxWait(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_TESTONBORROW); value = (String) properties.get(PROP_TESTONBORROW);
if (value != null) { if (value != null) {
dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue()); dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
} else {
Object o = properties.get(HB_PROP_TESTONBORROW);
if (o != null) {
if (o instanceof Boolean) {
dataSource.setTestOnBorrow((Boolean) o);
} else {
value = (String) o;
dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
}
}
} }
value = (String) properties.get(PROP_TESTONRETURN); value = (String) properties.get(PROP_TESTONRETURN);
if (value != null) { if (value != null) {
dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue()); dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
} else {
Object o = properties.get(HB_PROP_TESTONRETURN);
if (o != null) {
if (o instanceof Boolean) {
dataSource.setTestOnReturn((Boolean) o);
} else {
value = (String) o;
dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
}
}
} }
value = (String) properties.get(PROP_TIMEBETWEENEVICTIONRUNSMILLIS); value = (String) properties.get(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) { if (value != null) {
dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value)); dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
} else {
Object o = properties.get(HB_PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (o != null) {
if (o instanceof Integer) {
dataSource.setTimeBetweenEvictionRunsMillis((Integer) o);
} else {
value = (String) o;
dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_NUMTESTSPEREVICTIONRUN); value = (String) properties.get(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) { if (value != null) {
dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value)); dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
} else {
Object o = properties.get(HB_PROP_NUMTESTSPEREVICTIONRUN);
if (o != null) {
if (o instanceof Integer) {
dataSource.setNumTestsPerEvictionRun((Integer) o);
} else {
value = (String) o;
dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_MINEVICTABLEIDLETIMEMILLIS); value = (String) properties.get(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) { if (value != null) {
dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value)); dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
} else {
Object o = properties.get(HB_PROP_MINEVICTABLEIDLETIMEMILLIS);
if (o != null) {
if (o instanceof Integer) {
dataSource.setMinEvictableIdleTimeMillis((Integer) o);
} else {
value = (String) o;
dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(value));
}
}
} }
value = (String) properties.get(PROP_PHY_TIMEOUT_MILLIS); value = (String) properties.get(PROP_PHY_TIMEOUT_MILLIS);
@ -407,56 +283,26 @@ public class DruidDataSourceFactory implements ObjectFactory {
value = (String) properties.get(PROP_TESTWHILEIDLE); value = (String) properties.get(PROP_TESTWHILEIDLE);
if (value != null) { if (value != null) {
dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue()); dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
} else {
Object o = properties.get(HB_PROP_TESTWHILEIDLE);
if (o != null) {
if (o instanceof Boolean) {
dataSource.setTestWhileIdle((Boolean) o);
} else {
value = (String) o;
dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
}
}
} }
value = (String) properties.get(PROP_PASSWORD); value = (String) properties.get(PROP_PASSWORD);
if (value != null) { if (value != null) {
dataSource.setPassword(value); dataSource.setPassword(value);
} else {
value = (String) properties.get(HB_PROP_PASSWORD);
if (value != null) {
dataSource.setPassword(value);
}
} }
value = (String) properties.get(PROP_URL); value = (String) properties.get(PROP_URL);
if (value != null) { if (value != null) {
dataSource.setUrl(value); dataSource.setUrl(value);
} else {
value = (String) properties.get(HB_PROP_URL);
if (value != null) {
dataSource.setUrl(value);
}
} }
value = (String) properties.get(PROP_USERNAME); value = (String) properties.get(PROP_USERNAME);
if (value != null) { if (value != null) {
dataSource.setUsername(value); dataSource.setUsername(value);
} else {
value = (String) properties.get(HB_PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
}
} }
value = (String) properties.get(PROP_VALIDATIONQUERY); value = (String) properties.get(PROP_VALIDATIONQUERY);
if (value != null && value.length() > 0) { if (value != null) {
dataSource.setValidationQuery(value); dataSource.setValidationQuery(value);
} else {
value = (String) properties.get(HB_PROP_VALIDATIONQUERY);
if (value != null && value.length() > 0) {
dataSource.setValidationQuery(value);
}
} }
value = (String) properties.get(PROP_VALIDATIONQUERY_TIMEOUT); value = (String) properties.get(PROP_VALIDATIONQUERY_TIMEOUT);

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/DruidPooledStatement.java

@ -138,7 +138,7 @@ public class DruidPooledStatement extends PoolableWrapper implements Statement {
return; return;
} }
if (DbType.mysql != DbType.of(dataSource.dbTypeName)) { if (!JdbcUtils.isMysqlDbType(dataSource.dbTypeName)) {
return; return;
} }

8
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/vendor/MSSQLValidConnectionChecker.java vendored

@ -23,6 +23,7 @@ import java.sql.Statement;
import com.fr.third.alibaba.druid.pool.ValidConnectionChecker; import com.fr.third.alibaba.druid.pool.ValidConnectionChecker;
import com.fr.third.alibaba.druid.pool.ValidConnectionCheckerAdapter; import com.fr.third.alibaba.druid.pool.ValidConnectionCheckerAdapter;
import com.fr.third.alibaba.druid.util.JdbcUtils; import com.fr.third.alibaba.druid.util.JdbcUtils;
import com.fr.third.alibaba.druid.util.StringUtils;
/** /**
* A MSSQLValidConnectionChecker. * A MSSQLValidConnectionChecker.
@ -30,8 +31,9 @@ import com.fr.third.alibaba.druid.util.JdbcUtils;
public class MSSQLValidConnectionChecker extends ValidConnectionCheckerAdapter implements ValidConnectionChecker, Serializable { public class MSSQLValidConnectionChecker extends ValidConnectionCheckerAdapter implements ValidConnectionChecker, Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static final String DEFAULT_VALIDATION_QUERY = "SELECT 1";
public MSSQLValidConnectionChecker() { public MSSQLValidConnectionChecker(){
} }
@ -40,8 +42,8 @@ public class MSSQLValidConnectionChecker extends ValidConnectionCheckerAdapter i
return false; return false;
} }
if (validateQuery == null || validateQuery.isEmpty()) { if(StringUtils.isEmpty(validateQuery)) {
validateQuery = "select 1"; validateQuery = DEFAULT_VALIDATION_QUERY;
} }
Statement stmt = null; Statement stmt = null;

6
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/vendor/MySqlValidConnectionChecker.java vendored

@ -45,7 +45,7 @@ public class MySqlValidConnectionChecker extends ValidConnectionCheckerAdapter i
private Method ping; private Method ping;
private boolean usePingMethod = false; private boolean usePingMethod = false;
public MySqlValidConnectionChecker(){ public MySqlValidConnectionChecker(boolean usePingMethod){
try { try {
clazz = Utils.loadClass("com.mysql.jdbc.MySQLConnection"); clazz = Utils.loadClass("com.mysql.jdbc.MySQLConnection");
if (clazz == null) { if (clazz == null) {
@ -56,8 +56,8 @@ public class MySqlValidConnectionChecker extends ValidConnectionCheckerAdapter i
ping = clazz.getMethod("pingInternal", boolean.class, int.class); ping = clazz.getMethod("pingInternal", boolean.class, int.class);
} }
if (ping != null) { if (ping != null && usePingMethod) {
usePingMethod = true; this.usePingMethod = true;
} }
} catch (Exception e) { } catch (Exception e) {
LOG.warn("Cannot resolve com.mysql.jdbc.Connection.ping method. Will use 'SELECT 1' instead.", e); LOG.warn("Cannot resolve com.mysql.jdbc.Connection.ping method. Will use 'SELECT 1' instead.", e);

62
fine-druid/src/main/java/com/fr/third/alibaba/druid/pool/vendor/OceanBaseValidConnectionChecker.java vendored

@ -0,0 +1,62 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fr.third.alibaba.druid.pool.vendor;
import com.fr.third.alibaba.druid.DbType;
import com.fr.third.alibaba.druid.pool.ValidConnectionChecker;
import com.fr.third.alibaba.druid.pool.ValidConnectionCheckerAdapter;
import com.fr.third.alibaba.druid.util.JdbcUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class OceanBaseValidConnectionChecker extends ValidConnectionCheckerAdapter implements ValidConnectionChecker {
private String oracleModeValidateQuery = "SELECT 'x' FROM DUAL";
private String mysqlModeValidateQuery = "SELECT 'x'";
private DbType dbType;
public OceanBaseValidConnectionChecker() { configFromProperties(System.getProperties()); dbType = null; }
public OceanBaseValidConnectionChecker(DbType dbType) {this.dbType = dbType;configFromProperties(System.getProperties()); }
public boolean isValidConnection(final Connection c, String validateQuery, int validationQueryTimeout) throws Exception {
if (c.isClosed()) {
return false;
}
if (validateQuery == null || validateQuery.isEmpty()) {
if(dbType != null) {
if(dbType == DbType.oceanbase) {
validateQuery = mysqlModeValidateQuery;
} else {
validateQuery = oracleModeValidateQuery;
}
}
}
Statement stmt = null;
try {
stmt = c.createStatement();
if (validationQueryTimeout > 0) {
stmt.setQueryTimeout(validationQueryTimeout);
}
stmt.execute(validateQuery);
return true;
} catch (SQLException e) {
throw e;
} finally {
JdbcUtils.close(stmt);
}
}
}

14
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/PagerUtils.java

@ -29,6 +29,7 @@ import com.fr.third.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitorAda
import com.fr.third.alibaba.druid.sql.dialect.postgresql.ast.stmt.PGSelectQueryBlock; import com.fr.third.alibaba.druid.sql.dialect.postgresql.ast.stmt.PGSelectQueryBlock;
import com.fr.third.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerSelectQueryBlock; import com.fr.third.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerSelectQueryBlock;
import com.fr.third.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerTop; import com.fr.third.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerTop;
import com.fr.third.alibaba.druid.util.JdbcUtils;
import java.util.List; import java.util.List;
@ -157,12 +158,15 @@ public class PagerUtils {
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
case h2: case h2:
case ads: case ads:
case clickhouse:
return limitMySqlQueryBlock(queryBlock, dbType, offset, count, check); return limitMySqlQueryBlock(queryBlock, dbType, offset, count, check);
case postgresql: case postgresql:
case hive: case hive:
case odps: case odps:
case presto:
return limitSQLQueryBlock(queryBlock, dbType, offset, count, check); return limitSQLQueryBlock(queryBlock, dbType, offset, count, check);
case oracle: case oracle:
case oceanbase_oracle: case oceanbase_oracle:
@ -534,6 +538,7 @@ public class PagerUtils {
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
case ads: case ads:
return new MySqlSelectQueryBlock(); return new MySqlSelectQueryBlock();
case oracle: case oracle:
@ -638,7 +643,7 @@ public class PagerUtils {
public static boolean hasUnorderedLimit(String sql, DbType dbType) { public static boolean hasUnorderedLimit(String sql, DbType dbType) {
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType); List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (DbType.mysql == dbType) { if (JdbcUtils.isMysqlDbType(dbType)) {
MySqlUnorderedLimitDetectVisitor visitor = new MySqlUnorderedLimitDetectVisitor(); MySqlUnorderedLimitDetectVisitor visitor = new MySqlUnorderedLimitDetectVisitor();
@ -670,7 +675,7 @@ public class PagerUtils {
SQLOrderBy orderBy = x.getOrderBy(); SQLOrderBy orderBy = x.getOrderBy();
SQLLimit limit = x.getLimit(); SQLLimit limit = x.getLimit();
if (limit != null && (orderBy == null || orderBy.getItems().size() == 0)) { if (limit != null && (orderBy == null || orderBy.getItems().isEmpty())) {
boolean subQueryHasOrderBy = false; boolean subQueryHasOrderBy = false;
SQLTableSource from = x.getFrom(); SQLTableSource from = x.getFrom();
if (from instanceof SQLSubqueryTableSource) { if (from instanceof SQLSubqueryTableSource) {
@ -695,6 +700,7 @@ public class PagerUtils {
private static class OracleUnorderedLimitDetectVisitor extends OracleASTVisitorAdapter { private static class OracleUnorderedLimitDetectVisitor extends OracleASTVisitorAdapter {
public int unorderedLimitCount; public int unorderedLimitCount;
@Override
public boolean visit(SQLBinaryOpExpr x) { public boolean visit(SQLBinaryOpExpr x) {
SQLExpr left = x.getLeft(); SQLExpr left = x.getLeft();
SQLExpr right = x.getRight(); SQLExpr right = x.getRight();
@ -741,7 +747,7 @@ public class PagerUtils {
orderBy = select.getOrderBy(); orderBy = select.getOrderBy();
} }
if (orderBy == null || orderBy.getItems().size() == 0) { if (orderBy == null || orderBy.getItems().isEmpty()) {
unorderedLimitCount++; unorderedLimitCount++;
} }
} }
@ -779,7 +785,7 @@ public class PagerUtils {
SQLSelect select = (SQLSelect) parent; SQLSelect select = (SQLSelect) parent;
if (select.getOrderBy() == null || select.getOrderBy().getItems().size() == 0) { if (select.getOrderBy() == null || select.getOrderBy().getItems().isEmpty()) {
unorderedLimitCount++; unorderedLimitCount++;
} }

20
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/SQLTransformUtils.java

@ -158,7 +158,7 @@ public class SQLTransformUtils {
dataType = new SQLDataTypeImpl("double"); dataType = new SQLDataTypeImpl("double");
} else if (nameHash == FnvHash.Constants.NUMBER) { } else if (nameHash == FnvHash.Constants.NUMBER) {
if (argumentns.size() == 0) { if (argumentns.isEmpty()) {
dataType = new SQLDataTypeImpl("decimal", 38); dataType = new SQLDataTypeImpl("decimal", 38);
} else { } else {
SQLExpr arg0 = argumentns.get(0); SQLExpr arg0 = argumentns.get(0);
@ -230,7 +230,7 @@ public class SQLTransformUtils {
} else if (nameHash == FnvHash.Constants.RAW) { } else if (nameHash == FnvHash.Constants.RAW) {
int len; int len;
if (argumentns.size() == 0) { if (argumentns.isEmpty()) {
len = -1; len = -1;
} else if (argumentns.size() == 1) { } else if (argumentns.size() == 1) {
SQLExpr arg0 = argumentns.get(0); SQLExpr arg0 = argumentns.get(0);
@ -267,7 +267,7 @@ public class SQLTransformUtils {
} else { } else {
dataType = new SQLCharacterDataType("varchar", len); dataType = new SQLCharacterDataType("varchar", len);
} }
} else if (argumentns.size() == 0) { } else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType("char"); dataType = new SQLCharacterDataType("char");
} else { } else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -289,7 +289,7 @@ public class SQLTransformUtils {
} else { } else {
dataType = new SQLCharacterDataType("nvarchar", len); dataType = new SQLCharacterDataType("nvarchar", len);
} }
} else if (argumentns.size() == 0) { } else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType("nchar"); dataType = new SQLCharacterDataType("nchar");
} else { } else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -462,7 +462,7 @@ public class SQLTransformUtils {
dataType = new SQLDataTypeImpl(SQLDataType.Constants.DOUBLE_PRECISION); dataType = new SQLDataTypeImpl(SQLDataType.Constants.DOUBLE_PRECISION);
} else if (nameHash == FnvHash.Constants.NUMBER) { } else if (nameHash == FnvHash.Constants.NUMBER) {
if (argumentns.size() == 0) { if (argumentns.isEmpty()) {
dataType = new SQLDataTypeImpl(SQLDataType.Constants.DECIMAL, 38); dataType = new SQLDataTypeImpl(SQLDataType.Constants.DECIMAL, 38);
} else { } else {
SQLExpr arg0 = argumentns.get(0); SQLExpr arg0 = argumentns.get(0);
@ -536,7 +536,7 @@ public class SQLTransformUtils {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
} }
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR, len); dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR, len);
} else if (argumentns.size() == 0) { } else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR); dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else { } else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -558,7 +558,7 @@ public class SQLTransformUtils {
} else { } else {
dataType = new SQLCharacterDataType(SQLDataType.Constants.TEXT); dataType = new SQLCharacterDataType(SQLDataType.Constants.TEXT);
} }
} else if (argumentns.size() == 0) { } else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR); dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else { } else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -684,7 +684,7 @@ public class SQLTransformUtils {
} }
if (nameHashCode64 == FnvHash.Constants.CURRENT_TIMESTAMP) { if (nameHashCode64 == FnvHash.Constants.CURRENT_TIMESTAMP) {
if (parameters.size() == 0 && x.getParent() instanceof SQLColumnDefinition) { if (parameters.isEmpty() && x.getParent() instanceof SQLColumnDefinition) {
SQLDataType dataType = ((SQLColumnDefinition) x.getParent()).getDataType(); SQLDataType dataType = ((SQLColumnDefinition) x.getParent()).getDataType();
if (dataType.nameHashCode64() == FnvHash.Constants.TIMESTAMP if (dataType.nameHashCode64() == FnvHash.Constants.TIMESTAMP
&& dataType.getArguments().size() == 1) { && dataType.getArguments().size() == 1) {
@ -895,7 +895,7 @@ public class SQLTransformUtils {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
} }
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR, len); dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR, len);
} else if (argumentns.size() == 0) { } else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR); dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else { } else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -917,7 +917,7 @@ public class SQLTransformUtils {
} else { } else {
dataType = new SQLCharacterDataType(SQLDataType.Constants.TEXT); dataType = new SQLCharacterDataType(SQLDataType.Constants.TEXT);
} }
} else if (argumentns.size() == 0) { } else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR); dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else { } else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x)); throw new UnsupportedOperationException(SQLUtils.toOracleString(x));

13
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/SQLUtils.java

@ -43,6 +43,7 @@ import com.fr.third.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVis
import com.fr.third.alibaba.druid.sql.dialect.oracle.visitor.OracleToMySqlOutputVisitor; import com.fr.third.alibaba.druid.sql.dialect.oracle.visitor.OracleToMySqlOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.postgresql.visitor.PGOutputVisitor; import com.fr.third.alibaba.druid.sql.dialect.postgresql.visitor.PGOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor; import com.fr.third.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor;
import com.fr.third.alibaba.druid.sql.dialect.presto.visitor.PrestoOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerOutputVisitor; import com.fr.third.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor; import com.fr.third.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor;
import com.fr.third.alibaba.druid.sql.parser.*; import com.fr.third.alibaba.druid.sql.parser.*;
@ -478,6 +479,7 @@ public class SQLUtils {
} }
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
return new MySqlOutputVisitor(out); return new MySqlOutputVisitor(out);
case postgresql: case postgresql:
return new PGOutputVisitor(out); return new PGOutputVisitor(out);
@ -498,6 +500,8 @@ public class SQLUtils {
return new BlinkOutputVisitor(out); return new BlinkOutputVisitor(out);
case antspark: case antspark:
return new AntsparkOutputVisitor(out); return new AntsparkOutputVisitor(out);
case presto:
return new PrestoOutputVisitor(out);
case clickhouse: case clickhouse:
return new ClickhouseOutputVisitor(out); return new ClickhouseOutputVisitor(out);
default: default:
@ -532,6 +536,7 @@ public class SQLUtils {
return new OracleSchemaStatVisitor(repository); return new OracleSchemaStatVisitor(repository);
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
case elastic_search: case elastic_search:
return new MySqlSchemaStatVisitor(repository); return new MySqlSchemaStatVisitor(repository);
case postgresql: case postgresql:
@ -639,7 +644,7 @@ public class SQLUtils {
dbType = DbType.mysql; dbType = DbType.mysql;
} }
String formatMethod = ""; String formatMethod = "";
if (DbType.mysql == dbType) { if (JdbcUtils.isMysqlDbType(dbType)) {
formatMethod = "STR_TO_DATE"; formatMethod = "STR_TO_DATE";
if (StringUtils.isEmpty(pattern)) pattern = "%Y-%m-%d %H:%i:%s"; if (StringUtils.isEmpty(pattern)) pattern = "%Y-%m-%d %H:%i:%s";
} else if (DbType.oracle == dbType) { } else if (DbType.oracle == dbType) {
@ -701,7 +706,7 @@ public class SQLUtils {
List<SQLStatement> stmtList = parseStatements(sql, dbType); List<SQLStatement> stmtList = parseStatements(sql, dbType);
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + sql); throw new IllegalArgumentException("not support empty-statement :" + sql);
} }
@ -774,7 +779,7 @@ public class SQLUtils {
public static String addSelectItem(String selectSql, String expr, String alias, boolean first, DbType dbType) { public static String addSelectItem(String selectSql, String expr, String alias, boolean first, DbType dbType) {
List<SQLStatement> stmtList = parseStatements(selectSql, dbType); List<SQLStatement> stmtList = parseStatements(selectSql, dbType);
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + selectSql); throw new IllegalArgumentException("not support empty-statement :" + selectSql);
} }
@ -1011,7 +1016,7 @@ public class SQLUtils {
if (OracleUtils.isKeyword(normalizeName)) { if (OracleUtils.isKeyword(normalizeName)) {
return name; return name;
} }
} else if (DbType.mysql == dbType) { } else if (JdbcUtils.isMysqlDbType(dbType)) {
if (MySqlUtils.isKeyword(normalizeName)) { if (MySqlUtils.isKeyword(normalizeName)) {
return name; return name;
} }

16
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/SQLOrderBy.java

@ -26,7 +26,7 @@ public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
protected final List<SQLSelectOrderByItem> items = new ArrayList<SQLSelectOrderByItem>(); protected final List<SQLSelectOrderByItem> items = new ArrayList<SQLSelectOrderByItem>();
// for postgres // for postgres
private boolean sibings; private boolean siblings;
public SQLOrderBy(){ public SQLOrderBy(){
@ -57,12 +57,12 @@ public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
return this.items; return this.items;
} }
public boolean isSibings() { public boolean isSiblings() {
return this.sibings; return this.siblings;
} }
public void setSibings(boolean sibings) { public void setSiblings(boolean siblings) {
this.sibings = sibings; this.siblings = siblings;
} }
protected void accept0(SQLASTVisitor v) { protected void accept0(SQLASTVisitor v) {
@ -83,14 +83,14 @@ public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
SQLOrderBy order = (SQLOrderBy) o; SQLOrderBy order = (SQLOrderBy) o;
if (sibings != order.sibings) return false; if (siblings != order.siblings) return false;
return items.equals(order.items); return items.equals(order.items);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = items.hashCode(); int result = items.hashCode();
result = 31 * result + (sibings ? 1 : 0); result = 31 * result + (siblings ? 1 : 0);
return result; return result;
} }
@ -126,7 +126,7 @@ public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
x.items.add(item1); x.items.add(item1);
} }
x.sibings = sibings; x.siblings = siblings;
return x; return x;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLBinaryOpExpr.java

@ -462,7 +462,7 @@ public class SQLBinaryOpExpr extends SQLExprImpl implements SQLReplaceable, Seri
} }
public static SQLExpr or(List<? extends SQLExpr> list) { public static SQLExpr or(List<? extends SQLExpr> list) {
if (list.size() == 0) { if (list.isEmpty()) {
return null; return null;
} }
SQLExpr first = list.get(0); SQLExpr first = list.get(0);

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLBinaryOpExprGroup.java

@ -158,7 +158,7 @@ public class SQLBinaryOpExprGroup extends SQLExprImpl implements SQLReplaceable
SQLUtils.replaceInParent(this, items.get(0)); SQLUtils.replaceInParent(this, items.get(0));
} }
if (items.size() == 0) { if (items.isEmpty()) {
SQLUtils.replaceInParent(this, null); SQLUtils.replaceInParent(this, null);
} }

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLDateExpr.java

@ -210,7 +210,9 @@ public class SQLDateExpr extends SQLExprImpl implements SQLLiteralExpr, SQLValua
, DbType.postgresql , DbType.postgresql
, DbType.ads , DbType.ads
, DbType.hive , DbType.hive
, DbType.odps); , DbType.odps
, DbType.mariadb
, DbType.tidb);
public static boolean isSupport(DbType dbType) { public static boolean isSupport(DbType dbType) {
return (dbType.mask & supportDbTypes) != 0; return (dbType.mask & supportDbTypes) != 0;

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLDateTimeExpr.java

@ -149,6 +149,8 @@ public class SQLDateTimeExpr extends SQLExprImpl implements SQLLiteralExpr, SQLV
, DbType.presto , DbType.presto
, DbType.trino , DbType.trino
, DbType.postgresql , DbType.postgresql
, DbType.mariadb
, DbType.tidb
); );
public static boolean isSupport(DbType dbType) { public static boolean isSupport(DbType dbType) {

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLIntegerExpr.java

@ -199,7 +199,7 @@ public class SQLIntegerExpr extends SQLNumericLiteralExpr implements SQLValuable
} }
if (this.number instanceof Double && o.number instanceof Double) { if (this.number instanceof Double && o.number instanceof Double) {
return ((Float) this.number).compareTo((Float) o.number); return ((Double) this.number).compareTo((Double) o.number);
} }
return -1; return -1;

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/expr/SQLTimeExpr.java

@ -150,6 +150,8 @@ public class SQLTimeExpr extends SQLExprImpl implements SQLLiteralExpr, SQLValua
, DbType.presto , DbType.presto
, DbType.trino , DbType.trino
, DbType.postgresql , DbType.postgresql
, DbType.mariadb
, DbType.tidb
); );
public static boolean isSupport(DbType dbType) { public static boolean isSupport(DbType dbType) {

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLAnalyzeTableStatement.java

@ -66,7 +66,7 @@ public class SQLAnalyzeTableStatement extends SQLStatementImpl {
} }
public SQLExprTableSource getTable() { public SQLExprTableSource getTable() {
if (tableSources.size() == 0) { if (tableSources.isEmpty()) {
return null; return null;
} }
@ -86,7 +86,7 @@ public class SQLAnalyzeTableStatement extends SQLStatementImpl {
table.setParent(this); table.setParent(this);
} }
if (tableSources.size() == 0) { if (tableSources.isEmpty()) {
if (table == null) { if (table == null) {
return; return;
} }

8
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLCreateTableStatement.java

@ -525,7 +525,7 @@ public class SQLCreateTableStatement extends SQLStatementImpl implements SQLDDLS
if (element instanceof MySqlUnique) { if (element instanceof MySqlUnique) {
MySqlUnique unique = (MySqlUnique) element; MySqlUnique unique = (MySqlUnique) element;
if (unique.getColumns().size() == 0) { if (unique.getColumns().isEmpty()) {
continue; continue;
} }
@ -671,7 +671,7 @@ public class SQLCreateTableStatement extends SQLStatementImpl implements SQLDDLS
} }
} }
if (stmt.getItems().size() == 0) { if (stmt.getItems().isEmpty()) {
return null; return null;
} }
@ -1095,13 +1095,13 @@ public class SQLCreateTableStatement extends SQLStatementImpl implements SQLDDLS
if (e instanceof SQLUnique) { if (e instanceof SQLUnique) {
SQLUnique unique = (SQLUnique) e; SQLUnique unique = (SQLUnique) e;
unique.applyDropColumn(column); unique.applyDropColumn(column);
if (unique.getColumns().size() == 0) { if (unique.getColumns().isEmpty()) {
tableElementList.remove(i); tableElementList.remove(i);
} }
} else if (e instanceof MySqlTableIndex) { } else if (e instanceof MySqlTableIndex) {
MySqlTableIndex index = (MySqlTableIndex) e; MySqlTableIndex index = (MySqlTableIndex) e;
index.applyDropColumn(column); index.applyDropColumn(column);
if (index.getColumns().size() == 0) { if (index.getColumns().isEmpty()) {
tableElementList.remove(i); tableElementList.remove(i);
} }
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLDeleteStatement.java

@ -267,7 +267,7 @@ public class SQLDeleteStatement extends SQLStatementImpl implements SQLReplaceab
removedCount++; removedCount++;
} }
} }
if (items.size() == 0) { if (items.isEmpty()) {
where = null; where = null;
} }

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLInsertInto.java

@ -164,14 +164,14 @@ public abstract class SQLInsertInto extends SQLStatementImpl implements SQLRepla
} }
public ValuesClause getValues() { public ValuesClause getValues() {
if (valuesList.size() == 0) { if (valuesList.isEmpty()) {
return null; return null;
} }
return valuesList.get(0); return valuesList.get(0);
} }
public void setValues(ValuesClause values) { public void setValues(ValuesClause values) {
if (valuesList.size() == 0) { if (valuesList.isEmpty()) {
valuesList.add(values); valuesList.add(values);
} else { } else {
valuesList.set(0, values); valuesList.set(0, values);

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLSelect.java

@ -217,10 +217,10 @@ public class SQLSelect extends SQLObjectImpl implements SQLDbTypedObject {
public boolean isSimple() { public boolean isSimple() {
return withSubQuery == null return withSubQuery == null
&& (hints == null || hints.size() == 0) && (hints == null || hints.isEmpty())
&& restriction == null && restriction == null
&& (!forBrowse) && (!forBrowse)
&& (forXmlOptions == null || forXmlOptions.size() == 0) && (forXmlOptions == null || forXmlOptions.isEmpty())
&& xmlPath == null && xmlPath == null
&& rowCount == null && rowCount == null
&& offset == null; && offset == null;

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLSelectQueryBlock.java

@ -176,7 +176,7 @@ public class SQLSelectQueryBlock extends SQLSelectQueryBase implements SQLReplac
} }
} }
if (andList.size() == 0) { if (andList.isEmpty()) {
SQLUtils.replaceInParent(item, new SQLBooleanExpr(false)); SQLUtils.replaceInParent(item, new SQLBooleanExpr(false));
return; return;
} }
@ -1251,7 +1251,7 @@ public class SQLSelectQueryBlock extends SQLSelectQueryBase implements SQLReplac
removedCount++; removedCount++;
} }
} }
if (items.size() == 0) { if (items.isEmpty()) {
where = null; where = null;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLShowGrantsStatement.java

@ -47,7 +47,7 @@ public class SQLShowGrantsStatement extends SQLStatementImpl implements SQLShowS
} }
public void setOn(SQLExpr x) { public void setOn(SQLExpr x) {
if (x == null) { if (x != null) {
x.setParent(this); x.setParent(this);
} }
this.on = x; this.on = x;

6
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLUnionQuery.java

@ -75,7 +75,7 @@ public class SQLUnionQuery extends SQLSelectQueryBase implements SQLDbTypedObjec
} }
public SQLSelectQuery getLeft() { public SQLSelectQuery getLeft() {
if (relations.size() == 0) { if (relations.isEmpty()) {
return null; return null;
} }
return relations.get(0); return relations.get(0);
@ -86,7 +86,7 @@ public class SQLUnionQuery extends SQLSelectQueryBase implements SQLDbTypedObjec
left.setParent(this); left.setParent(this);
} }
if (relations.size() == 0) { if (relations.isEmpty()) {
relations.add(left); relations.add(left);
} else if (relations.size() <= 2) { } else if (relations.size() <= 2) {
relations.set(0, left); relations.set(0, left);
@ -111,7 +111,7 @@ public class SQLUnionQuery extends SQLSelectQueryBase implements SQLDbTypedObjec
right.setParent(this); right.setParent(this);
} }
if (relations.size() == 0) { if (relations.isEmpty()) {
relations.add(null); relations.add(null);
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/ast/statement/SQLUpdateStatement.java

@ -312,7 +312,7 @@ public class SQLUpdateStatement extends SQLStatementImpl implements SQLReplaceab
removedCount++; removedCount++;
} }
} }
if (items.size() == 0) { if (items.isEmpty()) {
where = null; where = null;
} }

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/builder/impl/SQLDeleteBuilderImpl.java

@ -42,7 +42,7 @@ public class SQLDeleteBuilderImpl implements SQLDeleteBuilder {
public SQLDeleteBuilderImpl(String sql, DbType dbType){ public SQLDeleteBuilderImpl(String sql, DbType dbType){
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType); List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + sql); throw new IllegalArgumentException("not support empty-statement :" + sql);
} }
@ -127,6 +127,8 @@ public class SQLDeleteBuilderImpl implements SQLDeleteBuilder {
case oracle: case oracle:
return new OracleDeleteStatement(); return new OracleDeleteStatement();
case mysql: case mysql:
case mariadb:
case tidb:
return new MySqlDeleteStatement(); return new MySqlDeleteStatement();
case postgresql: case postgresql:
return new PGDeleteStatement(); return new PGDeleteStatement();

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/builder/impl/SQLSelectBuilderImpl.java

@ -40,7 +40,7 @@ public class SQLSelectBuilderImpl implements SQLSelectBuilder {
public SQLSelectBuilderImpl(String sql, DbType dbType){ public SQLSelectBuilderImpl(String sql, DbType dbType){
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType); List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + sql); throw new IllegalArgumentException("not support empty-statement :" + sql);
} }

3
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/builder/impl/SQLUpdateBuilderImpl.java

@ -45,7 +45,7 @@ public class SQLUpdateBuilderImpl extends SQLBuilderImpl implements SQLUpdateBui
public SQLUpdateBuilderImpl(String sql, DbType dbType){ public SQLUpdateBuilderImpl(String sql, DbType dbType){
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType); List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + sql); throw new IllegalArgumentException("not support empty-statement :" + sql);
} }
@ -161,6 +161,7 @@ public class SQLUpdateBuilderImpl extends SQLBuilderImpl implements SQLUpdateBui
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
return new MySqlUpdateStatement(); return new MySqlUpdateStatement();
case oracle: case oracle:
return new OracleUpdateStatement(); return new OracleUpdateStatement();

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/db2/parser/DB2StatementParser.java

@ -70,7 +70,7 @@ public class DB2StatementParser extends SQLStatementParser {
SQLAlterTableAlterColumn alterColumn = new SQLAlterTableAlterColumn(); SQLAlterTableAlterColumn alterColumn = new SQLAlterTableAlterColumn();
alterColumn.setColumn(column); alterColumn.setColumn(column);
if (column.getDataType() == null && column.getConstraints().size() == 0) { if (column.getDataType() == null && column.getConstraints().isEmpty()) {
if (lexer.token() == Token.SET) { if (lexer.token() == Token.SET) {
lexer.nextToken(); lexer.nextToken();
if (lexer.token() == Token.NOT) { if (lexer.token() == Token.NOT) {

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/h2/visitor/H2OutputVisitor.java

@ -58,7 +58,7 @@ public class H2OutputVisitor extends SQLASTOutputVisitor implements H2ASTVisitor
} }
List<SQLInsertStatement.ValuesClause> valuesClauseList = x.getValuesList(); List<SQLInsertStatement.ValuesClause> valuesClauseList = x.getValuesList();
if (valuesClauseList.size() != 0) { if (!valuesClauseList.isEmpty()) {
println(); println();
print0(ucase ? "VALUES " : "values "); print0(ucase ? "VALUES " : "values ");
int size = valuesClauseList.size(); int size = valuesClauseList.size();

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlCreateTableSpaceStatement.java

@ -70,7 +70,7 @@ public class MySqlCreateTableSpaceStatement extends MySqlStatementImpl implement
if (x != null) { if (x != null) {
x.setParent(this); x.setParent(this);
} }
this.addDataFile = addDataFile; this.addDataFile = x;
} }
public SQLExpr getInitialSize() { public SQLExpr getInitialSize() {

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlKillStatement.java

@ -48,7 +48,7 @@ public class MySqlKillStatement extends SQLStatementImpl {
} }
public void setThreadId(SQLExpr threadId) { public void setThreadId(SQLExpr threadId) {
if (this.threadIds.size() == 0) { if (this.threadIds.isEmpty()) {
this.threadIds.add(threadId); this.threadIds.add(threadId);
return; return;
} }

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/parser/MySqlStatementParser.java

@ -1706,7 +1706,7 @@ public class MySqlStatementParser extends SQLStatementParser {
break; break;
} }
if (hints.size() >= 1 if (hints.size() >= 1
&& statementList.size() == 0 && statementList.isEmpty()
&& acceptHint) { && acceptHint) {
SQLCommentHint hint = hints.get(0); SQLCommentHint hint = hints.get(0);
String hintText = hint.getText().toUpperCase(); String hintText = hint.getText().toUpperCase();
@ -2346,7 +2346,7 @@ public class MySqlStatementParser extends SQLStatementParser {
break; break;
} }
if (stmt.getTables().size() != 0) { if (!stmt.getTables().isEmpty()) {
if (lexer.token() == Token.FOR) { if (lexer.token() == Token.FOR) {
lexer.nextToken(); lexer.nextToken();
acceptIdentifier("EXPORT"); acceptIdentifier("EXPORT");

16
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/mysql/visitor/MySqlOutputVisitor.java

@ -1244,7 +1244,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
} }
List<SQLExpr> duplicateKeyUpdate = x.getDuplicateKeyUpdate(); List<SQLExpr> duplicateKeyUpdate = x.getDuplicateKeyUpdate();
if (duplicateKeyUpdate.size() != 0) { if (!duplicateKeyUpdate.isEmpty()) {
println(); println();
print0(ucase ? "ON DUPLICATE KEY UPDATE " : "on duplicate key update "); print0(ucase ? "ON DUPLICATE KEY UPDATE " : "on duplicate key update ");
for (int i = 0, size = duplicateKeyUpdate.size(); i < size; ++i) { for (int i = 0, size = duplicateKeyUpdate.size(); i < size; ++i) {
@ -1278,7 +1278,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
SQLExpr value = values.get(i); SQLExpr value = values.get(i);
if (value instanceof SQLLiteralExpr || value instanceof SQLVariantRefExpr) { if (value instanceof SQLLiteralExpr || value instanceof SQLVariantRefExpr) {
continue; continue;
} else if (value instanceof SQLMethodInvokeExpr && ((SQLMethodInvokeExpr) value).getArguments().size() == 0) { } else if (value instanceof SQLMethodInvokeExpr && ((SQLMethodInvokeExpr) value).getArguments().isEmpty()) {
continue; continue;
} }
allConst = false; allConst = false;
@ -1433,13 +1433,13 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print0(ucase ? " LINES" : " lines"); print0(ucase ? " LINES" : " lines");
} }
if (x.getColumns().size() != 0) { if (!x.getColumns().isEmpty()) {
print0(" ("); print0(" (");
printAndAccept(x.getColumns(), ", "); printAndAccept(x.getColumns(), ", ");
print(')'); print(')');
} }
if (x.getSetList().size() != 0) { if (!x.getSetList().isEmpty()) {
print0(ucase ? " SET " : " set "); print0(ucase ? " SET " : " set ");
printAndAccept(x.getSetList(), ", "); printAndAccept(x.getSetList(), ", ");
} }
@ -1516,7 +1516,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
} }
List<SQLInsertStatement.ValuesClause> valuesClauseList = x.getValuesList(); List<SQLInsertStatement.ValuesClause> valuesClauseList = x.getValuesList();
if (valuesClauseList.size() != 0) { if (!valuesClauseList.isEmpty()) {
println(); println();
print0(ucase ? "VALUES " : "values "); print0(ucase ? "VALUES " : "values ");
int size = valuesClauseList.size(); int size = valuesClauseList.size();
@ -1758,7 +1758,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
x.getRowsIdentifiedBy().accept(this); x.getRowsIdentifiedBy().accept(this);
} }
if (x.getSetList().size() != 0) { if (!x.getSetList().isEmpty()) {
print0(ucase ? " SET " : " set "); print0(ucase ? " SET " : " set ");
printAndAccept(x.getSetList(), ", "); printAndAccept(x.getSetList(), ", ");
} }
@ -4218,7 +4218,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
} }
List<SQLParameter> parameters = x.getParameters(); List<SQLParameter> parameters = x.getParameters();
if (parameters.size() != 0) { if (!parameters.isEmpty()) {
this.indentCount++; this.indentCount++;
if (parent instanceof SQLCreateProcedureStatement) { if (parent instanceof SQLCreateProcedureStatement) {
printIndent(); printIndent();
@ -4600,7 +4600,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print(")"); print(")");
} }
if (x.getOptions().size() != 0) { if (!x.getOptions().isEmpty()) {
println(); println();
print0(ucase ? "SUBPARTITION OPTIONS (" : "subpartition options ("); print0(ucase ? "SUBPARTITION OPTIONS (" : "subpartition options (");
printAndAccept(x.getOptions(), ", "); printAndAccept(x.getOptions(), ", ");

0
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/oracle/ast/expr/OracleIntervalExpr.java

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/oracle/parser/OracleStatementParser.java

@ -2157,7 +2157,7 @@ public class OracleStatementParser extends SQLStatementParser {
while (lexer.token() == Token.INTO) { while (lexer.token() == Token.INTO) {
OracleMultiInsertStatement.InsertIntoClause clause = new OracleMultiInsertStatement.InsertIntoClause(); OracleMultiInsertStatement.InsertIntoClause clause = new OracleMultiInsertStatement.InsertIntoClause();
boolean acceptSubQuery = stmt.getEntries().size() == 0; boolean acceptSubQuery = stmt.getEntries().isEmpty();
parseInsert0(clause, acceptSubQuery); parseInsert0(clause, acceptSubQuery);
clause.setReturning(parseReturningClause()); clause.setReturning(parseReturningClause());

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/postgresql/ast/stmt/PGInsertStatement.java

@ -68,14 +68,14 @@ public class PGInsertStatement extends SQLInsertStatement implements PGSQLStatem
public ValuesClause getValues() { public ValuesClause getValues() {
if (valuesList.size() == 0) { if (valuesList.isEmpty()) {
return null; return null;
} }
return valuesList.get(0); return valuesList.get(0);
} }
public void setValues(ValuesClause values) { public void setValues(ValuesClause values) {
if (valuesList.size() == 0) { if (valuesList.isEmpty()) {
valuesList.add(values); valuesList.add(values);
} else { } else {
valuesList.set(0, values); valuesList.set(0, values);

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/postgresql/parser/PGSQLStatementParser.java

@ -459,7 +459,7 @@ public class PGSQLStatementParser extends SQLStatementParser {
SQLAlterTableAlterColumn alterColumn = new SQLAlterTableAlterColumn(); SQLAlterTableAlterColumn alterColumn = new SQLAlterTableAlterColumn();
alterColumn.setColumn(column); alterColumn.setColumn(column);
if (column.getDataType() == null && column.getConstraints().size() == 0) { if (column.getDataType() == null && column.getConstraints().isEmpty()) {
if (lexer.token() == Token.SET) { if (lexer.token() == Token.SET) {
lexer.nextToken(); lexer.nextToken();
if (lexer.token() == Token.NOT) { if (lexer.token() == Token.NOT) {

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/postgresql/visitor/PGOutputVisitor.java

@ -435,7 +435,7 @@ public class PGOutputVisitor extends SQLASTOutputVisitor implements PGASTVisitor
print('('); print('(');
expr.accept(this); expr.accept(this);
print(')'); print(')');
} else if (expr instanceof PGTypeCastExpr && dataType.getArguments().size() == 0) { } else if (expr instanceof PGTypeCastExpr && dataType.getArguments().isEmpty()) {
dataType.accept(this); dataType.accept(this);
print('('); print('(');
visit((PGTypeCastExpr) expr); visit((PGTypeCastExpr) expr);

56
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/ast/stmt/PrestoSelectStatement.java

@ -0,0 +1,56 @@
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fr.third.alibaba.druid.sql.dialect.presto.ast.stmt;
import com.fr.third.alibaba.druid.DbType;
import com.fr.third.alibaba.druid.sql.ast.SQLStatement;
import com.fr.third.alibaba.druid.sql.ast.statement.SQLSelect;
import com.fr.third.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.fr.third.alibaba.druid.sql.dialect.presto.visitor.PrestoVisitor;
import com.fr.third.alibaba.druid.sql.visitor.SQLASTVisitor;
/**
* presto select语句
*
* @author zhangcanlong
* @date 2022/01/11
*/
public class PrestoSelectStatement extends SQLSelectStatement implements SQLStatement {
public PrestoSelectStatement() {
super(DbType.postgresql);
}
public PrestoSelectStatement(SQLSelect select) {
super(select, DbType.postgresql);
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor instanceof PrestoVisitor) {
this.accept0((PrestoVisitor) visitor);
} else {
super.accept0(visitor);
}
}
public void accept0(PrestoVisitor visitor) {
if (visitor.visit(this)) {
this.acceptChild(visitor, this.select);
}
visitor.endVisit(this);
}
}

10
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/parser/PrestoExprParser.java

@ -16,13 +16,9 @@
package com.fr.third.alibaba.druid.sql.dialect.presto.parser; package com.fr.third.alibaba.druid.sql.dialect.presto.parser;
import com.fr.third.alibaba.druid.DbType; import com.fr.third.alibaba.druid.DbType;
import com.fr.third.alibaba.druid.sql.ast.SQLExpr; import com.fr.third.alibaba.druid.sql.parser.Lexer;
import com.fr.third.alibaba.druid.sql.ast.expr.SQLCharExpr; import com.fr.third.alibaba.druid.sql.parser.SQLExprParser;
import com.fr.third.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.fr.third.alibaba.druid.sql.parser.SQLParserFeature;
import com.fr.third.alibaba.druid.sql.ast.expr.SQLIntervalExpr;
import com.fr.third.alibaba.druid.sql.ast.expr.SQLIntervalUnit;
import com.fr.third.alibaba.druid.sql.dialect.phoenix.parser.PhoenixLexer;
import com.fr.third.alibaba.druid.sql.parser.*;
/** /**
* Created by wenshao on 16/9/13. * Created by wenshao on 16/9/13.

202
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/parser/PrestoSelectParser.java

@ -0,0 +1,202 @@
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fr.third.alibaba.druid.sql.dialect.presto.parser;
import com.fr.third.alibaba.druid.DbType;
import com.fr.third.alibaba.druid.sql.ast.SQLExpr;
import com.fr.third.alibaba.druid.sql.ast.SQLLimit;
import com.fr.third.alibaba.druid.sql.ast.SQLObject;
import com.fr.third.alibaba.druid.sql.ast.SQLSetQuantifier;
import com.fr.third.alibaba.druid.sql.ast.statement.SQLSelectQuery;
import com.fr.third.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.fr.third.alibaba.druid.sql.parser.SQLExprParser;
import com.fr.third.alibaba.druid.sql.parser.SQLSelectListCache;
import com.fr.third.alibaba.druid.sql.parser.SQLSelectParser;
import com.fr.third.alibaba.druid.sql.parser.Token;
import com.fr.third.alibaba.druid.util.FnvHash;
/**
* presto的 选择解析器
*
* @author zhangcanlong
* @date 2022/01/11
*/
public class PrestoSelectParser extends SQLSelectParser {
public PrestoSelectParser(SQLExprParser exprParser) {
super(exprParser);
}
public PrestoSelectParser(SQLExprParser exprParser, SQLSelectListCache selectListCache) {
super(exprParser, selectListCache);
}
public PrestoSelectParser(String sql) {
this(new PrestoExprParser(sql));
}
protected SQLExprParser createExprParser() {
return new PrestoExprParser(this.lexer);
}
@Override
public SQLSelectQuery query(SQLObject parent, boolean acceptUnion) {
if (this.lexer.token() == Token.LPAREN) {
this.lexer.nextToken();
SQLSelectQuery select = this.query();
this.accept(Token.RPAREN);
return this.queryRest(select, acceptUnion);
}
if (this.lexer.token() == Token.VALUES) {
return this.valuesQuery(acceptUnion);
}
SQLSelectQueryBlock queryBlock = new SQLSelectQueryBlock(this.dbType);
if (this.lexer.hasComment() && this.lexer.isKeepComments()) {
queryBlock.addBeforeComment(this.lexer.readAndResetComments());
}
this.accept(Token.SELECT);
if (this.lexer.token() == Token.HINT) {
this.exprParser.parseHints(queryBlock.getHints());
}
if (this.lexer.token() == Token.COMMENT) {
this.lexer.nextToken();
}
if (DbType.informix == this.dbType) {
if (this.lexer.identifierEquals(FnvHash.Constants.SKIP)) {
this.lexer.nextToken();
SQLExpr offset = this.exprParser.primary();
queryBlock.setOffset(offset);
}
if (this.lexer.identifierEquals(FnvHash.Constants.FIRST)) {
this.lexer.nextToken();
SQLExpr first = this.exprParser.primary();
queryBlock.setFirst(first);
}
}
if (this.lexer.token() == Token.DISTINCT) {
queryBlock.setDistionOption(SQLSetQuantifier.DISTINCT);
this.lexer.nextToken();
} else if (this.lexer.token() == Token.UNIQUE) {
queryBlock.setDistionOption(SQLSetQuantifier.UNIQUE);
this.lexer.nextToken();
} else if (this.lexer.token() == Token.ALL) {
queryBlock.setDistionOption(SQLSetQuantifier.ALL);
this.lexer.nextToken();
}
this.parseSelectList(queryBlock);
if (this.lexer.token() == Token.INTO) {
this.lexer.nextToken();
SQLExpr expr = this.expr();
if (this.lexer.token() != Token.COMMA) {
queryBlock.setInto(expr);
}
}
this.parseFrom(queryBlock);
this.parseWhere(queryBlock);
this.parseGroupBy(queryBlock);
if (this.lexer.identifierEquals(FnvHash.Constants.WINDOW)) {
this.parseWindow(queryBlock);
}
this.parseSortBy(queryBlock);
this.parseFetchClause(queryBlock);
if (this.lexer.token() == Token.FOR) {
this.lexer.nextToken();
this.accept(Token.UPDATE);
queryBlock.setForUpdate(true);
if (this.lexer.identifierEquals(FnvHash.Constants.NO_WAIT) || this.lexer.identifierEquals(FnvHash.Constants.NOWAIT)) {
this.lexer.nextToken();
queryBlock.setNoWait(true);
} else if (this.lexer.identifierEquals(FnvHash.Constants.WAIT)) {
this.lexer.nextToken();
SQLExpr waitTime = this.exprParser.primary();
queryBlock.setWaitTime(waitTime);
}
}
return this.queryRest(queryBlock, acceptUnion);
}
@Override
public void parseFetchClause(SQLSelectQueryBlock queryBlock) {
// 如果是presto,则先解析 offset 再解析limit
if (this.lexer.identifierEquals(FnvHash.Constants.OFFSET) || this.lexer.token() == Token.OFFSET) {
this.lexer.nextToken();
SQLExpr offset = this.exprParser.expr();
queryBlock.setOffset(offset);
if (this.lexer.identifierEquals(FnvHash.Constants.ROW) || this.lexer.identifierEquals(FnvHash.Constants.ROWS)) {
this.lexer.nextToken();
}
}
if (this.lexer.token() == Token.LIMIT) {
SQLLimit limit = queryBlock.getLimit();
// 原始的limit
SQLLimit originLimit = this.exprParser.parseLimit();
if (limit == null) {
limit = originLimit;
}
limit.setRowCount(originLimit.getRowCount());
queryBlock.setLimit(limit);
return;
}
if (this.lexer.token() == Token.FETCH) {
this.lexer.nextToken();
if (this.lexer.token() == Token.FIRST || this.lexer.token() == Token.NEXT || this.lexer.identifierEquals(FnvHash.Constants.NEXT)) {
this.lexer.nextToken();
} else {
this.acceptIdentifier("FIRST");
}
SQLExpr first = this.exprParser.primary();
queryBlock.setFirst(first);
if (this.lexer.identifierEquals(FnvHash.Constants.ROW) || this.lexer.identifierEquals(FnvHash.Constants.ROWS)) {
this.lexer.nextToken();
}
if (this.lexer.token() == Token.ONLY) {
this.lexer.nextToken();
} else {
this.acceptIdentifier("ONLY");
}
}
}
}

15
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/parser/PrestoStatementParser.java

@ -18,7 +18,8 @@ package com.fr.third.alibaba.druid.sql.dialect.presto.parser;
import com.fr.third.alibaba.druid.sql.ast.SQLExpr; import com.fr.third.alibaba.druid.sql.ast.SQLExpr;
import com.fr.third.alibaba.druid.sql.ast.SQLName; import com.fr.third.alibaba.druid.sql.ast.SQLName;
import com.fr.third.alibaba.druid.sql.ast.statement.SQLInsertInto; import com.fr.third.alibaba.druid.sql.ast.statement.SQLInsertInto;
import com.fr.third.alibaba.druid.sql.dialect.phoenix.parser.PhoenixExprParser; import com.fr.third.alibaba.druid.sql.ast.statement.SQLSelect;
import com.fr.third.alibaba.druid.sql.dialect.postgresql.ast.stmt.PGSelectStatement;
import com.fr.third.alibaba.druid.sql.parser.Lexer; import com.fr.third.alibaba.druid.sql.parser.Lexer;
import com.fr.third.alibaba.druid.sql.parser.SQLStatementParser; import com.fr.third.alibaba.druid.sql.parser.SQLStatementParser;
import com.fr.third.alibaba.druid.sql.parser.Token; import com.fr.third.alibaba.druid.sql.parser.Token;
@ -35,6 +36,18 @@ public class PrestoStatementParser extends SQLStatementParser {
super(new PrestoExprParser(lexer)); super(new PrestoExprParser(lexer));
} }
@Override
public PrestoSelectParser createSQLSelectParser() {
return new PrestoSelectParser(this.exprParser, selectListCache);
}
@Override
public PGSelectStatement parseSelect() {
PrestoSelectParser selectParser = createSQLSelectParser();
SQLSelect select = selectParser.select();
return new PGSelectStatement(select);
}
@Override @Override
protected void parseInsertColumns(SQLInsertInto insert) { protected void parseInsertColumns(SQLInsertInto insert) {
if (lexer.token() == Token.RPAREN ) { if (lexer.token() == Token.RPAREN ) {

47
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/presto/visitor/PrestoOutputVisitor.java

@ -0,0 +1,47 @@
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fr.third.alibaba.druid.sql.dialect.presto.visitor;
import com.fr.third.alibaba.druid.sql.ast.SQLLimit;
import com.fr.third.alibaba.druid.sql.dialect.phoenix.visitor.PhoenixASTVisitor;
import com.fr.third.alibaba.druid.sql.visitor.SQLASTOutputVisitor;
/**
* presto 的输出的视图信息
*
* @author zhangcanlong
* @since 2022-01-07
*/
public class PrestoOutputVisitor extends SQLASTOutputVisitor implements PhoenixASTVisitor {
public PrestoOutputVisitor(Appendable appender) {
super(appender);
}
public PrestoOutputVisitor(Appendable appender, boolean parameterized) {
super(appender, parameterized);
}
@Override
public boolean visit(SQLLimit x) {
if (x.getOffset() != null) {
this.print0(this.ucase ? " OFFSET " : " offset ");
x.getOffset().accept(this);
}
this.print0(this.ucase ? " LIMIT " : " limit ");
x.getRowCount().accept(this);
return false;
}
}

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/dialect/sqlserver/visitor/SQLServerOutputVisitor.java

@ -156,7 +156,7 @@ public class SQLServerOutputVisitor extends SQLASTOutputVisitor implements SQLSe
x.getOutput().accept(this); x.getOutput().accept(this);
} }
if (x.getValuesList().size() != 0) { if (!x.getValuesList().isEmpty()) {
println(); println();
print0(ucase ? "VALUES " : "values "); print0(ucase ? "VALUES " : "values ");
for (int i = 0, size = x.getValuesList().size(); i < size; ++i) { for (int i = 0, size = x.getValuesList().size(); i < size; ++i) {

8
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/parser/SQLExprParser.java

@ -2695,7 +2695,7 @@ public class SQLExprParser extends SQLParser {
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) { if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken(); lexer.nextToken();
orderBy.setSibings(true); orderBy.setSiblings(true);
} }
accept(Token.BY); accept(Token.BY);
@ -2745,7 +2745,7 @@ public class SQLExprParser extends SQLParser {
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) { if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken(); lexer.nextToken();
orderBy.setSibings(true); orderBy.setSiblings(true);
} }
accept(Token.BY); accept(Token.BY);
@ -2770,7 +2770,7 @@ public class SQLExprParser extends SQLParser {
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) { if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken(); lexer.nextToken();
orderBy.setSibings(true); orderBy.setSiblings(true);
} }
accept(Token.BY); accept(Token.BY);
@ -2795,7 +2795,7 @@ public class SQLExprParser extends SQLParser {
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) { if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken(); lexer.nextToken();
orderBy.setSibings(true); orderBy.setSiblings(true);
} }
accept(Token.BY); accept(Token.BY);

8
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/parser/SQLSelectParser.java

@ -1113,7 +1113,7 @@ public class SQLSelectParser extends SQLParser {
tableSource.setAlias(alias); tableSource.setAlias(alias);
if (tableSource instanceof SQLValuesTableSource if (tableSource instanceof SQLValuesTableSource
&& ((SQLValuesTableSource) tableSource).getColumns().size() == 0) { && ((SQLValuesTableSource) tableSource).getColumns().isEmpty()) {
SQLValuesTableSource values = (SQLValuesTableSource) tableSource; SQLValuesTableSource values = (SQLValuesTableSource) tableSource;
accept(Token.LPAREN); accept(Token.LPAREN);
this.exprParser.names(values.getColumns(), values); this.exprParser.names(values.getColumns(), values);
@ -1351,7 +1351,7 @@ public class SQLSelectParser extends SQLParser {
tableSource.setAlias(alias); tableSource.setAlias(alias);
if ((tableSource instanceof SQLValuesTableSource) if ((tableSource instanceof SQLValuesTableSource)
&& ((SQLValuesTableSource) tableSource).getColumns().size() == 0) { && ((SQLValuesTableSource) tableSource).getColumns().isEmpty()) {
SQLValuesTableSource values = (SQLValuesTableSource) tableSource; SQLValuesTableSource values = (SQLValuesTableSource) tableSource;
accept(Token.LPAREN); accept(Token.LPAREN);
this.exprParser.names(values.getColumns(), values); this.exprParser.names(values.getColumns(), values);
@ -1565,7 +1565,7 @@ public class SQLSelectParser extends SQLParser {
if (rightTableSource instanceof SQLValuesTableSource if (rightTableSource instanceof SQLValuesTableSource
&& (lexer.token == Token.AS || lexer.token == Token.IDENTIFIER) && (lexer.token == Token.AS || lexer.token == Token.IDENTIFIER)
&& rightTableSource.getAlias() == null && rightTableSource.getAlias() == null
&& ((SQLValuesTableSource) rightTableSource).getColumns().size() == 0 && ((SQLValuesTableSource) rightTableSource).getColumns().isEmpty()
) { ) {
if (lexer.token == Token.AS) { if (lexer.token == Token.AS) {
lexer.nextToken(); lexer.nextToken();
@ -1708,7 +1708,7 @@ public class SQLSelectParser extends SQLParser {
} else if (rightTableSource instanceof SQLExprTableSource } else if (rightTableSource instanceof SQLExprTableSource
&& ((SQLExprTableSource) rightTableSource).getExpr() instanceof SQLMethodInvokeExpr) { && ((SQLExprTableSource) rightTableSource).getExpr() instanceof SQLMethodInvokeExpr) {
List<SQLName> columns = ((SQLExprTableSource) rightTableSource).getColumns(); List<SQLName> columns = ((SQLExprTableSource) rightTableSource).getColumns();
if (columns.size() == 0) { if (columns.isEmpty()) {
lexer.nextToken(); lexer.nextToken();
this.exprParser.names(columns, rightTableSource); this.exprParser.names(columns, rightTableSource);
accept(Token.RPAREN); accept(Token.RPAREN);

1
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/repository/SchemaRepository.java

@ -413,6 +413,7 @@ public class SchemaRepository {
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
case sqlite: case sqlite:
resolveVisitor = new SchemaResolveVisitorFactory.MySqlResolveVisitor(this, optionsValue); resolveVisitor = new SchemaResolveVisitorFactory.MySqlResolveVisitor(this, optionsValue);
break; break;

1
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/transform/SQLRefactorVisitor.java

@ -29,6 +29,7 @@ public class SQLRefactorVisitor extends SQLASTVisitorAdapter {
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
case ads: case ads:
quote = '`'; quote = '`';
break; break;

3
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/ExportParameterVisitorUtils.java

@ -43,6 +43,7 @@ public final class ExportParameterVisitorUtils {
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
return new MySqlExportParameterVisitor(out); return new MySqlExportParameterVisitor(out);
case oracle: case oracle:
return new OracleExportParameterVisitor(out); return new OracleExportParameterVisitor(out);
@ -124,7 +125,7 @@ public final class ExportParameterVisitorUtils {
} else if (listItem instanceof SQLNumericLiteralExpr) { } else if (listItem instanceof SQLNumericLiteralExpr) {
Object listValue = ((SQLNumericLiteralExpr) listItem).getNumber(); Object listValue = ((SQLNumericLiteralExpr) listItem).getNumber();
listValues.add(listValue); listValues.add(listValue);
} else if (param instanceof SQLHexExpr) { } else if (listItem instanceof SQLHexExpr) {
Object listValue = ((SQLHexExpr) listItem).toBytes(); Object listValue = ((SQLHexExpr) listItem).toBytes();
listValues.add(listValue); listValues.add(listValue);
} }

7
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/ParameterizedOutputVisitorUtils.java

@ -34,6 +34,7 @@ import com.fr.third.alibaba.druid.sql.dialect.oracle.visitor.OracleASTParameteri
import com.fr.third.alibaba.druid.sql.dialect.oracle.visitor.OracleParameterizedOutputVisitor; import com.fr.third.alibaba.druid.sql.dialect.oracle.visitor.OracleParameterizedOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.phoenix.visitor.PhoenixOutputVisitor; import com.fr.third.alibaba.druid.sql.dialect.phoenix.visitor.PhoenixOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.postgresql.visitor.PGOutputVisitor; import com.fr.third.alibaba.druid.sql.dialect.postgresql.visitor.PGOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.presto.visitor.PrestoOutputVisitor;
import com.fr.third.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerOutputVisitor; import com.fr.third.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerOutputVisitor;
import com.fr.third.alibaba.druid.sql.parser.SQLParserFeature; import com.fr.third.alibaba.druid.sql.parser.SQLParserFeature;
import com.fr.third.alibaba.druid.sql.parser.SQLParserUtils; import com.fr.third.alibaba.druid.sql.parser.SQLParserUtils;
@ -78,7 +79,7 @@ public class ParameterizedOutputVisitorUtils {
return parameterize(sql, dbType, null, null); return parameterize(sql, dbType, null, null);
} }
public static String parameterize(String sql, DbType dbType, VisitorFeature ...features) { public static String parameterize(String sql, DbType dbType, VisitorFeature...features) {
return parameterize(sql, dbType, null, features); return parameterize(sql, dbType, null, features);
} }
@ -151,7 +152,7 @@ public class ParameterizedOutputVisitorUtils {
} }
List<SQLStatement> statementList = parser.parseStatementList(); List<SQLStatement> statementList = parser.parseStatementList();
if (statementList.size() == 0) { if (statementList.isEmpty()) {
return sql; return sql;
} }
@ -408,6 +409,8 @@ public class ParameterizedOutputVisitorUtils {
return new DB2OutputVisitor(out, true); return new DB2OutputVisitor(out, true);
case phoenix: case phoenix:
return new PhoenixOutputVisitor(out, true); return new PhoenixOutputVisitor(out, true);
case presto:
return new PrestoOutputVisitor(out, true);
default: default:
return new SQLASTOutputVisitor(out, true); return new SQLASTOutputVisitor(out, true);
} }

24
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SQLASTOutputVisitor.java

@ -684,7 +684,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
boolean isRoot = parent instanceof SQLSelectQueryBlock || parent instanceof SQLBinaryOpExprGroup; boolean isRoot = parent instanceof SQLSelectQueryBlock || parent instanceof SQLBinaryOpExprGroup;
List<SQLExpr> items = x.getItems(); List<SQLExpr> items = x.getItems();
if (items.size() == 0) { if (items.isEmpty()) {
print("true"); print("true");
return false; return false;
} }
@ -2060,7 +2060,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
boolean withGroup = x.isWithinGroup(); boolean withGroup = x.isWithinGroup();
if (withGroup) { if (withGroup) {
print0(ucase ? ") WITHIN GROUP (" : " within group ("); print0(ucase ? ") WITHIN GROUP (" : ") within group (");
} }
visitAggreateRest(x); visitAggreateRest(x);
@ -2718,7 +2718,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
List<SQLSelectOrderByItem> items = x.getItems(); List<SQLSelectOrderByItem> items = x.getItems();
if (items.size() > 0) { if (items.size() > 0) {
if (x.isSibings()) { if (x.isSiblings()) {
print0(ucase ? "ORDER SIBLINGS BY " : "order siblings by "); print0(ucase ? "ORDER SIBLINGS BY " : "order siblings by ");
} else { } else {
print0(ucase ? "ORDER BY " : "order by "); print0(ucase ? "ORDER BY " : "order by ");
@ -4801,7 +4801,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
} }
final List<List<SQLAssignItem>> storedBy = x.getStoredBy(); final List<List<SQLAssignItem>> storedBy = x.getStoredBy();
if (storedBy.size() != 0) { if (!storedBy.isEmpty()) {
println(); println();
print0(ucase ? "STORED BY " : "stored by "); print0(ucase ? "STORED BY " : "stored by ");
@ -6719,7 +6719,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override @Override
public boolean visit(SQLAlterTableEnableLifecycle x) { public boolean visit(SQLAlterTableEnableLifecycle x) {
if (x.getPartition().size() != 0) { if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition ("); print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", "); printAndAccept(x.getPartition(), ", ");
print0(") "); print0(") ");
@ -6731,7 +6731,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override @Override
public boolean visit(SQLAlterTableDisableLifecycle x) { public boolean visit(SQLAlterTableDisableLifecycle x) {
if (x.getPartition().size() != 0) { if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition ("); print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", "); printAndAccept(x.getPartition(), ", ");
print0(") "); print0(") ");
@ -6743,7 +6743,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override @Override
public boolean visit(SQLAlterTablePartition x) { public boolean visit(SQLAlterTablePartition x) {
if (x.getPartition().size() != 0) { if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition ("); print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", "); printAndAccept(x.getPartition(), ", ");
print0(") "); print0(") ");
@ -6753,13 +6753,13 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override @Override
public boolean visit(SQLAlterTablePartitionSetProperties x) { public boolean visit(SQLAlterTablePartitionSetProperties x) {
if (x.getPartition().size() != 0) { if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition ("); print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", "); printAndAccept(x.getPartition(), ", ");
print0(") "); print0(") ");
} }
if (x.getPartitionProperties().size() != 0) { if (!x.getPartitionProperties().isEmpty()) {
print0(ucase ? "SET PARTITIONPROPERTIES (" : "set partitionproperties ("); print0(ucase ? "SET PARTITIONPROPERTIES (" : "set partitionproperties (");
printAndAccept(x.getPartitionProperties(), ", "); printAndAccept(x.getPartitionProperties(), ", ");
print0(") "); print0(") ");
@ -6770,7 +6770,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override @Override
public boolean visit(SQLAlterTableTouch x) { public boolean visit(SQLAlterTableTouch x) {
print0(ucase ? "TOUCH" : "touch"); print0(ucase ? "TOUCH" : "touch");
if (x.getPartition().size() != 0) { if (!x.getPartition().isEmpty()) {
print0(ucase ? " PARTITION (" : " partition ("); print0(ucase ? " PARTITION (" : " partition (");
printAndAccept(x.getPartition(), ", "); printAndAccept(x.getPartition(), ", ");
print(')'); print(')');
@ -7290,7 +7290,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override @Override
public boolean visit(SQLPartitionByRange x) { public boolean visit(SQLPartitionByRange x) {
SQLExpr interval = x.getInterval(); SQLExpr interval = x.getInterval();
if (x.getColumns().size() == 0 if (x.getColumns().isEmpty()
&& (interval instanceof SQLBetweenExpr || interval instanceof SQLMethodInvokeExpr)) && (interval instanceof SQLBetweenExpr || interval instanceof SQLMethodInvokeExpr))
{ {
interval.accept(this); interval.accept(this);
@ -8911,7 +8911,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override @Override
public boolean visit(SQLBlockStatement x) { public boolean visit(SQLBlockStatement x) {
if (x.getParameters().size() != 0) { if (!x.getParameters().isEmpty()) {
this.indentCount++; this.indentCount++;
if (x.getParent() instanceof SQLCreateProcedureStatement) { if (x.getParent() instanceof SQLCreateProcedureStatement) {
SQLCreateProcedureStatement procedureStatement = (SQLCreateProcedureStatement) x.getParent(); SQLCreateProcedureStatement procedureStatement = (SQLCreateProcedureStatement) x.getParent();

4
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SQLDataTypeValidator.java

@ -127,7 +127,7 @@ public class SQLDataTypeValidator extends SQLASTVisitorAdapter {
} }
public static void check(List<SQLStatement> stmtList) { public static void check(List<SQLStatement> stmtList) {
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
return; return;
} }
@ -138,7 +138,7 @@ public class SQLDataTypeValidator extends SQLASTVisitorAdapter {
} }
public static void check(List<SQLStatement> stmtList, DbType dbType) { public static void check(List<SQLStatement> stmtList, DbType dbType) {
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
return; return;
} }

6
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SQLEvalVisitorUtils.java

@ -118,6 +118,7 @@ public class SQLEvalVisitorUtils {
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb: case mariadb:
case tidb:
case h2: case h2:
return new MySqlEvalVisitorImpl(); return new MySqlEvalVisitorImpl();
case oracle: case oracle:
@ -349,11 +350,10 @@ public class SQLEvalVisitorUtils {
} }
double doubleValue = castToDouble(paramValue); double doubleValue = castToDouble(paramValue);
int result = (int) Math.ceil(doubleValue); if (Double.isNaN(doubleValue)) {
if (Double.isNaN(result)) {
x.putAttribute(EVAL_VALUE, null); x.putAttribute(EVAL_VALUE, null);
} else { } else {
int result = (int) Math.ceil(doubleValue);
x.putAttribute(EVAL_VALUE, result); x.putAttribute(EVAL_VALUE, result);
} }
} else if ("cos".equals(methodName)) { } else if ("cos".equals(methodName)) {

9
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/SchemaStatVisitor.java

@ -602,6 +602,8 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter {
final SQLASTVisitor orderByVisitor; final SQLASTVisitor orderByVisitor;
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case mariadb:
case tidb:
return new MySqlOrderByStatVisitor(x); return new MySqlOrderByStatVisitor(x);
case postgresql: case postgresql:
return new PGOrderByStatVisitor(x); return new PGOrderByStatVisitor(x);
@ -3188,10 +3190,9 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter {
SQLExprTableSource table = x.getTable(); SQLExprTableSource table = x.getTable();
if (table != null) { if (table != null) {
table.accept(this); table.accept(this);
} for (SQLName column : x.getColumns()) {
addColumn(table.getName(), column.getSimpleName());
for (SQLName column : x.getColumns()) { }
addColumn(table.getName(), column.getSimpleName());
} }
return false; return false;

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/Ascii.java

@ -27,7 +27,7 @@ public class Ascii implements Function {
public final static Ascii instance = new Ascii(); public final static Ascii instance = new Ascii();
public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
if (x.getArguments().size() == 0) { if (x.getArguments().isEmpty()) {
return SQLEvalVisitor.EVAL_ERROR; return SQLEvalVisitor.EVAL_ERROR;
} }
SQLExpr param = x.getArguments().get(0); SQLExpr param = x.getArguments().get(0);

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/Char.java

@ -28,7 +28,7 @@ public class Char implements Function {
public final static Char instance = new Char(); public final static Char instance = new Char();
public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
if (x.getArguments().size() == 0) { if (x.getArguments().isEmpty()) {
return SQLEvalVisitor.EVAL_ERROR; return SQLEvalVisitor.EVAL_ERROR;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/If.java

@ -32,7 +32,7 @@ public class If implements Function {
public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
final List<SQLExpr> arguments = x.getArguments(); final List<SQLExpr> arguments = x.getArguments();
if (arguments.size() == 0) { if (arguments.isEmpty()) {
return EVAL_ERROR; return EVAL_ERROR;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/Isnull.java

@ -32,7 +32,7 @@ public class Isnull implements Function {
public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
final List<SQLExpr> arguments = x.getArguments(); final List<SQLExpr> arguments = x.getArguments();
if (arguments.size() == 0) { if (arguments.isEmpty()) {
return EVAL_ERROR; return EVAL_ERROR;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/OneParamFunctions.java

@ -32,7 +32,7 @@ public class OneParamFunctions implements Function {
public final static OneParamFunctions instance = new OneParamFunctions(); public final static OneParamFunctions instance = new OneParamFunctions();
public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
if (x.getArguments().size() == 0) { if (x.getArguments().isEmpty()) {
return SQLEvalVisitor.EVAL_ERROR; return SQLEvalVisitor.EVAL_ERROR;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/sql/visitor/functions/ToDate.java

@ -36,7 +36,7 @@ public class ToDate implements Function {
public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
final List<SQLExpr> arguments = x.getArguments(); final List<SQLExpr> arguments = x.getArguments();
if (arguments.size() == 0) { if (arguments.isEmpty()) {
return EVAL_ERROR; return EVAL_ERROR;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/calcite/CalciteMySqlNodeVisitor.java

@ -405,7 +405,7 @@ public class CalciteMySqlNodeVisitor extends MySqlASTVisitorAdapter {
List<SQLName> columns = x.getColumns(); List<SQLName> columns = x.getColumns();
SqlNode[] operands; SqlNode[] operands;
if (columns.size() == 0) { if (columns.isEmpty()) {
operands = new SqlNode[] { sqlNode, aliasIdentifier }; operands = new SqlNode[] { sqlNode, aliasIdentifier };
} else { } else {
operands = new SqlNode[columns.size() + 2]; operands = new SqlNode[columns.size() + 2];

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/console/DruidStat.java

@ -83,7 +83,7 @@ public class DruidStat {
if (option.printActiveConn()) { if (option.printActiveConn()) {
List<List<String>> content = (List<List<String>>) invokeService(jmxConn, Option.ACTIVE_CONN); List<List<String>> content = (List<List<String>>) invokeService(jmxConn, Option.ACTIVE_CONN);
if (content == null || content.size() == 0 ) { if (content == null || content.isEmpty() ) {
out.println("目前无活动中的数据库连接"); out.println("目前无活动中的数据库连接");
} else { } else {
TabledDataPrinter.printActiveConnStack(content, option); TabledDataPrinter.printActiveConnStack(content, option);

18
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/hibernate/DruidConnectionProvider.java

@ -18,20 +18,22 @@ package com.fr.third.alibaba.druid.support.hibernate;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import com.fr.third.alibaba.druid.pool.DruidDataSource; import com.fr.third.alibaba.druid.pool.DruidDataSource;
import com.fr.third.alibaba.druid.pool.DruidDataSourceFactory; import com.fr.third.alibaba.druid.pool.DruidDataSourceFactory;
import com.fr.third.org.hibernate.HibernateException;
import com.fr.third.org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import com.fr.third.org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import com.fr.third.org.hibernate.service.spi.Configurable; import com.fr.third.org.hibernate.exception.spi.Configurable;
import com.fr.third.org.hibernate.service.spi.Stoppable; import com.fr.third.org.hibernate.service.spi.Stoppable;
public class DruidConnectionProvider implements ConnectionProvider, Configurable, Stoppable { public class DruidConnectionProvider implements ConnectionProvider, Configurable, Stoppable {
private static final long serialVersionUID = 1026193803901107651L; private static final long serialVersionUID = 1026193803901107651L;
private DruidDataSource dataSource; private DruidDataSource dataSource;
public DruidConnectionProvider() { public DruidConnectionProvider(){
dataSource = new DruidDataSource(); dataSource = new DruidDataSource();
} }
@ -62,7 +64,7 @@ public class DruidConnectionProvider implements ConnectionProvider, Configurable
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Override //@Override
public void configure(Map configurationValues) { public void configure(Map configurationValues) {
try { try {
DruidDataSourceFactory.config(dataSource, configurationValues); DruidDataSourceFactory.config(dataSource, configurationValues);
@ -76,4 +78,12 @@ public class DruidConnectionProvider implements ConnectionProvider, Configurable
dataSource.close(); dataSource.close();
} }
@Override
public void configure(Properties properties) throws HibernateException {
try {
DruidDataSourceFactory.config(dataSource, properties);
} catch (SQLException e) {
throw new IllegalArgumentException("config error", e);
}
}
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/http/ResourceServlet.java

@ -255,7 +255,7 @@ public abstract class ResourceServlet extends HttpServlet {
boolean ipV6 = remoteAddress != null && remoteAddress.indexOf(':') != -1; boolean ipV6 = remoteAddress != null && remoteAddress.indexOf(':') != -1;
if (ipV6) { if (ipV6) {
return "0:0:0:0:0:0:0:1".equals(remoteAddress) || (denyList.size() == 0 && allowList.size() == 0); return "0:0:0:0:0:0:0:1".equals(remoteAddress) || (denyList.isEmpty() && allowList.isEmpty());
} }
IPAddress ipAddress = new IPAddress(remoteAddress); IPAddress ipAddress = new IPAddress(remoteAddress);

35
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/logging/LogFactory.java

@ -1,5 +1,5 @@
/* /*
* Copyright 1999-2017 Alibaba Group Holding Ltd. * Copyright 1999-2018 Alibaba Group Holding Ltd.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -26,27 +26,26 @@ public class LogFactory {
String logType= System.getProperty("druid.logType"); String logType= System.getProperty("druid.logType");
if(logType != null){ if(logType != null){
if(logType.equalsIgnoreCase("slf4j")){ if(logType.equalsIgnoreCase("slf4j")){
tryImplementation("com.fr.third.slf4j.Logger", "SLF4JImpl"); tryImplementation("com.fr.third.slf4j.Logger", "com.fr.third.alibaba.druid.support.logging.SLF4JImpl");
}else if(logType.equalsIgnoreCase("log4j")){ }else if(logType.equalsIgnoreCase("log4j")){
tryImplementation("org.apache.log4j.Logger", "Log4jImpl"); tryImplementation("org.apache.log4j.Logger", "com.fr.third.alibaba.druid.support.logging.Log4jImpl");
}else if(logType.equalsIgnoreCase("log4j2")){ }else if(logType.equalsIgnoreCase("log4j2")){
tryImplementation("org.apache.logging.log4j.Logger", "Log4j2Impl"); tryImplementation("org.apache.logging.log4j.Logger", "com.fr.third.alibaba.druid.support.logging.Log4j2Impl");
}else if(logType.equalsIgnoreCase("commonsLog")){ }else if(logType.equalsIgnoreCase("commonsLog")){
tryImplementation("org.apache.commons.logging.LogFactory", tryImplementation("org.apache.commons.logging.LogFactory",
"JakartaCommonsLoggingImpl"); "com.fr.third.alibaba.druid.support.logging.JakartaCommonsLoggingImpl");
}else if(logType.equalsIgnoreCase("jdkLog")){ }else if(logType.equalsIgnoreCase("jdkLog")){
tryImplementation("java.util.logging.Logger", "Jdk14LoggingImpl"); tryImplementation("java.util.logging.Logger", "com.fr.third.alibaba.druid.support.logging.Jdk14LoggingImpl");
} }
} }
tryImplementation("com.fr.third.slf4j.Logger", "SLF4JImpl");
// 优先选择log4j2防止漏洞
tryImplementation("com.fr.third.apache.logging.log4j.Logger", "FRLog4j2Impl");
// 优先选择log4j,而非Apache Common Logging. 因为后者无法设置真实Log调用者的信息 // 优先选择log4j,而非Apache Common Logging. 因为后者无法设置真实Log调用者的信息
tryImplementation("com.fr.third.apache.log4j.Logger", "FRLog4jImpl"); tryImplementation("com.fr.third.slf4j.Logger", "com.fr.third.alibaba.druid.support.logging.SLF4JImpl");
tryImplementation("org.apache.log4j.Logger", "Log4jImpl"); tryImplementation("org.apache.log4j.Logger", "com.fr.third.alibaba.druid.support.logging.Log4jImpl");
tryImplementation("org.apache.logging.log4j.Logger", "Log4j2Impl"); tryImplementation("com.fr.third.apache.logging.log4j.Logger", "com.fr.third.alibaba.druid.support.logging.Log4j2Impl");
tryImplementation("org.apache.commons.logging.LogFactory", "JakartaCommonsLoggingImpl"); tryImplementation("org.apache.commons.logging.LogFactory",
tryImplementation("java.util.logging.Logger", "Jdk14LoggingImpl"); "com.fr.third.alibaba.druid.support.logging.JakartaCommonsLoggingImpl");
tryImplementation("java.util.logging.Logger", "com.fr.third.alibaba.druid.support.logging.Jdk14LoggingImpl");
if (logConstructor == null) { if (logConstructor == null) {
try { try {
@ -65,13 +64,7 @@ public class LogFactory {
try { try {
Resources.classForName(testClassName); Resources.classForName(testClassName);
Class implClass = null; Class implClass = Resources.classForName(implClassName);
try {
implClass = Resources.classForName(implClassName);
} catch (Throwable t) {
implClassName = "com.fr.third.alibaba.druid.support.logging." + implClassName;
implClass = Resources.classForName(implClassName);
}
logConstructor = implClass.getConstructor(new Class[] { String.class }); logConstructor = implClass.getConstructor(new Class[] { String.class });
Class<?> declareClass = logConstructor.getDeclaringClass(); Class<?> declareClass = logConstructor.getDeclaringClass();

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/monitor/dao/MonitorDaoJdbcImpl.java

@ -498,7 +498,7 @@ public class MonitorDaoJdbcImpl implements MonitorDao {
} }
private void save(BeanInfo beanInfo, MonitorContext ctx, List<?> list) { private void save(BeanInfo beanInfo, MonitorContext ctx, List<?> list) {
if (list.size() == 0) { if (list.isEmpty()) {
return; return;
} }

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/opds/udf/ExportConditions.java

@ -60,7 +60,7 @@ public class ExportConditions extends UDF {
row.add(column.getTable()); row.add(column.getTable());
row.add(column.getName()); row.add(column.getName());
row.add(operator); row.add(operator);
if (values.size() == 0) { if (values.isEmpty()) {
row.add(null); row.add(null);
} else if (values.size() == 1) { } else if (values.size() == 1) {
if (compactValues != null && compactValues.booleanValue()) { if (compactValues != null && compactValues.booleanValue()) {

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/support/opds/udf/SqlTypeUDF.java

@ -155,7 +155,7 @@ public class SqlTypeUDF extends UDF {
try { try {
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType); List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) { if (stmtList.isEmpty()) {
return SQLType.EMPTY.name(); return SQLType.EMPTY.name();
} }

30
fine-druid/src/main/java/com/fr/third/alibaba/druid/util/ClassLoaderFactory.java

@ -1,30 +0,0 @@
package com.fr.third.alibaba.druid.util;
import java.util.ArrayList;
import java.util.List;
public class ClassLoaderFactory {
private static List<ClassLoaderHelper> helpers = new ArrayList<ClassLoaderHelper>();
public static void registerCLassLoaderHelper(ClassLoaderHelper helper) {
if(helper != null){
helpers.add(helper);
}
}
public static Class<?> loadClass(String className) throws ClassNotFoundException {
for(ClassLoaderHelper helper : helpers) {
try {
Class<?> clazz = helper.loadClass(className);
if(clazz != null){
return clazz;
}
} catch (ClassNotFoundException e) {
// skip
}
}
throw new ClassNotFoundException(className);
}
}

7
fine-druid/src/main/java/com/fr/third/alibaba/druid/util/ClassLoaderHelper.java

@ -1,7 +0,0 @@
package com.fr.third.alibaba.druid.util;
public interface ClassLoaderHelper {
Class<?> loadClass(String className) throws ClassNotFoundException;
}

13
fine-druid/src/main/java/com/fr/third/alibaba/druid/util/JdbcConstants.java

@ -56,6 +56,9 @@ public interface JdbcConstants {
String MARIADB = "mariadb"; String MARIADB = "mariadb";
String MARIADB_DRIVER = "org.mariadb.jdbc.Driver"; String MARIADB_DRIVER = "org.mariadb.jdbc.Driver";
DbType TIDB = DbType.tidb;
String TIDB_DRIVER = "io.tidb.bigdata.jdbc.TiDBDriver";
DbType DERBY = DbType.derby; DbType DERBY = DbType.derby;
String HBASE = "hbase"; String HBASE = "hbase";
@ -82,6 +85,7 @@ public interface JdbcConstants {
DbType OCEANBASE = DbType.oceanbase; DbType OCEANBASE = DbType.oceanbase;
DbType OCEANBASE_ORACLE = DbType.oceanbase_oracle; DbType OCEANBASE_ORACLE = DbType.oceanbase_oracle;
String OCEANBASE_DRIVER = "com.alipay.oceanbase.jdbc.Driver"; String OCEANBASE_DRIVER = "com.alipay.oceanbase.jdbc.Driver";
String OCEANBASE_DRIVER2 = "com.oceanbase.jdbc.Driver";
DbType INFORMIX = DbType.informix; DbType INFORMIX = DbType.informix;
@ -141,4 +145,13 @@ public interface JdbcConstants {
*/ */
DbType GREENPLUM = DbType.greenplum; DbType GREENPLUM = DbType.greenplum;
String GREENPLUM_DRIVER = "com.pivotal.jdbc.GreenplumDriver"; String GREENPLUM_DRIVER = "com.pivotal.jdbc.GreenplumDriver";
/**
* oscar
*/
DbType OSCAR = DbType.oscar;
String OSCAR_DRIVER = "com.oscar.Driver";
DbType TYDB = DbType.tydb;
String TYDB_DRIVER = "com.dbcp.jdbc.Driver";
} }

36
fine-druid/src/main/java/com/fr/third/alibaba/druid/util/JdbcUtils.java

@ -418,6 +418,8 @@ public final class JdbcUtils implements JdbcConstants {
return LOG4JDBC_DRIVER; return LOG4JDBC_DRIVER;
} else if (rawUrl.startsWith("jdbc:mariadb:")) { } else if (rawUrl.startsWith("jdbc:mariadb:")) {
return MARIADB_DRIVER; return MARIADB_DRIVER;
} else if (rawUrl.startsWith("jdbc:tidb:")) {
return TIDB_DRIVER;
} else if (rawUrl.startsWith("jdbc:oracle:") // } else if (rawUrl.startsWith("jdbc:oracle:") //
|| rawUrl.startsWith("JDBC:oracle:")) { || rawUrl.startsWith("JDBC:oracle:")) {
return ORACLE_DRIVER; return ORACLE_DRIVER;
@ -442,20 +444,8 @@ public final class JdbcUtils implements JdbcConstants {
} else if (rawUrl.startsWith("jdbc:odps:")) { } else if (rawUrl.startsWith("jdbc:odps:")) {
return ODPS_DRIVER; return ODPS_DRIVER;
} else if (rawUrl.startsWith("jdbc:hsqldb:")) { } else if (rawUrl.startsWith("jdbc:hsqldb:")) {
try { return "org.hsqldb.jdbcDriver";
Class.forName("com.fr.third.org.hsqldb.jdbcDriver"); } else if (rawUrl.startsWith("jdbc:db2:")) {
return "com.fr.third.org.hsqldb.jdbcDriver";
} catch (Throwable ignore) {
return "org.hsqldb.jdbcDriver";
}
} else if (rawUrl.startsWith("emb:jdbc:hsqldb:")) {
try {
Class.forName("com.fr.third.org.hsqldb.jdbcDriver");
return "com.fr.third.org.hsqldb.jdbcDriver";
} catch (Throwable ignore) {
return "org.hsqldb.jdbcDriver";
}
} else if (rawUrl.startsWith("jdbc:db2:")) {
// Resolve the DB2 driver from JDBC URL // Resolve the DB2 driver from JDBC URL
// Type2 COM.ibm.db2.jdbc.app.DB2Driver, url = jdbc:db2:databasename // Type2 COM.ibm.db2.jdbc.app.DB2Driver, url = jdbc:db2:databasename
// Type3 COM.ibm.db2.jdbc.net.DB2Driver, url = jdbc:db2:ServerIP:6789:databasename // Type3 COM.ibm.db2.jdbc.net.DB2Driver, url = jdbc:db2:ServerIP:6789:databasename
@ -537,6 +527,10 @@ public final class JdbcUtils implements JdbcConstants {
return JdbcConstants.POLARDB_DRIVER; return JdbcConstants.POLARDB_DRIVER;
} else if (rawUrl.startsWith("jdbc:highgo:")) { } else if (rawUrl.startsWith("jdbc:highgo:")) {
return "com.highgo.jdbc.Driver"; return "com.highgo.jdbc.Driver";
} else if (rawUrl.startsWith("jdbc:oscar")) {
return JdbcConstants.OSCAR_DRIVER;
} else if (rawUrl.startsWith("jdbc:dbcp:")) {
return JdbcConstants.TYDB_DRIVER;
} else { } else {
throw new SQLException("unknown jdbc driver : " + rawUrl); throw new SQLException("unknown jdbc driver : " + rawUrl);
} }
@ -554,6 +548,8 @@ public final class JdbcUtils implements JdbcConstants {
return DbType.mysql; return DbType.mysql;
} else if (rawUrl.startsWith("jdbc:mariadb:")) { } else if (rawUrl.startsWith("jdbc:mariadb:")) {
return DbType.mariadb; return DbType.mariadb;
} else if (rawUrl.startsWith("jdbc:tidb:")) {
return DbType.tidb;
} else if (rawUrl.startsWith("jdbc:oracle:") || rawUrl.startsWith("jdbc:log4jdbc:oracle:")) { } else if (rawUrl.startsWith("jdbc:oracle:") || rawUrl.startsWith("jdbc:log4jdbc:oracle:")) {
return DbType.oracle; return DbType.oracle;
} else if (rawUrl.startsWith("jdbc:alibaba:oracle:")) { } else if (rawUrl.startsWith("jdbc:alibaba:oracle:")) {
@ -576,7 +572,7 @@ public final class JdbcUtils implements JdbcConstants {
return DbType.postgresql; return DbType.postgresql;
} else if (rawUrl.startsWith("jdbc:edb:")) { } else if (rawUrl.startsWith("jdbc:edb:")) {
return DbType.edb; return DbType.edb;
} else if (rawUrl.startsWith("jdbc:hsqldb:") || rawUrl.startsWith("jdbc:log4jdbc:hsqldb:") || rawUrl.startsWith("emb:jdbc:hsqldb:") ) { } else if (rawUrl.startsWith("jdbc:hsqldb:") || rawUrl.startsWith("jdbc:log4jdbc:hsqldb:")) {
return DbType.hsql; return DbType.hsql;
} else if (rawUrl.startsWith("jdbc:odps:")) { } else if (rawUrl.startsWith("jdbc:odps:")) {
return DbType.odps; return DbType.odps;
@ -896,7 +892,7 @@ public final class JdbcUtils implements JdbcConstants {
} }
public static List<String> showTables(Connection conn, DbType dbType) throws SQLException { public static List<String> showTables(Connection conn, DbType dbType) throws SQLException {
if (DbType.mysql == dbType || DbType.oceanbase == dbType) { if (isMysqlDbType(dbType)) {
return MySqlUtils.showTables(conn); return MySqlUtils.showTables(conn);
} }
@ -915,7 +911,7 @@ public final class JdbcUtils implements JdbcConstants {
} }
public static String getCreateTableScript(Connection conn, DbType dbType, boolean sorted, boolean simplify) throws SQLException { public static String getCreateTableScript(Connection conn, DbType dbType, boolean sorted, boolean simplify) throws SQLException {
if (DbType.mysql == dbType || DbType.oceanbase == dbType) { if (isMysqlDbType(dbType)) {
return MySqlUtils.getCreateTableScript(conn, sorted, simplify); return MySqlUtils.getCreateTableScript(conn, sorted, simplify);
} }
@ -934,13 +930,13 @@ public final class JdbcUtils implements JdbcConstants {
public static boolean isOracleDbType(String dbType) { public static boolean isOracleDbType(String dbType) {
return DbType.oracle.name().equals(dbType) || // return DbType.oracle.name().equals(dbType) || //
DbType.oceanbase.name().equals(dbType) || // DbType.oceanbase_oracle.name().equals(dbType) || //
DbType.ali_oracle.name().equalsIgnoreCase(dbType); DbType.ali_oracle.name().equalsIgnoreCase(dbType);
} }
public static boolean isOracleDbType(DbType dbType) { public static boolean isOracleDbType(DbType dbType) {
return DbType.oracle == dbType || // return DbType.oracle == dbType || //
DbType.oceanbase == dbType || // DbType.oceanbase_oracle == dbType || //
DbType.ali_oracle == dbType; DbType.ali_oracle == dbType;
} }
@ -957,8 +953,10 @@ public final class JdbcUtils implements JdbcConstants {
switch (dbType) { switch (dbType) {
case mysql: case mysql:
case oceanbase: case oceanbase:
case ads:
case drds: case drds:
case mariadb: case mariadb:
case tidb:
case h2: case h2:
return true; return true;
default: default:

146
fine-druid/src/main/java/com/fr/third/alibaba/druid/util/MySqlUtils.java

@ -26,46 +26,61 @@ import java.lang.reflect.Method;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.sql.*; import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.*; import java.time.LocalDate;
import java.util.*; import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;
public class MySqlUtils { public class MySqlUtils {
static Class<?> utilClass; static Class<?> utilClass;
static boolean utilClassError = false; static boolean utilClassError = false;
static boolean utilClass_isJdbc4 = false; static boolean utilClass_isJdbc4 = false;
static Class<?> class_5_connection= null; static Class<?> class_5_connection = null;
static Method method_5_getPinGlobalTxToPhysicalConnection = null; static Method method_5_getPinGlobalTxToPhysicalConnection = null;
static Class<?> class_5_suspendableXAConnection = null; static Class<?> class_5_suspendableXAConnection = null;
static Constructor<?> constructor_5_suspendableXAConnection = null; static Constructor<?> constructor_5_suspendableXAConnection = null;
static Class<?> class_5_JDBC4SuspendableXAConnection = null; static Class<?> class_5_JDBC4SuspendableXAConnection = null;
static Constructor<?> constructor_5_JDBC4SuspendableXAConnection = null; static Constructor<?> constructor_5_JDBC4SuspendableXAConnection = null;
static Class<?> class_5_MysqlXAConnection = null; static Class<?> class_5_MysqlXAConnection = null;
static Constructor<?> constructor_5_MysqlXAConnection = null; static Constructor<?> constructor_5_MysqlXAConnection = null;
static Class<?> class_ConnectionImpl = null; static Class<?> class_ConnectionImpl = null;
static Method method_getId = null; static Method method_getId = null;
static boolean method_getId_error = false; static boolean method_getId_error = false;
static Class<?> class_6_ConnectionImpl = null; static Class<?> class_6_ConnectionImpl = null;
static Method method_6_getId = null; static Method method_6_getId = null;
volatile static Class<?> class_6_connection= null; volatile static Class<?> class_6_connection = null;
volatile static Method method_6_getPropertySet = null; volatile static Method method_6_getPropertySet = null;
volatile static Method method_6_getBooleanReadableProperty = null; volatile static Method method_6_getBooleanReadableProperty = null;
volatile static Method method_6_getValue = null; volatile static Method method_6_getValue = null;
volatile static boolean method_6_getValue_error = false; volatile static boolean method_6_getValue_error = false;
volatile static Class<?> class_6_suspendableXAConnection = null; volatile static Class<?> class_6_suspendableXAConnection = null;
volatile static Method method_6_getInstance = null; volatile static Method method_6_getInstance = null;
volatile static boolean method_6_getInstance_error = false; volatile static boolean method_6_getInstance_error = false;
volatile static Method method_6_getInstanceXA = null; volatile static Method method_6_getInstanceXA = null;
volatile static boolean method_6_getInstanceXA_error = false; volatile static boolean method_6_getInstanceXA_error = false;
volatile static Class<?> class_6_JDBC4SuspendableXAConnection = null; volatile static Class<?> class_6_JDBC4SuspendableXAConnection = null;
public static XAConnection createXAConnection(Driver driver, Connection physicalConn) throws SQLException { public static XAConnection createXAConnection(Driver driver, Connection physicalConn) throws SQLException {
@ -140,8 +155,7 @@ public class MySqlUtils {
.getMethod("getValue"); .getMethod("getValue");
} }
} } else {
else {
method_6_getPropertySet = class_6_connection.getMethod("getPropertySet"); method_6_getPropertySet = class_6_connection.getMethod("getPropertySet");
method_6_getBooleanReadableProperty = Class.forName("com.mysql.cj.api.conf.PropertySet").getMethod("getBooleanReadableProperty", String.class); method_6_getBooleanReadableProperty = Class.forName("com.mysql.cj.api.conf.PropertySet").getMethod("getBooleanReadableProperty", String.class);
method_6_getValue = Class.forName("com.mysql.cj.api.conf.ReadableProperty").getMethod("getValue"); method_6_getValue = Class.forName("com.mysql.cj.api.conf.ReadableProperty").getMethod("getValue");
@ -206,7 +220,7 @@ public class MySqlUtils {
return null; return null;
} }
return "KILL QUERY " + threadId; return "KILL QUERY " + threadId;
} }
@ -317,7 +331,7 @@ public class MySqlUtils {
} }
String ddlScript = buf.toString(); String ddlScript = buf.toString();
if (! (sorted || simplify)) { if (!(sorted || simplify)) {
return ddlScript; return ddlScript;
} }
@ -357,14 +371,16 @@ public class MySqlUtils {
} }
Class<?> clazz = conn.getClass(); Class<?> clazz = conn.getClass();
if (clazz.getName().equals("com.mysql.jdbc.ConnectionImpl")) { if (class_ConnectionImpl == null) {
class_ConnectionImpl = clazz; if (clazz.getName().equals("com.mysql.jdbc.ConnectionImpl")) {
} else if (clazz.getName().equals("com.mysql.jdbc.Connection")) { // mysql 5.0.x class_ConnectionImpl = clazz;
class_ConnectionImpl = clazz; } else if (clazz.getName().equals("com.mysql.jdbc.Connection")) { // mysql 5.0.x
} else if (clazz.getName().equals("com.mysql.cj.jdbc.ConnectionImpl")) { // mysql 5.0.x class_ConnectionImpl = clazz;
class_ConnectionImpl = clazz; } else if (clazz.getName().equals("com.mysql.cj.jdbc.ConnectionImpl")) { // mysql 5.0.x
} else if (clazz.getSuperclass().getName().equals("com.mysql.jdbc.ConnectionImpl")) { class_ConnectionImpl = clazz;
class_ConnectionImpl = clazz.getSuperclass(); } else if (clazz.getSuperclass().getName().equals("com.mysql.jdbc.ConnectionImpl")) {
class_ConnectionImpl = clazz.getSuperclass();
}
} }
if (class_ConnectionImpl == clazz || class_ConnectionImpl == clazz.getSuperclass()) { if (class_ConnectionImpl == clazz || class_ConnectionImpl == clazz.getSuperclass()) {
@ -385,9 +401,8 @@ public class MySqlUtils {
} }
public static long getLastPacketReceivedTimeMs(Connection conn) throws SQLException { public static long getLastPacketReceivedTimeMs(Connection conn) throws SQLException {
if (!class_connectionImpl_Error) { if (class_connectionImpl == null && !class_connectionImpl_Error) {
try { try {
mysqlJdbcVersion6 = false;
class_connectionImpl = Utils.loadClass("com.mysql.jdbc.MySQLConnection"); class_connectionImpl = Utils.loadClass("com.mysql.jdbc.MySQLConnection");
if (class_connectionImpl == null || class_connectionImpl.getClassLoader() != conn.getClass().getClassLoader()) { if (class_connectionImpl == null || class_connectionImpl.getClassLoader() != conn.getClass().getClassLoader()) {
class_connectionImpl = Utils.loadClass("com.mysql.cj.MysqlConnection"); class_connectionImpl = Utils.loadClass("com.mysql.cj.MysqlConnection");
@ -405,13 +420,15 @@ public class MySqlUtils {
} }
if(mysqlJdbcVersion6){ if(mysqlJdbcVersion6){
classJdbc = Utils.loadClass("com.mysql.cj.jdbc.JdbcConnection"); if (classJdbc == null) {
classJdbc = Utils.loadClass("com.mysql.cj.jdbc.JdbcConnection");
}
if (classJdbc == null) { if (classJdbc == null) {
return -1; return -1;
} }
if (!getIdleForError) { if (getIdleFor == null && !getIdleForError) {
try { try {
getIdleFor = classJdbc.getMethod("getIdleFor"); getIdleFor = classJdbc.getMethod("getIdleFor");
getIdleFor.setAccessible(true); getIdleFor.setAccessible(true);
@ -432,13 +449,13 @@ public class MySqlUtils {
return System.currentTimeMillis() return System.currentTimeMillis()
- ((Long) - ((Long)
getIdleFor.invoke(connImpl)) getIdleFor.invoke(connImpl))
.longValue(); .longValue();
} catch (Exception e) { } catch (Exception e) {
throw new SQLException("getIdleFor error", e); throw new SQLException("getIdleFor error", e);
} }
} else { } else {
if (!method_getIO_error) { if (method_getIO == null && !method_getIO_error) {
try { try {
method_getIO = class_connectionImpl.getMethod("getIO"); method_getIO = class_connectionImpl.getMethod("getIO");
} catch (Throwable error) { } catch (Throwable error) {
@ -450,7 +467,7 @@ public class MySqlUtils {
return -1; return -1;
} }
if (!class_MysqlIO_Error) { if (class_MysqlIO == null && !class_MysqlIO_Error) {
try { try {
class_MysqlIO = Utils.loadClass("com.mysql.jdbc.MysqlIO"); class_MysqlIO = Utils.loadClass("com.mysql.jdbc.MysqlIO");
} catch (Throwable error) { } catch (Throwable error) {
@ -462,7 +479,7 @@ public class MySqlUtils {
return -1; return -1;
} }
if (!method_getLastPacketReceivedTimeMs_error) { if (method_getLastPacketReceivedTimeMs == null && !method_getLastPacketReceivedTimeMs_error) {
try { try {
Method method = class_MysqlIO.getDeclaredMethod("getLastPacketReceivedTimeMs"); Method method = class_MysqlIO.getDeclaredMethod("getLastPacketReceivedTimeMs");
method.setAccessible(true); method.setAccessible(true);
@ -515,12 +532,12 @@ public class MySqlUtils {
return null; return null;
} }
public final static Charset GBK = Charset.forName("GBK"); public final static Charset GBK = Charset.forName("GBK");
public final static Charset BIG5 = Charset.forName("BIG5"); public final static Charset BIG5 = Charset.forName("BIG5");
public final static Charset UTF8 = Charset.forName("UTF-8"); public final static Charset UTF8 = Charset.forName("UTF-8");
public final static Charset UTF16 = Charset.forName("UTF-16"); public final static Charset UTF16 = Charset.forName("UTF-16");
public final static Charset UTF32 = Charset.forName("UTF-32"); public final static Charset UTF32 = Charset.forName("UTF-32");
public final static Charset ASCII = Charset.forName("ASCII"); public final static Charset ASCII = Charset.forName("ASCII");
public static void loadDataTypes(Set<String> dataTypes) { public static void loadDataTypes(Set<String> dataTypes) {
@ -1125,8 +1142,7 @@ public class MySqlUtils {
// yyyy-MM-dd HH.mm.ss // yyyy-MM-dd HH.mm.ss
if (c4 == '-' && c7 == '-' if (c4 == '-' && c7 == '-'
&& (c10 == ' ' || c10 == 'T') && (c10 == ' ' || c10 == 'T')
&& ((c13 == ':' && c16 == ':') || (c13 == '.' && c16 == '.'))) && ((c13 == ':' && c16 == ':') || (c13 == '.' && c16 == '.'))) {
{
M0 = c5; M0 = c5;
M1 = c6; M1 = c6;
d0 = c8; d0 = c8;
@ -1186,7 +1202,7 @@ public class MySqlUtils {
return null; return null;
} }
nanos = (c23 - '0') * 100000 nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000 + (c24 - '0') * 10000
+ (c25 - '0') * 1000 + (c25 - '0') * 1000
+ (c26 - '0') * 100 + (c26 - '0') * 100
@ -1302,7 +1318,7 @@ public class MySqlUtils {
S2 = x0; S2 = x0;
lastOff = length - 5; lastOff = length - 5;
} else if ((x2 == '+' || x2 == '-') && length == offset + 5) { } else if ((x2 == '+' || x2 == '-') && length == offset + 5) {
String zoneIdStr = new String(new char[] {x2, x1, x0}); String zoneIdStr = new String(new char[]{x2, x1, x0});
zoneId = ZoneId.of(zoneIdStr); zoneId = ZoneId.of(zoneIdStr);
lastOff = length - 4; lastOff = length - 4;
} else { } else {
@ -1583,8 +1599,7 @@ public class MySqlUtils {
// yyyy-MM-dd HH:mm:ss // yyyy-MM-dd HH:mm:ss
if (c4 == '-' && c7 == '-' if (c4 == '-' && c7 == '-'
&& (c10 == ' ' || c10 == 'T') && (c10 == ' ' || c10 == 'T')
&& c13 == ':' && c16 == ':') && c13 == ':' && c16 == ':') {
{
M0 = c5; M0 = c5;
M1 = c6; M1 = c6;
d0 = c8; d0 = c8;
@ -1645,7 +1660,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8)); throw new IllegalArgumentException(new String(str, UTF8));
} }
nanos = (c23 - '0') * 100000 nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000 + (c24 - '0') * 10000
+ (c25 - '0') * 1000 + (c25 - '0') * 1000
+ (c26 - '0') * 100 + (c26 - '0') * 100
@ -1666,7 +1681,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8)); throw new IllegalArgumentException(new String(str, UTF8));
} }
nanos = (c23 - '0') * 100000 nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000 + (c24 - '0') * 10000
+ (c25 - '0') * 1000 + (c25 - '0') * 1000
+ (c26 - '0') * 100 + (c26 - '0') * 100
@ -1684,7 +1699,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8)); throw new IllegalArgumentException(new String(str, UTF8));
} }
nanos = (c23 - '0') * 100000 nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000 + (c24 - '0') * 10000
+ (c25 - '0') * 1000 + (c25 - '0') * 1000
+ (c26 - '0') * 100; + (c26 - '0') * 100;
@ -1699,7 +1714,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8)); throw new IllegalArgumentException(new String(str, UTF8));
} }
nanos = (c23 - '0') * 100000 nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000 + (c24 - '0') * 10000
+ (c25 - '0') * 1000; + (c25 - '0') * 1000;
} }
@ -1908,7 +1923,7 @@ public class MySqlUtils {
return zdt; return zdt;
} }
private final static String[] parseFormats = new String[] { private final static String[] parseFormats = new String[]{
"HH:mm:ss", "HH:mm:ss",
"yyyyMMdd", "yyyyMMdd",
"yyyyMMddHHmmss", "yyyyMMddHHmmss",
@ -1924,7 +1939,8 @@ public class MySqlUtils {
"yyyy-MM-dd'T'HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss.SSS",
}; };
private final static long[] parseFormatCodes; private final static long[] parseFormatCodes;
static {
static {
long[] codes = new long[parseFormats.length]; long[] codes = new long[parseFormats.length];
for (int i = 0; i < parseFormats.length; i++) { for (int i = 0; i < parseFormats.length; i++) {
codes[i] = FnvHash.fnv1a_64(parseFormats[i]); codes[i] = FnvHash.fnv1a_64(parseFormats[i]);

24
fine-druid/src/main/java/com/fr/third/alibaba/druid/util/Utils.java

@ -233,32 +233,28 @@ public class Utils {
} }
public static Class<?> loadClass(String className) { public static Class<?> loadClass(String className) {
Class<?> clazz = null;
if (className == null) { if (className == null) {
return null; return null;
} }
ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
if (ctxClassLoader != null) {
try {
return ctxClassLoader.loadClass(className);
} catch (ClassNotFoundException e) {
// skip
}
}
try { try {
return Class.forName(className); return Class.forName(className);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
// skip // skip
} }
try { ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
return ClassLoaderFactory.loadClass(className); if (ctxClassLoader != null) {
} catch (ClassNotFoundException e) { try {
// skip clazz = ctxClassLoader.loadClass(className);
} catch (ClassNotFoundException e) {
// skip
}
} }
return null; return clazz;
} }
private static Date startTime; private static Date startTime;

1
fine-druid/src/main/java/com/fr/third/alibaba/druid/wall/WallFilter.java

@ -134,6 +134,7 @@ public class WallFilter extends FilterAdapter implements WallFilterMBean {
case oceanbase: case oceanbase:
case drds: case drds:
case mariadb: case mariadb:
case tidb:
case h2: case h2:
case presto: case presto:
case trino: case trino:

2
fine-druid/src/main/java/com/fr/third/alibaba/druid/wall/spi/ClickhouseWallProvider.java

@ -35,7 +35,7 @@ public class ClickhouseWallProvider extends WallProvider {
} }
public ClickhouseWallProvider(WallConfig config){ public ClickhouseWallProvider(WallConfig config){
super(config, DbType.postgresql); super(config, DbType.clickhouse);
} }
@Override @Override

Loading…
Cancel
Save