org.geotools.jdbc
Class SQLDialect

Object
  extended by SQLDialect
Direct Known Subclasses:
BasicSQLDialect, DB2SQLDialect, H2Dialect, MySQLDialect, PreparedStatementSQLDialect

public abstract class SQLDialect
extends Object

The driver used by JDBCDataStore to directly communicate with the database.

This class encapsulates all the database specific operations that JDBCDataStore needs to function. It is implemented on a per-database basis.

Type Mapping

One of the jobs of a dialect is to map sql types to java types and vice versa. This abstract implementation provides default mappings for "primitive" java types. The following mappings are provided. A '*' denotes that the mapping is the default java to sql mapping as well. Subclasses should extend (not override) the following methods to configure the mappings:

This class is intended to be stateless, therefore subclasses should not maintain any internal state. If for some reason a subclass must keep some state around (not recommended), it must ensure that the state is accessed in a thread safe manner.

Author:
Justin Deoliveira, The Open Planning Project
Module:
modules/library/jdbc (gt-jdbc.jar)

Field Summary
static FilterCapabilities BASE_DBMS_CAPABILITIES
          The basic filter capabilities all databases should have
protected  JDBCDataStore dataStore
          The datastore using the dialect
protected static Logger LOGGER
           
 
Constructor Summary
protected SQLDialect(JDBCDataStore dataStore)
          Creates the dialect.
 
Method Summary
protected  void addSupportedHints(Set<Hints.Key> hints)
          Add hints to the JDBC Feature Source.
 void applyLimitOffset(StringBuffer sql, int limit, int offset)
          Alters the query provided so that limit and offset are natively dealt with.
 CoordinateReferenceSystem createCRS(int srid, Connection cx)
          Turns the specified srid into a CoordinateReferenceSystem, or returns null if not possible.
abstract  Envelope decodeGeometryEnvelope(ResultSet rs, int column, Connection cx)
          Decodes the result of a spatial extent function in a SELECT statement.
 Geometry decodeGeometryValue(GeometryDescriptor descriptor, ResultSet rs, int column, GeometryFactory factory, Connection cx)
          Decodes a geometry value from the result of a query specifying the column as an index.
abstract  Geometry decodeGeometryValue(GeometryDescriptor descriptor, ResultSet rs, String column, GeometryFactory factory, Connection cx)
          Decodes a geometry value from the result of a query.
 void encodeColumnAlias(String raw, StringBuffer sql)
          Encodes the alias of a column in an sql query.
 void encodeColumnName(String raw, StringBuffer sql)
          Encodes the name of a column in an SQL statement.
 void encodeColumnType(String sqlTypeName, StringBuffer sql)
          Encodes the type of a column in an SQL CREATE TABLE statement.
 void encodeGeometryColumn(GeometryDescriptor gatt, int srid, StringBuffer sql)
          Encodes the name of a geometry column in a SELECT statement.
 void encodeGeometryColumnGeneralized(GeometryDescriptor gatt, int srid, StringBuffer sql, Double distance)
          Encodes a generalized geometry using a DB provided SQL function if available If not supported, subclasses should not implement Only called if is supported Example: sql.append( "asText(generalize(" ); column( gatt.getLocalName(), sql ); sql.append( "," ); sql.append(distance); sql.append( "))" );
 void encodeGeometryColumnSimplified(GeometryDescriptor gatt, int srid, StringBuffer sql, Double distance)
          Encodes a simplified geometry using a DB provided SQL function if available If not supported, subclasses should not implement Only called if is supported
abstract  void encodeGeometryEnvelope(String tableName, String geometryColumn, StringBuffer sql)
          Encodes the spatial extent function of a geometry column in a SELECT statement.
 void encodePostColumnCreateTable(AttributeDescriptor att, StringBuffer sql)
          Encodes anything post a column in a CREATE TABLE statement.
 void encodePostCreateTable(String tableName, StringBuffer sql)
          Encodes anything post a CREATE TABLE statement.
 void encodePrimaryKey(String column, StringBuffer sql)
          Encodes the primary key definition in a CREATE TABLE statement.
 void encodeSchemaName(String raw, StringBuffer sql)
          Encodes the name of a schema in an SQL statement.
 void encodeTableAlias(String raw, StringBuffer sql)
          Encodes the alias of a table in an sql query.
 void encodeTableName(String raw, StringBuffer sql)
          Encodes the name of a table in an SQL statement.
 Integer getGeometrySRID(String schemaName, String tableName, String columnName, Connection cx)
          Returns the spatial reference system identifier (srid) for a particular geometry column.
 String getGeometryTypeName(Integer type)
          Returns the name of a geometric type based on its integer constant.
 Object getLastAutoGeneratedValue(String schemaName, String tableName, String columnName, Connection cx)
          Obtains the last value of an auto generated column.
 Class<?> getMapping(ResultSet columnMetaData, Connection cx)
          Determines the class mapping for a particular column of a table.
 String getNameEscape()
          Returns the string used to escape names.
 Object getNextAutoGeneratedValue(String schemaName, String tableName, String columnName, Connection cx)
          Obtains the next value of an auto generated column.
 Object getNextSequenceValue(String schemaName, String sequenceName, Connection cx)
          Obtains the next value of a sequence, incrementing the sequence to the next state in the process.
 String getSequenceForColumn(String schemaName, String tableName, String columnName, Connection cx)
          Determines the name of the sequence (if any) which is used to increment generate values for a table column.
 boolean includeTable(String schemaName, String tableName, Connection cx)
          Determines if the specified table should be included in those published by the datastore.
 void initializeConnection(Connection cx)
          Initializes a newly created database connection.
 boolean isLimitOffsetSupported()
          Returns true if this dialect can encode both Query.getStartIndex() and Query.getMaxFeatures() into native SQL.
 boolean lookupGeneratedValuesPostInsert()
          Controls whether keys are looked up post or pre insert.
protected  String ne()
          Quick accessor for getNameEscape().
 void postCreateAttribute(AttributeDescriptor att, ResultSet columnMetadata, String tableName, String schemaName, Connection cx)
          Callback which executes after an attribute descriptor has been built from a table column.
 void postCreateFeatureType(SimpleFeatureType featureType, DatabaseMetaData metadata, String schemaName, Connection cx)
          Callback which executes after a feature type has been built from a database table.
 void postCreateTable(String schemaName, SimpleFeatureType featureType, Connection cx)
          Callback to execute any additional sql statements post a create table statement.
 void registerAggregateFunctions(Map<Class<? extends FeatureVisitor>,String> aggregates)
          Registers the set of aggregate functions the dialect is capable of handling.
 void registerClassToSqlMappings(Map<Class<?>,Integer> mappings)
          Registers the java type to sql type mappings that the datastore uses when reading and writing objects to and from the database
 void registerSqlTypeNameToClassMappings(Map<String,Class<?>> mappings)
          Registers the sql type name to java type mappings that the dialect uses when reading and writing objects to and from the database.
 void registerSqlTypeToClassMappings(Map<Integer,Class<?>> mappings)
          Registers the sql type to java type mappings that the dialect uses when reading and writing objects to and from the database.
 void registerSqlTypeToSqlTypeNameOverrides(Map<Integer,String> overrides)
          Registers any overrides that should occur when mapping an integer sql type value to an underlying sql type name.
 
Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

LOGGER

protected static final Logger LOGGER

BASE_DBMS_CAPABILITIES

public static FilterCapabilities BASE_DBMS_CAPABILITIES
The basic filter capabilities all databases should have


dataStore

protected JDBCDataStore dataStore
The datastore using the dialect

Constructor Detail

SQLDialect

protected SQLDialect(JDBCDataStore dataStore)
Creates the dialect.

Parameters:
dataStore - The dataStore using the dialect.
Method Detail

initializeConnection

public void initializeConnection(Connection cx)
                          throws SQLException
Initializes a newly created database connection.

Subclasses should override this method if there is some additional action that needs to be taken when a new connection to the database is created. The default implementation does nothing.

Parameters:
cx - The new database connection.
Throws:
SQLException

includeTable

public boolean includeTable(String schemaName,
                            String tableName,
                            Connection cx)
                     throws SQLException
Determines if the specified table should be included in those published by the datastore.

This method returns true if the table should be published as a feature type, otherwise it returns false. Subclasses should override this method, this default implementation returns true.

A database connection is provided to the dialect but it should not be closed. However any statements objects or result sets that are instantiated from it must be closed.

Parameters:
schemaName - The schema of the table, might be null..
tableName - The name of the table.
cx - Database connection.
Throws:
SQLException

registerSqlTypeNameToClassMappings

public void registerSqlTypeNameToClassMappings(Map<String,Class<?>> mappings)
Registers the sql type name to java type mappings that the dialect uses when reading and writing objects to and from the database.

Subclasses should extend (not override) this method to provide additional mappings, or to override mappings provided by this implementation. This implementation provides the following mappings:


getMapping

public Class<?> getMapping(ResultSet columnMetaData,
                           Connection cx)
                    throws SQLException
Determines the class mapping for a particular column of a table.

Implementing this method is optional. It is used to allow database to perform custom type mappings based on various column metadata. It is called before the mappings registered in registerSqlTypeToClassMappings(Map) and #registerSqlTypeNameToClassMappings(Map) are used to determine the mapping. Subclasses should implement as needed, this default implementation returns null.

The columnMetaData argument is provided from {@link DatabaseMetaData#getColumns(String, String, String, String)}.

Parameters:
columnMetaData - The column metadata
The - connection used to retrieve the metadata
Returns:
The class mapped to the to column, or null.
Throws:
SQLException

registerSqlTypeToClassMappings

public void registerSqlTypeToClassMappings(Map<Integer,Class<?>> mappings)
Registers the sql type to java type mappings that the dialect uses when reading and writing objects to and from the database.

Subclasses should extend (not override) this method to provide additional mappings, or to override mappings provided by this implementation. This implementation provides the following mappings:


registerClassToSqlMappings

public void registerClassToSqlMappings(Map<Class<?>,Integer> mappings)
Registers the java type to sql type mappings that the datastore uses when reading and writing objects to and from the database. *

Subclasses should extend (not override) this method to provide additional mappings, or to override mappings provided by this implementation. This implementation provides the following mappings:


registerSqlTypeToSqlTypeNameOverrides

public void registerSqlTypeToSqlTypeNameOverrides(Map<Integer,String> overrides)
Registers any overrides that should occur when mapping an integer sql type value to an underlying sql type name.

The default implementation of this method does nothing. Subclasses should override in cases where:

  • database type metadata does not provide enough information to properly map
  • to support custom types (those not in Types)


registerAggregateFunctions

public void registerAggregateFunctions(Map<Class<? extends FeatureVisitor>,String> aggregates)
Registers the set of aggregate functions the dialect is capable of handling.

Aggregate functions are handled via visitors of special types. The aggregates maps the class of the visitor to the associated function name. This base implementation handles some of the well known mappings:

Subclasses should extend (not override) to provide additional functions.


getNameEscape

public String getNameEscape()
Returns the string used to escape names.

This value is used to escape any name in a query. This includes columns, tables, schemas, indexes, etc... If no escape is necessary this method should return the empty string, and never return null.

This default implementation returns a single double quote ("), subclasses must override to provide a different espcape.


ne

protected final String ne()
Quick accessor for getNameEscape().


encodeColumnName

public void encodeColumnName(String raw,
                             StringBuffer sql)
Encodes the name of a column in an SQL statement.

This method wraps raw in the character provided by getNameEscape(). Subclasses usually dont override this method and instead override getNameEscape().


encodeColumnType

public void encodeColumnType(String sqlTypeName,
                             StringBuffer sql)
Encodes the type of a column in an SQL CREATE TABLE statement.

The default implementation simply outputs the sqlTypeName argument as is. Subclasses may override this method. Such cases might include:

  • A type definition requires some parameter, ex: size of a varchar
  • The provided attribute (att) contains some additional restrictions that can be encoded in the type, ex: field length

Parameters:
sqlTypeName -
sql -

encodeColumnAlias

public void encodeColumnAlias(String raw,
                              StringBuffer sql)
Encodes the alias of a column in an sql query.

This default implementation uses the syntax:

as "alias"
. Subclasses should override to provide a different syntax.


encodeTableAlias

public void encodeTableAlias(String raw,
                             StringBuffer sql)
Encodes the alias of a table in an sql query.

This default implementation uses the syntax:

as "alias"
. Subclasses should override to provide a different syntax.


encodeTableName

public void encodeTableName(String raw,
                            StringBuffer sql)
Encodes the name of a table in an SQL statement.

This method wraps raw in the character provided by getNameEscape(). Subclasses usually dont override this method and instead override getNameEscape().


encodeSchemaName

public void encodeSchemaName(String raw,
                             StringBuffer sql)
Encodes the name of a schema in an SQL statement.

This method wraps raw in the character provided by getNameEscape(). Subclasses usually dont override this method and instead override getNameEscape().


getGeometryTypeName

public String getGeometryTypeName(Integer type)
Returns the name of a geometric type based on its integer constant.

The constant, type, is registered in registerSqlTypeNameToClassMappings(Map).

This default implementation returns null, subclasses should override.


getGeometrySRID

public Integer getGeometrySRID(String schemaName,
                               String tableName,
                               String columnName,
                               Connection cx)
                        throws SQLException
Returns the spatial reference system identifier (srid) for a particular geometry column.

This method is given a direct connection to the database. The connection must not be closed. However any statements or result sets instantiated from the connection must be closed.

In the event that the srid cannot be determined, this method should return null.

Parameters:
schemaName - The database schema, could be null.
tableName - The table, never null.
columnName - The column name, never null
cx - The database connection.
Throws:
SQLException

createCRS

public CoordinateReferenceSystem createCRS(int srid,
                                           Connection cx)
                                    throws SQLException
Turns the specified srid into a CoordinateReferenceSystem, or returns null if not possible.

The implementation might just use CRS.decode("EPSG:" + srid), but most spatial databases will have their own SRS database that can be queried as well.

As a rule of thumb you should override this method if your spatial database uses codes that are not part of the EPSG standard database, of if for some reason you deem it preferable to use your database definition instead of an official EPSG one.

Most overrides will try out to decode the official EPSG code first, and fall back on the custom database definition otherwise

Parameters:
srid -
Returns:
Throws:
SQLException

encodeGeometryEnvelope

public abstract void encodeGeometryEnvelope(String tableName,
                                            String geometryColumn,
                                            StringBuffer sql)
Encodes the spatial extent function of a geometry column in a SELECT statement.

This method must also be sure to properly encode the name of the column with the encodeColumnName(String, StringBuffer) function.

Parameters:
tableName -

decodeGeometryEnvelope

public abstract Envelope decodeGeometryEnvelope(ResultSet rs,
                                                int column,
                                                Connection cx)
                                         throws SQLException,
                                                IOException
Decodes the result of a spatial extent function in a SELECT statement.

This method is given direct access to a result set. The column parameter is the index into the result set which contains the spatial extent value. The query for this value is build with the encodeGeometryEnvelope(String, String, StringBuffer) method.

This method must not read any other objects from the result set other then the one referenced by column.

Parameters:
rs - A result set
column - Index into the result set which points at the spatial extent value.
The - database connection.
Throws:
SQLException
IOException

encodeGeometryColumn

public void encodeGeometryColumn(GeometryDescriptor gatt,
                                 int srid,
                                 StringBuffer sql)
Encodes the name of a geometry column in a SELECT statement.

This method should wrap the column name in any functions that are used to retrieve its value. For instance, often it is necessary to use the function asText, or asWKB when fetching a geometry.

This method must also be sure to properly encode the name of the column with the encodeColumnName(String, StringBuffer) function.

Example:

   
   sql.append( "asText(" );
   column( gatt.getLocalName(), sql );
   sql.append( ")" );
   
 

This default implementation simply uses the column name without any wrapping function, subclasses must override.


encodeGeometryColumnGeneralized

public void encodeGeometryColumnGeneralized(GeometryDescriptor gatt,
                                            int srid,
                                            StringBuffer sql,
                                            Double distance)
Encodes a generalized geometry using a DB provided SQL function if available If not supported, subclasses should not implement Only called if is supported Example:

   
   sql.append( "asText(generalize(" );
   column( gatt.getLocalName(), sql );
   sql.append( "," );
   sql.append(distance);
   sql.append( "))" );
   
 


encodeGeometryColumnSimplified

public void encodeGeometryColumnSimplified(GeometryDescriptor gatt,
                                           int srid,
                                           StringBuffer sql,
                                           Double distance)
Encodes a simplified geometry using a DB provided SQL function if available If not supported, subclasses should not implement Only called if is supported

See Also:
SQLDialect#encodeGeometryColumnGeneralized(GeometryDescriptor, StringBuffer, Double)

decodeGeometryValue

public abstract Geometry decodeGeometryValue(GeometryDescriptor descriptor,
                                             ResultSet rs,
                                             String column,
                                             GeometryFactory factory,
                                             Connection cx)
                                      throws IOException,
                                             SQLException
Decodes a geometry value from the result of a query.

This method is given direct access to a result set. The column parameter is the index into the result set which contains the geometric value.

An implementation should deserialize the value provided by the result set into Geometry object. For example, consider an implementation which deserializes from well known text:

   String wkt = rs.getString( column );
   if ( wkt == null ) {
     return null;
   }
   return new WKTReader(factory).read( wkt );
   
Note that implementations must handle null values.

The factory parameter should be used to instantiate any geometry objects.

Throws:
IOException
SQLException

decodeGeometryValue

public Geometry decodeGeometryValue(GeometryDescriptor descriptor,
                                    ResultSet rs,
                                    int column,
                                    GeometryFactory factory,
                                    Connection cx)
                             throws IOException,
                                    SQLException
Decodes a geometry value from the result of a query specifying the column as an index.

See #decodeGeometryValue(GeometryDescriptor, ResultSet, String, GeometryFactory) for a more in depth description.

Throws:
IOException
SQLException
See Also:
#decodeGeometryValue(GeometryDescriptor, ResultSet, String, GeometryFactory)}.

encodePrimaryKey

public void encodePrimaryKey(String column,
                             StringBuffer sql)
Encodes the primary key definition in a CREATE TABLE statement.

Subclasses should override this method if need be, the default implementation does the following:

   
   encodeColumnName( column, sql );
   sql.append( " int PRIMARY KEY" );
   
 


encodePostColumnCreateTable

public void encodePostColumnCreateTable(AttributeDescriptor att,
                                        StringBuffer sql)
Encodes anything post a column in a CREATE TABLE statement.

This is appended after the column name and type. Subclasses may choose to override this method, the default implementation does nothing.

Parameters:
att - The attribute corresponding to the column.

encodePostCreateTable

public void encodePostCreateTable(String tableName,
                                  StringBuffer sql)
Encodes anything post a CREATE TABLE statement.

This is appended to a CREATE TABLE statement after the column definitions. This default implementation does nothing, subclasses should override as need be.


postCreateTable

public void postCreateTable(String schemaName,
                            SimpleFeatureType featureType,
                            Connection cx)
                     throws SQLException,
                            IOException
Callback to execute any additional sql statements post a create table statement.

This method should be implemented by subclasses that need to do some post processing on the database after a table has been created. Examples might include:

  • Creating a sequence for a primary key
  • Registering geometry column metadata
  • Creating a spatial index

A common case is creating an auto incrementing sequence for the primary key of a table. It should be noted that all tables created through the datastore use the column "fid" as the primary key.

A direct connection to the database is provided (cx). This connection must not be closed, however any statements or result sets instantiated from the connection must be closed.

Parameters:
schemaName - The name of the schema, may be null.
featureType - The feature type that has just been created on the database.
cx - Database connection.
Throws:
SQLException
IOException

postCreateAttribute

public void postCreateAttribute(AttributeDescriptor att,
                                ResultSet columnMetadata,
                                String tableName,
                                String schemaName,
                                Connection cx)
                         throws SQLException
Callback which executes after an attribute descriptor has been built from a table column.

The result set columnMetadata should not be modified in any way (including scrolling) , it should only be read from.

This base implementation does nothing, subclasses should override as need be.

Parameters:
att - The built attribute descriptor.
columnMetadata - The database metadata about the column.
tableName - The name of the table containing the column
schemaName - The name of the database scheam containing the table containing the column
cx - The database connection.
Throws:
SQLException

postCreateFeatureType

public void postCreateFeatureType(SimpleFeatureType featureType,
                                  DatabaseMetaData metadata,
                                  String schemaName,
                                  Connection cx)
                           throws SQLException
Callback which executes after a feature type has been built from a database table.

This base implementation does nothing, subclasses should override as need be.

Parameters:
featureType - The build feature type.
metadata - The database metadata.
schemaName - The name of the database scheam containing the table containing the column
cx - The database connection.
Throws:
SQLException

lookupGeneratedValuesPostInsert

public boolean lookupGeneratedValuesPostInsert()
Controls whether keys are looked up post or pre insert.

When a row is inserted into a table, and a key is automatically generated it can be looked up before the insert occurs, or after the insert has been made. Returning false will cause the lookup to occur before the insert via getNextAutoGeneratedValue(String, String, String, Connection). Returning true will cause the lookup to occur after the insert via getLastAutoGeneratedValue(String, String, String, Connection).

Subclasses returning false should implement:

Subclasses returning true should implement:


getNextAutoGeneratedValue

public Object getNextAutoGeneratedValue(String schemaName,
                                        String tableName,
                                        String columnName,
                                        Connection cx)
                                 throws SQLException
Obtains the next value of an auto generated column.

Implementations should determine the next value of a column for which values are automatically generated by the database.

This method is given a direct connection to the database, but this connection should never be closed. However any statements or result sets instantiated from the connection must be closed.

Implementations should handle the case where schemaName is null.

Parameters:
schemaName - The schema name, this might be null.
tableName - The name of the table.
columnName - The column.
cx - The database connection.
Returns:
The next value of the column, or null.
Throws:
SQLException

getLastAutoGeneratedValue

public Object getLastAutoGeneratedValue(String schemaName,
                                        String tableName,
                                        String columnName,
                                        Connection cx)
                                 throws SQLException
Obtains the last value of an auto generated column.

This method is only called when lookupGeneratedValuesPostInsert() returns true. Implementations should determine the previous value of a column for which was automatically generated by the database.

This method is given a direct connection to the database, but this connection should never be closed. However any statements or result sets instantiated from the connection must be closed.

Implementations should handle the case where schemaName is null.

Parameters:
schemaName - The schema name, this might be null.
tableName - The name of the table.
columnName - The column.
cx - The database connection.
Returns:
The previous value of the column, or null.
Throws:
SQLException

getSequenceForColumn

public String getSequenceForColumn(String schemaName,
                                   String tableName,
                                   String columnName,
                                   Connection cx)
                            throws SQLException
Determines the name of the sequence (if any) which is used to increment generate values for a table column.

This method should return null if no such sequence exists.

This method is given a direct connection to the database, but this connection should never be closed. However any statements or result sets instantiated from the connection must be closed.

Parameters:
schemaName - The schema name, this might be null.
tableName - The table name.
columnName - The column name.
cx - The database connection.
Throws:
SQLException

getNextSequenceValue

public Object getNextSequenceValue(String schemaName,
                                   String sequenceName,
                                   Connection cx)
                            throws SQLException
Obtains the next value of a sequence, incrementing the sequence to the next state in the process.

Implementations should determine the next value of a column for which values are automatically generated by the database.

This method is given a direct connection to the database, but this connection should never be closed. However any statements or result sets instantiated from the connection must be closed.

Implementations should handle the case where schemaName is null.

Parameters:
schemaName - The schema name, this might be null.
sequenceName - The name of the sequence.
cx - The database connection.
Returns:
The next value of the sequence, or null.
Throws:
SQLException

isLimitOffsetSupported

public boolean isLimitOffsetSupported()
Returns true if this dialect can encode both Query.getStartIndex() and Query.getMaxFeatures() into native SQL.

Returns:

applyLimitOffset

public void applyLimitOffset(StringBuffer sql,
                             int limit,
                             int offset)
Alters the query provided so that limit and offset are natively dealt with. This might mean simply appending some extra directive to the query, or wrapping it into a bigger one.

Parameters:
sql -
limit -
offset -

addSupportedHints

protected void addSupportedHints(Set<Hints.Key> hints)
Add hints to the JDBC Feature Source. A subclass can override possible hints (but not limited to) Hints.GEOMETRY_GENERALIZATION Hints.GEOMETRY_SIMPLIFICATION

Parameters:
hints -


Copyright © 1996-2010 Geotools. All Rights Reserved.