org.geotools.data.postgis
Class PostgisDataSource

java.lang.Object
  |
  +--org.geotools.data.AbstractDataSource
        |
        +--org.geotools.data.postgis.PostgisDataSource
All Implemented Interfaces:
DataSource, TransactionalDataSource

public class PostgisDataSource
extends AbstractDataSource
implements TransactionalDataSource

Connects to a Postgis database and returns properly formatted GML.

This standard class must exist for every supported datastore.

Simple Lockings Support: Long Term Feature Locking:

DataSource knows enough information to create the locking table by itself - the lockcheck function if the only gotcha in this setup it will be another thing to add to Postgis.

The main advantage to this solution is that Locks are present across transactions and other applications can continue to use the database safely concurrently with DataSource access. These locks have an associated exparation date which the lockcheck function will compare to the start of the current transaction.

Version:
$Id: PostgisDataSource.java,v 1.29 2003/07/18 23:15:09 cholmesny Exp $
Author:
Rob Hranac, Vision for New York, Chris Holmes, TOPP

Nested Class Summary
 
Nested classes inherited from class org.geotools.data.AbstractDataSource
AbstractDataSource.MetaDataSupport
 
Field Summary
private static AttributeTypeFactory attFactory
          Factory to create Attributes
(package private)  java.util.Set authorization
           
private  java.sql.Connection dbConnection
          A postgis connection.
static java.lang.String DEFAULT_FID_COLUMN
           
private  SQLEncoderPostgis encoder
          To create the sql where statement
private  java.lang.String fidColumn
          the name of the column to use for the featureId
private static com.vividsolutions.jts.geom.GeometryFactory geometryFactory
          Factory for producing geometries (from JTS).
private static com.vividsolutions.jts.io.WKTReader geometryReader
          Well Known Text reader (from JTS).
private static java.util.Map geometryTypeMap
           
private static com.vividsolutions.jts.io.WKTWriter geometryWriter
          Well Known Text writer (from JTS).
private static int HARD_MAX_FEATURES
          The limit on a select statement.
protected  Lock lock
          Gets the bounding box of this datasource using the default speed of this datasource as set by the implementer.
private static java.util.logging.Logger LOGGER
          The logger for the filter module.
private  int maxFeatures
          The maximum features allowed by the server for any given response.
private  FeatureType schema
          The maximum features allowed by the server for any given response.
private static java.util.Map sqlTypeMap
           
private  int srid
          The srid of the data in the table.
private  java.lang.String tableName
          A tablename.
 
Fields inherited from class org.geotools.data.AbstractDataSource
 
Constructor Summary
PostgisDataSource(java.sql.Connection dbConnection, java.lang.String tableName)
          Sets the table and datasource, rolls a new schema from the db.
 
Method Summary
 java.util.Set addFeatures(FeatureCollection collection)
          Returns a feature collection, based on the passed filter.
private  java.lang.String addQuotes(java.lang.Object value)
          Adds quotes to an object for storage in postgis.
private static void closeResultSet(java.sql.ResultSet result)
          Closes the result set.
 void commit()
          Makes all transactions made since the previous commit/rollback permanent.
private  java.lang.String createFid(java.lang.String featureId)
           
protected  DataSourceMetaData createMetaData()
          Creates the a metaData object.
private  java.lang.String formatFid(Feature feature)
          strips the tableName from the fid for those in the format featureName.3534 should maybe just strip out all alpha-numeric characters.
private  AttributeType[] getAttTypes(Query query)
           
 boolean getAutoCommit()
          Retrieves the current autoCommit mode for the current DataSource.
private  java.util.Set getFeatureIds(Query query)
          Helper method used to aquire id numbers for query.
 void getFeatures(FeatureCollection collection, Query query)
          Loads features from the datasource into the passed collection, based on the passed query.
static java.lang.String getFidColumn(java.sql.Connection dbConnection, java.lang.String tableName)
          Figures out what database column to use as the identifier for the feature.
private  java.util.Set getFidSet()
           
private static AttributeType getGeometryAttribute(java.sql.Connection dbConnection, java.lang.String tableName, java.lang.String columnName)
          Returns an attribute type for a geometry column in a feature table.
 FeatureType getSchema()
          Retrieves the featureType that features extracted from this datasource will be created with.
private static void initMaps()
          Initializes the mappings for mapping from sql columns to classes for attributes
 void lockFeatures()
          Lock entire table - don't think this is supposed to prevent addsFeatures().
 void lockFeatures(Filter filter)
          Lock features refered to by filter.
 void lockFeatures(Query query)
          Lock features refered to by Query
private  java.lang.String makeInsertSql(java.lang.String tableName, Feature feature)
          Creates a sql insert statement.
private  java.lang.String makeModifySql(AttributeType[] types, java.lang.Object[] values, java.lang.String whereStmt)
          Creates a sql update statement.
static FeatureType makeSchema(java.lang.String tableName, java.sql.Connection dbConnection)
          Creates a schema from the information in the tablename.
static FeatureType makeSchema(java.lang.String tableName, java.sql.Connection dbConnection, java.lang.String fidColumnName)
          Creates a schema from the information in the tablename.
 java.lang.String makeSql(SQLUnpacker unpacker, Query query)
          Creates a SQL statement for the PostGIS database.
 void modifyFeatures(AttributeType[] type, java.lang.Object[] value, Filter filter)
          Modifies the passed attribute types with the passed objects in all features that correspond to the passed OGS filter.
 void modifyFeatures(AttributeType type, java.lang.Object value, Filter filter)
          Modifies the passed attribute types with the passed objects in all features that correspond to the passed OGS filter.
static int querySRID(java.sql.Connection dbConnection, java.lang.String tableName)
          Gets the srid from the geometry_columns table of the datasource.
 void removeFeatures(Filter filter)
          Removes the features specified by the passed filter from the PostGIS database.
 void rollback()
          Undoes all transactions made since the last commit or rollback.
 void setAuthorization(java.lang.String[] lockIds)
          Provide Lock authorizations removeFeatures(), modifyFeatures() and unLockFeatures() operations.
 void setAutoCommit(boolean autoCommit)
          Sets this datasources auto-commit mode to the given state.
 void setCurrentLock(Lock lock)
          Configures lock operations to work against provided Lock.
 void setFeatures(FeatureCollection features)
          Deletes the all the current Features of this datasource and adds the new collection.
private  void sql(java.lang.String statement)
           
 void unLockFeatures(Query query)
          Remove Locks held on Features, authorization must be held in order to unlock.
 
Methods inherited from class org.geotools.data.AbstractDataSource
abortLoading, getBounds, getFeatures, getFeatures, getFeatures, getFeatures, getMetaData, makeDefaultQuery
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface org.geotools.data.TransactionalDataSource
unLockFeatures, unLockFeatures
 
Methods inherited from interface org.geotools.data.DataSource
abortLoading, getBounds, getFeatures, getFeatures, getFeatures, getFeatures, getMetaData
 

Field Detail

sqlTypeMap

private static java.util.Map sqlTypeMap

geometryTypeMap

private static java.util.Map geometryTypeMap

LOGGER

private static final java.util.logging.Logger LOGGER
The logger for the filter module.


geometryFactory

private static com.vividsolutions.jts.geom.GeometryFactory geometryFactory
Factory for producing geometries (from JTS).


geometryReader

private static com.vividsolutions.jts.io.WKTReader geometryReader
Well Known Text reader (from JTS).


geometryWriter

private static com.vividsolutions.jts.io.WKTWriter geometryWriter
Well Known Text writer (from JTS).


HARD_MAX_FEATURES

private static final int HARD_MAX_FEATURES
The limit on a select statement.

See Also:
Constant Field Values

DEFAULT_FID_COLUMN

public static final java.lang.String DEFAULT_FID_COLUMN
See Also:
Constant Field Values

attFactory

private static AttributeTypeFactory attFactory
Factory to create Attributes


maxFeatures

private int maxFeatures
The maximum features allowed by the server for any given response.


srid

private int srid
The srid of the data in the table.


encoder

private SQLEncoderPostgis encoder
To create the sql where statement


fidColumn

private java.lang.String fidColumn
the name of the column to use for the featureId


schema

private FeatureType schema
The maximum features allowed by the server for any given response.


dbConnection

private java.sql.Connection dbConnection
A postgis connection.


tableName

private java.lang.String tableName
A tablename.


lock

protected Lock lock
Gets the bounding box of this datasource using the default speed of this datasource as set by the implementer.


authorization

java.util.Set authorization
Constructor Detail

PostgisDataSource

public PostgisDataSource(java.sql.Connection dbConnection,
                         java.lang.String tableName)
                  throws DataSourceException
Sets the table and datasource, rolls a new schema from the db.

Parameters:
dbConnection - The datasource holding the table.
tableName - the name of the table that holds the features.
Throws:
DataSourceException - if there were problems constructing the schema.
Method Detail

initMaps

private static void initMaps()
Initializes the mappings for mapping from sql columns to classes for attributes


makeSchema

public static FeatureType makeSchema(java.lang.String tableName,
                                     java.sql.Connection dbConnection)
                              throws DataSourceException
Creates a schema from the information in the tablename.

Parameters:
tableName - The name of the table that holds the features.
dbConnection - The connection to the database holding the table.
Returns:
the schema reflecting features held in the table.
Throws:
DataSourceException - DOCUMENT ME!

makeSchema

public static FeatureType makeSchema(java.lang.String tableName,
                                     java.sql.Connection dbConnection,
                                     java.lang.String fidColumnName)
                              throws DataSourceException
Creates a schema from the information in the tablename.

Parameters:
tableName - The name of the table that holds the features.
dbConnection - The connection to the database holding the table.
fidColumnName - the name of the column to use as the fid.
Returns:
the schema reflecting features held in the table.
Throws:
DataSourceException - if there were problems reading sql or making the schema.

querySRID

public static int querySRID(java.sql.Connection dbConnection,
                            java.lang.String tableName)
                     throws DataSourceException
Gets the srid from the geometry_columns table of the datasource.

Parameters:
dbConnection - The connection to the database.
tableName - the name of the table to find the srid.
Returns:
the srid of the first geometry column of the table.
Throws:
DataSourceException - DOCUMENT ME!

getFidColumn

public static java.lang.String getFidColumn(java.sql.Connection dbConnection,
                                            java.lang.String tableName)
Figures out what database column to use as the identifier for the feature. For now it first tries to use the primary key (which should be the fid according to sfs for sql), and if there are none, then it uses the postgres specific invisible oid column.

Parameters:
dbConnection - The connection to the database.
tableName - The name of the table to get the id for.
Returns:
the name of the column to use as the fid.

getGeometryAttribute

private static AttributeType getGeometryAttribute(java.sql.Connection dbConnection,
                                                  java.lang.String tableName,
                                                  java.lang.String columnName)
                                           throws DataSourceException
Returns an attribute type for a geometry column in a feature table.

Parameters:
dbConnection - The JDBC connection.
tableName - The feature table name.
columnName - The geometry column name.
Returns:
Geometric attribute.
Throws:
java.lang.Exception - DOCUMENT ME!
DataSourceException

makeSql

public java.lang.String makeSql(SQLUnpacker unpacker,
                                Query query)
                         throws DataSourceException
Creates a SQL statement for the PostGIS database.

Parameters:
query - the getFeature query - for the tableName, properties and maxFeatures.
Returns:
Full SQL statement.
Throws:
DataSourceException - DOCUMENT ME!

getAttTypes

private AttributeType[] getAttTypes(Query query)
                             throws DataSourceException
DataSourceException

closeResultSet

private static void closeResultSet(java.sql.ResultSet result)
Closes the result set. Child class must remember to call.

Parameters:
result - The servlet request object.

getFeatures

public void getFeatures(FeatureCollection collection,
                        Query query)
                 throws DataSourceException
Loads features from the datasource into the passed collection, based on the passed query. Note that all data sources must support this method at a minimum.

Specified by:
getFeatures in interface DataSource
Specified by:
getFeatures in class AbstractDataSource
Parameters:
collection - The collection to put the features into.
query - a datasource query object. It encapsulates requested information, such as typeName, maxFeatures and filter.
Throws:
DataSourceException - For all data source errors.
See Also:
Query

createFid

private java.lang.String createFid(java.lang.String featureId)

addFeatures

public java.util.Set addFeatures(FeatureCollection collection)
                          throws DataSourceException
Returns a feature collection, based on the passed filter. The schema of the features passed in must match the schema of the datasource.

Specified by:
addFeatures in interface DataSource
Overrides:
addFeatures in class AbstractDataSource
Parameters:
collection - Add features to the PostGIS database.
Returns:
A set of featureIds of the features added.
Throws:
DataSourceException - if anything went wrong.

getFidSet

private java.util.Set getFidSet()
                         throws DataSourceException
DataSourceException

makeInsertSql

private java.lang.String makeInsertSql(java.lang.String tableName,
                                       Feature feature)
Creates a sql insert statement. Uses each feature's schema, which makes it possible to insert out of order, as well as inserting less than all features.

Parameters:
tableName - the name of the feature table being inserted into.
feature - the feature to add.
Returns:
an insert sql statement.

addQuotes

private java.lang.String addQuotes(java.lang.Object value)
Adds quotes to an object for storage in postgis. The object should be a string or a number. To perform an insert strings need quotes around them, and numbers work fine with quotes, so this method can be called on unknown objects.

Parameters:
value - The object to add quotes to.
Returns:
a string representation of the object with quotes.

removeFeatures

public void removeFeatures(Filter filter)
                    throws DataSourceException
Removes the features specified by the passed filter from the PostGIS database.

Specified by:
removeFeatures in interface DataSource
Overrides:
removeFeatures in class AbstractDataSource
Parameters:
filter - An OpenGIS filter; specifies which features to remove.
Throws:
DataSourceException - If anything goes wrong or if deleting is not supported.

modifyFeatures

public void modifyFeatures(AttributeType[] type,
                           java.lang.Object[] value,
                           Filter filter)
                    throws DataSourceException
Modifies the passed attribute types with the passed objects in all features that correspond to the passed OGS filter.

Specified by:
modifyFeatures in interface DataSource
Overrides:
modifyFeatures in class AbstractDataSource
Parameters:
type - The attributes to modify.
value - The values to put in the attribute types.
filter - An OGC filter to note which attributes to modify.
Throws:
DataSourceException - If modificaton is not supported, if the attribute and object arrays are not eqaul length, or if the object types do not match the attribute types.

formatFid

private java.lang.String formatFid(Feature feature)
strips the tableName from the fid for those in the format featureName.3534 should maybe just strip out all alpha-numeric characters.

Parameters:
feature - DOCUMENT ME!
Returns:
DOCUMENT ME!

modifyFeatures

public void modifyFeatures(AttributeType type,
                           java.lang.Object value,
                           Filter filter)
                    throws DataSourceException
Modifies the passed attribute types with the passed objects in all features that correspond to the passed OGS filter. A convenience method for single attribute modifications.

Specified by:
modifyFeatures in interface DataSource
Overrides:
modifyFeatures in class AbstractDataSource
Parameters:
type - The attributes to modify.
value - The values to put in the attribute types.
filter - An OGC filter to note which attributes to modify.
Throws:
DataSourceException - If modificaton is not supported, if the object type do not match the attribute type.

makeModifySql

private java.lang.String makeModifySql(AttributeType[] types,
                                       java.lang.Object[] values,
                                       java.lang.String whereStmt)
                                throws DataSourceException
Creates a sql update statement.

Parameters:
types - the attribute to be changed.
values - the value to change it to.
whereStmt - the feature to update.
Returns:
an update sql statement.
Throws:
DataSourceException - DOCUMENT ME!

getSchema

public FeatureType getSchema()
                      throws DataSourceException
Retrieves the featureType that features extracted from this datasource will be created with.

Specified by:
getSchema in interface DataSource
Specified by:
getSchema in class AbstractDataSource
Returns:
the schema of features created by this datasource.
Throws:
DataSourceException - if there are any problems getting the schema.

setFeatures

public void setFeatures(FeatureCollection features)
                 throws DataSourceException
Description copied from interface: DataSource
Deletes the all the current Features of this datasource and adds the new collection. Primarily used as a convenience method for file datasources.

Specified by:
setFeatures in interface DataSource
Overrides:
setFeatures in class AbstractDataSource
Parameters:
features - - the collection to be written
Throws:
DataSourceException - if there are any datasource errors.

commit

public void commit()
            throws DataSourceException
Makes all transactions made since the previous commit/rollback permanent. This method should be used only when auto-commit mode has been disabled. If autoCommit is true then this method does nothing.

Specified by:
commit in interface DataSource
Overrides:
commit in class AbstractDataSource
Throws:
DataSourceException - if there are any datasource errors.
See Also:
setAutoCommit(boolean)

rollback

public void rollback()
              throws DataSourceException
Undoes all transactions made since the last commit or rollback. This method should be used only when auto-commit mode has been disabled. This method should only be implemented if setAutoCommit(boolean) is also implemented.

Specified by:
rollback in interface DataSource
Overrides:
rollback in class AbstractDataSource
Throws:
DataSourceException - if there are problems with the datasource.
See Also:
setAutoCommit(boolean)

setAutoCommit

public void setAutoCommit(boolean autoCommit)
                   throws DataSourceException
Sets this datasources auto-commit mode to the given state. If a datasource is in auto-commit mode, then all its add, remove and modify calls will be executed and committed as individual transactions. Otherwise, those calls are grouped into a single transaction that is terminated by a call to either the method commit or the method rollback. By default, new datasources are in auto-commit mode.

Specified by:
setAutoCommit in interface DataSource
Overrides:
setAutoCommit in class AbstractDataSource
Parameters:
autoCommit - true to enable auto-commit mode, false to disable it.
Throws:
DataSourceException - DOCUMENT ME!
See Also:
setAutoCommit(boolean)

getAutoCommit

public boolean getAutoCommit()
                      throws DataSourceException
Retrieves the current autoCommit mode for the current DataSource. If the datasource does not implement setAutoCommit, then this method should always return true.

Specified by:
getAutoCommit in interface DataSource
Overrides:
getAutoCommit in class AbstractDataSource
Returns:
the current state of this datasource's autoCommit mode.
Throws:
DataSourceException - if a datasource access error occurs.
See Also:
setAutoCommit(boolean)

createMetaData

protected DataSourceMetaData createMetaData()
Creates the a metaData object. This method should be overridden in any subclass implementing any functions beyond getFeatures, so that clients recieve the proper information about the datasource's capabilities.

Overrides:
createMetaData in class AbstractDataSource
Returns:
the metadata for this datasource.
See Also:
#MetaDataSupport

setCurrentLock

public void setCurrentLock(Lock lock)
Configures lock operations to work against provided Lock.

Specified by:
setCurrentLock in interface TransactionalDataSource
Parameters:
lock -
See Also:
TransactionalDataSource.setCurrentLock(org.geotools.data.Lock)

lockFeatures

public void lockFeatures()
                  throws DataSourceException
Lock entire table - don't think this is supposed to prevent addsFeatures().

Specified by:
lockFeatures in interface TransactionalDataSource
Throws:
DataSourceException
See Also:
org.geotools.data.TransactionalDataSource#lock()

lockFeatures

public void lockFeatures(Filter filter)
                  throws DataSourceException
Lock features refered to by filter.

Specified by:
lockFeatures in interface TransactionalDataSource
Parameters:
filter -
Throws:
DataSourceException
See Also:
org.geotools.data.TransactionalDataSource#lock(org.geotools.filter.Filter)

lockFeatures

public void lockFeatures(Query query)
                  throws DataSourceException
Lock features refered to by Query

Specified by:
lockFeatures in interface TransactionalDataSource
Parameters:
query -
Throws:
DataSourceException
See Also:
org.geotools.data.TransactionalDataSource#lock(org.geotools.data.Query)

sql

private void sql(java.lang.String statement)

setAuthorization

public void setAuthorization(java.lang.String[] lockIds)
Provide Lock authorizations removeFeatures(), modifyFeatures() and unLockFeatures() operations.

Authorization is only provided for the current transaction. That is locks are not released - the transaction is ended.

Specified by:
setAuthorization in interface TransactionalDataSource
Parameters:
lockIds - LockIds for Long Transaction operations
See Also:
TransactionalDataSource.setAuthorization(java.lang.String[])

getFeatureIds

private java.util.Set getFeatureIds(Query query)
Helper method used to aquire id numbers for query.

Parameters:
query -
Returns:
Set if ids

unLockFeatures

public void unLockFeatures(Query query)
Remove Locks held on Features, authorization must be held in order to unlock.

Detailed Description of removeLock.

Specified by:
unLockFeatures in interface TransactionalDataSource
Parameters:
query - Query describing features to unlock.