Skip to content

Commit

Permalink
feat: disable foreign keys during dataset setup/teardown
Browse files Browse the repository at this point in the history
- Add postgres foreign key manager
- Add mysql foreign key manager
- Add mariadb foreign key manager
- Add mssql foreign key manager
- Add oracle foreign key manager
  • Loading branch information
mjeanroy committed Sep 17, 2023
1 parent 642e98f commit 3ae8aea
Show file tree
Hide file tree
Showing 21 changed files with 1,600 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
package com.github.mjeanroy.dbunit.commons.lang;

import static com.github.mjeanroy.dbunit.commons.lang.Strings.isBlank;
import static com.github.mjeanroy.dbunit.commons.lang.Strings.isEmpty;

/**
* Static PreConditions Utilities.
Expand Down Expand Up @@ -52,6 +53,26 @@ public static <T> T notNull(T value, String message, Object... params) {
return value;
}

/**
* Ensure that given {@code value} is not {@code null}, empty.
*
* @param value Value to check.
* @param message Error message.
* @param params Optional error message parameters.
* @return Value if it is not {@code null}, empty.
* @throws NullPointerException If {@code value} is null.
* @throws IllegalArgumentException If {@code value} is empty.
*/
public static String notEmpty(String value, String message, Object... params) {
notNull(value, message, params);

if (isEmpty(value)) {
throw new IllegalArgumentException(format(message, params));
}

return value;
}

/**
* Ensure that given {@code value} is not {@code null}, empty or blank.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ public static ToStringBuilder create(Class<?> klass) {
return new ToStringBuilder(klass);
}

/**
* Create the builder with given class of instance (the simple name will be used to start
* the {@code toString} value).
*
* @param instance The instance.
* @return The builder.
*/
public static ToStringBuilder create(Object instance) {
return new ToStringBuilder(instance.getClass());
}

/**
* The internal string builder.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package com.github.mjeanroy.dbunit.core.jdbc;

import com.github.mjeanroy.dbunit.exception.JdbcException;
import com.github.mjeanroy.dbunit.loggers.Logger;
import com.github.mjeanroy.dbunit.loggers.Loggers;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import static com.github.mjeanroy.dbunit.core.jdbc.JdbcUtils.executeUpdates;

abstract class AbstractJdbcDropCreateForeignKeyManager<T> implements JdbcForeignKeyManager {

private static final Logger log = Loggers.getLogger(AbstractJdbcDropCreateForeignKeyManager.class);

private List<T> foreignKeys;

AbstractJdbcDropCreateForeignKeyManager() {
// Initial state.
this.foreignKeys = null;
}

@Override
public final synchronized void disable(Connection connection) {
checkInitialState();

// Introspect foreign keys, so we can drop them
// and re-create them in the exact same configuration later.
foreignKeys = introspectForeignKeys(connection);

// We can now drop foreign these foreign keys.
dropForeignKeys(connection);
}

@Override
public final synchronized void enable(Connection connection) {
// Re-create foreign keys with the same initial configuration.
reCreateForeignKeys(connection);

// Go back to initial state.
foreignKeys = null;
}

private void checkInitialState() {
if (foreignKeys != null) {
throw new IllegalStateException(
"Cannot disable constraints, foreign keys have been dropped, please re-enable them before"
);
}
}

private void dropForeignKeys(Connection connection) {
if (foreignKeys == null) {
throw new IllegalStateException(
"Cannot disable constraints, foreign keys have not been introspected"
);
}

List<String> queries = new ArrayList<>(foreignKeys.size());
for (T foreignKey : foreignKeys) {
queries.add(
generateDropForeignKeyQuery(foreignKey)
);
}

try {
executeUpdates(connection, queries);
}
catch (Exception ex) {
log.error(ex.getMessage(), ex);
throw new JdbcException("Cannot disable foreign key constraints", ex);
}
}

private void reCreateForeignKeys(Connection connection) {
if (foreignKeys == null) {
throw new IllegalStateException(
"Cannot enable constraints, foreign keys have not been introspected, try disabling constraints first"
);
}

List<String> queries = new ArrayList<>(foreignKeys.size());
for (T foreignKey : foreignKeys) {
queries.add(
generateAddForeignKeyQuery(foreignKey)
);
}

try {
executeUpdates(connection, queries);
}
catch (Exception ex) {
log.error(ex.getMessage(), ex);
throw new JdbcException("Cannot enable foreign key constraints, please check your dataset", ex);
}
}

abstract List<T> introspectForeignKeys(Connection connection);

abstract String generateDropForeignKeyQuery(T foreignKey);

abstract String generateAddForeignKeyQuery(T foreignKey);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package com.github.mjeanroy.dbunit.core.jdbc;

import java.sql.Connection;

public interface JdbcForeignKeyManager {

void disable(Connection connection) throws Exception;

void enable(Connection connection) throws Exception;
}
63 changes: 63 additions & 0 deletions src/main/java/com/github/mjeanroy/dbunit/core/jdbc/JdbcUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,78 @@
package com.github.mjeanroy.dbunit.core.jdbc;

import com.github.mjeanroy.dbunit.exception.JdbcException;
import com.github.mjeanroy.dbunit.loggers.Logger;
import com.github.mjeanroy.dbunit.loggers.Loggers;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

final class JdbcUtils {

private static final Logger log = Loggers.getLogger(JdbcUtils.class);

private JdbcUtils() {
}

static void loadDriver(String driverClassName) {
log.info("Loading driver: {}", driverClassName);

try {
Class.forName(driverClassName);
}
catch (ClassNotFoundException ex) {
throw new JdbcException("Cannot load JDBC Driver: " + driverClassName, ex);
}
}

static ResultSet executeQuery(Connection connection, String query) {
log.debug("Executing query: {}", query);

try {
return connection.createStatement().executeQuery(query);
}
catch (Exception ex) {
throw new JdbcException("Cannot execute query: " + query, ex);
}
}

static <T> List<T> executeQuery(Connection connection, String query, ResultSetMapFunction<T> mapFunction) {
log.debug("Executing query: {}", query);

try (ResultSet resultSet = connection.createStatement().executeQuery(query)) {
log.debug("Extracting query results");
List<T> outputs = new ArrayList<>();
while (resultSet.next()) {
outputs.add(mapFunction.apply(resultSet));
}

return outputs;
}
catch (Exception ex) {
throw new JdbcException("Cannot execute query: " + query, ex);
}
}

static void executeUpdates(Connection connection, Collection<String> queries) {
log.debug("Extracting batch queries: {}", queries);
try (Statement statement = connection.createStatement()) {
for (String query : queries) {
log.debug("Adding query `{}` to batch statement", query);
statement.addBatch(query);
}

statement.executeBatch();
}
catch (Exception ex) {
throw new JdbcException("Cannot execute queries: " + queries, ex);
}
}

interface ResultSetMapFunction<T> {
T apply(ResultSet resultSet) throws Exception;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package com.github.mjeanroy.dbunit.core.jdbc;

import java.sql.Connection;

final class MariaDBForeignKeyManager implements JdbcForeignKeyManager {

// MariaDB is "just" a fork of MySQL, so it's a "MySQL" like engine.
// Let's reuse the MySQL implementation.
private final MySQLForeignKeyManager mySQLForeignKeyManager;

MariaDBForeignKeyManager() {
mySQLForeignKeyManager = new MySQLForeignKeyManager();
}

@Override
public void disable(Connection connection) {
mySQLForeignKeyManager.disable(connection);
}

@Override
public void enable(Connection connection) {
mySQLForeignKeyManager.enable(connection);
}
}
Loading

0 comments on commit 3ae8aea

Please sign in to comment.