Skip to content

Commit b380821

Browse files
author
diego Dupin
committed
[CONJ-909] adding createDatabaseIfNotExist option for 2.x compatibility
1 parent 900725f commit b380821

File tree

6 files changed

+56
-3
lines changed

6 files changed

+56
-3
lines changed

src/main/java/org/mariadb/jdbc/Configuration.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ public class Configuration {
6161
private String timezone = null;
6262
private Boolean autocommit = null;
6363
private boolean useMysqlMetadata = false;
64+
private boolean createDatabaseIfNotExist = false;
6465
private TransactionIsolation transactionIsolation = null;
6566
private int defaultFetchSize = 0;
6667
private int maxQuerySizeToLog = 1024;
@@ -153,6 +154,7 @@ private Configuration(
153154
String timezone,
154155
Boolean autocommit,
155156
boolean useMysqlMetadata,
157+
boolean createDatabaseIfNotExist,
156158
TransactionIsolation transactionIsolation,
157159
int defaultFetchSize,
158160
int maxQuerySizeToLog,
@@ -220,6 +222,7 @@ private Configuration(
220222
this.timezone = timezone;
221223
this.autocommit = autocommit;
222224
this.useMysqlMetadata = useMysqlMetadata;
225+
this.createDatabaseIfNotExist = createDatabaseIfNotExist;
223226
this.transactionIsolation = transactionIsolation;
224227
this.defaultFetchSize = defaultFetchSize;
225228
this.maxQuerySizeToLog = maxQuerySizeToLog;
@@ -319,6 +322,7 @@ private Configuration(
319322
Boolean useBulkStmts,
320323
Boolean autocommit,
321324
Boolean useMysqlMetadata,
325+
Boolean createDatabaseIfNotExist,
322326
Boolean includeInnodbStatusInDeadlockExceptions,
323327
Boolean includeThreadDumpInDeadlockExceptions,
324328
String servicePrincipalName,
@@ -395,6 +399,7 @@ private Configuration(
395399
if (useBulkStmts != null) this.useBulkStmts = useBulkStmts;
396400
if (autocommit != null) this.autocommit = autocommit;
397401
if (useMysqlMetadata != null) this.useMysqlMetadata = useMysqlMetadata;
402+
if (createDatabaseIfNotExist != null) this.createDatabaseIfNotExist = createDatabaseIfNotExist;
398403
if (includeInnodbStatusInDeadlockExceptions != null)
399404
this.includeInnodbStatusInDeadlockExceptions = includeInnodbStatusInDeadlockExceptions;
400405
if (includeThreadDumpInDeadlockExceptions != null)
@@ -687,6 +692,7 @@ public Configuration clone(String username, String password) {
687692
this.timezone,
688693
this.autocommit,
689694
this.useMysqlMetadata,
695+
this.createDatabaseIfNotExist,
690696
this.transactionIsolation,
691697
this.defaultFetchSize,
692698
this.maxQuerySizeToLog,
@@ -920,6 +926,10 @@ public boolean useMysqlMetadata() {
920926
return useMysqlMetadata;
921927
}
922928

929+
public boolean createDatabaseIfNotExist() {
930+
return createDatabaseIfNotExist;
931+
}
932+
923933
public boolean includeInnodbStatusInDeadlockExceptions() {
924934
return includeInnodbStatusInDeadlockExceptions;
925935
}
@@ -1198,6 +1208,7 @@ public static final class Builder implements Cloneable {
11981208
private String timezone;
11991209
private Boolean autocommit;
12001210
private Boolean useMysqlMetadata;
1211+
private Boolean createDatabaseIfNotExist;
12011212
private Integer defaultFetchSize;
12021213
private Integer maxQuerySizeToLog;
12031214
private Integer maxAllowedPacket;
@@ -1632,6 +1643,11 @@ public Builder useMysqlMetadata(Boolean useMysqlMetadata) {
16321643
return this;
16331644
}
16341645

1646+
public Builder createDatabaseIfNotExist(Boolean createDatabaseIfNotExist) {
1647+
this.createDatabaseIfNotExist = createDatabaseIfNotExist;
1648+
return this;
1649+
}
1650+
16351651
public Builder includeInnodbStatusInDeadlockExceptions(
16361652
Boolean includeInnodbStatusInDeadlockExceptions) {
16371653
this.includeInnodbStatusInDeadlockExceptions = includeInnodbStatusInDeadlockExceptions;
@@ -1789,6 +1805,7 @@ public Configuration build() throws SQLException {
17891805
this.useBulkStmts,
17901806
this.autocommit,
17911807
this.useMysqlMetadata,
1808+
this.createDatabaseIfNotExist,
17921809
this.includeInnodbStatusInDeadlockExceptions,
17931810
this.includeThreadDumpInDeadlockExceptions,
17941811
this.servicePrincipalName,

src/main/java/org/mariadb/jdbc/client/impl/ConnectionHelper.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ public static long initializeClientCapabilities(
189189
capabilities |= Capabilities.COMPRESS;
190190
}
191191

192-
if (configuration.database() != null) {
192+
if (configuration.database() != null && !configuration.createDatabaseIfNotExist()) {
193193
capabilities |= Capabilities.CONNECT_WITH_DB;
194194
}
195195
return capabilities;

src/main/java/org/mariadb/jdbc/client/impl/StandardClient.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,12 @@ private void postConnectionQueries() throws SQLException {
304304
commands.add("SET SESSION TRANSACTION READ ONLY");
305305
}
306306

307+
if (conf.database() != null && conf.createDatabaseIfNotExist()) {
308+
String escapedDb = conf.database().replace("`", "``");
309+
commands.add(String.format("CREATE DATABASE IF NOT EXISTS `%s`", escapedDb));
310+
commands.add(String.format("USE `%s`", escapedDb));
311+
}
312+
307313
try {
308314
List<Completion> res;
309315
ClientMessage[] msgs = new ClientMessage[commands.size()];

src/main/resources/driver.properties

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,5 @@ tcpKeepIdle=permit setting socket TCP_KEEPIDLE value. Only valid for java 11+(fo
6161
tcpKeepCount=permit setting socket TCP_KEEPCOUNT value. Only valid for java 11+(for previous version, this option will have no use). (Integer) Default null
6262
tcpKeepInterval=permit setting socket TCP_KEEPINTERVAL value. Only valid for java 11+(for previous version, this option will have no use). (Integer) Default null
6363
useMysqlMetadata=force DatabaseMetadata.getDatabaseProductName() to return "MySQL" (for compatibility reason)
64-
maxAllowedPacket=permit to driver to avoid sending command with size > to server max_allowed_packet, throwing an error in place of server dropping the connection.
64+
maxAllowedPacket=permit to driver to avoid sending command with size > to server max_allowed_packet, throwing an error in place of server dropping the connection.
65+
createDatabaseIfNotExist=the specified database in the url will be created if nonexistent. Default: false

src/test/java/org/mariadb/jdbc/integration/ConnectionTest.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,4 +1063,32 @@ public void timezone() throws SQLException {
10631063
con.isValid(1);
10641064
}
10651065
}
1066+
1067+
@Test
1068+
public void createDatabaseIfNotExist() throws SQLException {
1069+
Assumptions.assumeTrue(
1070+
!"skysql".equals(System.getenv("srv")) && !"skysql-ha".equals(System.getenv("srv")));
1071+
1072+
// ensure connecting without DB
1073+
String connStr =
1074+
String.format(
1075+
"jdbc:mariadb://%s:%s/?user=%s&password=%s&restrictedAuth=none&%s&createDatabaseIfNotExist",
1076+
hostname, port, user, password, defaultOther);
1077+
try (Connection con = DriverManager.getConnection(connStr)) {
1078+
con.createStatement().executeQuery("SELECT 1");
1079+
}
1080+
sharedConn.createStatement().execute("DROP DATABASE IF EXISTS `bla``f``l`");
1081+
String nonExistentDatabase = "bla`f`l";
1082+
connStr =
1083+
String.format(
1084+
"jdbc:mariadb://%s:%s/%s?user=%s&password=%s&restrictedAuth=none&%s&createDatabaseIfNotExist",
1085+
hostname, port, nonExistentDatabase, user, password, defaultOther);
1086+
try (Connection con = DriverManager.getConnection(connStr)) {
1087+
ResultSet rs = con.createStatement().executeQuery("select DATABASE()");
1088+
assertTrue(rs.next());
1089+
assertEquals(nonExistentDatabase, rs.getString(1));
1090+
}
1091+
1092+
sharedConn.createStatement().execute("DROP DATABASE IF EXISTS `bla``f``l`");
1093+
}
10661094
}

src/test/java/org/mariadb/jdbc/unit/util/ConfigurationTest.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -824,10 +824,11 @@ public void builder() throws SQLException {
824824
.serverSslCert("mycertPath")
825825
.serverRsaPublicKeyFile("RSAPath")
826826
.allowPublicKeyRetrieval(true)
827+
.createDatabaseIfNotExist(true)
827828
.maxAllowedPacket(8000)
828829
.build();
829830
assertEquals(
830-
"jdbc:mariadb://host1:3305,address=(host=host2)(port=3307)(type=replica)/db?user=me&password=pwd&timezone=UTC&autocommit=false&transactionIsolation=REPEATABLE_READ&defaultFetchSize=10&maxQuerySizeToLog=100&maxAllowedPacket=8000&geometryDefaultType=default&restrictedAuth=mysql_native_password,client_ed25519&socketFactory=someSocketFactory&connectTimeout=22&pipe=pipeName&localSocket=localSocket&tcpKeepAlive=false&tcpKeepIdle=10&tcpKeepCount=50&tcpKeepInterval=50&tcpAbortiveClose=true&localSocketAddress=localSocketAddress&socketTimeout=1000&useReadAheadInput=false&tlsSocketType=TLStype&sslMode=TRUST&serverSslCert=mycertPath&keyStore=/tmp&keyStorePassword=MyPWD&keyStoreType=JKS&enabledSslCipherSuites=myCipher,cipher2&enabledSslProtocolSuites=TLSv1.2&allowMultiQueries=true&allowLocalInfile=true&useCompression=true&useAffectedRows=true&useBulkStmts=false&cachePrepStmts=false&prepStmtCacheSize=2&useServerPrepStmts=true&credentialType=ENV&sessionVariables=blabla&connectionAttributes=bla=bla&servicePrincipalName=SPN&blankTableNameMeta=true&tinyInt1isBit=false&yearIsDateType=false&dumpQueriesOnException=true&includeInnodbStatusInDeadlockExceptions=true&includeThreadDumpInDeadlockExceptions=true&retriesAllDown=10&galeraAllowedState=A,B&transactionReplay=true&pool=true&poolName=myPool&maxPoolSize=16&minPoolSize=12&maxIdleTime=25000&registerJmxPool=false&poolValidMinDelay=260&useResetConnection=true&serverRsaPublicKeyFile=RSAPath&allowPublicKeyRetrieval=true",
831+
"jdbc:mariadb://host1:3305,address=(host=host2)(port=3307)(type=replica)/db?user=me&password=pwd&timezone=UTC&autocommit=false&createDatabaseIfNotExist=true&transactionIsolation=REPEATABLE_READ&defaultFetchSize=10&maxQuerySizeToLog=100&maxAllowedPacket=8000&geometryDefaultType=default&restrictedAuth=mysql_native_password,client_ed25519&socketFactory=someSocketFactory&connectTimeout=22&pipe=pipeName&localSocket=localSocket&tcpKeepAlive=false&tcpKeepIdle=10&tcpKeepCount=50&tcpKeepInterval=50&tcpAbortiveClose=true&localSocketAddress=localSocketAddress&socketTimeout=1000&useReadAheadInput=false&tlsSocketType=TLStype&sslMode=TRUST&serverSslCert=mycertPath&keyStore=/tmp&keyStorePassword=MyPWD&keyStoreType=JKS&enabledSslCipherSuites=myCipher,cipher2&enabledSslProtocolSuites=TLSv1.2&allowMultiQueries=true&allowLocalInfile=true&useCompression=true&useAffectedRows=true&useBulkStmts=false&cachePrepStmts=false&prepStmtCacheSize=2&useServerPrepStmts=true&credentialType=ENV&sessionVariables=blabla&connectionAttributes=bla=bla&servicePrincipalName=SPN&blankTableNameMeta=true&tinyInt1isBit=false&yearIsDateType=false&dumpQueriesOnException=true&includeInnodbStatusInDeadlockExceptions=true&includeThreadDumpInDeadlockExceptions=true&retriesAllDown=10&galeraAllowedState=A,B&transactionReplay=true&pool=true&poolName=myPool&maxPoolSize=16&minPoolSize=12&maxIdleTime=25000&registerJmxPool=false&poolValidMinDelay=260&useResetConnection=true&serverRsaPublicKeyFile=RSAPath&allowPublicKeyRetrieval=true",
831832
conf.toString());
832833
}
833834

0 commit comments

Comments
 (0)