View Javadoc
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.operations;
17  
18  import java.io.PrintStream;
19  import java.io.Reader;
20  import java.sql.Connection;
21  
22  import org.apache.ibatis.migration.ConnectionProvider;
23  import org.apache.ibatis.migration.MigrationException;
24  import org.apache.ibatis.migration.MigrationLoader;
25  import org.apache.ibatis.migration.options.DatabaseOperationOption;
26  import org.apache.ibatis.migration.utils.Util;
27  
28  public final class BootstrapOperation extends DatabaseOperation {
29    private final boolean force;
30  
31    public BootstrapOperation() {
32      this(false);
33    }
34  
35    public BootstrapOperation(boolean force) {
36      this.force = force;
37    }
38  
39    public BootstrapOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader,
40        DatabaseOperationOption option, PrintStream printStream) {
41      try (Connection con = connectionProvider.getConnection()) {
42        if (option == null) {
43          option = new DatabaseOperationOption();
44        }
45        if (changelogExists(con, option) && !force) {
46          println(printStream,
47              "For your safety, the bootstrap SQL script will only run before migrations are applied (i.e. before the changelog exists).  If you're certain, you can run it using the --force option.");
48        } else {
49          try (Reader bootstrapReader = migrationsLoader.getBootstrapReader()) {
50            if (bootstrapReader != null) {
51              println(printStream, Util.horizontalLine("Applying: bootstrap.sql", 80));
52              ScriptRunner runner = getScriptRunner(con, option, printStream);
53              runner.runScript(bootstrapReader);
54              println(printStream);
55            } else {
56              println(printStream, "Error, could not run bootstrap.sql.  The file does not exist.");
57            }
58          }
59        }
60        return this;
61      } catch (Exception e) {
62        throw new MigrationException("Error running bootstrapper.  Cause: " + e, e);
63      }
64    }
65  }