org.sormula.operation
Class SqlOperation<R>

java.lang.Object
  extended by org.sormula.operation.SqlOperation<R>
Type Parameters:
R - class type which contains members for columns of a row in a table
Direct Known Subclasses:
ModifyOperation, ScalarSelectOperation

public abstract class SqlOperation<R>
extends java.lang.Object

Base class for all database operations.

Since:
1.0
Author:
Jeff Miller

Constructor Summary
SqlOperation(Table<R> table)
          Constructs for a table.
 
Method Summary
 void cancel()
          Requests cancel for currently executing statement.
protected  void cascade(R row, boolean post)
          Executes all cascade operations that were created by prepareCascades().
 void close()
          Cleans up after operation is no longer needed.
protected  void closeCascades()
          Closes the CascadeOperation objects for this operation.
protected  void closeStatement()
          Closes the prepared statement for this operation.
protected  SormulaField<R,?> createTargetField(java.lang.reflect.Field field)
          Creates a SormulaField from Field.
abstract  void execute()
          Invokes an execute method on a prepared statement.
protected  java.lang.String getBaseSql()
          Gets the sql used by this operation.
protected  java.sql.Connection getConnection()
          Gets the JDBC connection used in this operation.
 java.lang.String getCustomSql()
          Gets custom sql set with setCustomSql(String).
protected  int getNextParameter()
          Gets the next JDBC parameter number used by PreparedStatement to set parameters.
 OperationTime getOperationTime()
          Gets the timings for this operation that have accumulated since setTimings(boolean) have been enabled.
 java.lang.Object[] getParameters()
          Gets parameters that were set by setParameters(Object...).
 java.lang.String getPreparedSql()
          Gets sql that was used in prepare().
protected  java.sql.PreparedStatement getPreparedStatement()
          Gets the prepared statement used by this operation.
 int getQueryTimeout()
          Gets the number of seconds the driver will wait for a Statement object to execute.
protected  java.lang.String getSql()
          Gets full sql statement to prepare.
 Table<R> getTable()
          Gets the table provided in the constructor.
protected  Table<?> getTargetTable(java.lang.Class<?> targetClass, java.lang.reflect.Field targetField)
          Gets a table object from database associated with this operation.
 java.lang.String getTimingId()
          Gets the timing id for this operation.
 java.lang.String getWhereConditionName()
          Gets where condition name supplied in setWhere(String)
protected  AbstractWhereTranslator<R> getWhereTranslator()
          Gets the translator to map row object values into where condition.
protected  void initOperationTime()
          Initializes OperationTime object that will record elapsed times for this operation.
 boolean isAutoGeneratedKeys()
          If true, Statement.getGeneratedKeys() is used to read column defined as identity and then sets the generated key value in the row.
 boolean isIncludeIdentityColumns()
          Tests if identity columns are used in this operation.
 boolean isReadOnly()
          Gets read-only indicator.
 boolean isTimings()
           
 void logTimings()
          Logs current timings for this operation to log.
protected  void prepare()
          Creates prepared statement for this operation and invokes prepareCascades() to prepare statements for any cascade operations.
protected  void prepareCascades()
          Prepares cascades for all cascade annotations on row class.
protected abstract  java.util.List<CascadeOperation<R,?>> prepareCascades(java.lang.reflect.Field field)
          Creates and prepares cascade operations based upon cascade annotations for a field.
protected  void prepareCheck()
          Prepares statement with prepare() if it is null.
protected  void prepareColumns(R row)
          Deprecated. 
protected  void prepareParameters()
          Deprecated. 
protected  void prepareWhere(R row)
          Deprecated. 
 void setAutoGeneratedKeys(boolean autoGeneratedKeys)
          Sets when to get generated keys from database.
protected  void setBaseSql(java.lang.String sql)
          Sets the base sql used by this operation.
 void setCustomSql(java.lang.String customSql)
          Sets sql to be appended to base sql in operation.
 void setIncludeIdentityColumns(boolean includeIdentityColumns)
          Sets when to generate identity columns.
protected  void setNextParameter(int nextParameter)
          Sets the next column index to use in PreparedStatement.
 void setParameters(java.lang.Object... parameters)
          Sets any parameters to be used by operation.
 void setQueryTimeout(int queryTimeout)
          Sets the number of seconds the driver will wait for a Statement object to execute.
 void setReadOnly(boolean readOnly)
          Sets read-only indicator.
 void setTimingId(java.lang.String timingId)
          Sets the id for the operation times getOperationTime().
 void setTimings(boolean on)
          Enables timings for this operation.
 void setWhere(java.lang.String whereConditionName)
          Sets where condition from annotation name as defined in Where.name() for row.
protected  void setWhereTranslator(AbstractWhereTranslator<R> whereTranslator)
          Sets the translator to map row object values into where condition.
protected  void writeColumns(R row)
          Sets all column parameters from a row using the table's RowTranslator.
protected
<T> void
writeParameter(int parameterIndex, T parameter)
           
protected  void writeParameters()
          Prepares statement and then sets all parameters with PreparedStatement.setObject(int, Object).
protected  void writeWhere(R row)
          Sets all where parameters from a row using the table's WhereTranslator.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SqlOperation

public SqlOperation(Table<R> table)
             throws OperationException
Constructs for a table.

The operation timings default to the current state of the database Database.isTimings(). If timings are enabled for database then all operations will be timed unless explicitly disabled. Operation gets the read only setting setReadOnly(boolean) from the database of the table Database.isReadOnly().

Parameters:
table - operations are performed on this table
Throws:
OperationException - if error
Method Detail

setParameters

public void setParameters(java.lang.Object... parameters)
Sets any parameters to be used by operation. Parameters must be in the same order as defined by Column.primaryKey() or Where annotation.

Parameters:
parameters - parameters as objects (not from row fields)

getParameters

public java.lang.Object[] getParameters()
Gets parameters that were set by setParameters(Object...).

Returns:
parameters for this operation

isReadOnly

public boolean isReadOnly()
Gets read-only indicator.

Returns:
true if modify operations are not permitted
Since:
1.6 and 2.0
See Also:
Database.isReadOnly()

setReadOnly

public void setReadOnly(boolean readOnly)
Sets read-only indicator. When true, this operation will will fail with an exception if it attempts to modify the database. By default read-only is set from the database associated with this operation, Database.isReadOnly(). Set to true as a safe-guard to prevent accidental modification of database.

Parameters:
readOnly - true to prevent modify operations
Since:
1.6 and 2.0
See Also:
Database.setReadOnly(boolean)

getQueryTimeout

public int getQueryTimeout()
Gets the number of seconds the driver will wait for a Statement object to execute.

Returns:
the current query timeout limit in seconds; zero means there is no limit
Since:
1.9 and 2.3
See Also:
Statement.getQueryTimeout()

setQueryTimeout

public void setQueryTimeout(int queryTimeout)
Sets the number of seconds the driver will wait for a Statement object to execute. This value is set when statement is prepared in prepare().

Parameters:
queryTimeout - the new query timeout limit in seconds; zero means there is no limit
Since:
1.9 and 2.3
See Also:
Statement.setQueryTimeout(int)

prepareParameters

@Deprecated
protected void prepareParameters()
                          throws OperationException
Deprecated. 

Replaced with writeParameters().

Throws:
OperationException

writeParameters

protected void writeParameters()
                        throws OperationException
Prepares statement and then sets all parameters with PreparedStatement.setObject(int, Object). prepareCheck() or prepare() must be invoked prior to using this method.

Throws:
OperationException - if error

writeParameter

protected <T> void writeParameter(int parameterIndex,
                                  T parameter)
                       throws java.lang.Exception
Throws:
java.lang.Exception

execute

public abstract void execute()
                      throws OperationException
Invokes an execute method on a prepared statement. The method invoked must be implemented by subclass based upon type of operation. prepareCheck() should be invoked prior to executing sql or use some other means of set up for prepared statement.

Throws:
OperationException - if error

cancel

public void cancel()
            throws OperationException
Requests cancel for currently executing statement. No synchronization is performed between the thread that invokes this method and other threads that may be modifying this object.

Throws:
OperationException - if error
Since:
1.9 and 2.3
See Also:
Statement.cancel()

close

public void close()
           throws OperationException
Cleans up after operation is no longer needed. The connection is not closed but all other objects created by this operations are closed. Prepared statement is closed and close method is invoked on all CascadeOperation objects. This method should be invoked when operation is no longer needed for proper JDBC clean up.

Throws:
OperationException - if error

getTimingId

public java.lang.String getTimingId()
Gets the timing id for this operation. If none is set then the default is the hexadecimal string of the hash code of getSql().

Returns:
timing id for this operation
Since:
1.5

setTimingId

public void setTimingId(java.lang.String timingId)
Sets the id for the operation times getOperationTime(). Typically the default id is sufficient. The id is a key into Database.getOperationTimeMap() which is used to sum multiple instances of timings for this operation.

Use a custom id to force all operations that use the custom id to be summed into one instance of OperationTime in Database.getOperationTimeMap(). A good custom id to use would be the class name of the class that is using the operation, Class.getName().

Parameters:
timingId - unique id associated with an operation(s)
Since:
1.5

setTimings

public void setTimings(boolean on)
Enables timings for this operation. When timings are enabled, prepare, write, execute, and read times are recorded. See getOperationTime(). Use logTimings() to write timings to log for this operation. Use Database.logTimings() to write all operation timings to log.

When on parameter is true, then instance of OperationTime is created at the start of execution for use by this operation. Use getOperationTime() to change default values.

Parameters:
on - true to recording execution times for this operation
Since:
1.5

isTimings

public boolean isTimings()
Returns:
true if timings are enabled; false if not
Since:
1.5

logTimings

public void logTimings()
Logs current timings for this operation to log. Alias for OperationTime.logTimings().

Since:
1.5

getOperationTime

public OperationTime getOperationTime()
Gets the timings for this operation that have accumulated since setTimings(boolean) have been enabled.

Returns:
operation time object containing execution times or NoOperationTime if timings are not enabled
Since:
1.5

initOperationTime

protected void initOperationTime()
Initializes OperationTime object that will record elapsed times for this operation. This method can't be invoked until timing id and/or sql is known so it is invoked by execute().


closeStatement

protected void closeStatement()
                       throws OperationException
Closes the prepared statement for this operation.

Throws:
OperationException - if error

closeCascades

protected void closeCascades()
                      throws OperationException
Closes the CascadeOperation objects for this operation.

Throws:
OperationException - if error

prepareCheck

protected void prepareCheck()
                     throws OperationException
Prepares statement with prepare() if it is null. Invoke prior to using prepared statement to insure that prepared statement has been set up through Connection.prepareStatement(String). Usually invoked prior to invoking a method on PreparedStatement.

Throws:
OperationException - if error

prepare

protected void prepare()
                throws OperationException
Creates prepared statement for this operation and invokes prepareCascades() to prepare statements for any cascade operations.

Throws:
OperationException - if error

prepareCascades

protected void prepareCascades()
                        throws OperationException
Prepares cascades for all cascade annotations on row class. Cascade annotations are OneToManyCascade, OneToOneCascade, and Cascade.

Throws:
OperationException - if error

prepareCascades

protected abstract java.util.List<CascadeOperation<R,?>> prepareCascades(java.lang.reflect.Field field)
                                                                  throws OperationException
Creates and prepares cascade operations based upon cascade annotations for a field.

Parameters:
field - annotation is for this field of row class R
Returns:
list of cascade operations; empty list for none
Throws:
OperationException - if error

cascade

protected void cascade(R row,
                       boolean post)
                throws OperationException
Executes all cascade operations that were created by prepareCascades().

Parameters:
row - instance of source row
post - true if post cascades are to be executed; false if pre cascades are to be executed
Throws:
OperationException - if error

getTargetTable

protected Table<?> getTargetTable(java.lang.Class<?> targetClass,
                                  java.lang.reflect.Field targetField)
                           throws OperationException
Gets a table object from database associated with this operation.

Parameters:
targetClass - class that cascade is to affect
targetField - target of cascade
Returns:
table for target class of annotation
Throws:
OperationException - if error

createTargetField

protected SormulaField<R,?> createTargetField(java.lang.reflect.Field field)
                                       throws OperationException
Creates a SormulaField from Field.

Parameters:
field - creates for this field
Returns:
sormula field based upon field parameter
Throws:
OperationException - if error

getSql

protected java.lang.String getSql()
Gets full sql statement to prepare. Default implementation is to use base sql + custom sql + where sql. Subclasses may override to create more detailed sql.

Returns:
sql to use in prepare()

getPreparedSql

public java.lang.String getPreparedSql()
Gets sql that was used in prepare().

Returns:
sql that was used in prepared statement
Since:
1.5

setCustomSql

public void setCustomSql(java.lang.String customSql)
Sets sql to be appended to base sql in operation. Use this to add specialized sql for operation.

Parameters:
customSql - additional sql to be added to base sql or null for none

getCustomSql

public java.lang.String getCustomSql()
Gets custom sql set with setCustomSql(String).

Returns:
custom sql or null if none

getTable

public Table<R> getTable()
Gets the table provided in the constructor.

Returns:
table to use in this operation

getConnection

protected java.sql.Connection getConnection()
Gets the JDBC connection used in this operation.

Returns:
Connection

setWhere

public void setWhere(java.lang.String whereConditionName)
              throws OperationException
Sets where condition from annotation name as defined in Where.name() for row.

Parameters:
whereConditionName - name of where condition to use; "primaryKey" for key defined by Column.primaryKey(); empty string for no where condition
Throws:
OperationException

getWhereConditionName

public java.lang.String getWhereConditionName()
Gets where condition name supplied in setWhere(String)

Returns:
where condition name

isIncludeIdentityColumns

public boolean isIncludeIdentityColumns()
Tests if identity columns are used in this operation. Default is true. Typically false for insert and update operations.

Returns:
true to include identity columns in sql
See Also:
Column.identity()

setIncludeIdentityColumns

public void setIncludeIdentityColumns(boolean includeIdentityColumns)
Sets when to generate identity columns.

Parameters:
includeIdentityColumns - true to include identity columns in sql

isAutoGeneratedKeys

public boolean isAutoGeneratedKeys()
If true, Statement.getGeneratedKeys() is used to read column defined as identity and then sets the generated key value in the row. Default is false. Typically true for insert operations.

Returns:
true if identity column is generated by database
See Also:
InsertOperation.processIdentityColumn(Object)

setAutoGeneratedKeys

public void setAutoGeneratedKeys(boolean autoGeneratedKeys)
Sets when to get generated keys from database.

Parameters:
autoGeneratedKeys - true if identity column is generated by database

prepareColumns

@Deprecated
protected void prepareColumns(R row)
                       throws OperationException
Deprecated. 

Replaced with writeColumns(Object).

Throws:
OperationException

writeColumns

protected void writeColumns(R row)
                     throws OperationException
Sets all column parameters from a row using the table's RowTranslator.

Parameters:
row - get column values from this row
Throws:
OperationException - if error

prepareWhere

@Deprecated
protected void prepareWhere(R row)
                     throws OperationException
Deprecated. 

Replaced with writeWhere(Object).

Throws:
OperationException

writeWhere

protected void writeWhere(R row)
                   throws OperationException
Sets all where parameters from a row using the table's WhereTranslator.

Parameters:
row - get where parameters from this row
Throws:
OperationException - if error

getBaseSql

protected java.lang.String getBaseSql()
Gets the sql used by this operation. Typically includes command like select, update, insert, delete, and columns. Does not include where, order by, or other additional sql.

Returns:
base sql used by this operation

setBaseSql

protected void setBaseSql(java.lang.String sql)
Sets the base sql used by this operation. See getBaseSql() for details.

Parameters:
sql - base sql used by this operation

getPreparedStatement

protected java.sql.PreparedStatement getPreparedStatement()
Gets the prepared statement used by this operation.

Returns:
prepared statement or null if statement has not been prepapred

getWhereTranslator

protected AbstractWhereTranslator<R> getWhereTranslator()
Gets the translator to map row object values into where condition.

Returns:
where translator or null if none

setWhereTranslator

protected void setWhereTranslator(AbstractWhereTranslator<R> whereTranslator)
Sets the translator to map row object values into where condition.

Parameters:
whereTranslator - where translator or null if none

getNextParameter

protected int getNextParameter()
Gets the next JDBC parameter number used by PreparedStatement to set parameters. Parameter number changes as column and where conditions are prepared. Parameter numbers start at 1 and occur for every "?" in the SQL statement. The parameter numbers are used as the first parameter in the various PreparedStatement set methods.

Returns:
the next PreparedStatement parameter to use

setNextParameter

protected void setNextParameter(int nextParameter)
Sets the next column index to use in PreparedStatement. See getNextParameter() for details.

Parameters:
nextParameter - the next PreparedStatement parameter to use