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

io.descoped.rawdata.provider.postgres.PostgresTransactionFactory Maven / Gradle / Ivy

The newest version!
package io.descoped.rawdata.provider.postgres;

import com.zaxxer.hikari.HikariDataSource;
import io.descoped.rawdata.provider.postgres.tx.Transaction;
import io.descoped.rawdata.provider.postgres.tx.TransactionFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PostgresTransactionFactory implements TransactionFactory {

    final HikariDataSource dataSource;

    public PostgresTransactionFactory(HikariDataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public PostgresTransaction createTransaction(boolean readOnly) throws PersistenceException {
        PostgresTransaction postgresTransaction = null;
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            postgresTransaction = new PostgresTransaction(connection);
            return postgresTransaction;
        } catch (SQLException e) {
            throw new PersistenceException(e);
        } finally {
            if (postgresTransaction == null && connection != null) {
                // exceptional return, do not leave connection open
                try {
                    connection.close();
                } catch (SQLException ex) {
                    // ignore
                }
            }
        }
    }

    @Override
    public boolean checkIfTableTopicExists(String topic, String table) {
        try (Transaction tx = createTransaction(true)) {
            try (PreparedStatement ps = tx.connection().prepareStatement("SELECT 1 FROM pg_tables WHERE schemaname = ? AND tablename = ?")) {
                ps.setString(1, "public");
                ps.setString(2, topic + "_" + table);
                try (ResultSet rs = ps.executeQuery()) {
                    return rs.next();
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public DataSource dataSource() {
        return dataSource;
    }

    @Override
    public void close() {
        dataSource.close();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy