Class Database<G>
- Type Parameters:
G- the type of geometry objects. Depends on the backing implementation (ESRI, JTS, Java2D…).
- Direct Known Subclasses:
Postgres
ResultSet.getInt(int)
and wraps the result in an Integer if it was not null) or can be a more
complex process (e.g. decode a geometry Well-Known Binary). This class does not perform the conversions directly,
but instead provides a converter object for each specified SQL type.
This base class provides mapping for common types (text, numbers, temporal objects, etc.) and for geometry types as specified in OpenGIS® Implementation Standard for Geographic information — Simple feature access — Part 2: SQL option. Subclasses can override some functions if a particular database software (e.g. PostGIS) provides specialized methods or have non-standard behavior for some data types.
Specializations
Subclasses may be defined for some database engines. Methods that can be overridden are:getMapping(Column)for adding column types to recognize.createInfoStatements(Connection)for more info about spatial information.addIgnoredTables(Map)for specifying more tables to ignore.
Multi-threading
This class is safe for concurrent use by many threads. This class does not hold JDBC resources such asConnection. Those resources are created temporarily when needed by InfoStatements.
Schema updates
Current implementation does not track changes in the database schema. if the database schema changes, then a newDatabase instance shall be created.- Since:
- 1.1
- Version:
- 1.2
- Author:
- Johann Sorel (Geomatys), Martin Desruisseaux (Geomatys), Alexis Manin (Geomatys)
-
Field Summary
FieldsModifier and TypeFieldDescriptionfinal StoreListenersWhere to send warnings.protected final DataSourceProvider of (pooled) connections to the database.static final StringThe SQL wildcard for any characters. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedDatabase(DataSource source, DatabaseMetaData metadata, Geometries<G> geomLibrary, StoreListeners listeners) Creates a new handler for a spatial database. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddIgnoredTables(Map<String, Boolean> ignoredTables) Adds to the given map a list of tables to ignore when searching for feature tables.final voidappendFunctionCall(SQLBuilder sql, String function) Appends a call to a function defined in the spatial schema.static Database<?> create(SQLStore store, DataSource source, Connection connection, GeometryLibrary geomLibrary, org.opengis.util.GenericName[] tableNames, ResourceDefinition[] queries, SchemaModifier customizer, StoreListeners listeners) Creates a new handler for a spatial database.protected InfoStatementscreateInfoStatements(Connection connection) Prepares a cache of statements about spatial information using the given connection.final FeatureSetReturns the table for the given name.protected final ValueGetter<?> forGeometry(Column columnDefinition) Returns a function for getting values from a geometry or geography column.protected intgetArrayComponentType(Column columnDefinition) Returns the type of components in SQL arrays stored in a column.protected BinaryEncodinggetBinaryEncoding(Column columnDefinition) Returns an identifier of the way binary data are encoded by the JDBC driver.protected ValueGetter<Object> Returns a mapping forTypes.JAVA_OBJECTor unrecognized types.protected org.opengis.geometry.EnvelopegetEstimatedExtent(TableReference table, Column[] columns, boolean recall) Computes an estimation of the envelope of all geometry columns in the given table.protected SelectionClauseWriterReturns the converter from filters/expressions to theWHEREpart of SQL statement.protected ValueGetter<?> getMapping(Column columnDefinition) Returns a function for getting values from a column having the given definition.final booleanReturnstrueif this database contains at least one geometry column.final booleanReturnstrueif this database contains at least one raster column.final booleanReturnstrueif this database is a spatial database.final voidlistTables(DatabaseMetaData metadata, MetadataBuilder builder) Stores information about tables in the given metadata.protected final voidSets the logger, class and method names of the given record, then logs it.final List<FeatureSet> tables()Returns all tables in declaration order.toString()Formats a graphical representation of this database for debugging purpose.
-
Field Details
-
WILDCARD
The SQL wildcard for any characters. A string containing only this wildcard means "any value" and can sometimes be replaced bynull.- See Also:
-
source
Provider of (pooled) connections to the database. -
listeners
Where to send warnings.- See Also:
-
-
Constructor Details
-
Database
protected Database(DataSource source, DatabaseMetaData metadata, Geometries<G> geomLibrary, StoreListeners listeners) throws SQLException Creates a new handler for a spatial database.- Parameters:
source- provider of (pooled) connections to the database.metadata- metadata about the database.geomLibrary- the factory to use for creating geometric objects.listeners- where to send warnings.- Throws:
SQLException- if an error occurred while reading database metadata.
-
-
Method Details
-
create
public static Database<?> create(SQLStore store, DataSource source, Connection connection, GeometryLibrary geomLibrary, org.opengis.util.GenericName[] tableNames, ResourceDefinition[] queries, SchemaModifier customizer, StoreListeners listeners) throws Exception Creates a new handler for a spatial database.- Parameters:
store- the data store for which we are creating a model. Used only in case of error.source- provider of (pooled) connections to the database.connection- connection to the database. Sometimes the caller already has a connection at hand.geomLibrary- the factory to use for creating geometric objects.tableNames- qualified name of the tables. Specified by users at construction time.queries- additional resources associated to SQL queries. Specified by users at construction time.customizer- user-specified modification to the features, ornullif none.listeners- where to send warnings.- Returns:
- handler for the spatial database.
- Throws:
SQLException- if a database error occurred while reading metadata.DataStoreException- if a logical error occurred while analyzing the database structure.Exception
-
listTables
public final void listTables(DatabaseMetaData metadata, MetadataBuilder builder) throws SQLException Stores information about tables in the given metadata. Only tables explicitly requested by the user are listed.- Parameters:
metadata- information about the database.builder- where to add information about the tables.- Throws:
SQLException- if an error occurred while fetching table information.
-
tables
Returns all tables in declaration order. The list contains only the tables explicitly requested at construction time.- Returns:
- all tables in an unmodifiable list.
-
findTable
Returns the table for the given name. The given name may be one of the tables specified at construction time, or one of its dependencies.- Parameters:
store- the data store for which we are fetching a table. Used only in case of error.name- name of the table to fetch.- Returns:
- the table (never null).
- Throws:
IllegalNameException- if no table of the given name is found or if the name is ambiguous.
-
appendFunctionCall
Appends a call to a function defined in the spatial schema. The function name will be prefixed by catalog and schema name if applicable. The function will not be quoted.- Parameters:
sql- the SQL builder where to add the spatial function name.function- the function to append.
-
isSpatial
public final boolean isSpatial()Returnstrueif this database is a spatial database. Tables such as "SPATIAL_REF_SYS" are used as sentinel values.- Returns:
- whether this database is a spatial database.
-
hasGeometry
public final boolean hasGeometry()Returnstrueif this database contains at least one geometry column. This information can be used for metadata purpose.- Returns:
- whether at least one geometry column has been found.
-
hasRaster
public final boolean hasRaster()Returnstrueif this database contains at least one raster column. This information can be used for metadata purpose.- Returns:
- whether at least one raster column has been found.
-
getMapping
Returns a function for getting values from a column having the given definition. The given definition should include data SQL type and type name. If no match is found, then this method returnsnull.The default implementation handles types declared in the
Typesclass and the geometry types defined in the spatial extensions defined by OGC standard. Subclasses should override if some types need to be handle in a non-standard way for a particular database product.- Parameters:
columnDefinition- information about the column to extract values from and expose through Java API.- Returns:
- converter to the corresponding java type, or
nullif this class cannot find a mapping.
-
getArrayComponentType
Returns the type of components in SQL arrays stored in a column. This method is invoked when=invalid reference
#typeTypes.ARRAY. The default implementation returnsTypes.OTHERbecause JDBC column metadata does not provide information about component types. Database-specific subclasses should override this method if they can provide that information from theColumn.typeNamevalue.- Parameters:
columnDefinition- information about the column to extract array component type.- Returns:
- one of
Typesconstants. - See Also:
-
getDefaultMapping
Returns a mapping forTypes.JAVA_OBJECTor unrecognized types. Some JDBC drivers wrap objects in implementation-specific classes, for examplePGobject. This method should be overwritten in database-specific subclasses for returning a value getter capable to unwrap the value.- Returns:
- the default mapping for unknown or unrecognized types.
-
getBinaryEncoding
Returns an identifier of the way binary data are encoded by the JDBC driver.- Parameters:
columnDefinition- information about the column to extract binary values from.- Returns:
- how the binary data are returned by the JDBC driver.
-
getEstimatedExtent
protected org.opengis.geometry.Envelope getEstimatedExtent(TableReference table, Column[] columns, boolean recall) throws SQLException Computes an estimation of the envelope of all geometry columns in the given table. The returned envelope shall contain at least the two-dimensional spatial components. Whether other dimensions (vertical and temporal) and present or not depends on the implementation. This method is invoked only if thecolumnsarray contains at least one geometry column.- Parameters:
table- the table for which to compute an estimation of the envelope.columns- all columns in the table. Implementation should ignore non-geometry columns. This is a reference to an internal array; do not modify.recall- if it is at least the second time that this method is invoked for the specified table.- Returns:
- an estimation of the spatiotemporal resource extent, or
nullif none. - Throws:
SQLException- if an error occurred while fetching the envelope.
-
forGeometry
Returns a function for getting values from a geometry or geography column. This is a helper method forgetMapping(Column)implementations.- Parameters:
columnDefinition- information about the column to extract values from and expose through Java API.- Returns:
- converter to the corresponding java type, or
nullif this class cannot find a mapping,
-
createInfoStatements
Prepares a cache of statements about spatial information using the given connection. Statements will be created only when first needed.- Parameters:
connection- the connection to use for creating statements.- Returns:
- a cache of prepared statements about spatial information.
-
addIgnoredTables
Adds to the given map a list of tables to ignore when searching for feature tables. The given map already contains the"SPATIAL_REF_SYS"and"GEOMETRY_COLUMNS"entries when this method is invoked. The default implementation adds nothing.Values tells whether the table can be used as a sentinel value for determining that this database is a spatial database.
- Parameters:
ignoredTables- where to add names of tables to ignore.
-
getFilterToSQL
Returns the converter from filters/expressions to theWHEREpart of SQL statement. Subclasses should override this method if their database supports an extended syntax for some filters or expressions.The returned instance is usually a singleton instance. The caller of this method may create a copy of the returned instance for removing some functions that are found to be unsupported by the database software. Consequently, implementation of this method can assume that the database supports all the spatial operations managed by the returned writer.
- Returns:
- the converter from filters/expressions to the
WHEREpart of SQL statement.
-
log
Sets the logger, class and method names of the given record, then logs it. This method declaresSQLStore.components()as the public source of the log.- Parameters:
record- the record to configure and log.
-
toString
Formats a graphical representation of this database for debugging purpose. This representation can be printed to the standard output stream (for example) if the output device uses a monospaced font and supports Unicode.
-