All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.icthh.xm.commons.migration.db.util.DatabaseUtil Maven / Gradle / Ivy

There is a newer version: 4.0.21
Show newest version
package com.icthh.xm.commons.migration.db.util;

import static com.icthh.xm.commons.tenant.TenantContextUtils.assertTenantKeyValid;

import com.icthh.xm.commons.migration.db.Constants;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * Utility for database operations.
 */
@UtilityClass
@SuppressWarnings("squid:S1118") // private constructor generated by lombok
@Slf4j
public final class DatabaseUtil {

    /**
     * Creates new database scheme.
     *
     * @param dataSource the datasource
     * @param name       schema name
     */
    public static void createSchema(DataSource dataSource, String name) throws SQLException {
        assertTenantKeyValid(name);
        executeUpdateWithAutoCommit(dataSource, String.format(Constants.DDL_CREATE_SCHEMA, name));
    }

    public static void executeUpdateWithAutoCommit(final DataSource dataSource, final String sql) throws SQLException {
        Connection connection = null;
        boolean autocommitBefore = false;
        Statement statement = null;
        try {
            connection = dataSource.getConnection();
            autocommitBefore = connection.getAutoCommit();
            statement = connection.createStatement();
            connection.setAutoCommit(true);
            log.info("execute sql: [{}], autocommit = {}", sql, connection.getAutoCommit());
            int res = statement.executeUpdate(sql);
            log.debug("result = {}", res);
        } finally {
            if (statement != null && !statement.isClosed()) {
                log.debug("close statement!");
                statement.close();
            }
            if (connection != null) {
                connection.setAutoCommit(autocommitBefore);
                if (!connection.isClosed()) {
                    log.debug("close connection! autocommit = {}", connection.getAutoCommit());
                    connection.close();
                }
            }
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy