de.mathema.pride
Class Database

java.lang.Object
  extended by de.mathema.pride.Database
All Implemented Interfaces:
SQLFormatter

public class Database
extends java.lang.Object
implements SQLFormatter

Database access class, providing base functionality for the persistence framework. The member functions in here are supposed to be rarely used by the application except common things like commit() and rollback().

Author:
Jan Lessner

Field Summary
static java.lang.String REVISION_ID
           
 
Constructor Summary
Database(java.lang.String dbname, ResourceAccessor accessor, ExceptionListener el, boolean log)
          Create a database object
 
Method Summary
 void addListener(TransactionListener l)
          Add a transaction listener to this database object
 void commit()
          Commit the current transaction.
 void createExtensions(java.lang.Object obj, ExtensionDescriptor xd)
          Create an object's generic extension attributes
 int createRecord(java.lang.String[] autoFields, java.lang.Object obj, RecordDescriptor red)
          Add a record to the database.
 int deleteRecord(java.lang.Object obj, RecordDescriptor red)
          Delete a record from the database.
 int deleteRecord(java.lang.String[] dbkeyfields, java.lang.Object obj, RecordDescriptor red)
          Delete a record from the database.
 int deleteRecord(java.lang.String where, java.lang.Object obj, RecordDescriptor red)
          Delete a record from the database.
 void endTransaction(boolean commit)
          Terminate the current transaction.
 void fetchExtensions(java.lang.Object obj, ExtensionDescriptor xd)
          Read an object's generic extension attributes
 void fetchExtensions(java.lang.Object obj, ExtensionDescriptor xd, java.lang.String[] attrNames)
          Read a subset of an object's generic extension attributes.
protected  ResultIterator fetchFirst(java.lang.String query, java.lang.Object obj, RecordDescriptor red, boolean keepRest)
          Fetches the first record from a result set returned for query.
 void fetchRecord(java.lang.Object primaryKey, java.lang.Object obj, RecordDescriptor red)
          Fetch a record from the database and store the results in a JAVA object according to the passed mapping descriptor.
 void fetchRecord(java.lang.Object obj, RecordDescriptor red)
          Fetch a record from the database and store the results in a JAVA object according to the passed mapping descriptor.
 java.lang.String formatOperator(java.lang.String operator, java.lang.Object rawValue)
           
 java.lang.Object formatPreparedValue(java.lang.Object value)
           
 java.lang.String formatValue(java.lang.Object value)
          Formats the passed object for SQL syntax, e.g. by putting single-quotes arround strings etc.
 java.sql.Connection getConnection()
          Returns a JDBC database connection for standard JDBC programming.
 java.lang.String getDBName()
          Return the name of the databaserepresented by this object.
 java.lang.String getDBType()
          Returns the type of DB being represented by the current resource accessor.
 java.lang.String getInsertionHeader(RecordDescriptor red, java.lang.String[] autoFields)
          Returns a header for a record inserting of the form "insert into ( ...
 java.lang.String getPhysicalTableName(ExtensionDescriptor xd)
           
 java.lang.String getPhysicalTableName(java.lang.String logicalTableName)
           
 java.util.Date getSystime()
          Returns the resource accessors timestamp, that is currently used to identify, that a date has to be replaced by the database server's system time.
 java.lang.String getTableName(RecordDescriptor red)
           
 java.lang.String getURL()
          Retrieves the URL for this DBMS represented by the ResourceAccessor.
 java.lang.String getUserName()
          Retrieves the user name as known to this database represented by the ResourceAccessor.
 boolean isLogging()
          Returns true if SQL logging is switched on
 ResultIterator query(java.lang.String[] dbfields, java.lang.Object obj, RecordDescriptor red, boolean all)
          Run a database query.
 ResultIterator query(java.lang.String dbfield, java.lang.Object value, java.lang.Object obj, RecordDescriptor red, boolean all)
          Run a database query.
 ResultIterator query(java.lang.String where, java.lang.Object obj, RecordDescriptor red, boolean all)
          Run a database query.
 ResultIterator queryAll(java.lang.Object obj, RecordDescriptor red)
          Run a database query, returning all records of the table denoted by parameter red.
 void releaseConnection()
          Close the current thread's connection for later reuse.
 void releaseConnection(java.sql.Connection con)
           
 void removeListener(TransactionListener l)
          Remove a transaction listener from this database object
 void rollback()
          Rollback the current transaction.
 boolean setLogging(boolean val)
          Switch SQL logging on and off.
 void sqlLog(java.lang.String operation)
          Writes the passed SQL string to the SQL log file.
 void sqlLogError(java.sql.SQLException sqlx)
           
 ResultIterator sqlQuery(java.lang.String operation)
          Runs an SQL query according to the passed operation
 ResultIterator sqlQuery(java.lang.String operation, java.lang.Object obj, RecordDescriptor red)
          Runs an SQL query and returns a ResultIterator, initialized with parameters obj and red and the ResultSet returned by the query.
 int sqlUpdate(java.lang.String operation)
          Like function above but without any auto-field expectations
 int sqlUpdate(java.lang.String operation, java.lang.String[] autoFields, java.lang.Object obj, RecordDescriptor red)
          Runs an SQL update statement according to the passed operation
protected  void storeExtensions(java.lang.Object obj, ExtensionDescriptor xd, boolean update)
          Store an object's generic extension attributes
 void updateExtensions(java.lang.Object obj, ExtensionDescriptor xd)
          Update an object's generic extension attributes
 void updateExtensions(java.lang.Object obj, ExtensionDescriptor xd, java.lang.String[] attrNames)
          Update a subset of an object's generic extension attributes
 int updateRecord(java.lang.Object obj, RecordDescriptor red)
          Update a database record with the data of a JAVA object according to the passed mapping descriptor.
 int updateRecord(java.lang.String[] dbkeyfields, java.lang.Object obj, RecordDescriptor red)
          Update a database record.
 int updateRecord(java.lang.String[] dbkeyfields, java.lang.String[] updatefields, java.lang.Object obj, RecordDescriptor red)
          Update a database record.
 int updateRecord(java.lang.String where, java.lang.Object obj, RecordDescriptor red)
          Update a database record.
 int updateRecord(java.lang.String where, java.lang.String[] updatefields, java.lang.Object obj, RecordDescriptor red)
          Update a database record.
protected  java.lang.String where(java.lang.String where)
           
 ResultIterator wildcardSearch(java.lang.String[] dbfields, java.lang.Object obj, RecordDescriptor red, boolean all)
          Like function query() above but selects using the like operator
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

REVISION_ID

public static final java.lang.String REVISION_ID
See Also:
Constant Field Values
Constructor Detail

Database

public Database(java.lang.String dbname,
                ResourceAccessor accessor,
                ExceptionListener el,
                boolean log)
Create a database object

Parameters:
log - writes SQL statements to log file if parameter log is true. The name of the logfile is determined by system property xbc.sqllog which default ./sql.log. It is recommended to use DatabaseFactory.getDatabase() instead.
Method Detail

getConnection

public java.sql.Connection getConnection()
                                  throws java.sql.SQLException
Returns a JDBC database connection for standard JDBC programming. There is one unique connection returned per thread.

Throws:
java.sql.SQLException

releaseConnection

public void releaseConnection()
                       throws java.sql.SQLException
Close the current thread's connection for later reuse. It is recommended to explicitely release connections if the associated thread is about to terminate or sleep for a long time. JDBC's built-in connection garbage collection is either not working at all or is not this agile as it may be required.

Throws:
java.sql.SQLException

releaseConnection

public void releaseConnection(java.sql.Connection con)
                       throws java.sql.SQLException
Throws:
java.sql.SQLException

getTableName

public java.lang.String getTableName(RecordDescriptor red)

getPhysicalTableName

public java.lang.String getPhysicalTableName(java.lang.String logicalTableName)

getPhysicalTableName

public java.lang.String getPhysicalTableName(ExtensionDescriptor xd)

getSystime

public java.util.Date getSystime()
Returns the resource accessors timestamp, that is currently used to identify, that a date has to be replaced by the database server's system time. If a date for an sql statement matches this value, it will be replaced by a database specific string in insert and update statements.


getURL

public java.lang.String getURL()
                        throws java.sql.SQLException
Retrieves the URL for this DBMS represented by the ResourceAccessor.

Returns:
the database url
Throws:
java.lang.Exception
java.sql.SQLException
See Also:
DatabaseMetaData

getDBName

public java.lang.String getDBName()
Return the name of the databaserepresented by this object. In a managed environment, it is a logical lookup name (JNDI name in J2EE), otherwise it is identical to the database URL (see function getURL()).

Returns:
The database name

getUserName

public java.lang.String getUserName()
                             throws java.sql.SQLException
Retrieves the user name as known to this database represented by the ResourceAccessor.

Parameters:
db -
Returns:
the user name
Throws:
java.sql.SQLException
See Also:
DatabaseMetaData

getDBType

public java.lang.String getDBType()
Returns the type of DB being represented by the current resource accessor. See constants in interface ResourceAccessor#DBType for the type keys which are supported by default.


formatValue

public java.lang.String formatValue(java.lang.Object value)
Formats the passed object for SQL syntax, e.g. by putting single-quotes arround strings etc. The function is not very flexible yet, it just supports special formatting for String, java.util.Date, java.sql.Date, java.sql.Timestamp, and null. All other other cases it runs value.toString()

Specified by:
formatValue in interface SQLFormatter

formatOperator

public java.lang.String formatOperator(java.lang.String operator,
                                       java.lang.Object rawValue)
Specified by:
formatOperator in interface SQLFormatter

formatPreparedValue

public java.lang.Object formatPreparedValue(java.lang.Object value)
Specified by:
formatPreparedValue in interface SQLFormatter

fetchFirst

protected ResultIterator fetchFirst(java.lang.String query,
                                    java.lang.Object obj,
                                    RecordDescriptor red,
                                    boolean keepRest)
                             throws java.sql.SQLException
Fetches the first record from a result set returned for query. The result is stored in the passed obj the mapping scheme of which is described by parameter red.

Returns:
null if parameter keepRest is true, i.e. only the very first matching record is of interest. A ResultIterator object otherwise, which allows to walk through the following records by storing them step by step into obj.
Throws:
java.sql.SQLException

sqlLog

public void sqlLog(java.lang.String operation)
Writes the passed SQL string to the SQL log file. The log file is wrapped every SQLMAXCOUNT lines.


sqlLogError

public void sqlLogError(java.sql.SQLException sqlx)

setLogging

public boolean setLogging(boolean val)
Switch SQL logging on and off.

Returns:
the current logging state, i.e. usually the desired state passed in parameter val except when toggling doesn't work. E.g. switching logging on doesn't work if there is no SQL log file specified.

isLogging

public boolean isLogging()
Returns true if SQL logging is switched on


sqlUpdate

public int sqlUpdate(java.lang.String operation,
                     java.lang.String[] autoFields,
                     java.lang.Object obj,
                     RecordDescriptor red)
              throws java.sql.SQLException
Runs an SQL update statement according to the passed operation

Parameters:
The - operation to execute
An - array of field which to fetch auto-generated values from after a successfull insertion. Should be null if either the operation is not an insertion or if there are no auto-fields existing
obj - The object to store auto-field values in
red - Descriptor providing the field mappings
Throws:
java.sql.SQLException

sqlUpdate

public int sqlUpdate(java.lang.String operation)
              throws java.sql.SQLException
Like function above but without any auto-field expectations

Throws:
java.sql.SQLException

sqlQuery

public ResultIterator sqlQuery(java.lang.String operation)
                        throws java.sql.SQLException
Runs an SQL query according to the passed operation

Throws:
java.sql.SQLException

sqlQuery

public ResultIterator sqlQuery(java.lang.String operation,
                               java.lang.Object obj,
                               RecordDescriptor red)
                        throws java.sql.SQLException
Runs an SQL query and returns a ResultIterator, initialized with parameters obj and red and the ResultSet returned by the query.

Throws:
java.sql.SQLException

where

protected java.lang.String where(java.lang.String where)

fetchRecord

public void fetchRecord(java.lang.Object primaryKey,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Fetch a record from the database and store the results in a JAVA object according to the passed mapping descriptor.

Parameters:
primaryKey - Primary key used for unique selection from the database
obj - Destination object to store the data in
red - Descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

fetchRecord

public void fetchRecord(java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Fetch a record from the database and store the results in a JAVA object according to the passed mapping descriptor.

Parameters:
obj - Destination object to store the data in and to take the primary key from
red - Descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

query

public ResultIterator query(java.lang.String dbfield,
                            java.lang.Object value,
                            java.lang.Object obj,
                            RecordDescriptor red,
                            boolean all)
                     throws java.sql.SQLException
Run a database query.

Parameters:
dbfield - table field which is to be used as selection criteria
value - value which the field determined by dbfield must match
obj - Destination object to store the data in
red - Descriptor providing the field mappings and the table name to access
all - Flag saying wether to fetch all matching records or only the first one
Returns:
A ResultIterator if parameter all is true, null otherwise. The first matching record's data is stored in obj. Following records can successivly be copied to obj using the ResultIterator.
Throws:
NoResultsException - if no matching record could be found
java.sql.SQLException

query

public ResultIterator query(java.lang.String[] dbfields,
                            java.lang.Object obj,
                            RecordDescriptor red,
                            boolean all)
                     throws java.sql.SQLException
Run a database query.

Parameters:
dbfields - table fields which are to be used as selection criteria
obj - both, destination object for result data and source object for the values selection field values
red - descriptor providing the field mappings and the table name to access
all - flag saying wether to fetch all matching records or only the first one
Returns:
A ResultIterator if parameter all is true, null otherwise. The first matching record's data is stored in obj. Following records can successivly be copied to obj using the ResultIterator.
Throws:
NoResultsException - if no matching record could be found
java.sql.SQLException

wildcardSearch

public ResultIterator wildcardSearch(java.lang.String[] dbfields,
                                     java.lang.Object obj,
                                     RecordDescriptor red,
                                     boolean all)
                              throws java.sql.SQLException
Like function query() above but selects using the like operator

Throws:
java.sql.SQLException

query

public ResultIterator query(java.lang.String where,
                            java.lang.Object obj,
                            RecordDescriptor red,
                            boolean all)
                     throws java.sql.SQLException
Run a database query.

Parameters:
where - where-clause to apply (excluding the keyword 'where'!)
obj - Destination object to store the data in
red - Descriptor providing the field mappings and the table name to access
all - Flag saying wether to fetch all matching records or only the first one
Returns:
A ResultIterator if parameter all is true, null otherwise. The first matching record's data is stored in obj. Following records can successivly be copied to obj using the ResultIterator.
Throws:
NoResultsException - if no matching record could be found
java.sql.SQLException

queryAll

public ResultIterator queryAll(java.lang.Object obj,
                               RecordDescriptor red)
                        throws java.sql.SQLException
Run a database query, returning all records of the table denoted by parameter red.

Parameters:
obj - Destination object to store the data in
red - Descriptor providing the field mappings and the table name to access
Returns:
A ResultIterator. The first matching record's data is stored in obj. Following records can successivly be copied to obj using the ResultIterator.
Throws:
NoResultsException - if no matching record could be found
java.sql.SQLException

updateRecord

public int updateRecord(java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Update a database record with the data of a JAVA object according to the passed mapping descriptor. The first attribute listed in parameter red is assumed to make up the primary key. It is used for unique object identification in the update statement's where-clause and is not modified

Parameters:
obj - Source object to extract the data from
red - Descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

updateRecord

public int updateRecord(java.lang.String[] dbkeyfields,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Update a database record.

Parameters:
dbkeyfields - database fields which are supposed to determine the records of interest. Typically the primary key, identifying a single object.
obj - source object to extract the data from. There are only those fields taken into account which are not listed in dbkeyfields
red - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

updateRecord

public int updateRecord(java.lang.String[] dbkeyfields,
                        java.lang.String[] updatefields,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Update a database record.

Parameters:
dbkeyfields - database fields which are supposed to determine the records of interest. Typically the primary key, identifying a single object.
obj - source object to extract the data from. There are only those fields taken into account which are not listed in dbkeyfields
red - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

updateRecord

public int updateRecord(java.lang.String where,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Update a database record.

Parameters:
where - where-clause, identifying the records of interest
obj - source object to extract the data from
red - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

updateRecord

public int updateRecord(java.lang.String where,
                        java.lang.String[] updatefields,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Update a database record.

Parameters:
where - where-clause, identifying the records of interest
obj - source object to extract the data from
red - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

getInsertionHeader

public java.lang.String getInsertionHeader(RecordDescriptor red,
                                           java.lang.String[] autoFields)
Returns a header for a record inserting of the form "insert into ( ... ) values " This function is helpfull to assemble bulk update statements.

Parameters:
descriptor - providing the field names and the table name to access
autoFields - list of fields being automatically managed and initialized by the database itself and must therefore not be provided on record creation. May be null if there are no fields to ignore.

createRecord

public int createRecord(java.lang.String[] autoFields,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Add a record to the database.

Parameters:
obj - source object to extract the data from
red - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

deleteRecord

public int deleteRecord(java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Delete a record from the database.

Parameters:
obj - source object to extract the object's key value from.
red - descriptor providing the field mappings and the table name to access. The very first field in the descriptor is supposed to make up the primary key
Throws:
java.sql.SQLException

deleteRecord

public int deleteRecord(java.lang.String where,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Delete a record from the database.

Parameters:
where - where-clause to select the records of interest
obj - not used
red - descriptor providing the table name to access.
Throws:
java.sql.SQLException

deleteRecord

public int deleteRecord(java.lang.String[] dbkeyfields,
                        java.lang.Object obj,
                        RecordDescriptor red)
                 throws java.sql.SQLException
Delete a record from the database.

Parameters:
dbkeyfields - database fields which are supposed to determine the records of interest. Typically the primary key, identifying a single object.
obj - source object to extract the key data from.
red - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

storeExtensions

protected void storeExtensions(java.lang.Object obj,
                               ExtensionDescriptor xd,
                               boolean update)
                        throws java.sql.SQLException
Store an object's generic extension attributes

Parameters:
obj - source object to extract the data from.
xd - descriptor providing the field mappings and the table name to access
update - updates existing generic attributes if true, creates new generic attributes otherwise.
Throws:
java.sql.SQLException

updateExtensions

public void updateExtensions(java.lang.Object obj,
                             ExtensionDescriptor xd)
                      throws java.sql.SQLException
Update an object's generic extension attributes

Parameters:
obj - source object to extract the data from.
xd - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

updateExtensions

public void updateExtensions(java.lang.Object obj,
                             ExtensionDescriptor xd,
                             java.lang.String[] attrNames)
                      throws java.sql.SQLException
Update a subset of an object's generic extension attributes

Parameters:
obj - source object to extract the data from.
xd - descriptor providing the field mappings and the table name to access
attrNames - names of attributes to update
Throws:
java.sql.SQLException

createExtensions

public void createExtensions(java.lang.Object obj,
                             ExtensionDescriptor xd)
                      throws java.sql.SQLException
Create an object's generic extension attributes

Parameters:
obj - source object to extract the data from.
xd - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

fetchExtensions

public void fetchExtensions(java.lang.Object obj,
                            ExtensionDescriptor xd)
                     throws java.sql.SQLException
Read an object's generic extension attributes

Parameters:
obj - destination object to the data in
xd - descriptor providing the field mappings and the table name to access
Throws:
java.sql.SQLException

fetchExtensions

public void fetchExtensions(java.lang.Object obj,
                            ExtensionDescriptor xd,
                            java.lang.String[] attrNames)
                     throws java.sql.SQLException
Read a subset of an object's generic extension attributes. NOT YET IMPLEMENTED!!

Parameters:
obj - destination object to the data in
xd - descriptor providing the field mappings and the table name to access
attrNames - names of the attributes to read
Throws:
java.sql.SQLException

endTransaction

public void endTransaction(boolean commit)
                    throws java.sql.SQLException
Terminate the current transaction. Runs all registered transaction listeners' commit resp. rollback functions first

Throws:
java.sql.SQLException

commit

public void commit()
            throws java.sql.SQLException
Commit the current transaction. Runs all registered transaction listeners' commit function first

Throws:
java.sql.SQLException

rollback

public void rollback()
              throws java.sql.SQLException
Rollback the current transaction. Runs all registered transaction listeners' rollback function first

Throws:
java.sql.SQLException

addListener

public void addListener(TransactionListener l)
Add a transaction listener to this database object


removeListener

public void removeListener(TransactionListener l)
Remove a transaction listener from this database object