Compare commits
No commits in common. "844b288a185feb4b9b617ead71d963b7a2629863" and "4e06d7c21bc2f7136363ebd82b59db6c61daabee" have entirely different histories.
844b288a18
...
4e06d7c21b
26 changed files with 275 additions and 272 deletions
|
@ -15,10 +15,10 @@ ext {
|
|||
description = 'JDBC connection pool and utilities'
|
||||
inceptionYear = '2018'
|
||||
url = 'https://xbib.org/' + user + '/' + name
|
||||
scmUrl = url
|
||||
scmUrl = 'https://xbib.org/' + user + '/' + name
|
||||
scmConnection = 'scm:git:git://xbib.org/' + user + '/' + name + '.git'
|
||||
scmDeveloperConnection = 'scm:git:ssh://forgejo@xbib.org:' + user + '/' + name + '.git'
|
||||
issueManagementSystem = 'Forgejo'
|
||||
issueManagementSystem = 'Github'
|
||||
issueManagementUrl = ext.scmUrl + '/issues'
|
||||
licenseName = 'The Apache License, Version 2.0'
|
||||
licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
group = org.xbib
|
||||
name = database
|
||||
version = 2.2.0
|
||||
version = 2.0.2
|
||||
|
||||
org.gradle.warning.mode = ALL
|
||||
|
|
|
@ -19,7 +19,7 @@ jar {
|
|||
tasks.withType(JavaCompile) {
|
||||
options.fork = true
|
||||
options.forkOptions.jvmArgs += ['-Duser.language=en','-Duser.country=US']
|
||||
options.compilerArgs << '-Xlint:all,-exports'
|
||||
options.compilerArgs << '-Xlint:all'
|
||||
options.encoding = 'UTF-8'
|
||||
}
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@ if (project.hasProperty('forgeJoToken')) {
|
|||
publishing {
|
||||
repositories {
|
||||
maven {
|
||||
url project.property('forgeJoUrl')
|
||||
url 'https://xbib.org/api/packages/joerg/maven'
|
||||
credentials(HttpHeaderCredentials) {
|
||||
name = "Authorization"
|
||||
value = "token ${project.property('forgeJoToken')}"
|
||||
|
|
27
gradle/publish/ivy.gradle
Normal file
27
gradle/publish/ivy.gradle
Normal file
|
@ -0,0 +1,27 @@
|
|||
apply plugin: 'ivy-publish'
|
||||
|
||||
publishing {
|
||||
repositories {
|
||||
ivy {
|
||||
url = "https://xbib.org/repo"
|
||||
}
|
||||
}
|
||||
publications {
|
||||
ivy(IvyPublication) {
|
||||
from components.java
|
||||
descriptor {
|
||||
license {
|
||||
name = 'The Apache License, Version 2.0'
|
||||
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
|
||||
}
|
||||
author {
|
||||
name = 'Jörg Prante'
|
||||
url = 'http://example.com/users/jane'
|
||||
}
|
||||
descriptor.description {
|
||||
text = rootProject.ext.description
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -19,7 +19,7 @@ publishing {
|
|||
id = 'jprante'
|
||||
name = 'Jörg Prante'
|
||||
email = 'joergprante@gmail.com'
|
||||
url = 'https://xbib.org/joerg'
|
||||
url = 'https://github.com/jprante'
|
||||
}
|
||||
}
|
||||
scm {
|
||||
|
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
2
gradle/wrapper/gradle-wrapper.properties
vendored
2
gradle/wrapper/gradle-wrapper.properties
vendored
|
@ -1,6 +1,6 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-all.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
|
20
gradlew.bat
vendored
20
gradlew.bat
vendored
|
@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
|
|||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
|
@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
|||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
|
|
|
@ -118,8 +118,7 @@ public class Pool implements BagStateListener {
|
|||
*
|
||||
* @param config the config
|
||||
*/
|
||||
public Pool(PoolConfig config) throws ClassNotFoundException,
|
||||
NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
|
||||
public Pool(PoolConfig config) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
|
||||
config.validate();
|
||||
this.config = config;
|
||||
logger.log(Level.INFO, () -> "starting new pool: " + config.getPoolName());
|
||||
|
@ -147,26 +146,16 @@ public class Pool implements BagStateListener {
|
|||
checkFailFast(initializationTimeout);
|
||||
}
|
||||
ThreadFactory threadFactory = config.getThreadFactory();
|
||||
ClassLoader contextClassLoader = config.getContextClassLoader();
|
||||
int maxPoolSize = config.getMaximumPoolSize();
|
||||
LinkedBlockingQueue<Runnable> addConnectionQueue = new LinkedBlockingQueue<>(maxPoolSize);
|
||||
this.addConnectionQueueReadOnlyView = Collections.unmodifiableCollection(addConnectionQueue);
|
||||
this.addConnectionExecutor = createThreadPoolExecutor(addConnectionQueue,
|
||||
poolName + " connection adder",
|
||||
threadFactory,
|
||||
contextClassLoader,
|
||||
new ThreadPoolExecutor.DiscardOldestPolicy());
|
||||
this.closeConnectionExecutor = createThreadPoolExecutor(maxPoolSize,
|
||||
poolName + " connection closer",
|
||||
threadFactory,
|
||||
contextClassLoader,
|
||||
new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
this.addConnectionExecutor = createThreadPoolExecutor(addConnectionQueue, poolName + " connection adder", threadFactory, new ThreadPoolExecutor.DiscardOldestPolicy());
|
||||
this.closeConnectionExecutor = createThreadPoolExecutor(maxPoolSize, poolName + " connection closer", threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
this.leakTaskFactory = new ProxyLeakTaskFactory(config.getLeakDetectionThreshold(), houseKeepingExecutorService);
|
||||
this.houseKeeperTask = houseKeepingExecutorService.scheduleWithFixedDelay(new HouseKeeper(this), 100L, config.getHousekeepingPeriodMs(), TimeUnit.MILLISECONDS);
|
||||
if (Boolean.getBoolean("org.xbib.jdbc.connection.pool.blockUntilFilled") && config.getInitializationFailTimeout() > 1) {
|
||||
int procs = Math.min(16, Runtime.getRuntime().availableProcessors());
|
||||
addConnectionExecutor.setCorePoolSize(procs);
|
||||
addConnectionExecutor.setMaximumPoolSize(procs);
|
||||
addConnectionExecutor.setCorePoolSize(Math.min(16, Runtime.getRuntime().availableProcessors()));
|
||||
addConnectionExecutor.setMaximumPoolSize(Math.min(16, Runtime.getRuntime().availableProcessors()));
|
||||
final long startTime = ClockSource.currentTime();
|
||||
while (ClockSource.elapsedMillis(startTime) < config.getInitializationFailTimeout() && getTotalConnections() < config.getMinimumIdle()) {
|
||||
quietlySleep(TimeUnit.MILLISECONDS.toMillis(100));
|
||||
|
@ -314,11 +303,8 @@ public class Pool implements BagStateListener {
|
|||
addConnectionExecutor.awaitTermination(getLoginTimeout(), TimeUnit.SECONDS);
|
||||
destroyHouseKeepingExecutorService();
|
||||
bag.close();
|
||||
final ExecutorService assassinExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(),
|
||||
poolName + " connection assassinator",
|
||||
config.getThreadFactory(),
|
||||
config.getContextClassLoader(),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
final ExecutorService assassinExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), poolName + " connection assassinator",
|
||||
config.getThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
try {
|
||||
final long start = ClockSource.currentTime();
|
||||
do {
|
||||
|
@ -427,7 +413,6 @@ public class Pool implements BagStateListener {
|
|||
if (ds == null) {
|
||||
String dsClassName = config.getDataSourceClassName();
|
||||
if (dsClassName != null) {
|
||||
// we must use the system class loader
|
||||
Class<?> clazz = Class.forName(dsClassName, true, ClassLoader.getSystemClassLoader());
|
||||
ds = (DataSource) clazz.getDeclaredConstructor().newInstance();
|
||||
} else if (url != null) {
|
||||
|
@ -829,8 +814,7 @@ public class Pool implements BagStateListener {
|
|||
private ScheduledExecutorService initializeHouseKeepingExecutorService() {
|
||||
if (config.getScheduledExecutor() == null) {
|
||||
ThreadFactory threadFactory = Optional.ofNullable(config.getThreadFactory()).orElseGet(() ->
|
||||
new DefaultThreadFactory(poolName + "-housekeeper",
|
||||
Thread.currentThread().getContextClassLoader(), true));
|
||||
new DefaultThreadFactory(poolName + "-housekeeper", true));
|
||||
ScheduledThreadPoolExecutor executor =
|
||||
new ScheduledThreadPoolExecutor(1, threadFactory,
|
||||
new ThreadPoolExecutor.DiscardPolicy());
|
||||
|
@ -883,18 +867,16 @@ public class Pool implements BagStateListener {
|
|||
*
|
||||
* @param queueSize the queue size
|
||||
* @param threadName the thread name
|
||||
* @param threadFactory an optional ThreadFactory, if null, a DefaultThreadFactory will be used
|
||||
* @param contextClassLoader the context class loader if the thread factory is null
|
||||
* @param threadFactory an optional ThreadFactory
|
||||
* @param policy the RejectedExecutionHandler policy
|
||||
* @return a ThreadPoolExecutor
|
||||
*/
|
||||
private ThreadPoolExecutor createThreadPoolExecutor(int queueSize,
|
||||
String threadName,
|
||||
ThreadFactory threadFactory,
|
||||
ClassLoader contextClassLoader,
|
||||
RejectedExecutionHandler policy) {
|
||||
if (threadFactory == null) {
|
||||
threadFactory = new DefaultThreadFactory(threadName, contextClassLoader, true);
|
||||
threadFactory = new DefaultThreadFactory(threadName, true);
|
||||
}
|
||||
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(queueSize);
|
||||
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,
|
||||
|
@ -915,10 +897,9 @@ public class Pool implements BagStateListener {
|
|||
private ThreadPoolExecutor createThreadPoolExecutor(BlockingQueue<Runnable> queue,
|
||||
String threadName,
|
||||
ThreadFactory threadFactory,
|
||||
ClassLoader contextClassLoader,
|
||||
RejectedExecutionHandler policy) {
|
||||
if (threadFactory == null) {
|
||||
threadFactory = new DefaultThreadFactory(threadName, contextClassLoader, true);
|
||||
threadFactory = new DefaultThreadFactory(threadName, true);
|
||||
}
|
||||
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,
|
||||
5, TimeUnit.SECONDS, queue, threadFactory, policy);
|
||||
|
@ -994,7 +975,7 @@ public class Pool implements BagStateListener {
|
|||
*
|
||||
* @return true if we should create a connection, false if the need has disappeared
|
||||
*/
|
||||
public synchronized boolean shouldCreateAnotherConnection() {
|
||||
synchronized boolean shouldCreateAnotherConnection() {
|
||||
return getTotalConnections() < config.getMaximumPoolSize() &&
|
||||
(bag.getWaitingThreadCount() > 0 || getIdleConnections() < config.getMinimumIdle());
|
||||
}
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package org.xbib.jdbc.connection.pool;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.sql.Connection;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
|
@ -75,8 +74,6 @@ public class PoolConfig {
|
|||
|
||||
private ThreadFactory threadFactory;
|
||||
|
||||
private ClassLoader contextClassLoader;
|
||||
|
||||
private ScheduledExecutorService scheduledExecutor;
|
||||
|
||||
/**
|
||||
|
@ -300,15 +297,6 @@ public class PoolConfig {
|
|||
this.dataSource = dataSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the fully qualified class name of the JDBC {@link DataSource} that will be used create Connections.
|
||||
*
|
||||
* @param className the fully qualified name of the JDBC {@link DataSource} class
|
||||
*/
|
||||
public void setDataSourceClassName(String className) {
|
||||
this.dataSourceClassName = className;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the JDBC {@link DataSource} class used to create Connections.
|
||||
*
|
||||
|
@ -318,6 +306,15 @@ public class PoolConfig {
|
|||
return dataSourceClassName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the fully qualified class name of the JDBC {@link DataSource} that will be used create Connections.
|
||||
*
|
||||
* @param className the fully qualified name of the JDBC {@link DataSource} class
|
||||
*/
|
||||
public void setDataSourceClassName(String className) {
|
||||
this.dataSourceClassName = className;
|
||||
}
|
||||
|
||||
public Properties getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
@ -327,47 +324,23 @@ public class PoolConfig {
|
|||
}
|
||||
|
||||
public void setDriverClassName(String driverClassName) {
|
||||
Class<?> driverClass = null;
|
||||
ClassLoader threadContextClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
if (threadContextClassLoader != null) {
|
||||
try {
|
||||
driverClass = threadContextClassLoader.loadClass(driverClassName);
|
||||
if (driverClass != null) {
|
||||
logger.log(Level.FINE, () -> "driver class found in thread context class loader:" + driverClassName);
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
logger.log(Level.FINE, () -> "failed to load driver class from thread context class loader" + driverClassName);
|
||||
}
|
||||
}
|
||||
Class<?> driverClass = attemptFromContextLoader(driverClassName);
|
||||
try {
|
||||
if (driverClass == null) {
|
||||
driverClass = getClass().getClassLoader().loadClass(driverClassName);
|
||||
if (driverClass != null) {
|
||||
logger.log(Level.FINE, () -> "driver class found in the class classloader: " + driverClassName);
|
||||
}
|
||||
driverClass = this.getClass().getClassLoader().loadClass(driverClassName);
|
||||
logger.log(Level.FINE, () -> "driver class found in the PoolConfig class classloader: " + driverClassName + " " + this.getClass().getClassLoader());
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
logger.log(Level.FINE, () -> "failed to load driver class from class classloader: " + driverClassName);
|
||||
}
|
||||
try {
|
||||
if (driverClass == null) {
|
||||
driverClass = ClassLoader.getSystemClassLoader().loadClass(driverClassName);
|
||||
if (driverClass != null) {
|
||||
logger.log(Level.FINE, () -> "driver class found in the system class classloader: " + driverClassName);
|
||||
|
||||
}
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
logger.log(Level.SEVERE, () -> "failed to load driver class from system class classloader: " + driverClassName);
|
||||
logger.log(Level.SEVERE, "failed to load driver class from PoolConfig class classloader: " + driverClassName + " " + this.getClass().getClassLoader());
|
||||
}
|
||||
if (driverClass == null) {
|
||||
throw new IllegalStateException("failed to load driver class " + driverClassName);
|
||||
throw new RuntimeException("failed to load driver class " + driverClassName + " in either of PoolConfig class loader or Thread context classloader");
|
||||
}
|
||||
try {
|
||||
driverClass.getConstructor().newInstance();
|
||||
this.driverClassName = driverClassName;
|
||||
} catch (InstantiationException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
|
||||
throw new IllegalStateException("failed to instantiate class " + driverClassName, e);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to instantiate class " + driverClassName, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -576,15 +549,6 @@ public class PoolConfig {
|
|||
return housekeepingPeriodMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the thread factory to be used to create threads.
|
||||
*
|
||||
* @param threadFactory the thread factory (setting to null causes the default thread factory to be used)
|
||||
*/
|
||||
public void setThreadFactory(ThreadFactory threadFactory) {
|
||||
this.threadFactory = threadFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the thread factory used to create threads.
|
||||
*
|
||||
|
@ -594,12 +558,29 @@ public class PoolConfig {
|
|||
return threadFactory;
|
||||
}
|
||||
|
||||
public void setContextClassLoader(ClassLoader contextClassLoader) {
|
||||
this.contextClassLoader = contextClassLoader;
|
||||
/**
|
||||
* Set the thread factory to be used to create threads.
|
||||
*
|
||||
* @param threadFactory the thread factory (setting to null causes the default thread factory to be used)
|
||||
*/
|
||||
public void setThreadFactory(ThreadFactory threadFactory) {
|
||||
this.threadFactory = threadFactory;
|
||||
}
|
||||
|
||||
public ClassLoader getContextClassLoader() {
|
||||
return contextClassLoader != null ? contextClassLoader : Thread.currentThread().getContextClassLoader();
|
||||
private Class<?> attemptFromContextLoader(String driverClassName) {
|
||||
ClassLoader threadContextClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
if (threadContextClassLoader != null) {
|
||||
try {
|
||||
Class<?> driverClass = threadContextClassLoader.loadClass(driverClassName);
|
||||
logger.log(Level.FINE, "Driver class found in Thread context class loader:" +
|
||||
driverClassName + " " + threadContextClassLoader);
|
||||
return driverClass;
|
||||
} catch (ClassNotFoundException e) {
|
||||
logger.log(Level.FINE, "Driver class not found in Thread context class loader, trying classloader: " +
|
||||
driverClassName + " " + threadContextClassLoader + " " + this.getClass().getClassLoader());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("StatementWithEmptyBody")
|
||||
|
|
|
@ -31,8 +31,7 @@ public class PoolEntryCreator implements Callable<Boolean> {
|
|||
final PoolEntry poolEntry = pool.createPoolEntry();
|
||||
if (poolEntry != null) {
|
||||
pool.bag.add(poolEntry);
|
||||
logger.log(Level.FINE, () -> MessageFormat.format("{0}: added connection {1} ",
|
||||
pool.poolName, poolEntry.getConnection()));
|
||||
logger.log(Level.FINE, () -> MessageFormat.format("{0}: added connection {1} ", pool.poolName, poolEntry.getConnection()));
|
||||
if (loggingPrefix != null) {
|
||||
pool.logPoolState(loggingPrefix);
|
||||
}
|
||||
|
|
|
@ -6,15 +6,10 @@ public class DefaultThreadFactory implements ThreadFactory {
|
|||
|
||||
private final String threadName;
|
||||
|
||||
private final ClassLoader contextClassLoader;
|
||||
|
||||
private final boolean daemon;
|
||||
|
||||
public DefaultThreadFactory(String threadName,
|
||||
ClassLoader contextClassLoader,
|
||||
boolean daemon) {
|
||||
public DefaultThreadFactory(String threadName, boolean daemon) {
|
||||
this.threadName = threadName;
|
||||
this.contextClassLoader = contextClassLoader;
|
||||
this.daemon = daemon;
|
||||
}
|
||||
|
||||
|
@ -22,7 +17,6 @@ public class DefaultThreadFactory implements ThreadFactory {
|
|||
public Thread newThread(Runnable r) {
|
||||
Thread thread = new Thread(r, threadName);
|
||||
thread.setDaemon(daemon);
|
||||
thread.setContextClassLoader(contextClassLoader);
|
||||
return thread;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,36 +17,24 @@ public class DriverDataSource implements DataSource {
|
|||
|
||||
private static final Logger logger = Logger.getLogger(DriverDataSource.class.getName());
|
||||
|
||||
static {
|
||||
DriverManager.setLogWriter(new PrintWriter(new LoggingOutputStream(logger)));
|
||||
DriverManager.drivers().forEach(d -> logger.log(Level.INFO, "found driver " + d));
|
||||
}
|
||||
|
||||
private static final String PASSWORD = "password";
|
||||
|
||||
private static final String USER = "user";
|
||||
|
||||
private static final String AUTOCOMMIT = "autocommit";
|
||||
|
||||
private final Properties driverProperties;
|
||||
|
||||
private String jdbcUrl;
|
||||
|
||||
private final Properties driverProperties;
|
||||
|
||||
private Driver driver;
|
||||
|
||||
public DriverDataSource(String jdbcUrl,
|
||||
String driverClassName,
|
||||
Properties properties,
|
||||
String username,
|
||||
String password) {
|
||||
public DriverDataSource(String jdbcUrl, String driverClassName, Properties properties, String username, String password) {
|
||||
this.jdbcUrl = jdbcUrl;
|
||||
this.driverProperties = new Properties();
|
||||
for (Entry<Object, Object> entry : properties.entrySet()) {
|
||||
driverProperties.setProperty(entry.getKey().toString(), entry.getValue().toString());
|
||||
}
|
||||
if (jdbcUrl != null) {
|
||||
logger.log(Level.INFO, () -> "DriverManager looking for JDBC URL " + jdbcUrl);
|
||||
}
|
||||
if (username != null) {
|
||||
setUser(username);
|
||||
}
|
||||
|
@ -63,25 +51,25 @@ public class DriverDataSource implements DataSource {
|
|||
}
|
||||
}
|
||||
if (driver == null) {
|
||||
logger.log(Level.WARNING, "Registered driver with driverClassName was not found, trying direct instantiation: " + driverClassName);
|
||||
logger.warning("Registered driver with driverClassName was not found, trying direct instantiation: " + driverClassName);
|
||||
Class<?> driverClass = null;
|
||||
ClassLoader threadContextClassLoader = Thread.currentThread().getContextClassLoader();
|
||||
try {
|
||||
if (threadContextClassLoader != null) {
|
||||
try {
|
||||
driverClass = threadContextClassLoader.loadClass(driverClassName);
|
||||
logger.log(Level.FINE, "Driver class found in Thread context class loader: " + driverClassName + " " + threadContextClassLoader);
|
||||
logger.fine("Driver class found in Thread context class loader: " + driverClassName + " " + threadContextClassLoader);
|
||||
} catch (ClassNotFoundException e) {
|
||||
logger.log(Level.FINE, "Driver class not found in Thread context class loader, trying classloader: " +
|
||||
logger.fine("Driver class not found in Thread context class loader, trying classloader: " +
|
||||
driverClassName + " " + threadContextClassLoader + " " + this.getClass().getClassLoader());
|
||||
}
|
||||
}
|
||||
if (driverClass == null) {
|
||||
driverClass = this.getClass().getClassLoader().loadClass(driverClassName);
|
||||
logger.log(Level.FINE, "Driver class found in the PoolConfig class classloader:" + driverClassName + " " + this.getClass().getClassLoader());
|
||||
logger.fine("Driver class found in the PoolConfig class classloader:" + driverClassName + " " + this.getClass().getClassLoader());
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
logger.log(Level.FINE, "Failed to load driver class from PoolConfig class classloader: " + driverClassName + " " + this.getClass().getClassLoader());
|
||||
logger.fine("Failed to load driver class from PoolConfig class classloader: " + driverClassName + " " + this.getClass().getClassLoader());
|
||||
}
|
||||
if (driverClass != null) {
|
||||
try {
|
||||
|
@ -92,17 +80,16 @@ public class DriverDataSource implements DataSource {
|
|||
}
|
||||
}
|
||||
}
|
||||
if (driver == null && jdbcUrl != null) {
|
||||
final String sanitizedUrl = jdbcUrl.replaceAll("([?&;][^&#;=]*[pP]assword=)[^&#;]*", "$1<masked>");
|
||||
try {
|
||||
final String sanitizedUrl = jdbcUrl.replaceAll("([?&;][^&#;=]*[pP]assword=)[^&#;]*", "$1<masked>");
|
||||
try {
|
||||
if (driver == null) {
|
||||
driver = DriverManager.getDriver(jdbcUrl);
|
||||
logger.log(Level.FINE, "Loaded driver with class name for jdbcUrl " + driver.getClass().getName() + " " + sanitizedUrl);
|
||||
if (!driver.acceptsURL(sanitizedUrl)) {
|
||||
throw new RuntimeException("Driver " + driverClassName + " claims to not accept jdbcUrl " + sanitizedUrl);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException("Failed to get driver instance for jdbcUrl " + sanitizedUrl, e);
|
||||
logger.fine("Loaded driver with class name for jdbcUrl " + driver.getClass().getName() + " " + sanitizedUrl);
|
||||
} else if (!driver.acceptsURL(jdbcUrl)) {
|
||||
throw new RuntimeException("Driver " + driverClassName + " claims to not accept jdbcUrl " + sanitizedUrl);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException("Failed to get driver instance for jdbcUrl " + sanitizedUrl, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,26 +0,0 @@
|
|||
package org.xbib.jdbc.connection.pool.util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class LoggingOutputStream extends ByteArrayOutputStream {
|
||||
|
||||
private final Logger logger;
|
||||
|
||||
public LoggingOutputStream(Logger logger) {
|
||||
super();
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException {
|
||||
super.flush();
|
||||
String s = new String(buf, 0, count);
|
||||
if (!s.isEmpty()) {
|
||||
logger.log(Level.FINE, s);
|
||||
}
|
||||
reset();
|
||||
}
|
||||
}
|
|
@ -17,10 +17,8 @@ public class HouseKeeperCleanupTest {
|
|||
private ScheduledThreadPoolExecutor executor;
|
||||
|
||||
@BeforeEach
|
||||
public void before() {
|
||||
ThreadFactory threadFactory = new DefaultThreadFactory("global-housekeeper",
|
||||
Thread.currentThread().getContextClassLoader(),
|
||||
true);
|
||||
public void before() throws Exception {
|
||||
ThreadFactory threadFactory = new DefaultThreadFactory("global-housekeeper", true);
|
||||
executor = new ScheduledThreadPoolExecutor(1, threadFactory,
|
||||
new ThreadPoolExecutor.DiscardPolicy());
|
||||
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
|
||||
|
|
|
@ -27,6 +27,7 @@ public class MariaDBTest extends CommonTest {
|
|||
static MariaDBContainer<?> mariaDBContainer;
|
||||
|
||||
static {
|
||||
// mariadb 10.3.6
|
||||
mariaDBContainer = new MariaDBContainer<>("mariadb")
|
||||
.withDatabaseName("testDB")
|
||||
.withUsername("testUser")
|
||||
|
@ -44,7 +45,7 @@ public class MariaDBTest extends CommonTest {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected DatabaseProvider createDatabaseProvider(OptionsOverride options) {
|
||||
protected DatabaseProvider createDatabaseProvider(OptionsOverride options) throws Exception {
|
||||
Config config = ConfigSupplier.of()
|
||||
.property("database.url", mariaDBContainer.getJdbcUrl())
|
||||
.property("database.user", "testUser")
|
||||
|
@ -94,14 +95,12 @@ public class MariaDBTest extends CommonTest {
|
|||
}
|
||||
|
||||
@Disabled("MariaDB temporarily disabled")
|
||||
@Test
|
||||
@Override
|
||||
public void intervals() {
|
||||
super.intervals();
|
||||
}
|
||||
|
||||
@Disabled("MariaDB temporarily disabled")
|
||||
@Test
|
||||
@Override
|
||||
public void metadataColumnTypes() {
|
||||
super.metadataColumnTypes();
|
||||
|
@ -252,4 +251,5 @@ public class MariaDBTest extends CommonTest {
|
|||
+ " str_varchar, str_fixed, str_lob, bin_blob, boolean_flag, date_millis, local_date from dbtest2 order by 1")
|
||||
.queryMany(SqlArgs::readRow));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -14,9 +14,6 @@ import org.xbib.jdbc.query.OptionsOverride;
|
|||
import org.xbib.jdbc.query.Schema;
|
||||
import org.xbib.jdbc.test.CommonTest;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Exercise Database functionality with a real Oracle database.
|
||||
*/
|
||||
|
@ -81,16 +78,4 @@ public class OracleTest extends CommonTest {
|
|||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTableExists() {
|
||||
db.dropTableQuietly("dbtest");
|
||||
new Schema().addTable("dbtest").addColumn("pk").primaryKey().schema().execute(db);
|
||||
assertTrue(db.tableExists("dbtest"));
|
||||
db.dropTableQuietly("dbtest");
|
||||
assertFalse(db.tableExists("dbtest"));
|
||||
db.ddl("create table \"dbtest\" (pk varchar(1))").execute();
|
||||
assertTrue(db.tableExists("dbtest"));
|
||||
db.dropTableQuietly("dbtest");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,7 +4,7 @@ import org.xbib.jdbc.postgresql.Postgresql;
|
|||
module org.xbib.jdbc.postgresql {
|
||||
requires org.xbib.jdbc.query;
|
||||
requires java.sql;
|
||||
requires org.postgresql.jdbc; // automatic module
|
||||
requires org.postgresql.jdbc;
|
||||
uses Flavor;
|
||||
exports org.xbib.jdbc.postgresql;
|
||||
provides Flavor with Postgresql;
|
||||
|
|
|
@ -35,7 +35,6 @@ public class Listener implements Runnable {
|
|||
while (true) {
|
||||
try (Statement stmt = connection.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("SELECT 1")) {
|
||||
//
|
||||
} catch (SQLException e) {
|
||||
errorConsumer.accept(e);
|
||||
}
|
||||
|
|
|
@ -102,7 +102,7 @@ public class DatabaseImpl implements Database {
|
|||
@Override
|
||||
public void commitNow() {
|
||||
if (options.ignoreTransactionControl()) {
|
||||
logger.log(Level.FINE, "Ignoring call to commitNow()");
|
||||
logger.fine("Ignoring call to commitNow()");
|
||||
return;
|
||||
}
|
||||
if (!options.allowTransactionControl()) {
|
||||
|
@ -118,7 +118,7 @@ public class DatabaseImpl implements Database {
|
|||
@Override
|
||||
public void rollbackNow() {
|
||||
if (options.ignoreTransactionControl()) {
|
||||
logger.log(Level.FINE, "Ignoring call to rollbackNow()");
|
||||
logger.fine("Ignoring call to rollbackNow()");
|
||||
return;
|
||||
}
|
||||
if (!options.allowTransactionControl()) {
|
||||
|
@ -200,22 +200,12 @@ public class DatabaseImpl implements Database {
|
|||
public boolean tableExists(String tableName, String schemaName) throws DatabaseException {
|
||||
if (tableName != null && connection != null) {
|
||||
try {
|
||||
// schema based check
|
||||
DatabaseMetaData metadata = connection.getMetaData();
|
||||
String normalizedTable = flavor().normalizeTableName(tableName);
|
||||
try (ResultSet resultSet = metadata.getTables(connection.getCatalog(), schemaName, normalizedTable, new String[]{"TABLE", "VIEW"})) {
|
||||
while (resultSet.next()) {
|
||||
if (normalizedTable.equals(resultSet.getString("TABLE_NAME"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// otherwise, do a simple check
|
||||
try (ResultSet resultSet = metadata.getTables(null, null, tableName, null) ) {
|
||||
while (resultSet.next()) {
|
||||
if (tableName.equals(resultSet.getString("TABLE_NAME"))) {
|
||||
return true;
|
||||
}
|
||||
ResultSet resultSet = metadata.getTables(connection.getCatalog(), schemaName, normalizedTable, new String[]{"TABLE", "VIEW"});
|
||||
while (resultSet.next()) {
|
||||
if (normalizedTable.equals(resultSet.getString("TABLE_NAME"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (SQLException exc) {
|
||||
|
@ -465,15 +455,20 @@ public class DatabaseImpl implements Database {
|
|||
return;
|
||||
}
|
||||
params.forEach((k, v) -> {
|
||||
switch (v) {
|
||||
case String s -> sql.argString(k, s);
|
||||
case Integer i -> sql.argInteger(k, i);
|
||||
case Long l -> sql.argLong(k, l);
|
||||
case Boolean b -> sql.argBoolean(k, b);
|
||||
case LocalDate localDate -> sql.argLocalDate(k, localDate);
|
||||
case LocalDateTime localDateTime -> sql.argLocalDateTime(k, localDateTime);
|
||||
case null, default ->
|
||||
throw new DatabaseException("unknown type for param: " + (v != null ? v.getClass() : "null"));
|
||||
if (v instanceof String) {
|
||||
sql.argString(k, (String) v);
|
||||
} else if (v instanceof Integer) {
|
||||
sql.argInteger(k, (Integer) v);
|
||||
} else if (v instanceof Long) {
|
||||
sql.argLong(k, (Long) v);
|
||||
} else if (v instanceof Boolean) {
|
||||
sql.argBoolean(k, (Boolean) v);
|
||||
} else if (v instanceof LocalDate) {
|
||||
sql.argLocalDate(k, (LocalDate) v);
|
||||
} else if (v instanceof LocalDateTime) {
|
||||
sql.argLocalDateTime(k, (LocalDateTime) v);
|
||||
} else {
|
||||
throw new DatabaseException("unknown type for param: " + (v != null ? v.getClass() : "null"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -483,15 +478,22 @@ public class DatabaseImpl implements Database {
|
|||
return;
|
||||
}
|
||||
params.forEach((k, v) -> {
|
||||
switch (v) {
|
||||
case String s -> sql.argString(k, s);
|
||||
case Integer i -> sql.argInteger(k, i);
|
||||
case Long l -> sql.argLong(k, l);
|
||||
case Boolean b -> sql.argBoolean(k, b);
|
||||
case LocalDate localDate -> sql.argLocalDate(k, localDate);
|
||||
case LocalDateTime localDateTime -> sql.argLocalDateTime(k, localDateTime);
|
||||
case null -> sql.argNull(k);
|
||||
default -> throw new DatabaseException("unknown type for param: " + v.getClass());
|
||||
if (v instanceof String) {
|
||||
sql.argString(k, (String) v);
|
||||
} else if (v instanceof Integer) {
|
||||
sql.argInteger(k, (Integer) v);
|
||||
} else if (v instanceof Long) {
|
||||
sql.argLong(k, (Long) v);
|
||||
} else if (v instanceof Boolean) {
|
||||
sql.argBoolean(k, (Boolean) v);
|
||||
} else if (v instanceof LocalDate) {
|
||||
sql.argLocalDate(k, (LocalDate) v);
|
||||
} else if (v instanceof LocalDateTime) {
|
||||
sql.argLocalDateTime(k, (LocalDateTime) v);
|
||||
} else if (v == null) {
|
||||
sql.argNull(k);
|
||||
} else {
|
||||
throw new DatabaseException("unknown type for param: " + v.getClass());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -501,15 +503,22 @@ public class DatabaseImpl implements Database {
|
|||
return;
|
||||
}
|
||||
params.forEach((k, v) -> {
|
||||
switch (v) {
|
||||
case String s -> sql.argString(k, s);
|
||||
case Integer i -> sql.argInteger(k, i);
|
||||
case Long l -> sql.argLong(k, l);
|
||||
case Boolean b -> sql.argBoolean(k, b);
|
||||
case LocalDate localDate -> sql.argLocalDate(k, localDate);
|
||||
case LocalDateTime localDateTime -> sql.argLocalDateTime(k, localDateTime);
|
||||
case null -> sql.argNull(k);
|
||||
default -> throw new DatabaseException("unknown type for param: " + v.getClass());
|
||||
if (v instanceof String) {
|
||||
sql.argString(k, (String) v);
|
||||
} else if (v instanceof Integer) {
|
||||
sql.argInteger(k, (Integer) v);
|
||||
} else if (v instanceof Long) {
|
||||
sql.argLong(k, (Long) v);
|
||||
} else if (v instanceof Boolean) {
|
||||
sql.argBoolean(k, (Boolean) v);
|
||||
} else if (v instanceof LocalDate) {
|
||||
sql.argLocalDate(k, (LocalDate) v);
|
||||
} else if (v instanceof LocalDateTime) {
|
||||
sql.argLocalDateTime(k, (LocalDateTime) v);
|
||||
} else if (v == null) {
|
||||
sql.argNull(k);
|
||||
} else {
|
||||
throw new DatabaseException("unknown type for param: " + v.getClass());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -550,10 +559,7 @@ public class DatabaseImpl implements Database {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void consumeQueue(String table,
|
||||
String channel,
|
||||
int limit,
|
||||
Consumer<String> consumer) throws SQLException {
|
||||
public void consumeQueue(String table, String channel, int limit, Consumer<String> consumer) throws SQLException {
|
||||
List<Long> consumedKeys = new ArrayList<>();
|
||||
try {
|
||||
connection.setAutoCommit(false);
|
||||
|
@ -566,12 +572,13 @@ public class DatabaseImpl implements Database {
|
|||
consumer.accept(resultSet.getString("data"));
|
||||
}
|
||||
succeedInQueue(connection, table, key);
|
||||
} catch (Exception e) {
|
||||
} catch (QueueException e) {
|
||||
connection.rollback();
|
||||
failInQueue(connection, table, key);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
connection.commit();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
|
|
@ -5,10 +5,13 @@ import org.xbib.jdbc.connection.pool.PoolDataSource;
|
|||
import org.xbib.jdbc.query.util.Metric;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Level;
|
||||
|
@ -20,7 +23,7 @@ import java.util.logging.Logger;
|
|||
* of this laziness, the underlying resources require explicit cleanup by calling either
|
||||
* commitAndClose() or rollbackAndClose().
|
||||
*/
|
||||
public final class DatabaseProvider implements Supplier<Database> {
|
||||
public final class DatabaseProvider implements Supplier<Database>, Closeable {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(DatabaseProvider.class.getName());
|
||||
|
||||
|
@ -44,7 +47,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
return new DatabaseProviderBuilderImpl(ds, () -> {
|
||||
try {
|
||||
if (ds == null) {
|
||||
throw new IllegalArgumentException("data source must not be null");
|
||||
throw new NullPointerException();
|
||||
}
|
||||
return ds.getConnection();
|
||||
} catch (Exception e) {
|
||||
|
@ -167,7 +170,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
try {
|
||||
code.run(this);
|
||||
complete = true;
|
||||
} catch (DatabaseException t) {
|
||||
} catch (ThreadDeath | DatabaseException t) {
|
||||
throw t;
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseException("Error during transaction", t);
|
||||
|
@ -185,7 +188,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
try {
|
||||
code.run(this);
|
||||
complete = true;
|
||||
} catch (DatabaseException t) {
|
||||
} catch (ThreadDeath | DatabaseException t) {
|
||||
throw t;
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseException("Error during transaction", t);
|
||||
|
@ -204,7 +207,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
try {
|
||||
result = code.run(this);
|
||||
complete = true;
|
||||
} catch (DatabaseException t) {
|
||||
} catch (ThreadDeath | DatabaseException t) {
|
||||
throw t;
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseException("Error during transaction", t);
|
||||
|
@ -224,7 +227,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
try {
|
||||
result = code.run(this);
|
||||
complete = true;
|
||||
} catch (DatabaseException t) {
|
||||
} catch (ThreadDeath | DatabaseException t) {
|
||||
throw t;
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseException("Error during transaction", t);
|
||||
|
@ -246,7 +249,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
try {
|
||||
code.run(this, tx);
|
||||
complete = true;
|
||||
} catch (DatabaseException t) {
|
||||
} catch (ThreadDeath | DatabaseException t) {
|
||||
throw t;
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseException("Error during transaction", t);
|
||||
|
@ -267,7 +270,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
try {
|
||||
code.run(this, tx);
|
||||
complete = true;
|
||||
} catch (DatabaseException t) {
|
||||
} catch (ThreadDeath | DatabaseException t) {
|
||||
throw t;
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseException("Error during transaction", t);
|
||||
|
@ -284,6 +287,9 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
if (database != null) {
|
||||
return database;
|
||||
}
|
||||
if (builder.isClosed()) {
|
||||
throw new DatabaseException("Called get() on a DatabaseProvider after close()");
|
||||
}
|
||||
Metric metric = new Metric(logger.isLoggable(Level.FINE));
|
||||
try {
|
||||
connection = builder.connectionProvider.get();
|
||||
|
@ -293,7 +299,7 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
// Don't try to be clever about clearing it conditionally.
|
||||
if (!builder.options.flavor().isAutoCommitOnly()) {
|
||||
connection.setAutoCommit(false);
|
||||
metric.checkpoint("setAutoCommit false");
|
||||
metric.checkpoint("setAutoCommit");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DatabaseException("Unable to set autoCommit for the connection", e);
|
||||
|
@ -387,7 +393,8 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (connection != null) {
|
||||
try {
|
||||
connection.close();
|
||||
|
@ -397,22 +404,26 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
}
|
||||
connection = null;
|
||||
database = null;
|
||||
builder.close();
|
||||
}
|
||||
|
||||
private static class DatabaseProviderBuilderImpl implements DatabaseProviderBuilder {
|
||||
private static class DatabaseProviderBuilderImpl implements DatabaseProviderBuilder, Closeable {
|
||||
|
||||
private final DataSource dataSource;
|
||||
private DataSource dataSource;
|
||||
|
||||
private final Supplier<Connection> connectionProvider;
|
||||
|
||||
private final Options options;
|
||||
|
||||
private final AtomicBoolean closed;
|
||||
|
||||
private DatabaseProviderBuilderImpl(DataSource dataSource,
|
||||
Supplier<Connection> connectionProvider,
|
||||
Options options) {
|
||||
this.dataSource = dataSource;
|
||||
this.connectionProvider = connectionProvider;
|
||||
this.options = options;
|
||||
this.closed = new AtomicBoolean(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -500,5 +511,20 @@ public final class DatabaseProvider implements Supplier<Database> {
|
|||
this.build().transact(tx);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (closed.compareAndSet(false, true)) {
|
||||
if (dataSource != null) {
|
||||
if (dataSource instanceof Closeable) {
|
||||
((Closeable) dataSource).close();
|
||||
}
|
||||
dataSource = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isClosed() {
|
||||
return closed.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
package org.xbib.jdbc.query;
|
||||
|
||||
public class QueueException extends DatabaseException {
|
||||
|
||||
public QueueException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
package org.xbib.jdbc.query;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
@ -14,6 +15,10 @@ public class Table extends ArrayList<List<Object>> implements List<List<Object>>
|
|||
|
||||
private String search;
|
||||
|
||||
private LocalDateTime from;
|
||||
|
||||
private LocalDateTime to;
|
||||
|
||||
private Integer offset;
|
||||
|
||||
private Integer size;
|
||||
|
@ -24,12 +29,11 @@ public class Table extends ArrayList<List<Object>> implements List<List<Object>>
|
|||
|
||||
private String groupByClause;
|
||||
|
||||
private final List<Map.Entry<String, Boolean>> sort;
|
||||
private final List<Map.Entry<String, Boolean>> sort = new ArrayList<>();
|
||||
|
||||
private long total;
|
||||
|
||||
public Table() {
|
||||
this.sort = new ArrayList<>();
|
||||
}
|
||||
|
||||
public void setStatement(String statement) {
|
||||
|
@ -56,6 +60,22 @@ public class Table extends ArrayList<List<Object>> implements List<List<Object>>
|
|||
return search;
|
||||
}
|
||||
|
||||
public void setFromDate(LocalDateTime from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public LocalDateTime getFromDate() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setToDate(LocalDateTime to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
public LocalDateTime getToDate() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setOffset(Integer offset) {
|
||||
this.offset = offset;
|
||||
}
|
||||
|
|
|
@ -18,9 +18,14 @@ import java.util.logging.Logger;
|
|||
* to prevent SQL injection or any other bad things.
|
||||
*/
|
||||
public class DebugSql {
|
||||
|
||||
public static final String PARAM_SQL_SEPARATOR = "\tParamSql:\t";
|
||||
|
||||
public static String printDebugOnlySqlString(String sql, Object[] args, Options options) {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
printSql(buf, sql, args, false, true, options);
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static void printSql(StringBuilder buf, String sql, Object[] args, Options options) {
|
||||
printSql(buf, sql, args, true, options.isLogParameters(), options);
|
||||
}
|
||||
|
@ -60,7 +65,8 @@ public class DebugSql {
|
|||
for (int i = 0; i < argsToPrint.length; i++) {
|
||||
buf.append(removeTabs(sqlParts[i]));
|
||||
Object argToPrint = argsToPrint[i];
|
||||
if (argToPrint instanceof String argToPrintString) {
|
||||
if (argToPrint instanceof String) {
|
||||
String argToPrintString = (String) argToPrint;
|
||||
int maxLength = options.maxStringLengthParam();
|
||||
if (argToPrintString.length() > maxLength && maxLength > 0) {
|
||||
buf.append("'").append(argToPrintString, 0, maxLength).append("...'");
|
||||
|
@ -71,12 +77,16 @@ public class DebugSql {
|
|||
}
|
||||
} else if (argToPrint instanceof SqlNull || argToPrint == null) {
|
||||
buf.append("null");
|
||||
} else if (argToPrint instanceof java.sql.Timestamp timestamp) {
|
||||
} else if (argToPrint instanceof java.sql.Timestamp) {
|
||||
java.sql.Timestamp timestamp = (java.sql.Timestamp) argToPrint;
|
||||
LocalDateTime localDateTime = timestamp.toLocalDateTime();
|
||||
buf.append(localDateTime.toString());
|
||||
} else if (argToPrint instanceof java.sql.Date date) {
|
||||
//buf.append(options.flavor().dateAsSqlFunction((Timestamp) argToPrint, options.calendarForTimestamps()));
|
||||
} else if (argToPrint instanceof java.sql.Date) {
|
||||
java.sql.Date date = (java.sql.Date) argToPrint;
|
||||
LocalDate localDate = date.toLocalDate();
|
||||
buf.append(localDate.toString());
|
||||
//buf.append(options.flavor().localDateAsSqlFunction((java.sql.Date) argToPrint));
|
||||
} else if (argToPrint instanceof Number) {
|
||||
buf.append(argToPrint);
|
||||
} else if (argToPrint instanceof Boolean) {
|
||||
|
@ -134,22 +144,25 @@ public class DebugSql {
|
|||
}
|
||||
|
||||
public static void logSuccess(String sqlType, Logger log, Metric metric, String sql, Object[] args, Options options) {
|
||||
if (log.isLoggable(Level.FINEST)) {
|
||||
log.log(Level.FINEST, () -> logMiddle('\t', sqlType, metric, null, sql, args, options));
|
||||
if (log.isLoggable(Level.FINE)) {
|
||||
String msg = logMiddle('\t', sqlType, metric, null, sql, args, options);
|
||||
log.fine(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public static void logWarning(String sqlType, Logger log, Metric metric, String errorCode, String sql, Object[] args,
|
||||
Options options, Throwable t) {
|
||||
if (log.isLoggable(Level.WARNING)) {
|
||||
log.log(Level.WARNING, logMiddle(' ', sqlType, metric, errorCode, sql, args, options), t);
|
||||
String msg = logMiddle(' ', sqlType, metric, errorCode, sql, args, options);
|
||||
log.log(Level.WARNING, msg, t);
|
||||
}
|
||||
}
|
||||
|
||||
public static void logError(String sqlType, Logger log, Metric metric, String errorCode, String sql, Object[] args,
|
||||
Options options, Throwable t) {
|
||||
if (log.isLoggable(Level.SEVERE)) {
|
||||
log.log(Level.SEVERE, logMiddle(' ', sqlType, metric, errorCode, sql, args, options), t);
|
||||
String msg = logMiddle(' ', sqlType, metric, errorCode, sql, args, options);
|
||||
log.log(Level.SEVERE, msg, t);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,23 +1,26 @@
|
|||
dependencyResolutionManagement {
|
||||
versionCatalogs {
|
||||
libs {
|
||||
version('gradle', '8.7')
|
||||
library('mariadb', 'org.mariadb.jdbc', 'mariadb-java-client').version('3.4.1')
|
||||
library('oracle', 'com.oracle.database.jdbc', 'ojdbc11').version('23.4.0.24.05')
|
||||
library('postgresql', 'org.postgresql', 'postgresql').version('42.7.3')
|
||||
version('gradle', '8.5')
|
||||
library('mariadb', 'org.mariadb.jdbc', 'mariadb-java-client').version('3.1.3')
|
||||
library('oracle', 'com.oracle.database.jdbc','ojdbc11').version('23.2.0.0')
|
||||
library('postgresql', 'org.postgresql', 'postgresql').version('42.6.0')
|
||||
}
|
||||
testLibs {
|
||||
version('junit', '5.10.2')
|
||||
version('testcontainers', '1.20.0')
|
||||
version('junit', '5.10.1')
|
||||
version('testcontainers', '1.19.1')
|
||||
library('junit-jupiter-api', 'org.junit.jupiter', 'junit-jupiter-api').versionRef('junit')
|
||||
library('junit-jupiter-params', 'org.junit.jupiter', 'junit-jupiter-params').versionRef('junit')
|
||||
library('junit-jupiter-engine', 'org.junit.jupiter', 'junit-jupiter-engine').versionRef('junit')
|
||||
library('junit-jupiter-platform-launcher', 'org.junit.platform', 'junit-platform-launcher').version('1.10.1')
|
||||
library('hamcrest', 'org.hamcrest', 'hamcrest-library').version('2.2')
|
||||
library('junit4', 'junit', 'junit').version('4.13.2')
|
||||
library('derby', 'org.apache.derby', 'derby').version('10.17.1.0')
|
||||
library('hsqldb', 'org.hsqldb', 'hsqldb').version('2.7.3')
|
||||
library('h2', 'com.h2database', 'h2').version('2.3.230')
|
||||
library('derby', 'org.apache.derby', 'derby').version('10.16.1.1')
|
||||
library('hsqldb', 'org.hsqldb', 'hsqldb').version('2.7.1')
|
||||
library('h2', 'com.h2database', 'h2').version('2.1.214')
|
||||
library('mariadb', 'org.mariadb.jdbc', 'mariadb-java-client').version('3.1.3')
|
||||
library('oracle', 'com.oracle.database.jdbc','ojdbc11').version('23.2.0.0')
|
||||
library('postgresql', 'org.postgresql', 'postgresql').version('42.6.0')
|
||||
library('mockito-core', 'org.mockito', 'mockito-core').version('5.3.1')
|
||||
library('testcontainers', 'org.testcontainers', 'testcontainers').versionRef('testcontainers')
|
||||
library('testcontainers-junit-jupiter', 'org.testcontainers', 'junit-jupiter').versionRef('testcontainers')
|
||||
|
@ -29,7 +32,6 @@ dependencyResolutionManagement {
|
|||
}
|
||||
|
||||
include 'jdbc-connection-pool'
|
||||
include 'jdbc-pool'
|
||||
include 'jdbc-query'
|
||||
include 'jdbc-test'
|
||||
include 'jdbc-mariadb'
|
||||
|
|
Loading…
Reference in a new issue