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),
oscar (1 << 40),
tidb ( 1 << 41),
tydb ( 1 << 42),
ingres (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, FilterManager.class.getClassLoader());
loadFilterConfig(filterProperties, Thread.currentThread().getContextClassLoader());
loadFilterConfig(filterProperties, FilterManager.class.getClassLoader());
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);
}
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
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;
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.Serializable;
import java.sql.Connection;
@ -43,35 +71,6 @@ import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
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 ljw [ljw2083@alibaba-inc.com]
@ -171,6 +170,8 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
protected volatile ValidConnectionChecker validConnectionChecker = null;
protected volatile boolean usePingMethod = false;
protected final Map<DruidPooledConnection, Object> activeConnections = new IdentityHashMap<DruidPooledConnection, Object>();
protected final static Object PRESENT = new Object();
@ -641,6 +642,14 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
this.validConnectionChecker = validConnectionChecker;
}
public boolean isUsePingMethod() {
return usePingMethod;
}
public void setUsePingMethod(boolean usePingMethod) {
this.usePingMethod = usePingMethod;
}
public String getValidConnectionCheckerClassName() {
if (validConnectionChecker == null) {
return null;
@ -1483,8 +1492,8 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
long lastPacketReceivedTimeMs = MySqlUtils.getLastPacketReceivedTimeMs(conn);
if (lastPacketReceivedTimeMs > 0) {
long mysqlIdleMillis = currentTimeMillis - lastPacketReceivedTimeMs;
if (lastPacketReceivedTimeMs > 0
&& timeBetweenEvictionRunsMillis > 0
if (lastPacketReceivedTimeMs > 0 //
&& this.timeBetweenEvictionRunsMillis > 0L
&& mysqlIdleMillis >= timeBetweenEvictionRunsMillis) {
discardConnection(holder);
String errorMsg = "discard long time none received connection. "
@ -1548,7 +1557,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
return true;
} catch (Throwable ex) {
LOG.debug(ex.getMessage(), ex);
// skip
return false;
} finally {
if (sqlFile != null) {
@ -1653,7 +1662,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
public Connection createPhysicalConnection(String url, Properties info) throws SQLException {
Connection conn;
if (getProxyFilters().size() == 0) {
if (getProxyFilters().isEmpty()) {
conn = getDriver().connect(url, info);
} else {
conn = new FilterChainImpl(this).connection_connect(info);
@ -1837,7 +1846,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
}
Collection<String> initSqls = getConnectionInitSqls();
if (initSqls.size() == 0
if (initSqls.isEmpty()
&& variables == null
&& globalVariables == null) {
return;
@ -1856,7 +1865,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements
}
DbType dbType = DbType.of(this.dbTypeName);
if (dbType == DbType.mysql || dbType == DbType.ads) {
if (JdbcUtils.isMysqlDbType(dbType)) {
if (variables != null) {
ResultSet rs = null;
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;
public DruidConnectionHolder(DruidAbstractDataSource dataSource, PhysicalConnectionInfo pyConnectInfo)
throws SQLException{
throws SQLException{
this(dataSource,
pyConnectInfo.getPhysicalConnection(),
pyConnectInfo.getConnectNanoSpan(),
pyConnectInfo.getVairiables(),
pyConnectInfo.getGlobalVairiables());
pyConnectInfo.getPhysicalConnection(),
pyConnectInfo.getConnectNanoSpan(),
pyConnectInfo.getVairiables(),
pyConnectInfo.getGlobalVairiables());
}
public DruidConnectionHolder(DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan)
throws SQLException{
throws SQLException{
this(dataSource, conn, connectNanoSpan, null, null);
}
public DruidConnectionHolder(DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan,
Map<String, Object> variables, Map<String, Object> globleVariables)
throws SQLException{
throws SQLException{
this.dataSource = dataSource;
this.conn = conn;
this.createNanoSpan = connectNanoSpan;
@ -136,16 +136,11 @@ public final class DruidConnectionHolder {
holdabilityUnsupported = true;
}
LOG.warn("getHoldability error", e);
} catch (AbstractMethodError e){
LOG.warn("getHoldability error", e);
}
}
}
try {
this.underlyingReadOnly = conn.isReadOnly();
} catch (Throwable e){
}
this.underlyingReadOnly = conn.isReadOnly();
try {
this.underlyingTransactionIsolation = conn.getTransactionIsolation();
} 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 {
private final static Log LOG = LogFactory.getLog(DruidDataSource.class);
private static final long serialVersionUID = 1L;
private final static Log LOG = LogFactory.getLog(DruidDataSource.class);
private static final long serialVersionUID = 1L;
// stats
private volatile long recycleErrorCount = 0L;
private long connectCount = 0L;
private long closeCount = 0L;
private volatile long connectErrorCount = 0L;
private long recycleCount = 0L;
private long removeAbandonedCount = 0L;
private long notEmptyWaitCount = 0L;
private long notEmptySignalCount = 0L;
private long notEmptyWaitNanos = 0L;
private int keepAliveCheckCount = 0;
private int activePeak = 0;
private long activePeakTime = 0;
private int poolingPeak = 0;
private long poolingPeakTime = 0;
private volatile long recycleErrorCount = 0L;
private long connectCount = 0L;
private long closeCount = 0L;
private volatile long connectErrorCount = 0L;
private long recycleCount = 0L;
private long removeAbandonedCount = 0L;
private long notEmptyWaitCount = 0L;
private long notEmptySignalCount = 0L;
private long notEmptyWaitNanos = 0L;
private int keepAliveCheckCount = 0;
private int activePeak = 0;
private long activePeakTime = 0;
private int poolingPeak = 0;
private long poolingPeakTime = 0;
// store
private volatile DruidConnectionHolder[] connections;
private int poolingCount = 0;
private int activeCount = 0;
private volatile long discardCount = 0;
private int notEmptyWaitThreadCount = 0;
private int notEmptyWaitThreadPeak = 0;
private int poolingCount = 0;
private int activeCount = 0;
private volatile long discardCount = 0;
private int notEmptyWaitThreadCount = 0;
private int notEmptyWaitThreadPeak = 0;
//
private DruidConnectionHolder[] evictConnections;
private DruidConnectionHolder[] keepAliveConnections;
private DruidConnectionHolder[] evictConnections;
private DruidConnectionHolder[] keepAliveConnections;
// threads
private volatile ScheduledFuture<?> destroySchedulerFuture;
private DestroyTask destroyTask;
private volatile ScheduledFuture<?> destroySchedulerFuture;
private DestroyTask destroyTask;
private volatile Future<?> createSchedulerFuture;
private volatile Future<?> createSchedulerFuture;
private CreateConnectionThread createConnectionThread;
private PeriodDetectionThread periodDetectionThread;
private DestroyConnectionThread destroyConnectionThread;
private LogStatsThread logStatsThread;
private int createTaskCount;
private CreateConnectionThread createConnectionThread;
private DestroyConnectionThread destroyConnectionThread;
private LogStatsThread logStatsThread;
private int createTaskCount;
private volatile long createTaskIdSeed = 1L;
private long[] createTasks;
private volatile long createTaskIdSeed = 1L;
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 volatile long resetCount = 0L;
private boolean resetStatEnable = true;
private volatile long resetCount = 0L;
private String initStackTrace;
private String initStackTrace;
private volatile boolean closing = false;
private volatile boolean closed = false;
private long closeTimeMillis = -1L;
private volatile boolean closing = false;
private volatile boolean closed = false;
private long closeTimeMillis = -1L;
protected JdbcDataSourceStat dataSourceStat;
protected JdbcDataSourceStat dataSourceStat;
private boolean useGlobalDataSourceStat = false;
private boolean mbeanRegistered = false;
public static ThreadLocal<Long> waitNanosLocal = new ThreadLocal<Long>();
private boolean logDifferentThread = true;
private volatile boolean keepAlive = false;
private SQLException initException = null;
private boolean asyncInit = false;
protected boolean killWhenSocketReadTimeout = false;
protected boolean checkExecuteTime = false;
private boolean useGlobalDataSourceStat = false;
private boolean mbeanRegistered = false;
public static ThreadLocal<Long> waitNanosLocal = new ThreadLocal<Long>();
private boolean logDifferentThread = true;
private volatile boolean keepAlive = false;
private boolean asyncInit = false;
protected boolean killWhenSocketReadTimeout = false;
protected boolean checkExecuteTime = false;
private static List<Filter> autoFilters = null;
private boolean loadSpifilterSkip = false;
private volatile DataSourceDisableException disableException = null;
private static List<Filter> autoFilters = null;
private boolean loadSpifilterSkip = false;
private volatile DataSourceDisableException disableException = null;
protected static final AtomicLongFieldUpdater<DruidDataSource> recycleErrorCountUpdater
= AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "recycleErrorCount");
@ -180,11 +178,11 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
protected static final AtomicLongFieldUpdater<DruidDataSource> createTaskIdSeedUpdater
= AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "createTaskIdSeed");
public DruidDataSource() {
public DruidDataSource(){
this(false);
}
public DruidDataSource(boolean fairLock) {
public DruidDataSource(boolean fairLock){
super(fairLock);
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() {
return killWhenSocketReadTimeout;
}
@ -839,11 +798,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
public void init() throws SQLException {
if (initException != null) {
LOG.error("{dataSource-" + this.getID() + "} init error", initException);
throw initException;
}
if (inited) {
return;
}
@ -889,10 +843,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
DbType dbType = DbType.of(this.dbTypeName);
if (dbType == DbType.mysql
|| dbType == DbType.mariadb
|| dbType == DbType.oceanbase
|| dbType == DbType.ads) {
if (JdbcUtils.isMysqlDbType(dbType)) {
boolean cacheServerConfigurationSet = false;
if (this.connectProperties.containsKey("cacheServerConfiguration")) {
cacheServerConfigurationSet = true;
@ -993,7 +944,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
createAndLogThread();
createAndStartCreatorThread();
createAndStartDestroyThread();
createAndStartDetectThread();
initedLatch.await();
init = true;
@ -1018,13 +968,16 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
} catch (SQLException e) {
LOG.error("{dataSource-" + this.getID() + "} init error", e);
initException = e;
throw e;
} catch (InterruptedException e) {
throw new SQLException(e.getMessage(), e);
} catch (Throwable e) {
initException = new SQLException(e.getMessage());
} catch (RuntimeException e){
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} catch (Error e){
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} finally {
inited = true;
lock.unlock();
@ -1122,7 +1075,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
period = 1000;
}
destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destroyTask, period, period,
TimeUnit.MILLISECONDS);
TimeUnit.MILLISECONDS);
initedLatch.countDown();
return;
}
@ -1134,7 +1087,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
protected void createAndStartCreatorThread() {
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.start();
return;
@ -1143,15 +1096,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
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
*
@ -1237,21 +1181,21 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
return;
}
String infoMessage = "";
String errorMessage = "";
if (isTestOnBorrow()) {
infoMessage += "testOnBorrow is true, ";
if (testOnBorrow) {
errorMessage += "testOnBorrow is true, ";
}
if (isTestOnReturn()) {
infoMessage += "testOnReturn is true, ";
if (testOnReturn) {
errorMessage += "testOnReturn is true, ";
}
if (isTestWhileIdle()) {
infoMessage += "testWhileIdle is true, ";
if (testWhileIdle) {
errorMessage += "testWhileIdle is true, ";
}
LOG.info(infoMessage + "validationQuery not set");
LOG.error(errorMessage + "validationQuery not set");
}
protected void resolveDriver() throws SQLException {
@ -1289,7 +1233,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (driver.getMajorVersion() < 10) {
throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "."
+ driver.getMinorVersion());
+ driver.getMinorVersion());
}
if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) {
@ -1333,7 +1277,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (query instanceof SQLSelectQueryBlock) {
if (((SQLSelectQueryBlock) query).getFrom() == null) {
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 (((SQLSelectQueryBlock) query).getFrom() == null) {
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();
if (JdbcUtils.isMySqlDriver(realDriverClassName)) {
this.validConnectionChecker = new MySqlValidConnectionChecker();
this.validConnectionChecker = new MySqlValidConnectionChecker(usePingMethod);
} else if (realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER)
|| realDriverClassName.equals(JdbcConstants.ORACLE_DRIVER2)) {
this.validConnectionChecker = new OracleValidConnectionChecker();
} else if (realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER)
|| realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_SQLJDBC4)
|| realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_JTDS)) {
|| realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_SQLJDBC4)
|| realDriverClassName.equals(JdbcConstants.SQL_SERVER_DRIVER_JTDS)) {
this.validConnectionChecker = new MSSQLValidConnectionChecker();
} else if (realDriverClassName.equals(JdbcConstants.POSTGRESQL_DRIVER)
|| realDriverClassName.equals(JdbcConstants.ENTERPRISEDB_DRIVER)
|| realDriverClassName.equals(JdbcConstants.POLARDB_DRIVER)) {
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() {
@ -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();
if (realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER) //
|| realDriverClassName.equals(JdbcConstants.MYSQL_DRIVER_6)) {
@ -1453,7 +1402,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException {
init();
checkThread();
if (filters.size() > 0) {
FilterChainImpl filterChain = new FilterChainImpl(this);
return filterChain.dataSource_connect(this, maxWaitMillis);
@ -1474,7 +1422,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException {
int notFullTimeoutRetryCnt = 0;
for (; ; ) {
for (;;) {
// handle notFullTimeoutRetry
DruidPooledConnection poolableConnection;
try {
@ -1508,10 +1456,10 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (testWhileIdle) {
final DruidConnectionHolder holder = poolableConnection.holder;
long currentTimeMillis = System.currentTimeMillis();
long lastActiveTimeMillis = holder.lastActiveTimeMillis;
long lastExecTimeMillis = holder.lastExecTimeMillis;
long lastKeepTimeMillis = holder.lastKeepTimeMillis;
long currentTimeMillis = System.currentTimeMillis();
long lastActiveTimeMillis = holder.lastActiveTimeMillis;
long lastExecTimeMillis = holder.lastExecTimeMillis;
long lastKeepTimeMillis = holder.lastKeepTimeMillis;
if (checkExecuteTime
&& lastExecTimeMillis != lastActiveTimeMillis) {
@ -1522,7 +1470,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
lastActiveTimeMillis = lastKeepTimeMillis;
}
long idleMillis = currentTimeMillis - lastActiveTimeMillis;
long idleMillis = currentTimeMillis - lastActiveTimeMillis;
long timeBetweenEvictionRunsMillis = this.timeBetweenEvictionRunsMillis;
@ -1532,7 +1480,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (idleMillis >= timeBetweenEvictionRunsMillis
|| idleMillis < 0 // unexcepted branch
) {
) {
boolean validate = testConnectionInternal(poolableConnection.holder, poolableConnection.conn);
if (!validate) {
if (LOG.isDebugEnabled()) {
@ -1540,7 +1488,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
discardConnection(poolableConnection.holder);
continue;
continue;
}
}
}
@ -1643,7 +1591,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
DruidConnectionHolder holder;
for (boolean createDirect = false; ; ) {
for (boolean createDirect = false;;) {
if (createDirect) {
createStartNanosUpdater.set(this, System.nanoTime());
if (creatingCountUpdater.compareAndSet(this, 0, 1)) {
@ -1792,10 +1740,10 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
StringBuilder buf = new StringBuilder(128);
buf.append("wait millis ")//
.append(waitNanos / (1000 * 1000))//
.append(", active ").append(activeCount)//
.append(", maxActive ").append(maxActive)//
.append(", creating ").append(creatingCount)//
.append(waitNanos / (1000 * 1000))//
.append(", active ").append(activeCount)//
.append(", maxActive ").append(maxActive)//
.append(", creating ").append(creatingCount)//
;
if (creatingCount > 0 && createStartNanos > 0) {
long createElapseMillis = (System.nanoTime() - createStartNanos) / (1000 * 1000);
@ -1808,21 +1756,17 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
buf.append(", createErrorCount ").append(createErrorCount);
}
JdbcDataSourceStat sourceStat = this.getDataSourceStat();
if (sourceStat != null) {
List<JdbcSqlStatValue> sqlList = sourceStat.getRuningSqlList();
for (int i = 0; i < sqlList.size(); ++i) {
if (i != 0) {
buf.append('\n');
} else {
buf.append(", ");
}
JdbcSqlStatValue sql = sqlList.get(i);
buf.append("runningSqlCount ");
buf.append(sql.getRunningCount());
buf.append(" : ");
buf.append(sql.getSql());
List<JdbcSqlStatValue> sqlList = this.getDataSourceStat().getRuningSqlList();
for (int i = 0; i < sqlList.size(); ++i) {
if (i != 0) {
buf.append('\n');
} else {
buf.append(", ");
}
JdbcSqlStatValue sql = sqlList.get(i);
buf.append("runningSqlCount ").append(sql.getRunningCount());
buf.append(" : ");
buf.append(sql.getSql());
}
String errorMessage = buf.toString();
@ -1914,12 +1858,13 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
lock.unlock();
}
if (onFatalError && holder != null && holder.getDataSource() != null) {
if(onFatalError && holder != null && holder.getDataSource() != null) {
ReentrantLock dataSourceLock = holder.getDataSource().lock;
dataSourceLock.lock();
try {
emptySignal();
} finally {
}
finally {
dataSourceLock.unlock();
}
}
@ -1956,8 +1901,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
if (logDifferentThread //
&& (!isAsyncCloseConnectionEnable()) //
&& pooledConnection.ownerThread != Thread.currentThread()//
&& (!isAsyncCloseConnectionEnable()) //
&& pooledConnection.ownerThread != Thread.currentThread()//
) {
LOG.warn("get/close not same thread");
}
@ -2152,10 +2097,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
destroyConnectionThread.interrupt();
}
if (periodDetectionThread != null) {
periodDetectionThread.interrupt();
}
if (createSchedulerFuture != null) {
createSchedulerFuture.cancel(true);
}
@ -2213,7 +2154,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
@Override
public Object run() {
ObjectName objectName = DruidDataSourceStatManager.addDataSource(DruidDataSource.this,
DruidDataSource.this.name);
DruidDataSource.this.name);
DruidDataSource.this.setObjectName(objectName);
DruidDataSource.this.mbeanRegistered = true;
@ -2307,7 +2248,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
private DruidConnectionHolder pollLast(long nanos) throws InterruptedException, SQLException {
long estimate = nanos;
for (; ; ) {
for (;;) {
if (poolingCount == 0) {
emptySignal(); // send signal to CreateThread create connection
@ -2328,8 +2269,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try {
long startEstimate = estimate;
estimate = notEmpty.awaitNanos(estimate); // signal by
// recycle or
// creator
// recycle or
// creator
notEmptyWaitCount++;
notEmptyWaitNanos += (startEstimate - estimate);
@ -2553,7 +2494,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
value.setCommitCount(commitCountUpdater.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.setStartTransactionCount(startTransactionCountUpdater.getAndSet(this, 0));
@ -2631,7 +2572,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
clearCreateTask(createTaskId);
if (poolingCount + createTaskCount < notEmptyWaitThreadCount //
&& activeCount + poolingCount + createTaskCount < maxActive) {
&& activeCount + poolingCount + createTaskCount < maxActive) {
emptySignal();
}
}
@ -2643,7 +2584,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public class CreateConnectionTask implements Runnable {
private int errorCount = 0;
private int errorCount = 0;
private boolean initTask = false;
private final long taskId;
@ -2662,7 +2603,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
private void runInternal() {
for (; ; ) {
for (;;) {
// addLast
lock.lock();
@ -2828,9 +2769,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
public class CreateConnectionThread extends Thread {
private volatile boolean started = true;
public CreateConnectionThread(String name) {
public CreateConnectionThread(String name){
super(name);
this.setDaemon(true);
}
@ -2840,7 +2780,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
long lastDiscardCount = 0;
int errorCount = 0;
for (; ; ) {
for (;;) {
// addLast
try {
lock.lockInterruptibly();
@ -2889,7 +2829,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if ((!closing) && (!closed)) {
LOG.error("create connection Thread Interrupted, url: " + jdbcUrl, e);
}
DruidDataSource.this.doSomethingBeforeCreationThreadBreak();
break;
} finally {
lock.unlock();
@ -2899,13 +2838,9 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try {
connection = createPhysicalConnection();
} catch (SQLException | RuntimeException e) {
if (e instanceof SQLException) {
LOG.error("create connection error, url: " + jdbcUrl + ", errorCode " + ((SQLException) e).getErrorCode()
+ ", state " + ((SQLException) e).getSQLState(), e);
} else {
LOG.error("create connection error", e);
}
} catch (SQLException e) {
LOG.error("create connection SQLException, url: " + jdbcUrl + ", errorCode " + e.getErrorCode()
+ ", state " + e.getSQLState(), e);
errorCount++;
if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) {
@ -2926,16 +2861,17 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try {
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) {
LOG.error("create connection Error", e);
setFailContinuous(true);
DruidDataSource.this.doSomethingBeforeCreationThreadBreak();
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 {
private volatile boolean started = true;
public DestroyConnectionThread(String name) {
public DestroyConnectionThread(String name){
super(name);
this.setDaemon(true);
}
@ -3006,7 +2904,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public void run() {
initedLatch.countDown();
for (; ; ) {
for (;;) {
// 从前面开始删除
try {
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 {
@ -3057,14 +2948,14 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
public class LogStatsThread extends Thread {
public LogStatsThread(String name) {
public LogStatsThread(String name){
super(name);
this.setDaemon(true);
}
public void run() {
try {
for (; ; ) {
for (;;) {
try {
logStats();
} catch (Exception e) {
@ -3090,7 +2981,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
try {
Iterator<DruidPooledConnection> iter = activeConnections.keySet().iterator();
for (; iter.hasNext(); ) {
for (; iter.hasNext();) {
DruidPooledConnection pooledConnection = iter.next();
if (pooledConnection.isRunning()) {
@ -3142,7 +3033,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
buf.append("ownerThread current state is " + pooledConnection.getOwnerThread().getState()
+ ", current stackTrace\n");
+ ", current stackTrace\n");
trace = pooledConnection.getOwnerThread().getStackTrace();
for (int i = 0; i < trace.length; i++) {
buf.append("\tat ");
@ -3158,9 +3049,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
return removeCount;
}
/**
* Instance key
*/
/** Instance key */
protected String instanceKey = null;
public Reference getReference() throws NamingException {
@ -3241,7 +3130,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder connection = connections[i];
if ((onFatalError || fatalErrorIncrement > 0) && (lastFatalErrorTimeMillis > connection.connectTimeMillis)) {
if ((onFatalError || fatalErrorIncrement > 0) && (lastFatalErrorTimeMillis > connection.connectTimeMillis)) {
keepAliveConnections[keepAliveCount++] = connection;
continue;
}
@ -3865,7 +3754,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
if (this.statLogger != null
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
return true;
}
@ -3881,7 +3770,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
if (this.statLogger != null
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
return (T) statLogger;
}
@ -3925,7 +3814,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
int fillCount = 0;
for (; ; ) {
for (;;) {
try {
lock.lockInterruptibly();
} 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;
private final static String HIBERNATE_PREFIX = "hibernate.";
private final static String HIBERNATE_CONN_PREFIX = "connection.";
public final static String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
public final static String PROP_DEFAULTREADONLY = "defaultReadOnly";
public final static String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
public final static String PROP_DEFAULTCATALOG = "defaultCatalog";
public final static String PROP_DRIVERCLASSNAME = "driverClassName";
public final static String HB_PROP_DRIVERCLASSNAME = HIBERNATE_PREFIX + HIBERNATE_CONN_PREFIX + "driver_class";
public final static String PROP_MAXACTIVE = "maxActive";
public final static String HB_PROP_MAXACTIVE = HIBERNATE_PREFIX + "maxActive";
public final static String PROP_MAXIDLE = "maxIdle";
public final static String HB_PROP_MAXIDLE = HIBERNATE_PREFIX + "maxIdle";
public final static String PROP_MINIDLE = "minIdle";
public final static String HB_PROP_MINIDLE = HIBERNATE_PREFIX + "minIdle";
public final static String PROP_INITIALSIZE = "initialSize";
public final static String HB_PROP_INITIALSIZE = HIBERNATE_PREFIX + "initialSize";
public final static String PROP_MAXWAIT = "maxWait";
public final static String HB_PROP_MAXWAIT = HIBERNATE_PREFIX + "maxWait";
public final static String PROP_TESTONBORROW = "testOnBorrow";
public final static String HB_PROP_TESTONBORROW = HIBERNATE_PREFIX + "testOnBorrow";
public final static String PROP_TESTONRETURN = "testOnReturn";
public final static String HB_PROP_TESTONRETURN = HIBERNATE_PREFIX + "testOnReturn";
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_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
public final static String PROP_DEFAULTREADONLY = "defaultReadOnly";
public final static String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
public final static String PROP_DEFAULTCATALOG = "defaultCatalog";
public final static String PROP_DRIVERCLASSNAME = "driverClassName";
public final static String PROP_MAXACTIVE = "maxActive";
public final static String PROP_MAXIDLE = "maxIdle";
public final static String PROP_MINIDLE = "minIdle";
public final static String PROP_INITIALSIZE = "initialSize";
public final static String PROP_MAXWAIT = "maxWait";
public final static String PROP_TESTONBORROW = "testOnBorrow";
public final static String PROP_TESTONRETURN = "testOnReturn";
public final static String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
public final static String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
public final static String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
public final static String PROP_PHY_TIMEOUT_MILLIS = "phyTimeoutMillis";
public final static String PROP_TESTWHILEIDLE = "testWhileIdle";
public final static String PROP_PASSWORD = "password";
public final static String PROP_URL = "url";
public final static String PROP_USERNAME = "username";
public final static String PROP_VALIDATIONQUERY = "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_REMOVEABANDONED = "removeAbandoned";
public final static String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
public final static String PROP_LOGABANDONED = "logAbandoned";
public final static String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
public final static String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
public final static String PROP_CONNECTIONPROPERTIES = "connectionProperties";
public final static String PROP_FILTERS = "filters";
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_NAME = "name";
public final static String PROP_INIT = "init";
public final static String PROP_REMOVEABANDONED = "removeAbandoned";
public final static String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
public final static String PROP_LOGABANDONED = "logAbandoned";
public final static String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
public final static String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
public final static String PROP_CONNECTIONPROPERTIES = "connectionProperties";
public final static String PROP_FILTERS = "filters";
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_NAME = "name";
public final static String PROP_INIT = "init";
private final static String[] ALL_PROPERTIES = {
PROP_DEFAULTAUTOCOMMIT,
@ -242,161 +223,56 @@ public class DruidDataSourceFactory implements ObjectFactory {
value = (String) properties.get(PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
} else {
value = (String) properties.get(HB_PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
}
}
value = (String) properties.get(PROP_MAXACTIVE);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
if (value != null) {
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);
@ -407,56 +283,26 @@ public class DruidDataSourceFactory implements ObjectFactory {
value = (String) properties.get(PROP_TESTWHILEIDLE);
if (value != null) {
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);
if (value != null) {
dataSource.setPassword(value);
} else {
value = (String) properties.get(HB_PROP_PASSWORD);
if (value != null) {
dataSource.setPassword(value);
}
}
value = (String) properties.get(PROP_URL);
if (value != null) {
dataSource.setUrl(value);
} else {
value = (String) properties.get(HB_PROP_URL);
if (value != null) {
dataSource.setUrl(value);
}
}
value = (String) properties.get(PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
} else {
value = (String) properties.get(HB_PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
}
}
value = (String) properties.get(PROP_VALIDATIONQUERY);
if (value != null && value.length() > 0) {
if (value != null) {
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);

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;
}
if (DbType.mysql != DbType.of(dataSource.dbTypeName)) {
if (!JdbcUtils.isMysqlDbType(dataSource.dbTypeName)) {
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.ValidConnectionCheckerAdapter;
import com.fr.third.alibaba.druid.util.JdbcUtils;
import com.fr.third.alibaba.druid.util.StringUtils;
/**
* A MSSQLValidConnectionChecker.
@ -30,8 +31,9 @@ import com.fr.third.alibaba.druid.util.JdbcUtils;
public class MSSQLValidConnectionChecker extends ValidConnectionCheckerAdapter implements ValidConnectionChecker, Serializable {
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;
}
if (validateQuery == null || validateQuery.isEmpty()) {
validateQuery = "select 1";
if(StringUtils.isEmpty(validateQuery)) {
validateQuery = DEFAULT_VALIDATION_QUERY;
}
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 boolean usePingMethod = false;
public MySqlValidConnectionChecker(){
public MySqlValidConnectionChecker(boolean usePingMethod){
try {
clazz = Utils.loadClass("com.mysql.jdbc.MySQLConnection");
if (clazz == null) {
@ -56,8 +56,8 @@ public class MySqlValidConnectionChecker extends ValidConnectionCheckerAdapter i
ping = clazz.getMethod("pingInternal", boolean.class, int.class);
}
if (ping != null) {
usePingMethod = true;
if (ping != null && usePingMethod) {
this.usePingMethod = true;
}
} catch (Exception 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.sqlserver.ast.SQLServerSelectQueryBlock;
import com.fr.third.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerTop;
import com.fr.third.alibaba.druid.util.JdbcUtils;
import java.util.List;
@ -157,12 +158,15 @@ public class PagerUtils {
switch (dbType) {
case mysql:
case mariadb:
case tidb:
case h2:
case ads:
case clickhouse:
return limitMySqlQueryBlock(queryBlock, dbType, offset, count, check);
case postgresql:
case hive:
case odps:
case presto:
return limitSQLQueryBlock(queryBlock, dbType, offset, count, check);
case oracle:
case oceanbase_oracle:
@ -534,6 +538,7 @@ public class PagerUtils {
switch (dbType) {
case mysql:
case mariadb:
case tidb:
case ads:
return new MySqlSelectQueryBlock();
case oracle:
@ -638,7 +643,7 @@ public class PagerUtils {
public static boolean hasUnorderedLimit(String sql, DbType dbType) {
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (DbType.mysql == dbType) {
if (JdbcUtils.isMysqlDbType(dbType)) {
MySqlUnorderedLimitDetectVisitor visitor = new MySqlUnorderedLimitDetectVisitor();
@ -670,7 +675,7 @@ public class PagerUtils {
SQLOrderBy orderBy = x.getOrderBy();
SQLLimit limit = x.getLimit();
if (limit != null && (orderBy == null || orderBy.getItems().size() == 0)) {
if (limit != null && (orderBy == null || orderBy.getItems().isEmpty())) {
boolean subQueryHasOrderBy = false;
SQLTableSource from = x.getFrom();
if (from instanceof SQLSubqueryTableSource) {
@ -695,6 +700,7 @@ public class PagerUtils {
private static class OracleUnorderedLimitDetectVisitor extends OracleASTVisitorAdapter {
public int unorderedLimitCount;
@Override
public boolean visit(SQLBinaryOpExpr x) {
SQLExpr left = x.getLeft();
SQLExpr right = x.getRight();
@ -741,7 +747,7 @@ public class PagerUtils {
orderBy = select.getOrderBy();
}
if (orderBy == null || orderBy.getItems().size() == 0) {
if (orderBy == null || orderBy.getItems().isEmpty()) {
unorderedLimitCount++;
}
}
@ -779,7 +785,7 @@ public class PagerUtils {
SQLSelect select = (SQLSelect) parent;
if (select.getOrderBy() == null || select.getOrderBy().getItems().size() == 0) {
if (select.getOrderBy() == null || select.getOrderBy().getItems().isEmpty()) {
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");
} else if (nameHash == FnvHash.Constants.NUMBER) {
if (argumentns.size() == 0) {
if (argumentns.isEmpty()) {
dataType = new SQLDataTypeImpl("decimal", 38);
} else {
SQLExpr arg0 = argumentns.get(0);
@ -230,7 +230,7 @@ public class SQLTransformUtils {
} else if (nameHash == FnvHash.Constants.RAW) {
int len;
if (argumentns.size() == 0) {
if (argumentns.isEmpty()) {
len = -1;
} else if (argumentns.size() == 1) {
SQLExpr arg0 = argumentns.get(0);
@ -267,7 +267,7 @@ public class SQLTransformUtils {
} else {
dataType = new SQLCharacterDataType("varchar", len);
}
} else if (argumentns.size() == 0) {
} else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType("char");
} else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -289,7 +289,7 @@ public class SQLTransformUtils {
} else {
dataType = new SQLCharacterDataType("nvarchar", len);
}
} else if (argumentns.size() == 0) {
} else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType("nchar");
} else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -462,7 +462,7 @@ public class SQLTransformUtils {
dataType = new SQLDataTypeImpl(SQLDataType.Constants.DOUBLE_PRECISION);
} else if (nameHash == FnvHash.Constants.NUMBER) {
if (argumentns.size() == 0) {
if (argumentns.isEmpty()) {
dataType = new SQLDataTypeImpl(SQLDataType.Constants.DECIMAL, 38);
} else {
SQLExpr arg0 = argumentns.get(0);
@ -536,7 +536,7 @@ public class SQLTransformUtils {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
}
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR, len);
} else if (argumentns.size() == 0) {
} else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -558,7 +558,7 @@ public class SQLTransformUtils {
} else {
dataType = new SQLCharacterDataType(SQLDataType.Constants.TEXT);
}
} else if (argumentns.size() == 0) {
} else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -684,7 +684,7 @@ public class SQLTransformUtils {
}
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();
if (dataType.nameHashCode64() == FnvHash.Constants.TIMESTAMP
&& dataType.getArguments().size() == 1) {
@ -895,7 +895,7 @@ public class SQLTransformUtils {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
}
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR, len);
} else if (argumentns.size() == 0) {
} else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else {
throw new UnsupportedOperationException(SQLUtils.toOracleString(x));
@ -917,7 +917,7 @@ public class SQLTransformUtils {
} else {
dataType = new SQLCharacterDataType(SQLDataType.Constants.TEXT);
}
} else if (argumentns.size() == 0) {
} else if (argumentns.isEmpty()) {
dataType = new SQLCharacterDataType(SQLDataType.Constants.CHAR);
} else {
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.postgresql.visitor.PGOutputVisitor;
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.SQLServerSchemaStatVisitor;
import com.fr.third.alibaba.druid.sql.parser.*;
@ -478,6 +479,7 @@ public class SQLUtils {
}
case mysql:
case mariadb:
case tidb:
return new MySqlOutputVisitor(out);
case postgresql:
return new PGOutputVisitor(out);
@ -498,6 +500,8 @@ public class SQLUtils {
return new BlinkOutputVisitor(out);
case antspark:
return new AntsparkOutputVisitor(out);
case presto:
return new PrestoOutputVisitor(out);
case clickhouse:
return new ClickhouseOutputVisitor(out);
default:
@ -532,6 +536,7 @@ public class SQLUtils {
return new OracleSchemaStatVisitor(repository);
case mysql:
case mariadb:
case tidb:
case elastic_search:
return new MySqlSchemaStatVisitor(repository);
case postgresql:
@ -639,7 +644,7 @@ public class SQLUtils {
dbType = DbType.mysql;
}
String formatMethod = "";
if (DbType.mysql == dbType) {
if (JdbcUtils.isMysqlDbType(dbType)) {
formatMethod = "STR_TO_DATE";
if (StringUtils.isEmpty(pattern)) pattern = "%Y-%m-%d %H:%i:%s";
} else if (DbType.oracle == dbType) {
@ -701,7 +706,7 @@ public class SQLUtils {
List<SQLStatement> stmtList = parseStatements(sql, dbType);
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
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) {
List<SQLStatement> stmtList = parseStatements(selectSql, dbType);
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + selectSql);
}
@ -1011,7 +1016,7 @@ public class SQLUtils {
if (OracleUtils.isKeyword(normalizeName)) {
return name;
}
} else if (DbType.mysql == dbType) {
} else if (JdbcUtils.isMysqlDbType(dbType)) {
if (MySqlUtils.isKeyword(normalizeName)) {
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>();
// for postgres
private boolean sibings;
private boolean siblings;
public SQLOrderBy(){
@ -57,12 +57,12 @@ public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
return this.items;
}
public boolean isSibings() {
return this.sibings;
public boolean isSiblings() {
return this.siblings;
}
public void setSibings(boolean sibings) {
this.sibings = sibings;
public void setSiblings(boolean siblings) {
this.siblings = siblings;
}
protected void accept0(SQLASTVisitor v) {
@ -83,14 +83,14 @@ public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
SQLOrderBy order = (SQLOrderBy) o;
if (sibings != order.sibings) return false;
if (siblings != order.siblings) return false;
return items.equals(order.items);
}
@Override
public int hashCode() {
int result = items.hashCode();
result = 31 * result + (sibings ? 1 : 0);
result = 31 * result + (siblings ? 1 : 0);
return result;
}
@ -126,7 +126,7 @@ public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
x.items.add(item1);
}
x.sibings = sibings;
x.siblings = siblings;
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) {
if (list.size() == 0) {
if (list.isEmpty()) {
return null;
}
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));
}
if (items.size() == 0) {
if (items.isEmpty()) {
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.ads
, DbType.hive
, DbType.odps);
, DbType.odps
, DbType.mariadb
, DbType.tidb);
public static boolean isSupport(DbType dbType) {
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.trino
, DbType.postgresql
, DbType.mariadb
, DbType.tidb
);
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) {
return ((Float) this.number).compareTo((Float) o.number);
return ((Double) this.number).compareTo((Double) o.number);
}
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.trino
, DbType.postgresql
, DbType.mariadb
, DbType.tidb
);
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() {
if (tableSources.size() == 0) {
if (tableSources.isEmpty()) {
return null;
}
@ -86,7 +86,7 @@ public class SQLAnalyzeTableStatement extends SQLStatementImpl {
table.setParent(this);
}
if (tableSources.size() == 0) {
if (tableSources.isEmpty()) {
if (table == null) {
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) {
MySqlUnique unique = (MySqlUnique) element;
if (unique.getColumns().size() == 0) {
if (unique.getColumns().isEmpty()) {
continue;
}
@ -671,7 +671,7 @@ public class SQLCreateTableStatement extends SQLStatementImpl implements SQLDDLS
}
}
if (stmt.getItems().size() == 0) {
if (stmt.getItems().isEmpty()) {
return null;
}
@ -1095,13 +1095,13 @@ public class SQLCreateTableStatement extends SQLStatementImpl implements SQLDDLS
if (e instanceof SQLUnique) {
SQLUnique unique = (SQLUnique) e;
unique.applyDropColumn(column);
if (unique.getColumns().size() == 0) {
if (unique.getColumns().isEmpty()) {
tableElementList.remove(i);
}
} else if (e instanceof MySqlTableIndex) {
MySqlTableIndex index = (MySqlTableIndex) e;
index.applyDropColumn(column);
if (index.getColumns().size() == 0) {
if (index.getColumns().isEmpty()) {
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++;
}
}
if (items.size() == 0) {
if (items.isEmpty()) {
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() {
if (valuesList.size() == 0) {
if (valuesList.isEmpty()) {
return null;
}
return valuesList.get(0);
}
public void setValues(ValuesClause values) {
if (valuesList.size() == 0) {
if (valuesList.isEmpty()) {
valuesList.add(values);
} else {
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() {
return withSubQuery == null
&& (hints == null || hints.size() == 0)
&& (hints == null || hints.isEmpty())
&& restriction == null
&& (!forBrowse)
&& (forXmlOptions == null || forXmlOptions.size() == 0)
&& (forXmlOptions == null || forXmlOptions.isEmpty())
&& xmlPath == null
&& rowCount == 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));
return;
}
@ -1251,7 +1251,7 @@ public class SQLSelectQueryBlock extends SQLSelectQueryBase implements SQLReplac
removedCount++;
}
}
if (items.size() == 0) {
if (items.isEmpty()) {
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) {
if (x == null) {
if (x != null) {
x.setParent(this);
}
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() {
if (relations.size() == 0) {
if (relations.isEmpty()) {
return null;
}
return relations.get(0);
@ -86,7 +86,7 @@ public class SQLUnionQuery extends SQLSelectQueryBase implements SQLDbTypedObjec
left.setParent(this);
}
if (relations.size() == 0) {
if (relations.isEmpty()) {
relations.add(left);
} else if (relations.size() <= 2) {
relations.set(0, left);
@ -111,7 +111,7 @@ public class SQLUnionQuery extends SQLSelectQueryBase implements SQLDbTypedObjec
right.setParent(this);
}
if (relations.size() == 0) {
if (relations.isEmpty()) {
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++;
}
}
if (items.size() == 0) {
if (items.isEmpty()) {
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){
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + sql);
}
@ -127,6 +127,8 @@ public class SQLDeleteBuilderImpl implements SQLDeleteBuilder {
case oracle:
return new OracleDeleteStatement();
case mysql:
case mariadb:
case tidb:
return new MySqlDeleteStatement();
case postgresql:
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){
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
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){
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + sql);
}
@ -161,6 +161,7 @@ public class SQLUpdateBuilderImpl extends SQLBuilderImpl implements SQLUpdateBui
switch (dbType) {
case mysql:
case mariadb:
case tidb:
return new MySqlUpdateStatement();
case oracle:
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();
alterColumn.setColumn(column);
if (column.getDataType() == null && column.getConstraints().size() == 0) {
if (column.getDataType() == null && column.getConstraints().isEmpty()) {
if (lexer.token() == Token.SET) {
lexer.nextToken();
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();
if (valuesClauseList.size() != 0) {
if (!valuesClauseList.isEmpty()) {
println();
print0(ucase ? "VALUES " : "values ");
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) {
x.setParent(this);
}
this.addDataFile = addDataFile;
this.addDataFile = x;
}
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) {
if (this.threadIds.size() == 0) {
if (this.threadIds.isEmpty()) {
this.threadIds.add(threadId);
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;
}
if (hints.size() >= 1
&& statementList.size() == 0
&& statementList.isEmpty()
&& acceptHint) {
SQLCommentHint hint = hints.get(0);
String hintText = hint.getText().toUpperCase();
@ -2346,7 +2346,7 @@ public class MySqlStatementParser extends SQLStatementParser {
break;
}
if (stmt.getTables().size() != 0) {
if (!stmt.getTables().isEmpty()) {
if (lexer.token() == Token.FOR) {
lexer.nextToken();
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();
if (duplicateKeyUpdate.size() != 0) {
if (!duplicateKeyUpdate.isEmpty()) {
println();
print0(ucase ? "ON DUPLICATE KEY UPDATE " : "on duplicate key update ");
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);
if (value instanceof SQLLiteralExpr || value instanceof SQLVariantRefExpr) {
continue;
} else if (value instanceof SQLMethodInvokeExpr && ((SQLMethodInvokeExpr) value).getArguments().size() == 0) {
} else if (value instanceof SQLMethodInvokeExpr && ((SQLMethodInvokeExpr) value).getArguments().isEmpty()) {
continue;
}
allConst = false;
@ -1433,13 +1433,13 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print0(ucase ? " LINES" : " lines");
}
if (x.getColumns().size() != 0) {
if (!x.getColumns().isEmpty()) {
print0(" (");
printAndAccept(x.getColumns(), ", ");
print(')');
}
if (x.getSetList().size() != 0) {
if (!x.getSetList().isEmpty()) {
print0(ucase ? " SET " : " set ");
printAndAccept(x.getSetList(), ", ");
}
@ -1516,7 +1516,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
}
List<SQLInsertStatement.ValuesClause> valuesClauseList = x.getValuesList();
if (valuesClauseList.size() != 0) {
if (!valuesClauseList.isEmpty()) {
println();
print0(ucase ? "VALUES " : "values ");
int size = valuesClauseList.size();
@ -1758,7 +1758,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
x.getRowsIdentifiedBy().accept(this);
}
if (x.getSetList().size() != 0) {
if (!x.getSetList().isEmpty()) {
print0(ucase ? " SET " : " set ");
printAndAccept(x.getSetList(), ", ");
}
@ -4218,7 +4218,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
}
List<SQLParameter> parameters = x.getParameters();
if (parameters.size() != 0) {
if (!parameters.isEmpty()) {
this.indentCount++;
if (parent instanceof SQLCreateProcedureStatement) {
printIndent();
@ -4600,7 +4600,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print(")");
}
if (x.getOptions().size() != 0) {
if (!x.getOptions().isEmpty()) {
println();
print0(ucase ? "SUBPARTITION OPTIONS (" : "subpartition options (");
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) {
OracleMultiInsertStatement.InsertIntoClause clause = new OracleMultiInsertStatement.InsertIntoClause();
boolean acceptSubQuery = stmt.getEntries().size() == 0;
boolean acceptSubQuery = stmt.getEntries().isEmpty();
parseInsert0(clause, acceptSubQuery);
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() {
if (valuesList.size() == 0) {
if (valuesList.isEmpty()) {
return null;
}
return valuesList.get(0);
}
public void setValues(ValuesClause values) {
if (valuesList.size() == 0) {
if (valuesList.isEmpty()) {
valuesList.add(values);
} else {
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();
alterColumn.setColumn(column);
if (column.getDataType() == null && column.getConstraints().size() == 0) {
if (column.getDataType() == null && column.getConstraints().isEmpty()) {
if (lexer.token() == Token.SET) {
lexer.nextToken();
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('(');
expr.accept(this);
print(')');
} else if (expr instanceof PGTypeCastExpr && dataType.getArguments().size() == 0) {
} else if (expr instanceof PGTypeCastExpr && dataType.getArguments().isEmpty()) {
dataType.accept(this);
print('(');
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;
import com.fr.third.alibaba.druid.DbType;
import com.fr.third.alibaba.druid.sql.ast.SQLExpr;
import com.fr.third.alibaba.druid.sql.ast.expr.SQLCharExpr;
import com.fr.third.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
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.*;
import com.fr.third.alibaba.druid.sql.parser.Lexer;
import com.fr.third.alibaba.druid.sql.parser.SQLExprParser;
import com.fr.third.alibaba.druid.sql.parser.SQLParserFeature;
/**
* 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.SQLName;
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.SQLStatementParser;
import com.fr.third.alibaba.druid.sql.parser.Token;
@ -35,6 +36,18 @@ public class PrestoStatementParser extends SQLStatementParser {
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
protected void parseInsertColumns(SQLInsertInto insert) {
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);
}
if (x.getValuesList().size() != 0) {
if (!x.getValuesList().isEmpty()) {
println();
print0(ucase ? "VALUES " : "values ");
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)) {
lexer.nextToken();
orderBy.setSibings(true);
orderBy.setSiblings(true);
}
accept(Token.BY);
@ -2745,7 +2745,7 @@ public class SQLExprParser extends SQLParser {
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken();
orderBy.setSibings(true);
orderBy.setSiblings(true);
}
accept(Token.BY);
@ -2770,7 +2770,7 @@ public class SQLExprParser extends SQLParser {
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken();
orderBy.setSibings(true);
orderBy.setSiblings(true);
}
accept(Token.BY);
@ -2795,7 +2795,7 @@ public class SQLExprParser extends SQLParser {
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken();
orderBy.setSibings(true);
orderBy.setSiblings(true);
}
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);
if (tableSource instanceof SQLValuesTableSource
&& ((SQLValuesTableSource) tableSource).getColumns().size() == 0) {
&& ((SQLValuesTableSource) tableSource).getColumns().isEmpty()) {
SQLValuesTableSource values = (SQLValuesTableSource) tableSource;
accept(Token.LPAREN);
this.exprParser.names(values.getColumns(), values);
@ -1351,7 +1351,7 @@ public class SQLSelectParser extends SQLParser {
tableSource.setAlias(alias);
if ((tableSource instanceof SQLValuesTableSource)
&& ((SQLValuesTableSource) tableSource).getColumns().size() == 0) {
&& ((SQLValuesTableSource) tableSource).getColumns().isEmpty()) {
SQLValuesTableSource values = (SQLValuesTableSource) tableSource;
accept(Token.LPAREN);
this.exprParser.names(values.getColumns(), values);
@ -1565,7 +1565,7 @@ public class SQLSelectParser extends SQLParser {
if (rightTableSource instanceof SQLValuesTableSource
&& (lexer.token == Token.AS || lexer.token == Token.IDENTIFIER)
&& rightTableSource.getAlias() == null
&& ((SQLValuesTableSource) rightTableSource).getColumns().size() == 0
&& ((SQLValuesTableSource) rightTableSource).getColumns().isEmpty()
) {
if (lexer.token == Token.AS) {
lexer.nextToken();
@ -1708,7 +1708,7 @@ public class SQLSelectParser extends SQLParser {
} else if (rightTableSource instanceof SQLExprTableSource
&& ((SQLExprTableSource) rightTableSource).getExpr() instanceof SQLMethodInvokeExpr) {
List<SQLName> columns = ((SQLExprTableSource) rightTableSource).getColumns();
if (columns.size() == 0) {
if (columns.isEmpty()) {
lexer.nextToken();
this.exprParser.names(columns, rightTableSource);
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) {
case mysql:
case mariadb:
case tidb:
case sqlite:
resolveVisitor = new SchemaResolveVisitorFactory.MySqlResolveVisitor(this, optionsValue);
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) {
case mysql:
case mariadb:
case tidb:
case ads:
quote = '`';
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) {
case mysql:
case mariadb:
case tidb:
return new MySqlExportParameterVisitor(out);
case oracle:
return new OracleExportParameterVisitor(out);
@ -124,7 +125,7 @@ public final class ExportParameterVisitorUtils {
} else if (listItem instanceof SQLNumericLiteralExpr) {
Object listValue = ((SQLNumericLiteralExpr) listItem).getNumber();
listValues.add(listValue);
} else if (param instanceof SQLHexExpr) {
} else if (listItem instanceof SQLHexExpr) {
Object listValue = ((SQLHexExpr) listItem).toBytes();
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.phoenix.visitor.PhoenixOutputVisitor;
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.parser.SQLParserFeature;
import com.fr.third.alibaba.druid.sql.parser.SQLParserUtils;
@ -78,7 +79,7 @@ public class ParameterizedOutputVisitorUtils {
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);
}
@ -151,7 +152,7 @@ public class ParameterizedOutputVisitorUtils {
}
List<SQLStatement> statementList = parser.parseStatementList();
if (statementList.size() == 0) {
if (statementList.isEmpty()) {
return sql;
}
@ -408,6 +409,8 @@ public class ParameterizedOutputVisitorUtils {
return new DB2OutputVisitor(out, true);
case phoenix:
return new PhoenixOutputVisitor(out, true);
case presto:
return new PrestoOutputVisitor(out, true);
default:
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;
List<SQLExpr> items = x.getItems();
if (items.size() == 0) {
if (items.isEmpty()) {
print("true");
return false;
}
@ -2060,7 +2060,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
boolean withGroup = x.isWithinGroup();
if (withGroup) {
print0(ucase ? ") WITHIN GROUP (" : " within group (");
print0(ucase ? ") WITHIN GROUP (" : ") within group (");
}
visitAggreateRest(x);
@ -2718,7 +2718,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
List<SQLSelectOrderByItem> items = x.getItems();
if (items.size() > 0) {
if (x.isSibings()) {
if (x.isSiblings()) {
print0(ucase ? "ORDER SIBLINGS BY " : "order siblings by ");
} else {
print0(ucase ? "ORDER BY " : "order by ");
@ -4801,7 +4801,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
}
final List<List<SQLAssignItem>> storedBy = x.getStoredBy();
if (storedBy.size() != 0) {
if (!storedBy.isEmpty()) {
println();
print0(ucase ? "STORED BY " : "stored by ");
@ -6719,7 +6719,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override
public boolean visit(SQLAlterTableEnableLifecycle x) {
if (x.getPartition().size() != 0) {
if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", ");
print0(") ");
@ -6731,7 +6731,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override
public boolean visit(SQLAlterTableDisableLifecycle x) {
if (x.getPartition().size() != 0) {
if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", ");
print0(") ");
@ -6743,7 +6743,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override
public boolean visit(SQLAlterTablePartition x) {
if (x.getPartition().size() != 0) {
if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", ");
print0(") ");
@ -6753,13 +6753,13 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override
public boolean visit(SQLAlterTablePartitionSetProperties x) {
if (x.getPartition().size() != 0) {
if (!x.getPartition().isEmpty()) {
print0(ucase ? "PARTITION (" : "partition (");
printAndAccept(x.getPartition(), ", ");
print0(") ");
}
if (x.getPartitionProperties().size() != 0) {
if (!x.getPartitionProperties().isEmpty()) {
print0(ucase ? "SET PARTITIONPROPERTIES (" : "set partitionproperties (");
printAndAccept(x.getPartitionProperties(), ", ");
print0(") ");
@ -6770,7 +6770,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override
public boolean visit(SQLAlterTableTouch x) {
print0(ucase ? "TOUCH" : "touch");
if (x.getPartition().size() != 0) {
if (!x.getPartition().isEmpty()) {
print0(ucase ? " PARTITION (" : " partition (");
printAndAccept(x.getPartition(), ", ");
print(')');
@ -7290,7 +7290,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override
public boolean visit(SQLPartitionByRange x) {
SQLExpr interval = x.getInterval();
if (x.getColumns().size() == 0
if (x.getColumns().isEmpty()
&& (interval instanceof SQLBetweenExpr || interval instanceof SQLMethodInvokeExpr))
{
interval.accept(this);
@ -8911,7 +8911,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter implements Paramet
@Override
public boolean visit(SQLBlockStatement x) {
if (x.getParameters().size() != 0) {
if (!x.getParameters().isEmpty()) {
this.indentCount++;
if (x.getParent() instanceof SQLCreateProcedureStatement) {
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) {
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
return;
}
@ -138,7 +138,7 @@ public class SQLDataTypeValidator extends SQLASTVisitorAdapter {
}
public static void check(List<SQLStatement> stmtList, DbType dbType) {
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
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) {
case mysql:
case mariadb:
case tidb:
case h2:
return new MySqlEvalVisitorImpl();
case oracle:
@ -349,11 +350,10 @@ public class SQLEvalVisitorUtils {
}
double doubleValue = castToDouble(paramValue);
int result = (int) Math.ceil(doubleValue);
if (Double.isNaN(result)) {
if (Double.isNaN(doubleValue)) {
x.putAttribute(EVAL_VALUE, null);
} else {
int result = (int) Math.ceil(doubleValue);
x.putAttribute(EVAL_VALUE, result);
}
} 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;
switch (dbType) {
case mysql:
case mariadb:
case tidb:
return new MySqlOrderByStatVisitor(x);
case postgresql:
return new PGOrderByStatVisitor(x);
@ -3188,10 +3190,9 @@ public class SchemaStatVisitor extends SQLASTVisitorAdapter {
SQLExprTableSource table = x.getTable();
if (table != null) {
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;

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 Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
if (x.getArguments().size() == 0) {
if (x.getArguments().isEmpty()) {
return SQLEvalVisitor.EVAL_ERROR;
}
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 Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
if (x.getArguments().size() == 0) {
if (x.getArguments().isEmpty()) {
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) {
final List<SQLExpr> arguments = x.getArguments();
if (arguments.size() == 0) {
if (arguments.isEmpty()) {
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) {
final List<SQLExpr> arguments = x.getArguments();
if (arguments.size() == 0) {
if (arguments.isEmpty()) {
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 Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
if (x.getArguments().size() == 0) {
if (x.getArguments().isEmpty()) {
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) {
final List<SQLExpr> arguments = x.getArguments();
if (arguments.size() == 0) {
if (arguments.isEmpty()) {
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();
SqlNode[] operands;
if (columns.size() == 0) {
if (columns.isEmpty()) {
operands = new SqlNode[] { sqlNode, aliasIdentifier };
} else {
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()) {
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("目前无活动中的数据库连接");
} else {
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.SQLException;
import java.util.Map;
import java.util.Properties;
import com.fr.third.alibaba.druid.pool.DruidDataSource;
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.service.spi.Configurable;
import com.fr.third.org.hibernate.exception.spi.Configurable;
import com.fr.third.org.hibernate.service.spi.Stoppable;
public class DruidConnectionProvider implements ConnectionProvider, Configurable, Stoppable {
private static final long serialVersionUID = 1026193803901107651L;
private DruidDataSource dataSource;
private DruidDataSource dataSource;
public DruidConnectionProvider() {
public DruidConnectionProvider(){
dataSource = new DruidDataSource();
}
@ -62,7 +64,7 @@ public class DruidConnectionProvider implements ConnectionProvider, Configurable
}
@SuppressWarnings("rawtypes")
@Override
//@Override
public void configure(Map configurationValues) {
try {
DruidDataSourceFactory.config(dataSource, configurationValues);
@ -76,4 +78,12 @@ public class DruidConnectionProvider implements ConnectionProvider, Configurable
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;
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);

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");
* 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");
if(logType != null){
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")){
tryImplementation("org.apache.log4j.Logger", "Log4jImpl");
tryImplementation("org.apache.log4j.Logger", "com.fr.third.alibaba.druid.support.logging.Log4jImpl");
}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")){
tryImplementation("org.apache.commons.logging.LogFactory",
"JakartaCommonsLoggingImpl");
"com.fr.third.alibaba.druid.support.logging.JakartaCommonsLoggingImpl");
}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调用者的信息
tryImplementation("com.fr.third.apache.log4j.Logger", "FRLog4jImpl");
tryImplementation("org.apache.log4j.Logger", "Log4jImpl");
tryImplementation("org.apache.logging.log4j.Logger", "Log4j2Impl");
tryImplementation("org.apache.commons.logging.LogFactory", "JakartaCommonsLoggingImpl");
tryImplementation("java.util.logging.Logger", "Jdk14LoggingImpl");
tryImplementation("com.fr.third.slf4j.Logger", "com.fr.third.alibaba.druid.support.logging.SLF4JImpl");
tryImplementation("org.apache.log4j.Logger", "com.fr.third.alibaba.druid.support.logging.Log4jImpl");
tryImplementation("com.fr.third.apache.logging.log4j.Logger", "com.fr.third.alibaba.druid.support.logging.Log4j2Impl");
tryImplementation("org.apache.commons.logging.LogFactory",
"com.fr.third.alibaba.druid.support.logging.JakartaCommonsLoggingImpl");
tryImplementation("java.util.logging.Logger", "com.fr.third.alibaba.druid.support.logging.Jdk14LoggingImpl");
if (logConstructor == null) {
try {
@ -65,13 +64,7 @@ public class LogFactory {
try {
Resources.classForName(testClassName);
Class implClass = null;
try {
implClass = Resources.classForName(implClassName);
} catch (Throwable t) {
implClassName = "com.fr.third.alibaba.druid.support.logging." + implClassName;
implClass = Resources.classForName(implClassName);
}
Class implClass = Resources.classForName(implClassName);
logConstructor = implClass.getConstructor(new Class[] { String.class });
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) {
if (list.size() == 0) {
if (list.isEmpty()) {
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.getName());
row.add(operator);
if (values.size() == 0) {
if (values.isEmpty()) {
row.add(null);
} else if (values.size() == 1) {
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 {
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
if (stmtList.size() == 0) {
if (stmtList.isEmpty()) {
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_DRIVER = "org.mariadb.jdbc.Driver";
DbType TIDB = DbType.tidb;
String TIDB_DRIVER = "io.tidb.bigdata.jdbc.TiDBDriver";
DbType DERBY = DbType.derby;
String HBASE = "hbase";
@ -82,6 +85,7 @@ public interface JdbcConstants {
DbType OCEANBASE = DbType.oceanbase;
DbType OCEANBASE_ORACLE = DbType.oceanbase_oracle;
String OCEANBASE_DRIVER = "com.alipay.oceanbase.jdbc.Driver";
String OCEANBASE_DRIVER2 = "com.oceanbase.jdbc.Driver";
DbType INFORMIX = DbType.informix;
@ -141,4 +145,13 @@ public interface JdbcConstants {
*/
DbType GREENPLUM = DbType.greenplum;
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;
} else if (rawUrl.startsWith("jdbc:mariadb:")) {
return MARIADB_DRIVER;
} else if (rawUrl.startsWith("jdbc:tidb:")) {
return TIDB_DRIVER;
} else if (rawUrl.startsWith("jdbc:oracle:") //
|| rawUrl.startsWith("JDBC:oracle:")) {
return ORACLE_DRIVER;
@ -442,20 +444,8 @@ public final class JdbcUtils implements JdbcConstants {
} else if (rawUrl.startsWith("jdbc:odps:")) {
return ODPS_DRIVER;
} else if (rawUrl.startsWith("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("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:")) {
return "org.hsqldb.jdbcDriver";
} else if (rawUrl.startsWith("jdbc:db2:")) {
// Resolve the DB2 driver from JDBC URL
// Type2 COM.ibm.db2.jdbc.app.DB2Driver, url = jdbc:db2: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;
} else if (rawUrl.startsWith("jdbc:highgo:")) {
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 {
throw new SQLException("unknown jdbc driver : " + rawUrl);
}
@ -554,6 +548,8 @@ public final class JdbcUtils implements JdbcConstants {
return DbType.mysql;
} else if (rawUrl.startsWith("jdbc:mariadb:")) {
return DbType.mariadb;
} else if (rawUrl.startsWith("jdbc:tidb:")) {
return DbType.tidb;
} else if (rawUrl.startsWith("jdbc:oracle:") || rawUrl.startsWith("jdbc:log4jdbc:oracle:")) {
return DbType.oracle;
} else if (rawUrl.startsWith("jdbc:alibaba:oracle:")) {
@ -576,7 +572,7 @@ public final class JdbcUtils implements JdbcConstants {
return DbType.postgresql;
} else if (rawUrl.startsWith("jdbc: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;
} else if (rawUrl.startsWith("jdbc: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 {
if (DbType.mysql == dbType || DbType.oceanbase == dbType) {
if (isMysqlDbType(dbType)) {
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 {
if (DbType.mysql == dbType || DbType.oceanbase == dbType) {
if (isMysqlDbType(dbType)) {
return MySqlUtils.getCreateTableScript(conn, sorted, simplify);
}
@ -934,13 +930,13 @@ public final class JdbcUtils implements JdbcConstants {
public static boolean isOracleDbType(String dbType) {
return DbType.oracle.name().equals(dbType) || //
DbType.oceanbase.name().equals(dbType) || //
DbType.oceanbase_oracle.name().equals(dbType) || //
DbType.ali_oracle.name().equalsIgnoreCase(dbType);
}
public static boolean isOracleDbType(DbType dbType) {
return DbType.oracle == dbType || //
DbType.oceanbase == dbType || //
DbType.oceanbase_oracle == dbType || //
DbType.ali_oracle == dbType;
}
@ -957,8 +953,10 @@ public final class JdbcUtils implements JdbcConstants {
switch (dbType) {
case mysql:
case oceanbase:
case ads:
case drds:
case mariadb:
case tidb:
case h2:
return true;
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.BigInteger;
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.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.time.LocalDate;
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.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;
public class MySqlUtils {
static Class<?> utilClass;
static boolean utilClassError = false;
static boolean utilClass_isJdbc4 = false;
static Class<?> utilClass;
static boolean utilClassError = false;
static boolean utilClass_isJdbc4 = false;
static Class<?> class_5_connection= null;
static Method method_5_getPinGlobalTxToPhysicalConnection = null;
static Class<?> class_5_suspendableXAConnection = null;
static Class<?> class_5_connection = null;
static Method method_5_getPinGlobalTxToPhysicalConnection = null;
static Class<?> class_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 Class<?> class_5_MysqlXAConnection = null;
static Class<?> class_5_MysqlXAConnection = null;
static Constructor<?> constructor_5_MysqlXAConnection = null;
static Class<?> class_ConnectionImpl = null;
static Method method_getId = null;
static boolean method_getId_error = false;
static Class<?> class_ConnectionImpl = null;
static Method method_getId = null;
static boolean method_getId_error = false;
static Class<?> class_6_ConnectionImpl = null;
static Method method_6_getId = null;
static Class<?> class_6_ConnectionImpl = null;
static Method method_6_getId = null;
volatile static Class<?> class_6_connection= null;
volatile static Method method_6_getPropertySet = null;
volatile static Method method_6_getBooleanReadableProperty = null;
volatile static Method method_6_getValue = null;
volatile static boolean method_6_getValue_error = false;
volatile static Class<?> class_6_connection = null;
volatile static Method method_6_getPropertySet = null;
volatile static Method method_6_getBooleanReadableProperty = null;
volatile static Method method_6_getValue = null;
volatile static boolean method_6_getValue_error = false;
volatile static Class<?> class_6_suspendableXAConnection = null;
volatile static Method method_6_getInstance = null;
volatile static boolean method_6_getInstance_error = false;
volatile static Method method_6_getInstanceXA = null;
volatile static boolean method_6_getInstanceXA_error = false;
volatile static Class<?> class_6_JDBC4SuspendableXAConnection = null;
volatile static Class<?> class_6_suspendableXAConnection = null;
volatile static Method method_6_getInstance = null;
volatile static boolean method_6_getInstance_error = false;
volatile static Method method_6_getInstanceXA = null;
volatile static boolean method_6_getInstanceXA_error = false;
volatile static Class<?> class_6_JDBC4SuspendableXAConnection = null;
public static XAConnection createXAConnection(Driver driver, Connection physicalConn) throws SQLException {
@ -140,8 +155,7 @@ public class MySqlUtils {
.getMethod("getValue");
}
}
else {
} else {
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_getValue = Class.forName("com.mysql.cj.api.conf.ReadableProperty").getMethod("getValue");
@ -206,7 +220,7 @@ public class MySqlUtils {
return null;
}
return "KILL QUERY " + threadId;
return "KILL QUERY " + threadId;
}
@ -317,7 +331,7 @@ public class MySqlUtils {
}
String ddlScript = buf.toString();
if (! (sorted || simplify)) {
if (!(sorted || simplify)) {
return ddlScript;
}
@ -357,14 +371,16 @@ public class MySqlUtils {
}
Class<?> clazz = conn.getClass();
if (clazz.getName().equals("com.mysql.jdbc.ConnectionImpl")) {
class_ConnectionImpl = clazz;
} else if (clazz.getName().equals("com.mysql.jdbc.Connection")) { // mysql 5.0.x
class_ConnectionImpl = clazz;
} else if (clazz.getName().equals("com.mysql.cj.jdbc.ConnectionImpl")) { // mysql 5.0.x
class_ConnectionImpl = clazz;
} else if (clazz.getSuperclass().getName().equals("com.mysql.jdbc.ConnectionImpl")) {
class_ConnectionImpl = clazz.getSuperclass();
if (class_ConnectionImpl == null) {
if (clazz.getName().equals("com.mysql.jdbc.ConnectionImpl")) {
class_ConnectionImpl = clazz;
} else if (clazz.getName().equals("com.mysql.jdbc.Connection")) { // mysql 5.0.x
class_ConnectionImpl = clazz;
} else if (clazz.getName().equals("com.mysql.cj.jdbc.ConnectionImpl")) { // mysql 5.0.x
class_ConnectionImpl = clazz;
} else if (clazz.getSuperclass().getName().equals("com.mysql.jdbc.ConnectionImpl")) {
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 {
if (!class_connectionImpl_Error) {
if (class_connectionImpl == null && !class_connectionImpl_Error) {
try {
mysqlJdbcVersion6 = false;
class_connectionImpl = Utils.loadClass("com.mysql.jdbc.MySQLConnection");
if (class_connectionImpl == null || class_connectionImpl.getClassLoader() != conn.getClass().getClassLoader()) {
class_connectionImpl = Utils.loadClass("com.mysql.cj.MysqlConnection");
@ -405,13 +420,15 @@ public class MySqlUtils {
}
if(mysqlJdbcVersion6){
classJdbc = Utils.loadClass("com.mysql.cj.jdbc.JdbcConnection");
if (classJdbc == null) {
classJdbc = Utils.loadClass("com.mysql.cj.jdbc.JdbcConnection");
}
if (classJdbc == null) {
return -1;
}
if (!getIdleForError) {
if (getIdleFor == null && !getIdleForError) {
try {
getIdleFor = classJdbc.getMethod("getIdleFor");
getIdleFor.setAccessible(true);
@ -432,13 +449,13 @@ public class MySqlUtils {
return System.currentTimeMillis()
- ((Long)
getIdleFor.invoke(connImpl))
getIdleFor.invoke(connImpl))
.longValue();
} catch (Exception e) {
throw new SQLException("getIdleFor error", e);
}
} else {
if (!method_getIO_error) {
if (method_getIO == null && !method_getIO_error) {
try {
method_getIO = class_connectionImpl.getMethod("getIO");
} catch (Throwable error) {
@ -450,7 +467,7 @@ public class MySqlUtils {
return -1;
}
if (!class_MysqlIO_Error) {
if (class_MysqlIO == null && !class_MysqlIO_Error) {
try {
class_MysqlIO = Utils.loadClass("com.mysql.jdbc.MysqlIO");
} catch (Throwable error) {
@ -462,7 +479,7 @@ public class MySqlUtils {
return -1;
}
if (!method_getLastPacketReceivedTimeMs_error) {
if (method_getLastPacketReceivedTimeMs == null && !method_getLastPacketReceivedTimeMs_error) {
try {
Method method = class_MysqlIO.getDeclaredMethod("getLastPacketReceivedTimeMs");
method.setAccessible(true);
@ -515,12 +532,12 @@ public class MySqlUtils {
return null;
}
public final static Charset GBK = Charset.forName("GBK");
public final static Charset BIG5 = Charset.forName("BIG5");
public final static Charset UTF8 = Charset.forName("UTF-8");
public final static Charset UTF16 = Charset.forName("UTF-16");
public final static Charset UTF32 = Charset.forName("UTF-32");
public final static Charset ASCII = Charset.forName("ASCII");
public final static Charset GBK = Charset.forName("GBK");
public final static Charset BIG5 = Charset.forName("BIG5");
public final static Charset UTF8 = Charset.forName("UTF-8");
public final static Charset UTF16 = Charset.forName("UTF-16");
public final static Charset UTF32 = Charset.forName("UTF-32");
public final static Charset ASCII = Charset.forName("ASCII");
public static void loadDataTypes(Set<String> dataTypes) {
@ -1125,8 +1142,7 @@ public class MySqlUtils {
// yyyy-MM-dd HH.mm.ss
if (c4 == '-' && c7 == '-'
&& (c10 == ' ' || c10 == 'T')
&& ((c13 == ':' && c16 == ':') || (c13 == '.' && c16 == '.')))
{
&& ((c13 == ':' && c16 == ':') || (c13 == '.' && c16 == '.'))) {
M0 = c5;
M1 = c6;
d0 = c8;
@ -1186,7 +1202,7 @@ public class MySqlUtils {
return null;
}
nanos = (c23 - '0') * 100000
nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000
+ (c25 - '0') * 1000
+ (c26 - '0') * 100
@ -1302,7 +1318,7 @@ public class MySqlUtils {
S2 = x0;
lastOff = length - 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);
lastOff = length - 4;
} else {
@ -1583,8 +1599,7 @@ public class MySqlUtils {
// yyyy-MM-dd HH:mm:ss
if (c4 == '-' && c7 == '-'
&& (c10 == ' ' || c10 == 'T')
&& c13 == ':' && c16 == ':')
{
&& c13 == ':' && c16 == ':') {
M0 = c5;
M1 = c6;
d0 = c8;
@ -1645,7 +1660,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8));
}
nanos = (c23 - '0') * 100000
nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000
+ (c25 - '0') * 1000
+ (c26 - '0') * 100
@ -1666,7 +1681,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8));
}
nanos = (c23 - '0') * 100000
nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000
+ (c25 - '0') * 1000
+ (c26 - '0') * 100
@ -1684,7 +1699,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8));
}
nanos = (c23 - '0') * 100000
nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000
+ (c25 - '0') * 1000
+ (c26 - '0') * 100;
@ -1699,7 +1714,7 @@ public class MySqlUtils {
throw new IllegalArgumentException(new String(str, UTF8));
}
nanos = (c23 - '0') * 100000
nanos = (c23 - '0') * 100000
+ (c24 - '0') * 10000
+ (c25 - '0') * 1000;
}
@ -1908,7 +1923,7 @@ public class MySqlUtils {
return zdt;
}
private final static String[] parseFormats = new String[] {
private final static String[] parseFormats = new String[]{
"HH:mm:ss",
"yyyyMMdd",
"yyyyMMddHHmmss",
@ -1924,7 +1939,8 @@ public class MySqlUtils {
"yyyy-MM-dd'T'HH:mm:ss.SSS",
};
private final static long[] parseFormatCodes;
static {
static {
long[] codes = new long[parseFormats.length];
for (int i = 0; i < parseFormats.length; 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) {
Class<?> clazz = null;
if (className == null) {
return null;
}
ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
if (ctxClassLoader != null) {
try {
return ctxClassLoader.loadClass(className);
} catch (ClassNotFoundException e) {
// skip
}
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
// skip
}
try {
return ClassLoaderFactory.loadClass(className);
} catch (ClassNotFoundException e) {
// skip
ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
if (ctxClassLoader != null) {
try {
clazz = ctxClassLoader.loadClass(className);
} catch (ClassNotFoundException e) {
// skip
}
}
return null;
return clazz;
}
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 drds:
case mariadb:
case tidb:
case h2:
case presto:
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){
super(config, DbType.postgresql);
super(config, DbType.clickhouse);
}
@Override

Loading…
Cancel
Save