Create the track segments table to store the segments of a track

@param connection
@param trackSegementsTableName
@param isH2 set true if it's an H2 database
@return
@throws SQLException
350819
public static PreparedStatement createTrackSegmentsTable(Connection connection, String trackSegementsTableName,boolean isH2) throws SQLException {
        try (Statement stmt = connection.createStatement()) {
            StringBuilder sb = new StringBuilder("CREATE TABLE ");
            sb.append(trackSegementsTableName).append(" (");
            if (isH2) {
                sb.append("the_geom LINESTRING CHECK ST_SRID(THE_GEOM) = 4326,");
            } else {
                sb.append("the_geom GEOMETRY(LINESTRING, 4326),");
            }
            sb.append(" id INT,");
            sb.append(GPXTags.EXTENSIONS).append(" TEXT,");
            sb.append("id_track INT);");
            stmt.execute(sb.toString());
        }
        //We return the preparedstatement of the waypoints table
        StringBuilder insert = new StringBuilder("INSERT INTO ").append(trackSegementsTableName).append(" VALUES ( ?");
        for (int i = 1; i < GpxMetadata.TRKSEGFIELDCOUNT; i++) {
            insert.append(",?");
        }
        insert.append(");");
        return connection.prepareStatement(insert.toString());

    }
1020621
public static void createEmptyTable(Connection connection, String tableReference) throws SQLException {
        try (Statement statement = connection.createStatement()) {
            statement.execute("CREATE TABLE "+ tableReference+ " ()");
        }
    }
1291929
private void processCreateStreamStatement(DDLStatement stmt, Database db, DdlProceduresToLoad whichProcs)
            throws VoltCompilerException {
        String statement = stmt.statement;
        Matcher statementMatcher = SQLParser.matchCreateStream(statement);
        if (statementMatcher.matches()) {
            // check the table portion
            String tableName = checkIdentifierStart(statementMatcher.group(1), statement);
            String targetName = null;
            String columnName = null;

            // Parse the EXPORT and PARTITION clauses.
            if ((statementMatcher.groupCount() > 1) &&
                (statementMatcher.group(2) != null) &&
                (!statementMatcher.group(2).isEmpty())) {
                String clauses = statementMatcher.group(2);
                Matcher matcher = SQLParser.matchAnyCreateStreamStatementClause(clauses);
                int start = 0;
                while ( matcher.find(start)) {
                    start = matcher.end();

                    if (matcher.group(1) != null) {
                        // Add target info if it's an Export clause. Only one is allowed
                        if (targetName != null) {
                            throw m_compiler.new VoltCompilerException(
                                "Only one Export clause is allowed for CREATE STREAM.");
                        }
                        targetName = matcher.group(1);
                    }
                    else {
                        // Add partition info if it's a PARTITION clause. Only one is allowed.
                        if (columnName != null) {
                            throw m_compiler.new VoltCompilerException(
                                "Only one PARTITION clause is allowed for CREATE STREAM.");
                        }
                        columnName = matcher.group(2);
                    }
                }
            }
            VoltXMLElement tableXML = m_schema.findChild("table", tableName.toUpperCase());
            if (tableXML != null) {
                tableXML.attributes.put("stream", "true");
            } else {
                throw m_compiler.new VoltCompilerException(String.format(
                        "Invalid STREAM statement: table %s does not exist", tableName));
            }
            // process partition if specified
            if (columnName != null) {
                tableXML.attributes.put("partitioncolumn", columnName.toUpperCase());
                // Column validity check done by VoltCompiler in post-processing

                // mark the table as dirty for the purposes of caching sql statements
                m_compiler.markTableAsDirty(tableName);
            }

            // process export
            targetName = (targetName != null) ? checkIdentifierStart(
                    targetName, statement) : Constants.DEFAULT_EXPORT_CONNECTOR_NAME;

            if (tableXML.attributes.containsKey("drTable") && "ENABLE".equals(tableXML.attributes.get("drTable"))) {
                throw m_compiler.new VoltCompilerException(String.format(
                        "Invalid CREATE STREAM statement: table %s is a DR table.", tableName));
            } else {
                tableXML.attributes.put("export", targetName);
            }
        } else {
            throw m_compiler.new VoltCompilerException(String.format("Invalid CREATE STREAM statement: \"%s\", "
                    + "expected syntax: CREATE STREAM <table> [PARTITION ON COLUMN <column-name>] [EXPORT TO TARGET <target>] (column datatype, ...); ",
                    statement.substring(0, statement.length() - 1)));
        }
    }
758063
def add_segment(self, segment):
        
        self.tracks.add(segment.track)
        self.segments.append(segment)
1028753
public static PreparedStatement createWayTagTable(Connection connection, String wayTagTableName, String tagTableName) throws SQLException {
        try (Statement stmt = connection.createStatement()) {
            StringBuilder sb = new StringBuilder("CREATE TABLE ");
            sb.append(wayTagTableName);
            sb.append("(ID_WAY BIGINT, ID_TAG BIGINT, VALUE VARCHAR);");
            stmt.execute(sb.toString());
        }
        //We return the preparedstatement of the way tag table
        StringBuilder insert = new StringBuilder("INSERT INTO ");
        insert.append(wayTagTableName);
        insert.append("VALUES ( ?, ");
        insert.append("(SELECT ID_TAG FROM ").append(tagTableName).append(" WHERE TAG_KEY = ? LIMIT 1)");
        insert.append(", ?);");
        return connection.prepareStatement(insert.toString());
    }
312240
public static Connection createSpatialDataBase(String dbName, boolean initSpatial )throws SQLException, ClassNotFoundException {
        return createSpatialDataBase(dbName, initSpatial, H2_PARAMETERS);
    }
537141
public static Set<String> getForeignKeys(DriverTypeEnum.ConnectionProperties theConnectionProperties, String theTableName, String theForeignTable) throws SQLException {
		DataSource dataSource = Objects.requireNonNull(theConnectionProperties.getDataSource());
		try (Connection connection = dataSource.getConnection()) {
			return theConnectionProperties.getTxTemplate().execute(t -> {
				DatabaseMetaData metadata;
				try {
					metadata = connection.getMetaData();
					ResultSet indexes = metadata.getCrossReference(connection.getCatalog(), connection.getSchema(), massageIdentifier(metadata, theTableName), connection.getCatalog(), connection.getSchema(), massageIdentifier(metadata, theForeignTable));

					Set<String> columnNames = new HashSet<>();
					while (indexes.next()) {
						String tableName = toUpperCase(indexes.getString("PKTABLE_NAME"), Locale.US);
						if (!theTableName.equalsIgnoreCase(tableName)) {
							continue;
						}
						tableName = toUpperCase(indexes.getString("FKTABLE_NAME"), Locale.US);
						if (!theForeignTable.equalsIgnoreCase(tableName)) {
							continue;
						}

						String fkName = indexes.getString("FK_NAME");
						fkName = toUpperCase(fkName, Locale.US);
						columnNames.add(fkName);
					}

					return columnNames;
				} catch (SQLException e) {
					throw new InternalErrorException(e);
				}
			});
		}
	}
188989
public static void registerSpatialTables(Connection connection) throws SQLException {
        Statement st = connection.createStatement();
        st.execute("drop view if exists geometry_columns");
        st.execute("create view geometry_columns as select TABLE_CATALOG f_table_catalog,TABLE_SCHEMA f_table_schema,TABLE_NAME f_table_name," +
                "COLUMN_NAME f_geometry_column,1 storage_type,_GeometryTypeFromConstraint(CHECK_CONSTRAINT || REMARKS, NUMERIC_PRECISION) geometry_type," +
                "_DimensionFromConstraint(TABLE_CATALOG,TABLE_SCHEMA, TABLE_NAME,COLUMN_NAME,CHECK_CONSTRAINT) coord_dimension," +
                "_ColumnSRID(TABLE_CATALOG,TABLE_SCHEMA, TABLE_NAME,COLUMN_NAME,CHECK_CONSTRAINT) srid," +
                " _GeometryTypeNameFromConstraint(CHECK_CONSTRAINT || REMARKS, NUMERIC_PRECISION) type" +
                " from INFORMATION_SCHEMA.COLUMNS WHERE TYPE_NAME = 'GEOMETRY'");
        ResultSet rs = connection.getMetaData().getTables("","PUBLIC","SPATIAL_REF_SYS",null);
        if(!rs.next()) {
        	InputStreamReader reader = new InputStreamReader(
					H2GISFunctions.class.getResourceAsStream("spatial_ref_sys.sql"));
			RunScript.execute(connection, reader);
				
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    }
37154
public void createTables(Connection connection, TableCreationMode mode, boolean createIndexes) {
        ArrayList<Type<?>> sorted = sortTypes();
        try (Statement statement = connection.createStatement()) {
            if (mode == TableCreationMode.DROP_CREATE) {
                ArrayList<Type<?>> reversed = sortTypes();
                Collections.reverse(reversed);
                executeDropStatements(statement, reversed);
            }
            for (Type<?> type : sorted) {
                String sql = tableCreateStatement(type, mode);
                statementListeners.beforeExecuteUpdate(statement, sql, null);
                statement.execute(sql);
                statementListeners.afterExecuteUpdate(statement, 0);
            }
            if (createIndexes) {
                for (Type<?> type : sorted) {
                    createIndexes(connection, mode, type);
                }
            }
        } catch (SQLException e) {
            throw new TableModificationException(e);
        }
    }
244963
public static PreparedStatement createRelationMemberTable(Connection connection, String relationMemberTable) throws SQLException {
        try (Statement stmt = connection.createStatement()) {
            StringBuilder sb = new StringBuilder("CREATE TABLE ");
            sb.append(relationMemberTable);
            sb.append("(ID_RELATION BIGINT, ID_SUB_RELATION BIGINT, ROLE VARCHAR, RELATION_ORDER INT);");
            stmt.execute(sb.toString());
        }
        return connection.prepareStatement("INSERT INTO " + relationMemberTable + " VALUES ( ?,?,?,?);");
    }
947897
public List<String> getTracksString(Map<String, GenomeBrowserTrack> entityTracks) {
    List<String> results = new ArrayList<>();
    if (hasPermission()) {
      Map<String, GenomeBrowserTrack> allTracks = new HashMap<>(entityTracks);
      for (GenomeBrowserTrack track : entityTracks.values()) {
        allTracks.putAll(getReferenceTracks(track));
      }
      results =
          allTracks
              .values()
              .stream()
              .map(GenomeBrowserTrack::toTrackString)
              .collect(Collectors.toList());
    }
    return results;
  }
757326
public static boolean hasField(Connection connection, String tableName, String fieldName) throws SQLException {
        final Statement statement = connection.createStatement();
        try {
            final ResultSet resultSet = statement.executeQuery(
                    "SELECT * FROM " + TableLocation.parse(tableName) + " LIMIT 0;");
            try {
                return hasField(resultSet.getMetaData(), fieldName);
            } finally {
                resultSet.close();
            }
        } catch (SQLException ex) {
            return false;
        } finally {
            statement.close();
        }
    }
1045795
private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,
			List<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails)
			throws SQLException {
		StringBuilder sb = new StringBuilder(256);
		if (logDetails) {
			logger.info("creating table '{}'", tableInfo.getTableName());
		}
		sb.append("CREATE TABLE ");
		if (ifNotExists && databaseType.isCreateIfNotExistsSupported()) {
			sb.append("IF NOT EXISTS ");
		}
		databaseType.appendEscapedEntityName(sb, tableInfo.getTableName());
		sb.append(" (");
		List<String> additionalArgs = new ArrayList<String>();
		List<String> statementsBefore = new ArrayList<String>();
		List<String> statementsAfter = new ArrayList<String>();
		// our statement will be set here later
		boolean first = true;
		for (FieldType fieldType : tableInfo.getFieldTypes()) {
			// skip foreign collections
			if (fieldType.isForeignCollection()) {
				continue;
			} else if (first) {
				first = false;
			} else {
				sb.append(", ");
			}
			String columnDefinition = fieldType.getColumnDefinition();
			if (columnDefinition == null) {
				// we have to call back to the database type for the specific create syntax
				databaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore,
						statementsAfter, queriesAfter);
			} else {
				// hand defined field
				databaseType.appendEscapedEntityName(sb, fieldType.getColumnName());
				sb.append(' ').append(columnDefinition).append(' ');
			}
		}
		// add any sql that sets any primary key fields
		databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,
				queriesAfter);
		// add any sql that sets any unique fields
		databaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,
				queriesAfter);
		for (String arg : additionalArgs) {
			// we will have spat out one argument already so we don't have to do the first dance
			sb.append(", ").append(arg);
		}
		sb.append(") ");
		databaseType.appendCreateTableSuffix(sb);
		statements.addAll(statementsBefore);
		statements.add(sb.toString());
		statements.addAll(statementsAfter);
		addCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails);
		addCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails);
	}
979958
public static boolean createTableIfNotExists(final Connection conn, final String tableName, final String schema) {
        if (doesTableExist(conn, tableName)) {
            return false;
        }

        try {
            execute(conn, schema);

            return true;
        } catch (SQLException e) {
            return false;
        }
    }
678452
protected void setUp() throws SQLException {
		Connection c = null;
		try {
			c = DriverManager.getConnection("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
			Statement stmt = c.createStatement();
			stmt.execute("create table foo (id number(6), dsc varchar2(256))");
			stmt.close();
		} finally {
			if (c != null) {
				c.close();
			}
		}
	}
311889
public static PreparedStatement createTrackPointsTable(Connection connection, String trackPointsTableName,boolean isH2) throws SQLException {
        try (Statement stmt = connection.createStatement()) {
            StringBuilder sb = new StringBuilder("CREATE TABLE ");
            sb.append(trackPointsTableName).append(" (");
            if(isH2){
                sb.append("the_geom POINT CHECK ST_SRID(THE_GEOM) = 4326,");
            }
            else{
                sb.append("the_geom GEOMETRY(POINT, 4326),");
            }
            sb.append(" id INT,");
            sb.append(GPXTags.LAT.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.LON.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.ELE.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.TIME.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.MAGVAR.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.GEOIDHEIGHT.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.NAME.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.CMT.toLowerCase()).append(" TEXT,");
            sb.append("description").append(" TEXT,");
            sb.append(GPXTags.SRC.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.HREF.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.HREFTITLE.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.SYM.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.TYPE.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.FIX.toLowerCase()).append(" TEXT,");
            sb.append(GPXTags.SAT.toLowerCase()).append(" INT,");
            sb.append(GPXTags.HDOP.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.VDOP.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.PDOP.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.AGEOFDGPSDATA.toLowerCase()).append(" FLOAT8,");
            sb.append(GPXTags.DGPSID.toLowerCase()).append(" INT,");
            sb.append(GPXTags.EXTENSIONS.toLowerCase()).append(" BOOLEAN,");
            sb.append("track_segment_id").append(" INT);");
            stmt.execute(sb.toString());
        }
        //We return the preparedstatement of the waypoints table
        StringBuilder insert = new StringBuilder("INSERT INTO ").append(trackPointsTableName).append(" VALUES ( ?");
        for (int i = 1; i < GpxMetadata.RTEPTFIELDCOUNT; i++) {
            insert.append(",?");
        }
        insert.append(");");
        return connection.prepareStatement(insert.toString());
    }
1213270
public boolean read(Connection connection, String tableName, File inputFile, ProgressVisitor progress) throws SQLException {
        this.progress = progress.subProcess(100);
        // Initialisation
        final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData());
        boolean success = false;
        TableLocation requestedTable = TableLocation.parse(tableName, isH2);
        String osmTableName = requestedTable.getTable();
        checkOSMTables(connection, isH2, requestedTable, osmTableName);
        createOSMDatabaseModel(connection, isH2, requestedTable, osmTableName);

        FileInputStream fs = null;
        try {
            fs = new FileInputStream(inputFile);
            this.fc = fs.getChannel();
            this.fileSize = fc.size();
            if (fileSize > 0) {
                // Given the file size and an average node file size.
                // Skip how many nodes in order to update progression at a step of 1%
                readFileSizeEachNode = Math.max(1, (this.fileSize / AVERAGE_NODE_SIZE) / 100);
                nodeCountProgress = 0;
                XMLReader parser = XMLReaderFactory.createXMLReader();
                parser.setErrorHandler(this);
                parser.setContentHandler(this);
                if (inputFile.getName().endsWith(".osm")) {
                    parser.parse(new InputSource(fs));
                } else if (inputFile.getName().endsWith(".osm.gz")) {
                    parser.parse(new InputSource(new GZIPInputStream(fs)));
                } else if (inputFile.getName().endsWith(".osm.bz2")) {
                    parser.parse(new InputSource(new BZip2CompressorInputStream(fs)));
                } else {
                    throw new SQLException("Supported formats are .osm, .osm.gz, .osm.bz2");
                }
            }
            success = true;
        } catch (SAXException ex) {
            throw new SQLException(ex);
        } catch (IOException ex) {
            throw new SQLException("Cannot parse the file " + inputFile.getAbsolutePath(), ex);
        } finally {
            try {
                if (fs != null) {
                    fs.close();
                }
            } catch (IOException ex) {
                throw new SQLException("Cannot close the file " + inputFile.getAbsolutePath(), ex);
            }
            // When the reading ends, close() method has to be called
            if (nodePreparedStmt != null) {
                nodePreparedStmt.close();
            }
            if (nodeTagPreparedStmt != null) {
                nodeTagPreparedStmt.close();
            }
            if (wayPreparedStmt != null) {
                wayPreparedStmt.close();
            }
            if (wayTagPreparedStmt != null) {
                wayTagPreparedStmt.close();
            }
            if (wayNodePreparedStmt != null) {
                wayNodePreparedStmt.close();
            }
            if (relationPreparedStmt != null) {
                relationPreparedStmt.close();
            }
            if (relationTagPreparedStmt != null) {
                relationTagPreparedStmt.close();
            }
            if (nodeMemberPreparedStmt != null) {
                nodeMemberPreparedStmt.close();
            }
            if (wayMemberPreparedStmt != null) {
                wayMemberPreparedStmt.close();
            }
            if (relationMemberPreparedStmt != null) {
                relationMemberPreparedStmt.close();
            }
            if(tagPreparedStmt!=null){
                tagPreparedStmt.close();
            }
        }

        return success;
    }