org.tentackle.db
Class Db

java.lang.Object
  extended by org.tentackle.db.Db
All Implemented Interfaces:
Cloneable, Comparable<Db>

public class Db
extends Object
implements Cloneable, Comparable<Db>

A logical database connection. Db connections are an abstraction for a connection between a client and a server, whereas "server" is not necessarily a database server, because Db connections can be either local or remote.
A local Db talks to a database backend via a ConnectionManager which is responsible for the physical JDBC-connection. However, there is no 1:1 relationship between a Db and a physical connection. This is up to the connection manager. Local Db connections are used in client applications running in 2-tier mode or in application servers.
Remote Db connections are connected to a Tentackle application server via RMI. Client applications running in 3-tier mode (more precise n-tier, with n >= 3) use remote connections.
With the abstraction of a logical Db connection, Tentackle applications are able to run both in 2- or n-tier mode without a single modification to the source code. It's just a small change in a config file.

The configuration is achieved by a property file, which is located by the UserInfo passed to the Db.

Local connections can be either a DataSource bound via JNDI or a direct JDBC connection. JNDI is used in application servers, for example running a JRuby on Rails WebApplication from within Glassfish. JDBC connections are for standalone 2-tier applications or Tentackle application servers.
For local connections via JDBC the file contains at least the following properties:

 driver=jdbc-driver
 url=jdbc-url
 
 Example:
 driver=org.postgresql.Driver
 url=jdbc:postgresql://gonzo.krake.local/erp
 
Local connections via JNDI need only the url. The url starts with "jndi:" and is followed by the JNDI-name. The optional database backend type is only necessary if it cannot be determined from the connection's metadata. The following types are currently supported: db2, ingres, informix, mssql, mysql, oracle and postgres.
 url=jndi:name[:database-type]
 
 Example:
 url=jndi:jdbc/erpPool
 
For remote connections only one line is required at minimum:
 url=rmi://hostname[:port]/service
 
 Example:
 url=rmi://gonzo.krake.local:28004/ErpServer
 
The port is optional and defaults to 1099 (the default RMI registry). For setting up an application server please refer to DbServer.

Optionally, the following properties can be defined:

For local connections via JDBC:

For local connections via JDBC or JNDI:

For remote connections, the property file will be sent to the server. This can be used to set some application specific options or to tune the connection. For example, if the server requires an SSL connection, the client can request to turn off SSL after successful login. Or clients using slow communication lines may request compression. The following properties are already predefined:

Author:
harald

Field Summary
static CharConverter passwordObfuscator
          The current password obfuscator
static CharConverter usernameObfuscator
          The current username obfuscator
static String WHERE_CLAUSE
          "WHERE"
static String WHEREALL_CLAUSE
          "WHERE 1=1" allows AND to be added
static String WHEREAND_CLAUSE
          WHEREALL_CLAUSE + AND will be replaced by...
static String WHEREOR_CLAUSE
          WHEREALL_CLAUSE + OR will be replaced by...
 
Constructor Summary
Db(ConnectionManager conMgr, UserInfo ui)
          Creates an instance of a logical db connection.
Db(UserInfo ui)
          Creates an instance of a db-connection with the default connection manager as defined by DbGlobal.connectionManager.
 
Method Summary
 int addIdSource(IdSource idSource)
          Subclasses get their default ID-Source from the Db-connection.
 StringBuilder addLimitOffsetToSql(StringBuilder sql, int limit, int offset)
          Adds a limit and offset clause to an SQL statement according to the database backend in use.
 void appendDeferredModificationLog(ModificationLog log)
          Appends a ModificationLog object to the deferred log list.
 int appendLimitOffsetToPreparedStatement(int ndx, PreparedStatementWrapper st, int limit, int offset)
          Appends limit and offset parameters to a prepared statement according to the database in use.
static void applyToCollection(Db db, Collection<? extends DbObject> list)
          Sets the context in a collection of DbObjects.
static void applyToDbObject(Db db, DbObject obj)
          Sets the db in a DbObject if not null.
 void assertNotRemote()
          asserts that this is not a remote connection
 void assertRemote()
          asserts that this is a remote connection
 boolean begin()
          Starts a transaction.
Does nothing if a transaction is already running!
 boolean begin(String txName)
          Starts a transaction.
Does nothing if a transaction is already running!
 void clearCloned()
          Clears the cloned state.
 void clearPassword()
          Clears all passwords (stored in char[]-arrays) so that they are no more visible in memory.
 Db clone()
          Clones a logical connection.
 void close()
          Close a database connection.
 boolean commit(boolean autoCommit)
          Commits a transaction if the corresponding begin() has started it.
 int compareTo(Db db)
          Compares two db instances.
 Connection connect()
          Creates a physical low level connection to the local db server via JDBC using this Db (authentication by userinfo or fixed user/password).
 Thread createKeepAliveThread(long interval)
          Creates a simple thread that keeps this db connection "alive", for example while the user is prompted to answer a question from within ModificationThread.runOnce(java.lang.Runnable).
If remote connections don't receive an alive signal within a given timeout the server usually assumes a dead session and closes it.
 StatementWrapper createStatement()
          Creates a non-prepared statement.
 void finalize()
          finalizer if connection is broken
 Db getClonedFromDb()
          Gets the original db if this db is cloned.
 int getConnectionId()
          Gets the connection id.
 ConnectionManager getConnectionManager()
          Gets the connection manager for this Db.
 char[] getDbPassword()
          Gets the fixed password
 String getDbUser()
          Gets the name of the effective database user.
 IdSource getDefaultIdSource()
          Gets the default IdSource.
 List<ModificationLog> getDeferredModificationLogList()
          Gets the deferred ModificationLogs.
 String getDriver()
          Gets the driver of the connection.
 int getFetchSize()
          Gets the default fetchsize
 int getGroupId()
          Gets the group instance number.
 IdSource getIdSource(int id)
          Gets the idsource by handle local to this db
 IdSourceConfigurator getIdSourceConfigurator()
          Gets the ID-Source configurator.
 Exception getLoginFailedCause()
          Gets the Exception that caused the last open() to fail.
 long getLogModificationTxId()
          Returns the current transaction id from the last BEGIN modification log.
 int getMaxRows()
          gets the maximum number of rows in resultsets.
 ModificationCounter getModificationCounter(String tableName)
          Gets the ModificationCounter for a given tablename.
 DbPool getPool()
          Gets the pool manager.
 int getPoolId()
          Gets the poolid.
 PreparedStatementWrapper getPreparedStatement(int id)
          Gets the prepared statement.
 PreparedStatementWrapper getPreparedStatement(String sql)
          Get prepared statement with ResultSet.TYPE_FORWARD_ONLY and ResultSet.CONCUR_READ_ONLY.
 PreparedStatementWrapper getPreparedStatement(String sql, int resultSetType)
          Get prepared statement with ResultSet.CONCUR_READ_ONLY.
 PreparedStatementWrapper getPreparedStatement(String sql, int resultSetType, int resultSetConcurrency)
          Combination of prepareStatement(sql,...) and getPreparedStatement(stmtId).
 RemoteDbConnection getRemoteConnection()
          Gets the remote connection object.
 RemoteDelegate getRemoteDelegate(int id)
          Gets the remote delegate by its id.
 RemoteDbSession getRemoteSession()
          Gets the remote session object.
 int getResultSetConcurrency(int stmtId)
          Get the resultSetConcurrency of a prepared statement.
 int getResultSetType(int stmtId)
          Gets the resultSetType of a prepared statement.
 String getSqlText(int stmtId)
          Gets the sql-string of a prepared statement.
 int getStatementId(String sql)
          Get the ID of a prepared statement by its SQL-string.
 int getStatementId(String sql, int resultSetType)
          Get the ID of a prepared statement by its SQL-string and result set type.
 int getStatementId(String sql, int resultSetType, int resultSetConcurrency)
          Get the ID of a prepared statement by its SQL-string, result set type and concurrency.
 long getTxCount()
          Transactions get a unique transaction number by counting the transactions per Db instance.
 String getTxName()
          Gets the optional transaction name.
 DbObject getTxObject()
          Gets the optional transaction object.
 int getUpdateCount()
          Gets the number of objects modified since the last begin().
 String getUrl()
          Gets the url if this is a remote connection
 UserInfo getUserInfo()
          Gets the current user info.
 boolean isAlive()
          Checks whether the db connection is still in use.
 boolean isAutoCommit()
          Gets the current autocommit state.
 boolean isCloned()
          Gets the cloned state.
 boolean isCountModificationAllowed()
          Checks whether objects are allowed to count modifications.
 boolean isDb2()
          For applications that need to know the kind of database backend.
 boolean isInformix()
          For applications that need to know the kind of database backend.
 boolean isIngres()
          For applications that need to know the kind of database backend.
 boolean isLogModificationAllowed()
          Gets the state of logModificationAllowed.
 boolean isLogModificationDeferred()
          Gets the state for logModificationDeferred.
 boolean isLogModificationTxEnabled()
          Gets the value of logModificationTx.
 boolean isMssql()
          For applications that need to know the kind of database backend.
 boolean isMysql()
          For applications that need to know the kind of database backend.
 boolean isObfuscatedLogin()
          Gets the obfuscated login flag (a feature that will be removed soon...)
 boolean isOpen()
          Gets the connection state.
 boolean isOracle()
          For applications that need to know the kind of database backend.
 boolean isPooled()
          Checks whether this Db is pooled.
 boolean isPostgres()
          For applications that need to know the kind of database backend.
 boolean isRemote()
          Gets the type of the logical connection.
 boolean isUniqueViolation()
          When updates or inserts fail this might be due to a unique voilation.
 boolean isUniqueViolationLogEnabled()
          Checks whether unique violations are logged.
 boolean open()
          Open a database connection.
static int prepareRemoteDelegate(Class clazz)
          Prepares a RemoteDelegate.
 int prepareStatement(String sql)
          Creates a prepared statement with ResultSet.TYPE_FORWARD_ONLY and ResultSet.CONCUR_READ_ONLY.
 int prepareStatement(String sql, int resultSetType)
          Creates a prepared statement with ResultSet.CONCUR_READ_ONLY.
 int prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
          Creates a prepared statement.
Statements are bound to the db (i.e.
 int prependLimitOffsetToPreparedStatement(int ndx, PreparedStatementWrapper st, int limit, int offset)
          Prepends limit and offset parameters to a prepared statement according to the database in use.
 void registerCommitTxRunnable(CommitTxRunnable txRunnable)
          Registers a CommitTxRunnable to be invoked just before committing a transaction.
 void registerRollbackTxRunnable(RollbackTxRunnable txRunnable)
          Registers a RollbackTxRunnable to be invoked just before rolling back a transaction.
 boolean rollback(boolean autoCommit)
          Rolls back a transaction if the corresponding begin() has started it.
 void setAlive(boolean alive)
          Sets the db connection's alive state.
 void setCountModificationAllowed(boolean countModificationAllowed)
          Defines whether objects are allowed to count modifications.
 void setDefaultIdSource(IdSource idSource)
          Set the default IdSource.
This is the source that is used to generate unique object IDs if classes did not configure their own source.
 void setFetchSize(int fetchSize)
          Sets the default fetchsize for all "wrapped" statements (PreparedStatementWrapper and StatementWrapper)
 void setGroupId(int number)
          Sets the group number for this db.
 void setIdSource(int id, IdSource idSource)
          Sets the idsource by handle local to this db.
 void setIdSourceConfigurator(IdSourceConfigurator idConfig)
          Sets the ID-Source configurator.
 void setLoginFailedCause(Exception loginFailedCause)
          Sets the cause for login failed.
 void setLogModificationAllowed(boolean logModificationAllowed)
          Sets the modification allowed state.
 void setLogModificationDeferred(boolean logModificationDeferred)
          Sets the modification deferred state.
In deferred mode the ModificationLog objects are not written to the database.
 void setLogModificationTxEnabled(boolean logModificationTxEnabled)
          Turn transaction-logging on or off.
 void setLogModificationTxId(long logModificationTxId)
          Sets the transaction id.
 void setMaxRows(int maxRows)
          sets the maximum number of rows in resultsets.
 void setPool(DbPool dbPool)
          Sets the pool manager.
 void setPoolId(int poolId)
          Sets the pool id.
 void setTxObject(DbObject txObject)
          Sets the optional transaction object.
By default, whenever a transaction is initiated by a persistence operation of a DbObject or DbObject.isTxObject() returns true, that object becomes the "parent" of the transaction.
 void setUniqueViolation(boolean uniqueViolation)
          Sets the unique violation flag.
 void setUniqueViolationLogEnabled(boolean logUniqueViolation)
          By default, unique violations are logged.
 void setUserInfo(UserInfo ui)
          Sets the userInfo.
 String sqlFormatLimitClause(String par)
          Returns the limit clause formatted for the given database.
 String sqlFormatLimitOffsetClause(String limitPar, String offsetPar)
          Returns the limit clause formatted for the given database.
 String sqlFormatOffsetClause(String par)
          Returns the limit clause formatted for the given database.
 boolean sqlRequiresExtraCommit()
          According to the JDBC-specs Connection.setAutoCommit(boolean)(true) should commit, but some backends require an extra Connection.commit().
 boolean sqlRequiresLimitAppended()
          The top/limit/first clause has to be appended by some dbms and to be prepended by others.
 boolean sqlRequiresLimitBeforeOffset()
          The limit + offset/skip clause has to be appended by some dbms and to be prepended by others.
 boolean sqlRequiresLimitOffsetAppended()
          The limit + offset/skip clause has to be appended by some dbms and to be prepended by others.
 boolean sqlRequiresNestedLimitOffsetSelect()
          Returns true if limit+offset clause requires a nested select.
 boolean sqlRequiresNestedLimitSelect()
          Returns true if limit clause requires a nested select.
 boolean sqlRequiresNestedOffsetSelect()
          Returns true if offset clause requires a nested select.
 boolean sqlRequiresOffsetAppended()
          The offset/skip clause has to be appended by some dbms and to be prepended by others.
 boolean sqlResultSetIsClosedSupported()
           
 String toString()
          for logging
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

WHEREALL_CLAUSE

public static final String WHEREALL_CLAUSE
"WHERE 1=1" allows AND to be added

See Also:
Constant Field Values

WHEREAND_CLAUSE

public static final String WHEREAND_CLAUSE
WHEREALL_CLAUSE + AND will be replaced by... WHERE_CLAUSE

See Also:
Constant Field Values

WHEREOR_CLAUSE

public static final String WHEREOR_CLAUSE
WHEREALL_CLAUSE + OR will be replaced by... WHERE_CLAUSE

See Also:
Constant Field Values

WHERE_CLAUSE

public static final String WHERE_CLAUSE
"WHERE"

See Also:
Constant Field Values

passwordObfuscator

public static CharConverter passwordObfuscator
The current password obfuscator


usernameObfuscator

public static CharConverter usernameObfuscator
The current username obfuscator

Constructor Detail

Db

public Db(ConnectionManager conMgr,
          UserInfo ui)
Creates an instance of a logical db connection.

Parameters:
conMgr - the connection manager to use for this db
ui - user information

Db

public Db(UserInfo ui)
Creates an instance of a db-connection with the default connection manager as defined by DbGlobal.connectionManager.

Parameters:
ui - user information
Method Detail

toString

public String toString()
for logging

Overrides:
toString in class Object
Returns:
a string representation of the object.

compareTo

public int compareTo(Db db)
Compares two db instances. Implemented for trees, caches, etc... because they need a Comparable. We simply use the instanceNumber. Because the instanceNumber is unique, we don't need to override equals/hash.

Specified by:
compareTo in interface Comparable<Db>
Parameters:
db - the db connection to compare this db with
Returns:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

getConnectionManager

public ConnectionManager getConnectionManager()
Gets the connection manager for this Db.

Returns:
the connection manager

setPool

public void setPool(DbPool dbPool)
Sets the pool manager. The method is invoked from a DbPool when the Db is created.

Parameters:
dbPool - the db pool, null = not pooled

getPool

public DbPool getPool()
Gets the pool manager.

Returns:
the db pool, null = not pooled

isPooled

public boolean isPooled()
Checks whether this Db is pooled.

Returns:
true if pooled, false if not pooled

setPoolId

public void setPoolId(int poolId)
Sets the pool id. The method is invoked from a DbPool when the Db is used in a pool.

Parameters:
poolId - the ID given by the pool (> 1), 0 = not used (free Db)

getPoolId

public int getPoolId()
Gets the poolid.

Returns:
the Id given by the pool if used, 0 = not used.

getRemoteConnection

public RemoteDbConnection getRemoteConnection()
Gets the remote connection object.

Returns:
the connection object, null if local

getRemoteSession

public RemoteDbSession getRemoteSession()
Gets the remote session object.

Returns:
the session, null if local

connect

public Connection connect()
                   throws SQLException
Creates a physical low level connection to the local db server via JDBC using this Db (authentication by userinfo or fixed user/password).

Returns:
the low level JDBC connection
Throws:
SQLException - if connection failed

isAlive

public boolean isAlive()
Checks whether the db connection is still in use. Whenever a StatementWrapper or PreparedStatementWrapper is used (i.e executeQuery or executeUpdate), the db connection is set to be alive. Some other thread may clear this flag regulary and check whether it has been set in the meantime.

Returns:
true if connection still in use, false if not used since last setAlive(false).

setAlive

public void setAlive(boolean alive)
Sets the db connection's alive state.

Parameters:
alive - is true to signal it's alive, false to clear

setIdSourceConfigurator

public void setIdSourceConfigurator(IdSourceConfigurator idConfig)
Sets the ID-Source configurator.

Parameters:
idConfig - the configurator

getIdSourceConfigurator

public IdSourceConfigurator getIdSourceConfigurator()
Gets the ID-Source configurator.

Returns:
the configurator

open

public boolean open()
Open a database connection. If the login failes due to wrong passwords or denied access by the application server, the method handleConnectException(java.lang.Exception) is invoked. If the application is not terminated due a severe error, getLoginFailedCause() holds the reason, for example "already logged in".

Returns:
true if open, else false

getLoginFailedCause

public Exception getLoginFailedCause()
Gets the Exception that caused the last open() to fail.

Returns:
the cause

setLoginFailedCause

public void setLoginFailedCause(Exception loginFailedCause)
Sets the cause for login failed.

Parameters:
loginFailedCause - the Exception

clearPassword

public void clearPassword()
Clears all passwords (stored in char[]-arrays) so that they are no more visible in memory.


close

public void close()
Close a database connection.


finalize

public void finalize()
finalizer if connection is broken

Overrides:
finalize in class Object

isOpen

public boolean isOpen()
Gets the connection state.

Returns:
true if db is open, else false

getTxCount

public long getTxCount()
Transactions get a unique transaction number by counting the transactions per Db instance.

Returns:
the current transaction counter

getTxName

public String getTxName()
Gets the optional transaction name. Useful to distinguish transactions in logModification or alike. The tx-name is cleared after commit or rollback.

Returns:
the transaction name, null if no tx set.

setTxObject

public void setTxObject(DbObject txObject)
Sets the optional transaction object.
By default, whenever a transaction is initiated by a persistence operation of a DbObject or DbObject.isTxObject() returns true, that object becomes the "parent" of the transaction. The txObject is mainly used for logging and enhanced auditing (partial history) during transactions. The txObject is cleared at the end of the transaction.

Parameters:
txObject - the transaction object, null to clear

getTxObject

public DbObject getTxObject()
Gets the optional transaction object.

Returns:
the transaction object, null if none

begin

public boolean begin(String txName)
Starts a transaction.
Does nothing if a transaction is already running!

Parameters:
txName - is the optional transaction name, null if none
Returns:
the old commit value, true if a new transaction was begun

begin

public boolean begin()
Starts a transaction.
Does nothing if a transaction is already running!

Returns:
the old commit value, true if a new transaction was begun

getUpdateCount

public int getUpdateCount()
Gets the number of objects modified since the last begin(). The method is provided to check whether objects have been modified at all.

Returns:
the number of modified objects

registerCommitTxRunnable

public void registerCommitTxRunnable(CommitTxRunnable txRunnable)
Registers a CommitTxRunnable to be invoked just before committing a transaction.

Parameters:
txRunnable - the runnable to register

registerRollbackTxRunnable

public void registerRollbackTxRunnable(RollbackTxRunnable txRunnable)
Registers a RollbackTxRunnable to be invoked just before rolling back a transaction.

Parameters:
txRunnable - the runnable to register

commit

public boolean commit(boolean autoCommit)
Commits a transaction if the corresponding begin() has started it. The corresponding begin() is determined by the autoCommit parameter. If autoCommit is true (which is the value begin() returned), the tx is committed. If false, the begin() was nested within an already running tx, so it is ignored.

Parameters:
autoCommit - the old autoCommit state before begin()
Returns:
true if tx was really committed, false if not.

rollback

public boolean rollback(boolean autoCommit)
Rolls back a transaction if the corresponding begin() has started it. The corresponding begin() is determined by the autoCommit parameter. If autoCommit is true (which is the value begin() returned), the tx is rolled back. If false, the begin() was nested within an already running tx, so it is ignored.

Parameters:
autoCommit - the old autoCommit state before begin()
Returns:
true if tx was really rolled back, false if not.

getConnectionId

public int getConnectionId()
Gets the connection id. This is a unique number assigned to this Db by the ConnectionManager.

Returns:
the connection id, 0 = Db is new and not connected so far

setGroupId

public void setGroupId(int number)
Sets the group number for this db. This is an optional number describing groups of db-connections, which is particulary useful in rmi-servers: if one connection fails, all others should be closed as well. Groups are only meaningful for local db-connections, i.e. for remote dbs the group instance refers to that of the rmi-server.

Parameters:
number - is the group number, 0 = no group

getGroupId

public int getGroupId()
Gets the group instance number.

Returns:
the instance number, 0 = no group.

createStatement

public StatementWrapper createStatement()
Creates a non-prepared statement.

Non-prepared statements attach the db as soon as they are instatiated! The db is detached after executeUpdate or after executeQuery when its result set is closed.

Returns:
the statement wrapper

prepareStatement

public int prepareStatement(String sql,
                            int resultSetType,
                            int resultSetConcurrency)
Creates a prepared statement.
Statements are bound to the db (i.e. connection). If the statement is already prepared, it will not be prepared again, but the ID of the existing statement returned. Statements are unique for sql+resultSetType+resultSetConcurrency. The statement ID is unique among all DB-instances. The ID starts at 1 (not 0).

Parameters:
sql - the SQL string
resultSetType - is one of ResultSet.TYPE_...
resultSetConcurrency - is one of ResultSet.CONCUR_..
Returns:
the statement ID

prepareStatement

public int prepareStatement(String sql,
                            int resultSetType)
Creates a prepared statement with ResultSet.CONCUR_READ_ONLY. This is the default for 99% of all applications.

Parameters:
sql - the SQL string
resultSetType - is one of ResultSet.TYPE_...
Returns:
statement id

prepareStatement

public int prepareStatement(String sql)
Creates a prepared statement with ResultSet.TYPE_FORWARD_ONLY and ResultSet.CONCUR_READ_ONLY.

Parameters:
sql - the SQL string
Returns:
statement id

getResultSetType

public int getResultSetType(int stmtId)
Gets the resultSetType of a prepared statement. Once prepared, you cannot change the resultSetType.

Parameters:
stmtId - the statement id
Returns:
the resultset type

getResultSetConcurrency

public int getResultSetConcurrency(int stmtId)
Get the resultSetConcurrency of a prepared statement. Once prepared, you cannot change the resultSetConcurrency.

Parameters:
stmtId - the statement id
Returns:
the concurrency

getSqlText

public String getSqlText(int stmtId)
Gets the sql-string of a prepared statement.

Parameters:
stmtId - the statement id
Returns:
the sql string

getStatementId

public int getStatementId(String sql,
                          int resultSetType,
                          int resultSetConcurrency)
Get the ID of a prepared statement by its SQL-string, result set type and concurrency. A convenient way to re-use prepared statements for example in qbf searchs.

Parameters:
sql - the sql string
resultSetType - the result set type
resultSetConcurrency - the concurrency
Returns:
the statement ID or 0 if no such statement
See Also:
ResultSet

getStatementId

public int getStatementId(String sql,
                          int resultSetType)
Get the ID of a prepared statement by its SQL-string and result set type. The concurrency is assumed as ResultSet.CONCUR_READ_ONLY.

Parameters:
sql - the sql string
resultSetType - the result set type
Returns:
the statement ID or 0 if no such statement
See Also:
ResultSet

getStatementId

public int getStatementId(String sql)
Get the ID of a prepared statement by its SQL-string. The result set type is assumed as ResultSet.TYPE_FORWARD_ONLY and the concurrency as ResultSet.CONCUR_READ_ONLY.

Parameters:
sql - the sql string
Returns:
the statement ID or 0 if no such statement
See Also:
ResultSet

getPreparedStatement

public PreparedStatementWrapper getPreparedStatement(int id)
Gets the prepared statement.

Getting the prepared statement will attach the db to a connection. The db will be detached after executeUpdate() or executeQuery when its result set is closed.

Parameters:
id - the statement id
Returns:
the prepared statement for this db

getPreparedStatement

public PreparedStatementWrapper getPreparedStatement(String sql,
                                                     int resultSetType,
                                                     int resultSetConcurrency)
Combination of prepareStatement(sql,...) and getPreparedStatement(stmtId). Often used in searchQbf-methods.

Parameters:
sql - the SQL string
resultSetType - is one of ResultSet.TYPE_...
resultSetConcurrency - is one of ResultSet.CONCUR_..
Returns:
the statement

getPreparedStatement

public PreparedStatementWrapper getPreparedStatement(String sql,
                                                     int resultSetType)
Get prepared statement with ResultSet.CONCUR_READ_ONLY. This is the method most often used in searchQbf!

Parameters:
sql - the SQL string
resultSetType - is one of ResultSet.TYPE_...
Returns:
the statement

getPreparedStatement

public PreparedStatementWrapper getPreparedStatement(String sql)
Get prepared statement with ResultSet.TYPE_FORWARD_ONLY and ResultSet.CONCUR_READ_ONLY.

Parameters:
sql - the SQL string
Returns:
the statement

isAutoCommit

public boolean isAutoCommit()
Gets the current autocommit state.

Returns:
false if in between a transaction, true otherwise

getUserInfo

public UserInfo getUserInfo()
Gets the current user info.

Returns:
the UserInfo

setUserInfo

public void setUserInfo(UserInfo ui)
Sets the userInfo. This will *NOT* send the userinfo to the remote server if this is a remote db.

Parameters:
ui - the userinfo.

getUrl

public String getUrl()
Gets the url if this is a remote connection

Returns:
the url, null if local

getDriver

public String getDriver()
Gets the driver of the connection.

Returns:
the string of the driver, the name of the Db-class for remote connections

clone

public Db clone()
Clones a logical connection.

Connections may be cloned, which results in a new connection using the cloned userinfo of the original connection. If the old db is already open, the new db will be opened as well. If the old db is closed, the cloned db will be closed.

Overrides:
clone in class Object
Returns:
a clone of this instance.
See Also:
Cloneable

getClonedFromDb

public Db getClonedFromDb()
Gets the original db if this db is cloned.

Returns:
the orginal db, null if this db is not cloned.

clearCloned

public void clearCloned()
Clears the cloned state. Useful if the information is no longer needed.


isCloned

public boolean isCloned()
Gets the cloned state.

Returns:
true if this db is cloned

getFetchSize

public int getFetchSize()
Gets the default fetchsize

Returns:
the default fetchSize.

setFetchSize

public void setFetchSize(int fetchSize)
Sets the default fetchsize for all "wrapped" statements (PreparedStatementWrapper and StatementWrapper)

Parameters:
fetchSize - the new default fetchSize

getMaxRows

public int getMaxRows()
gets the maximum number of rows in resultsets.

Returns:
the max rows, 0 = no limit

setMaxRows

public void setMaxRows(int maxRows)
sets the maximum number of rows in resultsets.

Parameters:
maxRows - the max rows, 0 = no limit (default)

isRemote

public boolean isRemote()
Gets the type of the logical connection.

Returns:
true if remote, false if local

assertNotRemote

public void assertNotRemote()
asserts that this is not a remote connection


assertRemote

public void assertRemote()
asserts that this is a remote connection


prepareRemoteDelegate

public static int prepareRemoteDelegate(Class clazz)
Prepares a RemoteDelegate.

The delegates for the DbObject-classes "live" in the db, i.e. the remote session. Thus, delegates are unique per class AND db! In order for the DbObject-derived classes to quickly map to the corresponding delegate, the delegates get a unique handle, i.e. an index to an array of delegates, which in turn is unique among ALL sessions.

Parameters:
clazz - is the DbObject-class
Returns:
the handle

getRemoteDelegate

public RemoteDelegate getRemoteDelegate(int id)
Gets the remote delegate by its id.

Parameters:
id - is the handle for the delegate
Returns:
the delegate for this session

isCountModificationAllowed

public boolean isCountModificationAllowed()
Checks whether objects are allowed to count modifications. The default is true.

Returns:
true if objects are allowed to count modifications

setCountModificationAllowed

public void setCountModificationAllowed(boolean countModificationAllowed)
Defines whether objects are allowed to count modifications. Useful to turn off modcount for a special (temporary) connection doing certain tasks that should not be counted.

Parameters:
countModificationAllowed - true if allowed, false if turned off

getModificationCounter

public ModificationCounter getModificationCounter(String tableName)
Gets the ModificationCounter for a given tablename. If a counter does not exists, a new one will be created.

Parameters:
tableName - is the name of the table
Returns:
the ModificationCounter object for this table and db

setLogModificationAllowed

public void setLogModificationAllowed(boolean logModificationAllowed)
Sets the modification allowed state. Useful to turn off modlog for a special (temporary) connection doing certain tasks that should not be logged. The state will be handed over to the remote db-connection as well.

Parameters:
logModificationAllowed - true to allow, false to deny

isLogModificationAllowed

public boolean isLogModificationAllowed()
Gets the state of logModificationAllowed.

Returns:
true if modification logging is allowed (default).

setLogModificationDeferred

public void setLogModificationDeferred(boolean logModificationDeferred)
Sets the modification deferred state.
In deferred mode the ModificationLog objects are not written to the database. Instead they are kept in memory and can be processed later via getDeferredModificationLogList(). The state will be handed over to the remote db-connection as well.

Note: deferred logs are used to minimize roundtrips in distributed applications. See the PoolKeeper project for more details.

Parameters:
logModificationDeferred - true to allow, false to deny

isLogModificationDeferred

public boolean isLogModificationDeferred()
Gets the state for logModificationDeferred.

Returns:
true if modification logging is deferred. Default is not deferred.

appendDeferredModificationLog

public void appendDeferredModificationLog(ModificationLog log)
Appends a ModificationLog object to the deferred log list.

Parameters:
log - the modlog object to append

getDeferredModificationLogList

public List<ModificationLog> getDeferredModificationLogList()
Gets the deferred ModificationLogs. Upon return the list of deferred logs is always cleared.

Returns:
the deferred logs, null = no logs

applyToDbObject

public static void applyToDbObject(Db db,
                                   DbObject obj)
Sets the db in a DbObject if not null.

Parameters:
db - the db connection
obj - the database object

applyToCollection

public static void applyToCollection(Db db,
                                     Collection<? extends DbObject> list)
Sets the context in a collection of DbObjects.

Parameters:
db - the db connection
list - the collection of database objects

getDefaultIdSource

public IdSource getDefaultIdSource()
Gets the default IdSource.

Returns:
the idSource

setDefaultIdSource

public void setDefaultIdSource(IdSource idSource)
Set the default IdSource.
This is the source that is used to generate unique object IDs if classes did not configure their own source.

Parameters:
idSource - New value of property idSource.

addIdSource

public int addIdSource(IdSource idSource)
Subclasses get their default ID-Source from the Db-connection. However, the classVariables get initialized only once (when the class is loaded), so multiple db-connections will have to provide their own IdSource PER db! Same trick as with prepared statements: IdSources are mapped by a static index. This method adds an id-source to the db-local pool and returns an index to it.

Parameters:
idSource - source to get a handle for
Returns:
the handle

getIdSource

public IdSource getIdSource(int id)
Gets the idsource by handle local to this db

Parameters:
id - handle of the IdSource
Returns:
the IdSource or null if not prepared yet for this db-connection

setIdSource

public void setIdSource(int id,
                        IdSource idSource)
Sets the idsource by handle local to this db. Apps need to set this in MT-applications. The idSources[] will be enlarged if not large enough.

Parameters:
id - handle of the IdSource
idSource - the IdSource or null if not prepared yet for this db-connection

isUniqueViolation

public boolean isUniqueViolation()
When updates or inserts fail this might be due to a unique voilation. In such a case no exception is thrown but the corresponding methods return false and set the unique violation flag.

Returns:
true if last insert/update returned false due to a unique violation.

setUniqueViolation

public void setUniqueViolation(boolean uniqueViolation)
Sets the unique violation flag.

Parameters:
uniqueViolation - true if violation, false if not

isUniqueViolationLogEnabled

public boolean isUniqueViolationLogEnabled()
Checks whether unique violations are logged.

Returns:
true if unique violations are logged

setUniqueViolationLogEnabled

public void setUniqueViolationLogEnabled(boolean logUniqueViolation)
By default, unique violations are logged. However, this feature can be turned off (usually temporarily).

Parameters:
logUniqueViolation - true if unique violations are logged (default)

getLogModificationTxId

public long getLogModificationTxId()
Returns the current transaction id from the last BEGIN modification log. The tx-ID is only available if logModificationTx is true.

Returns:
the tx ID, 0 if no transaction is pending.

setLogModificationTxId

public void setLogModificationTxId(long logModificationTxId)
Sets the transaction id. Normally the tx-ID is derived from the id of the BEGIN-modlog so it's not necessary to invoke this method from an application. (Poolkeeper's replication layer will do so!)

Parameters:
logModificationTxId - the transaction ID

isLogModificationTxEnabled

public boolean isLogModificationTxEnabled()
Gets the value of logModificationTx.

Returns:
true if transaction begin/end is logged in the modification log, false if not (default)

setLogModificationTxEnabled

public void setLogModificationTxEnabled(boolean logModificationTxEnabled)
Turn transaction-logging on or off. Default is off.
With enabled logging the transactions are logged in the ModificationLog as well.

Parameters:
logModificationTxEnabled - true to turn on transaction logging.

getDbUser

public String getDbUser()
Gets the name of the effective database user. Nice to tell whether password authentication must be done in application, if any.

Returns:
dbUser or null if user is the same as in userInfo.

getDbPassword

public char[] getDbPassword()
Gets the fixed password

Returns:
the fixed password, null if from userinfo

isObfuscatedLogin

public boolean isObfuscatedLogin()
Gets the obfuscated login flag (a feature that will be removed soon...)

Returns:
true if login is obfuscated

isPostgres

public boolean isPostgres()
For applications that need to know the kind of database backend.

Returns:
true if the database backend is Postgres.

isIngres

public boolean isIngres()
For applications that need to know the kind of database backend.

Returns:
true if the database backend is Ingres.

isMysql

public boolean isMysql()
For applications that need to know the kind of database backend.

Returns:
true if the database backend is MySQL.

isOracle

public boolean isOracle()
For applications that need to know the kind of database backend.

Returns:
true if the database backend is Oracle.

isInformix

public boolean isInformix()
For applications that need to know the kind of database backend.

Returns:
true if the database backend is Informix.

isMssql

public boolean isMssql()
For applications that need to know the kind of database backend.

Returns:
true if the database backend is Microsoft-SQL-Server.

isDb2

public boolean isDb2()
For applications that need to know the kind of database backend.

Returns:
true if the database backend is DB2.

sqlRequiresExtraCommit

public boolean sqlRequiresExtraCommit()
According to the JDBC-specs Connection.setAutoCommit(boolean)(true) should commit, but some backends require an extra Connection.commit().

Returns:
true if the database needs an extra commit

sqlRequiresLimitAppended

public boolean sqlRequiresLimitAppended()
The top/limit/first clause has to be appended by some dbms and to be prepended by others.

Returns:
true if dbms requires the limit clause to be appended, false if prepended

sqlRequiresNestedLimitSelect

public boolean sqlRequiresNestedLimitSelect()
Returns true if limit clause requires a nested select. Notice: oracle needs a special nested select, so you have to explictly check for isOracle()! (see wurblets)

Returns:
true if database requires nested select

sqlFormatLimitClause

public String sqlFormatLimitClause(String par)
Returns the limit clause formatted for the given database. Works for all except oracle.

Parameters:
par - is either a hard-coded parameter or '?' in prepared statements
Returns:
the formatted sql string

sqlRequiresOffsetAppended

public boolean sqlRequiresOffsetAppended()
The offset/skip clause has to be appended by some dbms and to be prepended by others.

Returns:
true if dbms requires the limit clause to be appended, false if prepended

sqlRequiresNestedOffsetSelect

public boolean sqlRequiresNestedOffsetSelect()
Returns true if offset clause requires a nested select. Notice: oracle needs a special nested select, so you have to explictly check for isOracle()! (see wurblets)

Returns:
true if database requires nested select

sqlFormatOffsetClause

public String sqlFormatOffsetClause(String par)
Returns the limit clause formatted for the given database. Works for all except oracle.

Parameters:
par - is either a hard-coded parameter or '?' in prepared statements
Returns:
the formatted sql string

sqlRequiresLimitOffsetAppended

public boolean sqlRequiresLimitOffsetAppended()
The limit + offset/skip clause has to be appended by some dbms and to be prepended by others.

Returns:
true if dbms requires the limit clause to be appended, false if prepended

sqlRequiresLimitBeforeOffset

public boolean sqlRequiresLimitBeforeOffset()
The limit + offset/skip clause has to be appended by some dbms and to be prepended by others.

Returns:
true if limit parameter comes first, then the offset

sqlRequiresNestedLimitOffsetSelect

public boolean sqlRequiresNestedLimitOffsetSelect()
Returns true if limit+offset clause requires a nested select. Notice: oracle needs a special nested select, so you have to explictly check for isOracle()! (see wurblets)

Returns:
true if database requires nested select

sqlFormatLimitOffsetClause

public String sqlFormatLimitOffsetClause(String limitPar,
                                         String offsetPar)
Returns the limit clause formatted for the given database. Works for all except oracle.

Parameters:
limitPar - the sql string for the limit parameter value
offsetPar - the sql string for the offset parameter value
Returns:
the formatted sql string

sqlResultSetIsClosedSupported

public boolean sqlResultSetIsClosedSupported()
Returns:
true if the JDBC driver supports ResultSet.isClosed()

addLimitOffsetToSql

public StringBuilder addLimitOffsetToSql(StringBuilder sql,
                                         int limit,
                                         int offset)
Adds a limit and offset clause to an SQL statement according to the database backend in use.

Parameters:
sql - the original SQL string buffer
limit - the limit value, ≤ 0 if no limit clause
offset - the offset value, ≤ 0 if no offset clause
Returns:
the modified sql string buffer
See Also:
prependLimitOffsetToPreparedStatement(int, org.tentackle.db.PreparedStatementWrapper, int, int), appendLimitOffsetToPreparedStatement(int, org.tentackle.db.PreparedStatementWrapper, int, int)

prependLimitOffsetToPreparedStatement

public int prependLimitOffsetToPreparedStatement(int ndx,
                                                 PreparedStatementWrapper st,
                                                 int limit,
                                                 int offset)
Prepends limit and offset parameters to a prepared statement according to the database in use.

Parameters:
ndx - starting parameter index, usually 1
st - the prepared statement
limit - the limit value, ≤ 0 if no limit clause
offset - the offset value, ≤ 0 if no offset clause
Returns:
the possibly changed parameter index
See Also:
#addLimitOffsetToSql(java.lang.String, int, int)

appendLimitOffsetToPreparedStatement

public int appendLimitOffsetToPreparedStatement(int ndx,
                                                PreparedStatementWrapper st,
                                                int limit,
                                                int offset)
Appends limit and offset parameters to a prepared statement according to the database in use.

Parameters:
ndx - starting parameter index
st - the prepared statement
limit - the limit value, ≤ 0 if no limit clause
offset - the offset value, ≤ 0 if no offset clause
Returns:
the possibly changed parameter index
See Also:
#addLimitOffsetToSql(java.lang.String, int, int)

createKeepAliveThread

public Thread createKeepAliveThread(long interval)
Creates a simple thread that keeps this db connection "alive", for example while the user is prompted to answer a question from within ModificationThread.runOnce(java.lang.Runnable).
If remote connections don't receive an alive signal within a given timeout the server usually assumes a dead session and closes it.
 Example: 
    Thread keepAliveThread = db.createKeepAliveThread(5000);
    keepAliveThread.start();
    ...
    ...
    keepAliveThread.interrupt();
    keepAliveThread.join();
 

Parameters:
interval - the interval in [ms] to trigger the alive signal
Returns:
the thread, not started yet


Copyright © 2001-2008 Harald Krake, Bergstr. 48, 78098 Triberg, Germany, harald@krake.de