// Flatten the nested upgrade script into a buffer
  public static String buildCommand(
      NestedScriptParser dbCommandParser, String scriptDir, String scriptFile)
      throws IllegalFormatException, IOException {

    BufferedReader bfReader =
        new BufferedReader(new FileReader(scriptDir + File.separatorChar + scriptFile));
    String currLine;
    StringBuilder sb = new StringBuilder();
    String currentCommand = null;
    while ((currLine = bfReader.readLine()) != null) {
      currLine = currLine.trim();
      if (currLine.isEmpty()) {
        continue; // skip empty lines
      }

      if (currentCommand == null) {
        currentCommand = currLine;
      } else {
        currentCommand = currentCommand + " " + currLine;
      }
      if (dbCommandParser.isPartialCommand(currLine)) {
        // if its a partial line, continue collecting the pieces
        continue;
      }

      // if this is a valid executable command then add it to the buffer
      if (!dbCommandParser.isNonExecCommand(currentCommand)) {
        currentCommand = dbCommandParser.cleanseCommand(currentCommand);

        if (dbCommandParser.isNestedScript(currentCommand)) {
          // if this is a nested sql script then flatten it
          String currScript = dbCommandParser.getScriptName(currentCommand);
          sb.append(buildCommand(dbCommandParser, scriptDir, currScript));
        } else {
          // Now we have a complete statement, process it
          // write the line to buffer
          sb.append(currentCommand);
          sb.append(System.getProperty("line.separator"));
        }
      }
      currentCommand = null;
    }
    bfReader.close();
    return sb.toString();
  }
  // run beeline on the given sentry store scrip, flatten the nested scripts into single file
  private void runBeeLine(String scriptDir, String scriptFile) throws IOException {
    NestedScriptParser dbCommandParser = SentrySchemaHelper.getDbCommandParser(dbType);
    dbCommandParser.setDbOpts(getDbOpts());
    // expand the nested script
    String sqlCommands = buildCommand(dbCommandParser, scriptDir, scriptFile);
    File tmpFile = File.createTempFile("schematool", ".sql");
    tmpFile.deleteOnExit();

    // write out the buffer into a file. Add beeline commands for autocommit and close
    FileWriter fstream = new FileWriter(tmpFile.getPath());
    BufferedWriter out = new BufferedWriter(fstream);

    out.write("!set Silent " + verbose + System.getProperty("line.separator"));
    out.write("!autocommit on" + System.getProperty("line.separator"));
    out.write("!set Isolation TRANSACTION_READ_COMMITTED" + System.getProperty("line.separator"));
    out.write("!set AllowMultiLineCommand false" + System.getProperty("line.separator"));
    out.write(sqlCommands);
    out.write("!closeall" + System.getProperty("line.separator"));
    out.close();
    runBeeLine(tmpFile.getPath());
  }