-
Notifications
You must be signed in to change notification settings - Fork 350
/
DataSourceUtils.java
74 lines (66 loc) · 2.66 KB
/
DataSourceUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* Copyright 2023 Datastrato.
* This software is licensed under the Apache License version 2.
*/
package com.datastrato.gravitino.catalog.jdbc.utils;
import com.datastrato.gravitino.catalog.jdbc.config.JdbcConfig;
import com.datastrato.gravitino.exceptions.GravitinoRuntimeException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
/**
* Utility class for creating a {@link DataSource} from a {@link JdbcConfig}. It is mainly
* responsible for creating connection pool management of data sources and configuring some
* connection pools. The apache-dbcp2 connection pool is used here.
*/
public class DataSourceUtils {
/** SQL statements for database connection pool testing. */
private static final String POOL_TEST_QUERY = "SELECT 1";
public static DataSource createDataSource(Map<String, String> properties) {
return createDataSource(new JdbcConfig(properties));
}
public static DataSource createDataSource(JdbcConfig jdbcConfig)
throws GravitinoRuntimeException {
try {
return createDBCPDataSource(jdbcConfig);
} catch (Exception exception) {
throw new GravitinoRuntimeException("Error creating datasource", exception);
}
}
private static DataSource createDBCPDataSource(JdbcConfig jdbcConfig) throws Exception {
BasicDataSource basicDataSource =
BasicDataSourceFactory.createDataSource(getProperties(jdbcConfig));
basicDataSource.setUrl(jdbcConfig.getJdbcUrl());
if (null != jdbcConfig.getUsername()) {
basicDataSource.setUsername(jdbcConfig.getUsername());
}
if (null != jdbcConfig.getPassword()) {
basicDataSource.setPassword(jdbcConfig.getPassword());
}
basicDataSource.setMaxTotal(jdbcConfig.getPoolMaxSize());
basicDataSource.setMinIdle(jdbcConfig.getPoolMinSize());
// Set each time a connection is taken out from the connection pool, a test statement will be
// executed to confirm whether the connection is valid.
basicDataSource.setTestOnBorrow(true);
basicDataSource.setValidationQuery(POOL_TEST_QUERY);
return basicDataSource;
}
private static Properties getProperties(JdbcConfig jdbcConfig) {
Properties properties = new Properties();
properties.putAll(jdbcConfig.getAllConfig());
return properties;
}
public static void closeDataSource(DataSource dataSource) {
if (null != dataSource) {
try {
assert dataSource instanceof BasicDataSource;
((BasicDataSource) dataSource).close();
} catch (SQLException ignore) {
// no op
}
}
}
}