Generate and write sql statements to output file

@param revTableExists
if revision table does not exists -&gt; create index
@param pageTableExists
if page table does not exists -&gt; create index
@param mode
generation mode
552855
void writeSQL(boolean revTableExists, boolean pageTableExists, GeneratorMode mode)
	{
		try (Writer writer = new BufferedWriter(new OutputStreamWriter(
				new BufferedOutputStream(new FileOutputStream(outputPath)), charset))){
			StringBuilder dataToDump = new StringBuilder();

			dataToDump.append(generateTemplateIdSQLStatement(this.tableExists));

			if (mode.active_for_pages) {
				dataToDump.append(generatePageSQLStatement(pageTableExists,
						mode.templateNameToPageId));
			}
			if (mode.active_for_revisions) {
				dataToDump.append(generateRevisionSQLStatement(revTableExists,
						mode.templateNameToRevId));
			}
			writer.write(dataToDump.toString());
		}
		catch (IOException e) {
			logger.error("Error writing SQL file: {}", e.getMessage(), e);
		}
	}
1190680
public void createTables( boolean makeIndexes ) throws Exception {
        database.executeInsertUpdateDeleteSql("DROP TABLE IF EXISTS " + TABLE_TILES);
        database.executeInsertUpdateDeleteSql("DROP TABLE IF EXISTS " + TABLE_METADATA);
        database.executeInsertUpdateDeleteSql(CREATE_TILES);
        database.executeInsertUpdateDeleteSql(CREATE_METADATA);
        if (makeIndexes) {
            createIndexes();
        }
    }
1302026
public void createTables(TableCreationMode mode) {
        try (Connection connection = getConnection()) {
            connection.setAutoCommit(false);
            createTables(connection, mode, true);
            connection.commit();
        } catch (SQLException e) {
            throw new TableModificationException(e);
        }
    }
55601
@Then("^table '(.+?)' exists$")
    public void checkTable(String tableName) throws Exception {
        Statement myStatement = null;
        Connection myConnection = this.commonspec.getConnection();

        //query checks table existence, existence table name in system table  pg_tables
        String query = "SELECT * FROM pg_tables WHERE tablename = " + "\'" + tableName + "\'" + ";";
        try {
            myStatement = myConnection.createStatement();
            java.sql.ResultSet rs = myStatement.executeQuery(query);
            //if there are no data row
            if (rs.next() == false) {
                Assertions.assertThat(rs.next()).as("there are no table " + tableName).isTrue();
            } else {
                //data exist
                String resultTableName = rs.getString(2);
                assertThat(resultTableName).as("there are incorrect table name " + tableName).contains(tableName);
            }
            rs.close();
            myStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
983192
protected void append(AppendRecord record, InputStream in, int length)
            throws JournalException {

        try {
            conHelper.exec(insertRevisionStmtSQL, record.getRevision(), getId(), record.getProducerId(),
                new StreamWrapper(in, length));

        } catch (SQLException e) {
            String msg = "Unable to append revision " + lockedRevision + ".";
            throw new JournalException(msg, e);
        }
    }
388849
public boolean revisionContainsTemplateNameWithoutIndex(int revId, String templateName) throws WikiApiException{
    	if(revApi==null){
    		revApi = new RevisionApi(wiki.getDatabaseConfiguration());
    	}
    	if(parser==null){
    		//TODO switch to SWEBLE
    		MediaWikiParserFactory pf = new MediaWikiParserFactory(
    				wiki.getDatabaseConfiguration().getLanguage());
    		pf.setTemplateParserClass(ShowTemplateNamesAndParameters.class);
    		parser = pf.createParser();
    	}

    	List<Template> tplList = parser.parse(revApi.getRevision(revId).getRevisionText()).getTemplates();
    	for(Template tpl:tplList){
    		if(tpl.getName().equalsIgnoreCase(templateName)){
    			return true;
    		}
    	}
    	return false;
    }
881836
@Override
  public List<String> generateQueries() {

    ensureParentOfStagingPathExists();

    List<String> hiveQueries = Lists.newArrayList();
    /*
     * Setting partition mode to 'nonstrict' is needed to improve readability of the code.
     * If we do not set dynamic partition mode to nonstrict, we will have to write partition values also,
     * and because hive considers partition as a virtual column, we also have to write each of the column
     * name in the query (in place of *) to match source and target columns.
     */
    hiveQueries.add("SET hive.exec.dynamic.partition.mode=nonstrict");

    Preconditions.checkNotNull(this.workUnit, "Workunit must not be null");
    EventWorkunitUtils.setBeginDDLBuildTimeMetadata(this.workUnit, System.currentTimeMillis());

    HiveConverterUtils.createStagingDirectory(fs, outputTableMetadata.getDestinationDataPath(),
        conversionEntity, this.workUnitState);

    // Create DDL statement for table
    String createStagingTableDDL =
        HiveConverterUtils.generateCreateDuplicateTableDDL(
            inputDbName,
            inputTableName,
            stagingTableName,
            stagingDataLocation,
            Optional.of(outputDatabaseName));
    hiveQueries.add(createStagingTableDDL);
    log.debug("Create staging table DDL:\n" + createStagingTableDDL);


    String insertInStagingTableDML =
        HiveConverterUtils
            .generateTableCopy(
                inputTableName,
                stagingTableName,
                conversionEntity.getTable().getDbName(),
                outputDatabaseName,
                Optional.of(partitionsDMLInfo));
    hiveQueries.add(insertInStagingTableDML);
    log.debug("Conversion staging DML: " + insertInStagingTableDML);

    log.info("Conversion Queries {}\n",  hiveQueries);

    EventWorkunitUtils.setEndDDLBuildTimeMetadata(workUnit, System.currentTimeMillis());
    return hiveQueries;
  }
1342355
public void createTable(TableSpec spec) throws SQLException {
        Statement s = createStatement();
        Iterator<String> iter = m_converter.getDDL(spec).iterator();
        while (iter.hasNext()) {
            String updateSQL = iter.next();
            s.executeUpdate(updateSQL);
        }
    }
339163
public boolean tableExists(TableReference tableRef) throws IOException {
    try {
      Table fetchedTable = service.tables().get(
          tableRef.getProjectId(), tableRef.getDatasetId(), tableRef.getTableId()).execute();
      logger.atFine().log(
          "Successfully fetched table '%s' for tableRef '%s'", fetchedTable, tableRef);
      return true;
    } catch (IOException ioe) {
      if (errorExtractor.itemNotFound(ioe)) {
        return false;
      } else {
        // Unhandled exceptions should just propagate up.
        throw ioe;
      }
    }
  }
402925
private static int findCommonAncestor(RevisionInternal rev, List<String> possibleRevIDs) {
        if (possibleRevIDs == null || possibleRevIDs.size() == 0) {
            return 0;
        }
        List<String> history = Database.parseCouchDBRevisionHistory(rev.getProperties());

        //rev is missing _revisions property
        assert (history != null);

        boolean changed = history.retainAll(possibleRevIDs);
        String ancestorID = history.size() == 0 ? null : history.get(0);

        if (ancestorID == null) {
            return 0;
        }

        int generation = RevisionUtils.parseRevIDNumber(ancestorID);

        return generation;
    }
1273306
private void verifyTableExists(BaseDaoImpl<?, ?> dao) {
		try {
			if (!dao.isTableExists()) {
				throw new GeoPackageException(
						"Table or view does not exist for: "
								+ dao.getDataClass().getSimpleName());
			}
		} catch (SQLException e) {
			throw new GeoPackageException(
					"Failed to detect if table or view exists for dao: "
							+ dao.getDataClass().getSimpleName(), e);
		}
	}
809127
public static String generateNextRevisionId(String revisionId) {
        validateRevisionId(revisionId);
        int generation = generationFromRevId(revisionId);
        String digest = createUUID();
        return Integer.toString(generation + 1) + "-" + digest;
    }
154208
public boolean tableExists(String table)
		throws SQLException
	{

		PreparedStatement statement = null;
		ResultSet result = null;
		try {
			statement = this.connection.prepareStatement("SHOW TABLES;");
			result = execute(statement);

			if (result == null) {
				return false;
			}
			boolean found = false;
			while(result.next()){
					if(table.equalsIgnoreCase(result.getString(1))){
						found = true;
					}
			}
			return found;

		}
		finally {
			if (statement != null) {
				statement.close();
			}
			if (result != null) {
				result.close();
			}
		}

	}
404540
private void writeHeader()
		throws SQLException
	{

		Statement query;
		String[] revTableHeaderQueries;

		revTableHeaderQueries = sqlEncoder.getTable();

		//commit revision table header
		for (String revTableHeaderQuery : revTableHeaderQueries) {
			query = connection.createStatement();

			query.executeUpdate(revTableHeaderQuery);
			query.close();
		}

	}
377518
private void checkViewSources(ArrayList<Table> tableList) throws VoltCompilerException {
        HashSet<String> tableSet = new HashSet<>();
        for (Table tbl : tableList) {
            if (! tableSet.add(tbl.getTypeName())) {
                String errMsg = "Table " + tbl.getTypeName() + " appeared in the table list more than once: " +
                                "materialized view does not support self-join.";
                throw m_compiler.new VoltCompilerException(errMsg);
            }
        }
    }
381261
public static void createTables(Connection connection) throws IOException, SQLException {
        StringBuilder sB = new StringBuilder();
        sB.append("CREATE TABLE ");
        sB.append(TABLE_BOOKMARKS);
        sB.append(" (");
        sB.append(COLUMN_ID);
        sB.append(" INTEGER PRIMARY KEY, ");
        sB.append(COLUMN_LON).append(" REAL NOT NULL, ");
        sB.append(COLUMN_LAT).append(" REAL NOT NULL,");
        sB.append(COLUMN_ZOOM).append(" REAL NOT NULL,");
        sB.append(COLUMN_NORTHBOUND).append(" REAL NOT NULL,");
        sB.append(COLUMN_SOUTHBOUND).append(" REAL NOT NULL,");
        sB.append(COLUMN_WESTBOUND).append(" REAL NOT NULL,");
        sB.append(COLUMN_EASTBOUND).append(" REAL NOT NULL,");
        sB.append(COLUMN_TEXT).append(" TEXT NOT NULL ");
        sB.append(");");
        String CREATE_TABLE_BOOKMARKS = sB.toString();

        sB = new StringBuilder();
        sB.append("CREATE INDEX bookmarks_x_by_y_idx ON ");
        sB.append(TABLE_BOOKMARKS);
        sB.append(" ( ");
        sB.append(COLUMN_LON);
        sB.append(", ");
        sB.append(COLUMN_LAT);
        sB.append(" );");
        String CREATE_INDEX_BOOKMARKS_X_BY_Y = sB.toString();

        try (Statement statement = connection.createStatement()) {
            statement.setQueryTimeout(30); // set timeout to 30 sec.

            statement.executeUpdate(CREATE_TABLE_BOOKMARKS);
            statement.executeUpdate(CREATE_INDEX_BOOKMARKS_X_BY_Y);
        } catch (Exception e) {
            throw new IOException(e.getLocalizedMessage());
        }
    }
438745
void writeStatement(Session session, String s) {

        try {
            dbLogWriter.writeLogStatement(session, s);
        } catch (IOException e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR, logFileName);
        }

        if (maxLogSize > 0 && dbLogWriter.size() > maxLogSize) {
            database.logger.needsCheckpoint = true;
        }
    }