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
18 import java.io.Reader;
19 import java.io.StringReader;
20 import java.sql.Connection;
21 import java.sql.SQLException;
22
23 import org.apache.ibatis.migration.Change;
24 import org.apache.ibatis.migration.ConnectionProvider;
25 import org.apache.ibatis.migration.operations.ScriptRunner;
26
27 public class HookContext {
28 private ConnectionProvider connectionProvider;
29 private ScriptRunner scriptRunner;
30 private Change change;
31
32 public HookContext(ConnectionProvider connectionProvider, ScriptRunner scriptRunner, Change change) {
33 this.connectionProvider = connectionProvider;
34 this.scriptRunner = scriptRunner;
35 this.change = change;
36 }
37
38 /**
39 * @return A new {@link Connection} to the database. The returned connection must be closed.
40 *
41 * @throws SQLException
42 * If a database access error occurs.
43 */
44 public Connection getConnection() throws SQLException {
45 return connectionProvider.getConnection();
46 }
47
48 /**
49 * @param reader
50 * Source of the SQL to execute.
51 */
52 public void executeSql(Reader reader) {
53 scriptRunner.runScript(reader);
54 }
55
56 /**
57 * @param sql
58 * SQL to execute.
59 */
60 public void executeSql(String sql) {
61 try (StringReader reader = new StringReader(sql)) {
62 executeSql(reader);
63 }
64 }
65
66 /**
67 * @return Returns an instance of {@link Change} object for an each hook; <code>null</code> otherwise.
68 */
69 public Change getChange() {
70 return change;
71 }
72 }