HookContext.java

  1. /*
  2.  *    Copyright 2010-2023 the original author or authors.
  3.  *
  4.  *    Licensed under the Apache License, Version 2.0 (the "License");
  5.  *    you may not use this file except in compliance with the License.
  6.  *    You may obtain a copy of the License at
  7.  *
  8.  *       https://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  *    Unless required by applicable law or agreed to in writing, software
  11.  *    distributed under the License is distributed on an "AS IS" BASIS,
  12.  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  *    See the License for the specific language governing permissions and
  14.  *    limitations under the License.
  15.  */
  16. package org.apache.ibatis.migration.hook;

  17. import java.io.Reader;
  18. import java.io.StringReader;
  19. import java.sql.Connection;
  20. import java.sql.SQLException;

  21. import org.apache.ibatis.migration.Change;
  22. import org.apache.ibatis.migration.ConnectionProvider;
  23. import org.apache.ibatis.migration.operations.ScriptRunner;

  24. public class HookContext {
  25.   private ConnectionProvider connectionProvider;
  26.   private ScriptRunner scriptRunner;
  27.   private Change change;

  28.   public HookContext(ConnectionProvider connectionProvider, ScriptRunner scriptRunner, Change change) {
  29.     this.connectionProvider = connectionProvider;
  30.     this.scriptRunner = scriptRunner;
  31.     this.change = change;
  32.   }

  33.   /**
  34.    * @return A new {@link Connection} to the database. The returned connection must be closed.
  35.    *
  36.    * @throws SQLException
  37.    *           If a database access error occurs.
  38.    */
  39.   public Connection getConnection() throws SQLException {
  40.     return connectionProvider.getConnection();
  41.   }

  42.   /**
  43.    * @param reader
  44.    *          Source of the SQL to execute.
  45.    */
  46.   public void executeSql(Reader reader) {
  47.     scriptRunner.runScript(reader);
  48.   }

  49.   /**
  50.    * @param sql
  51.    *          SQL to execute.
  52.    */
  53.   public void executeSql(String sql) {
  54.     try (StringReader reader = new StringReader(sql)) {
  55.       executeSql(reader);
  56.     }
  57.   }

  58.   /**
  59.    * @return Returns an instance of {@link Change} object for an each hook; <code>null</code> otherwise.
  60.    */
  61.   public Change getChange() {
  62.     return change;
  63.   }
  64. }