|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +package org.apache.polaris.extension.persistence.relational.jdbc; |
| 20 | + |
| 21 | +import static java.nio.charset.StandardCharsets.UTF_8; |
| 22 | + |
| 23 | +import java.io.BufferedReader; |
| 24 | +import java.io.IOException; |
| 25 | +import java.io.InputStreamReader; |
| 26 | +import java.sql.Connection; |
| 27 | +import java.sql.ResultSet; |
| 28 | +import java.sql.SQLException; |
| 29 | +import java.sql.Statement; |
| 30 | +import java.util.List; |
| 31 | +import java.util.Objects; |
| 32 | +import javax.sql.DataSource; |
| 33 | +import org.slf4j.Logger; |
| 34 | +import org.slf4j.LoggerFactory; |
| 35 | + |
| 36 | +public class DatasourceOperations { |
| 37 | + private static final Logger LOGGER = LoggerFactory.getLogger(DatasourceOperations.class); |
| 38 | + |
| 39 | + private static final String ALREADY_EXISTS_STATE_POSTGRES = "42P07"; |
| 40 | + private static final String CONSTRAINT_VIOLATION_SQL_CODE = "23505"; |
| 41 | + |
| 42 | + private final DataSource datasource; |
| 43 | + |
| 44 | + public DatasourceOperations(DataSource datasource) { |
| 45 | + this.datasource = datasource; |
| 46 | + } |
| 47 | + |
| 48 | + public void executeScript(String scriptFilePath) throws SQLException { |
| 49 | + ClassLoader classLoader = DatasourceOperations.class.getClassLoader(); |
| 50 | + try (Connection connection = borrowConnection(); |
| 51 | + Statement statement = connection.createStatement()) { |
| 52 | + BufferedReader reader = |
| 53 | + new BufferedReader( |
| 54 | + new InputStreamReader( |
| 55 | + Objects.requireNonNull(classLoader.getResourceAsStream(scriptFilePath)), UTF_8)); |
| 56 | + StringBuilder sqlBuffer = new StringBuilder(); |
| 57 | + String line; |
| 58 | + while ((line = reader.readLine()) != null) { |
| 59 | + line = line.trim(); |
| 60 | + if (!line.isEmpty() && !line.startsWith("--")) { // Ignore empty lines and comments |
| 61 | + sqlBuffer.append(line).append("\n"); |
| 62 | + if (line.endsWith(";")) { // Execute statement when semicolon is found |
| 63 | + String sql = sqlBuffer.toString().trim(); |
| 64 | + try { |
| 65 | + int rowsUpdated = statement.executeUpdate(sql); |
| 66 | + LOGGER.debug("Query {} executed {} rows affected", sql, rowsUpdated); |
| 67 | + } catch (SQLException e) { |
| 68 | + LOGGER.error("Error executing query {}", sql, e); |
| 69 | + // re:throw this as unhandled exception |
| 70 | + throw new RuntimeException(e); |
| 71 | + } |
| 72 | + sqlBuffer.setLength(0); // Clear the buffer for the next statement |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + } catch (IOException e) { |
| 77 | + LOGGER.error("Error reading the script file", e); |
| 78 | + throw new RuntimeException(e); |
| 79 | + } catch (SQLException e) { |
| 80 | + LOGGER.error("Error executing the script file", e); |
| 81 | + throw e; |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + public <T> List<T> executeSelect(String query, Class<T> targetClass) throws SQLException { |
| 86 | + try (Connection connection = borrowConnection(); |
| 87 | + Statement statement = connection.createStatement(); |
| 88 | + ResultSet s = statement.executeQuery(query)) { |
| 89 | + List<T> results = ResultSetToObjectConverter.convert(s, targetClass); |
| 90 | + return results.isEmpty() ? null : results; |
| 91 | + } catch (SQLException e) { |
| 92 | + LOGGER.error("Error executing query {}", query, e); |
| 93 | + throw e; |
| 94 | + } catch (Exception e) { |
| 95 | + throw new RuntimeException(e); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + public int executeUpdate(String query) throws SQLException { |
| 100 | + try (Connection connection = borrowConnection(); |
| 101 | + Statement statement = connection.createStatement()) { |
| 102 | + return statement.executeUpdate(query); |
| 103 | + } catch (SQLException e) { |
| 104 | + LOGGER.error("Error executing query {}", query, e); |
| 105 | + throw e; |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + public int executeUpdate(String query, Statement statement) throws SQLException { |
| 110 | + LOGGER.debug("Executing query {} within transaction", query); |
| 111 | + try { |
| 112 | + return statement.executeUpdate(query); |
| 113 | + } catch (SQLException e) { |
| 114 | + LOGGER.error("Error executing query {}", query, e); |
| 115 | + throw e; |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + public void runWithinTransaction(TransactionCallback callback) throws SQLException { |
| 120 | + Connection connection = null; |
| 121 | + try { |
| 122 | + connection = borrowConnection(); |
| 123 | + connection.setAutoCommit(false); // Disable auto-commit to start a transaction |
| 124 | + |
| 125 | + boolean result; |
| 126 | + try (Statement statement = connection.createStatement()) { |
| 127 | + result = callback.execute(statement); |
| 128 | + } |
| 129 | + |
| 130 | + if (result) { |
| 131 | + connection.commit(); // Commit the transaction if successful |
| 132 | + } else { |
| 133 | + connection.rollback(); // Rollback the transaction if not successful |
| 134 | + } |
| 135 | + |
| 136 | + } catch (SQLException e) { |
| 137 | + if (connection != null) { |
| 138 | + try { |
| 139 | + connection.rollback(); // Rollback on exception |
| 140 | + } catch (SQLException ex) { |
| 141 | + LOGGER.error("Error rolling back transaction", ex); |
| 142 | + throw e; |
| 143 | + } |
| 144 | + } |
| 145 | + LOGGER.error("Caught Error while executing transaction", e); |
| 146 | + throw e; |
| 147 | + } finally { |
| 148 | + if (connection != null) { |
| 149 | + try { |
| 150 | + connection.setAutoCommit(true); // Restore auto-commit |
| 151 | + connection.close(); |
| 152 | + } catch (SQLException e) { |
| 153 | + LOGGER.error("Error closing connection", e); |
| 154 | + throw e; |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + // Interface for transaction callback |
| 161 | + public interface TransactionCallback { |
| 162 | + boolean execute(Statement statement) throws SQLException; |
| 163 | + } |
| 164 | + |
| 165 | + public boolean isConstraintViolation(SQLException e) { |
| 166 | + return CONSTRAINT_VIOLATION_SQL_CODE.equals(e.getSQLState()); |
| 167 | + } |
| 168 | + |
| 169 | + public boolean isAlreadyExistsException(SQLException e) { |
| 170 | + return ALREADY_EXISTS_STATE_POSTGRES.equals(e.getSQLState()); |
| 171 | + } |
| 172 | + |
| 173 | + private Connection borrowConnection() throws SQLException { |
| 174 | + return datasource.getConnection(); |
| 175 | + } |
| 176 | +} |
0 commit comments