public abstract class AbstractDatabaseEngine extends Object implements DatabaseEngine
This Engine already provides thread safeness to all public exposed methods
| Modifier and Type | Field and Description |
|---|---|
protected Connection |
conn
The database connection.
|
protected String |
currentSchema
The current schema that's being used by the engine.
|
static QueryExceptionHandler |
DEFAULT_QUERY_EXCEPTION_HANDLER
The default instance of
QueryExceptionHandler to be used in disambiguating SQL exceptions. |
protected static org.slf4j.Marker |
dev
The dev Marker.
|
protected Dialect |
dialect
The dialect.
|
protected ExceptionHandler |
eh
The exception handler to control the flow when defining new entities.
|
protected Map<String,MappedEntity> |
entities
Map of entities.
|
protected com.google.inject.Injector |
injector
The Guice injector.
|
protected org.slf4j.Logger |
logger
The logger that will be used.
|
protected org.slf4j.Logger |
notificationLogger
The notification logger for administration.
|
protected PdbProperties |
properties
The configuration.
|
protected ExecutorService |
socketTimeoutExecutor
An
ExecutorService to be used by the DB drivers to break a connection if it has been blocked for longer
than the specified socket timeout |
protected Map<String,PreparedStatementCapsule> |
stmts
Map of prepared statements.
|
protected AbstractTranslator |
translator
The translator in place.
|
| Constructor and Description |
|---|
AbstractDatabaseEngine(String driver,
PdbProperties properties,
Dialect dialect)
Creates a new instance of
AbstractDatabaseEngine. |
| Modifier and Type | Method and Description |
|---|---|
void |
addBatch(String name,
EntityEntry entry)
Add an entry to the batch.
|
protected abstract void |
addColumn(DbEntity entity,
DbColumn... columns)
Adds the column to an existent table.
|
void |
addEntity(DbEntity entity)
Adds an entity to the engine.
|
protected void |
addFks(DbEntity entity)
Adds all foreign keys defined in the entity to the table in the database.
|
protected void |
addFks(DbEntity entity,
Set<DbFk> fks)
Adds foreign key constraints to the table in the database that the provided entity represents.
|
protected abstract void |
addIndexes(DbEntity entity)
Add the desired indexes.
|
protected abstract void |
addPrimaryKey(DbEntity entity)
Add a primary key to the entity.
|
protected abstract void |
addSequences(DbEntity entity)
Adds the necessary sequences.
|
void |
beginTransaction()
Starts a transaction.
|
boolean |
checkConnection()
Checks if the connection is alive.
|
boolean |
checkConnection(boolean forceReconnect)
Checks if the connection is alive.
|
protected boolean |
checkConnection(Connection conn)
Checks if the connection is alive.
|
void |
clearParameters(String name)
Clears the prepared statement parameters.
|
void |
close()
Closes the connection to the database.
|
String |
commentCharacter() |
void |
commit()
Commits the current transaction.
|
protected void |
connect()
Connects to the database.
|
boolean |
containsEntity(String name)
Returns if the current engine contains the entity.
|
<PB extends PdbBatch> |
createBatch(BatchConfig<PB> batchConfig)
Creates a new
PdbBatch to which entries can be added; it then flushes those entries to the database,
periodically on a set timeout, or when a maximum number of entries has been reached. |
AbstractBatch |
createBatch(int batchSize,
long batchTimeout)
Creates a new batch that periodically flushes a batch.
|
AbstractBatch |
createBatch(int batchSize,
long batchTimeout,
String batchName)
Creates a new batch that periodically flushes a batch.
|
AbstractBatch |
createBatch(int batchSize,
long batchTimeout,
String batchName,
BatchListener batchListener)
Creates a new batch that periodically flushes a batch.
|
AbstractBatch |
createBatch(int batchSize,
long batchTimeout,
String batchName,
BatchListener batchListener,
org.slf4j.Logger confidentialLogger)
Creates a new batch that periodically flushes a batch.
|
AbstractBatch |
createBatch(int batchSize,
long batchTimeout,
String batchName,
FailureListener failureListener)
Creates a new batch that periodically flushes a batch.
|
void |
createPreparedStatement(String name,
Expression query)
Creates a prepared statement.
|
void |
createPreparedStatement(String name,
Expression query,
int timeout)
Creates a prepared statement.
|
void |
createPreparedStatement(String name,
String query)
Creates a prepared statement.
|
void |
createPreparedStatement(String name,
String query,
int timeout)
Creates a prepared statement.
|
protected abstract MappedEntity |
createPreparedStatementForInserts(DbEntity entity)
Creates and gets the prepared statement that will be used for insertions.
|
protected abstract ResultIterator |
createResultIterator(PreparedStatement ps)
Creates a specific
ResultIterator for the engine in place given a prepared statement. |
protected abstract ResultIterator |
createResultIterator(Statement statement,
String sql)
Creates a specific
ResultIterator given the engine implementation. |
protected Statement |
createSelectStatement(int readTimeout)
Creates a
Statement that will be used for selects, i.e., may have an associated
read timeout. |
protected abstract void |
createTable(DbEntity entity)
Creates the table.
|
protected abstract long |
doPersist(PreparedStatement ps,
MappedEntity me,
boolean useAutoInc,
int lastBindPosition)
DB engine specific auxiliary method for
persist(String, EntityEntry, boolean) to effectively perform
the persist action. |
protected abstract void |
dropColumn(DbEntity entity,
String... columns)
Drops the column.
|
void |
dropEntity(DbEntity entity)
Drops everything that belongs to the entity.
|
void |
dropEntity(String entity)
Drops an entity.
|
protected String |
dropFkQuery(String table,
String fkName)
Gets the query to drop a foreign key.
|
protected void |
dropFks(String table)
Drops all foreign keys from the table.
|
protected void |
dropFks(String table,
Set<String> fks)
Drops foreign keys from a table.
|
protected abstract void |
dropSequences(DbEntity entity)
Drops the sequences of the entity.
|
protected abstract void |
dropTable(DbEntity entity)
Drops the table.
|
void |
dropView(String view)
Drops a view.
|
DatabaseEngine |
duplicate(Properties mergeProperties,
boolean copyEntities)
Duplicates a connection.
|
protected int |
entityToPreparedStatement(DbEntity entity,
PreparedStatement ps,
EntityEntry entry,
boolean useAutoInc)
Translates the given entry entity to the prepared statement.
|
protected int |
entityToPreparedStatementForBatch(DbEntity entity,
PreparedStatement ps,
EntityEntry entry,
boolean useAutoInc)
Translates the given entry entity to the prepared statement when used in the context of batch updates.
|
protected int |
entityToPreparedStatementInternal(DbEntity entity,
PreparedStatement ps,
EntityEntry entry,
boolean useAutoInc,
boolean fromBatch)
Translates the given entry entity to the prepared statement.
|
String |
escapeCharacter() |
void |
executePS(String name)
Executes the specified prepared statement.
|
Integer |
executePSUpdate(String name)
Executes update on the specified prepared statement.
|
int |
executeUpdate(Expression query)
Executes the given update.
|
int |
executeUpdate(String query)
Executes a native query.
|
protected void |
executeUpdateSilently(String statement)
Executes the given statement.
|
void |
flush()
Flushes the batches for all the registered entities.
|
Connection |
getConnection()
Checks if the connection is available and returns it.
|
protected Properties |
getDBProperties()
Get the properties to be passed to the database connection that will be created.
|
Dialect |
getDialect()
Gets the dialect being used.
|
Map<String,DbEntityType> |
getEntities()
Gets the database entities for the current schema.
|
Map<String,DbEntityType> |
getEntities(String schemaPattern)
Gets the database entities for the specified schema.
|
protected String |
getFinalJdbcConnection(String jdbc)
Gets the final JDBC connection.
|
protected ResultSet |
getImportedKeys(String entityName)
Gets a description of the columns that are referenced by the given table's foreign key columns.
|
Map<String,DbColumnType> |
getMetadata(String tableNamePattern)
Gets the table metadata (table must be in the current schema).
|
Map<String,DbColumnType> |
getMetadata(String schemaPattern,
String tableNamePattern)
Gets the table metadata (table must be in the current schema).
|
protected PreparedStatement |
getPreparedStatementForPersist(boolean useAutoInc,
MappedEntity mappedEntity)
Gets the
PreparedStatement to use in a persist operation, depending on whether autoInc is to be used or not. |
protected String |
getPrivateKey()
Reads the private key from the secret location.
|
PdbProperties |
getProperties()
Gets the properties in use.
|
ResultIterator |
getPSIterator(String name)
Creates an iterator for the
PreparedStatement bound to the given name. |
ResultIterator |
getPSIterator(String name,
int fetchSize)
Creates an iterator for the
PreparedStatement bound to the given name. |
List<Map<String,ResultColumn>> |
getPSResultSet(String name)
Gets the result set of the specified prepared statement.
|
protected QueryExceptionHandler |
getQueryExceptionHandler()
Gets the instance of
QueryExceptionHandler to be used in disambiguating SQL exceptions. |
Map<String,DbColumnType> |
getQueryMetadata(Expression query)
Gets the query metadata.
|
Map<String,DbColumnType> |
getQueryMetadata(String query)
Gets the query metadata.
|
String |
getSchema()
Gets the schema being used in the current
connection. |
abstract Class<? extends AbstractTranslator> |
getTranslatorClass()
Gets the class that translates SQL bound to this engine.
|
protected void |
handleOperation(OperationFault opFault,
Exception exception)
Controls if the given faulty operation must be silenced or not.
|
boolean |
hasIdentityColumn(DbEntity entity)
Check if the entity has an identity column.
|
protected void |
inject(Expression... objs) |
boolean |
isTransactionActive()
Checks if a transaction is active.
|
ResultIterator |
iterator(Expression query)
Creates an iterator for the given SQL expression.
|
ResultIterator |
iterator(Expression query,
int fetchSize)
Creates an iterator for the given SQL expression.
|
ResultIterator |
iterator(Expression query,
int fetchSize,
int readTimeoutOverride)
Creates an iterator for the given SQL expression overriding the configured query
timeout (see
PdbProperties.getSelectQueryTimeout()) if the underlying engine
supports query timeouts. |
ResultIterator |
iterator(String query)
Creates an iterator for the given SQL sentence.
|
ResultIterator |
iterator(String query,
int fetchSize)
Creates an iterator for the given SQL sentence.
|
ResultIterator |
iterator(String query,
int fetchSize,
int readTimeoutOverride)
Creates an iterator for the given SQL sentence overriding the configured query
timeout (see
PdbProperties.getSelectQueryTimeout()) if the underlying engine
supports query timeouts. |
void |
loadEntity(DbEntity entity)
Loads an entity into the engine.
|
protected byte[] |
objectToArray(Object val)
Converts an object to byte array.
|
protected void |
onConnectionCreated()
To be called when the connection to the database is successfully created.
|
Long |
persist(String name,
EntityEntry entry)
Persists a given entry.
|
Long |
persist(String name,
EntityEntry entry,
boolean useAutoInc)
Persists a given entry.
|
boolean |
preparedStatementExists(String name)
Checks if there's a prepared statement with the given name.
|
protected List<Map<String,ResultColumn>> |
processResultIterator(ResultIterator it)
Process a whole
ResultIterator. |
List<Map<String,ResultColumn>> |
query(Expression query)
Executes the given query.
|
List<Map<String,ResultColumn>> |
query(Expression query,
int readTimeoutOverride)
Executes the given query overriding the configured query timeout (see
PdbProperties.getSelectQueryTimeout())
if the underlying engine supports query timeouts. |
List<Map<String,ResultColumn>> |
query(String query)
Executes the given query.
|
List<Map<String,ResultColumn>> |
query(String query,
int readTimeoutOverride)
Executes the given native query overriding the configured query timeout (see
PdbProperties.getSelectQueryTimeout()
if the underlying engine supports query timeouts. |
protected void |
reconnectExceptionally(String message)
Verifies if a connection to the database is available, if not, an attempts to reestablished it are made by
the
getConnection(). |
DbEntity |
removeEntity(String name)
Removes the entity given the name.
|
void |
removePreparedStatement(String name)
Removes the given prepared statement.
|
void |
rollback()
Rolls back a transaction.
|
void |
setExceptionHandler(ExceptionHandler eh)
Sets the given exception handler in the engine.
|
void |
setParameter(String name,
int index,
Object param)
Sets the parameter on the specified index.
|
void |
setParameter(String name,
int index,
Object param,
DbColumnType paramType)
Sets the parameter on the specified index given its type.
|
void |
setParameters(String name,
Object... params)
Sets the parameters on the specified prepared statement.
|
protected void |
setParameterValues(PreparedStatement ps,
int index,
Object param)
Sets the value of a parameter in
index to the value provided in param. |
protected void |
setPreparedStatementValue(PreparedStatement ps,
int index,
DbColumn dbColumn,
Object value,
boolean fromBatch)
Sets a value in the prepared statement.
|
protected void |
setSchema(String schema)
Sets the schema for the current
connection. |
protected void |
setTransactionIsolation()
Sets the transaction isolation level.
|
protected DbColumnType |
toPdbType(int type,
String typeName)
Maps the database type to
DbColumnType. |
String |
translate(Expression query)
Translates the given expression to the current dialect.
|
protected String |
translateType(DbColumn column)
Translates the type present in the given column.
|
void |
updateEntity(DbEntity entity)
Updates an entity in the engine.
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitisStringAggDistinctCapable@Inject protected com.google.inject.Injector injector
@Inject protected AbstractTranslator translator
protected Connection conn
protected static final org.slf4j.Marker dev
protected final org.slf4j.Logger logger
protected final org.slf4j.Logger notificationLogger
protected final Map<String,MappedEntity> entities
protected final Map<String,PreparedStatementCapsule> stmts
protected String currentSchema
protected final PdbProperties properties
protected final Dialect dialect
protected ExceptionHandler eh
protected final ExecutorService socketTimeoutExecutor
ExecutorService to be used by the DB drivers to break a connection if it has been blocked for longer
than the specified socket timeoutpublic static final QueryExceptionHandler DEFAULT_QUERY_EXCEPTION_HANDLER
QueryExceptionHandler to be used in disambiguating SQL exceptions.public AbstractDatabaseEngine(String driver, PdbProperties properties, Dialect dialect) throws DatabaseEngineException
AbstractDatabaseEngine.driver - The driver to connect to the database.properties - The properties of the connection.dialect - The dialect in use.DatabaseEngineException - When errors occur trying to set up the database connection.protected String getPrivateKey() throws Exception
Exception - If something occurs while reading.protected Properties getDBProperties()
AbstractDatabaseEngine
implementation to specify them. This is used, for instance, to set the database connection timeout.protected void connect()
throws Exception
Exception - If connection is not possible, or failed to decrypt username/password if encryption was provided.protected void onConnectionCreated()
throws DatabaseEngineException
DatabaseEngineException - If something wrong occurs while interacting with the database.protected String getFinalJdbcConnection(String jdbc)
Implementations might override this method in order to change the JDBC connection.
jdbc - The current JDBC connection.protected void setTransactionIsolation()
throws SQLException
SQLException - If a database access error occurs.public abstract Class<? extends AbstractTranslator> getTranslatorClass()
public Connection getConnection() throws RetryLimitExceededException, InterruptedException, RecoveryException
getConnection in interface DatabaseEngineRetryLimitExceededException - If the retry limit is exceeded.InterruptedException - If the thread is interrupted during reconnection.RecoveryExceptionpublic void close()
close in interface DatabaseEngineclose in interface AutoCloseablepublic void beginTransaction()
throws DatabaseEngineRuntimeException
Connection.getAutoCommit()).beginTransaction in interface DatabaseEngineDatabaseEngineRuntimeException - If something goes wrong while beginning transaction.public void addEntity(DbEntity entity) throws DatabaseEngineException
addEntity in interface DatabaseEngineentity - The entity to add.DatabaseEngineException - If something goes wrong while creating the structures.public void loadEntity(DbEntity entity) throws DatabaseEngineException
DatabaseEngine
No DDL commands will be executed, only prepared statements will be created in order to persist
data into the entities.
loadEntity in interface DatabaseEngineentity - The entity to load into the connection.DatabaseEngineException - If something goes wrong while loading the entity.public void updateEntity(DbEntity entity) throws DatabaseEngineException
If the entity does not exist in the instance, the method addEntity(DbEntity) will be invoked.
The engine will compare the entity with the getMetadata(String) information and update the schema of the table.
ATTENTION: This method will only add new columns or drop removed columns in the database table. It will also drop and create foreign keys. Primary Keys, Indexes and column types changes will not be updated.
updateEntity in interface DatabaseEngineentity - The entity to update.DatabaseEngineException - If something goes wrong while updating the entity.protected ResultSet getImportedKeys(String entityName) throws DatabaseEngineException, SQLException
entityName - The entity name.ResultSet containing information about columns referenced by a foreign key.DatabaseEngineException - If it isn't possible to get current database metadata.SQLException - If a database access error occurs when getting key information.public DbEntity removeEntity(String name)
DatabaseEngineremoveEntity in interface DatabaseEnginename - The name of the entity to remove.public boolean containsEntity(String name)
DatabaseEnginecontainsEntity in interface DatabaseEnginename - The entity name.public void dropEntity(String entity) throws DatabaseEngineException
dropEntity in interface DatabaseEngineentity - The entity name.DatabaseEngineException - If something goes wrong while dropping the entity.public void dropEntity(DbEntity entity) throws DatabaseEngineException
dropEntity in interface DatabaseEngineentity - The entity.DatabaseEngineException - If something goes wrong while dropping the structures.public void dropView(String view) throws DatabaseEngineException
DatabaseEnginedropView in interface DatabaseEngineview - The view name.DatabaseEngineException - If something goes wrong while dropping the view.public Long persist(String name, EntityEntry entry) throws DatabaseEngineException
If you are inside of an explicit transaction, changes will only be visible upon explicit commit, otherwise a commit will immediately take place.
persist in interface DatabaseEnginename - The entity name.entry - The entry to persist.DatabaseEngineException - If something goes wrong while persisting data.public final Long persist(String name, EntityEntry entry, boolean useAutoInc) throws DatabaseEngineException
If you are inside of an explicit transaction, changes will only be visible upon explicit commit, otherwise a commit will immediately take place.
persist in interface DatabaseEnginename - The entity name.entry - The entry to persist.useAutoInc - Use or not the autoinc.DatabaseEngineException - If something goes wrong while persisting data.protected PreparedStatement getPreparedStatementForPersist(boolean useAutoInc, MappedEntity mappedEntity)
PreparedStatement to use in a persist operation, depending on whether autoInc is to be used or not.useAutoInc - Whether to use autoInc.mappedEntity - The mapped entity for which to get the prepared statement.PreparedStatement.protected abstract long doPersist(PreparedStatement ps, MappedEntity me, boolean useAutoInc, int lastBindPosition) throws Exception
persist(String, EntityEntry, boolean) to effectively perform
the persist action.ps - The PreparedStatement to use in the persist operationme - The mapped entity on which to persist.useAutoInc - Whether to use autoInc.lastBindPosition - The position (1-based) of the last bind parameter that was filled in the prepared statement.0 if there's no auto generated value). If the table has more
than 1 column with auto generated values, then it will return the first column found.Exception - if any problem occurs while persisting.public void flush()
throws DatabaseEngineException
flush in interface DatabaseEngineDatabaseEngineException - If something goes wrong while persisting data.public void commit()
throws DatabaseEngineRuntimeException
beginTransaction().commit in interface DatabaseEngineDatabaseEngineRuntimeException - If something goes wrong while persisting data.public void rollback()
throws DatabaseEngineRuntimeException
beginTransaction().rollback in interface DatabaseEngineDatabaseEngineRuntimeException - If the rollback fails.public boolean isTransactionActive()
throws DatabaseEngineRuntimeException
DatabaseEngineisTransactionActive in interface DatabaseEngineDatabaseEngineRuntimeException - If the access to the database fails.public int executeUpdate(String query) throws DatabaseEngineException
executeUpdate in interface DatabaseEnginequery - The query to execute.DatabaseEngineException - If something goes wrong executing the native query.protected Statement createSelectStatement(int readTimeout) throws SQLException
Statement that will be used for selects, i.e., may have an associated
read timeout.readTimeout - The timeout.StatementSQLException - If there is an error creating the statement.public int executeUpdate(Expression query) throws DatabaseEngineException
executeUpdate in interface DatabaseEnginequery - The update to execute.DatabaseEngineException - If something goes wrong executing the update.public String translate(Expression query)
translate in interface DatabaseEnginequery - The query to translate.public Dialect getDialect()
DatabaseEnginegetDialect in interface DatabaseEnginepublic <PB extends PdbBatch> PB createBatch(BatchConfig<PB> batchConfig)
DatabaseEnginePdbBatch to which entries can be added; it then flushes those entries to the database,
periodically on a set timeout, or when a maximum number of entries has been reached.
NOTES:
AutoCloseable.close() should be called before closing the session with the database, to dispose of all
the resources such as executors and extra connections.createBatch in interface DatabaseEnginebatchConfig - The batch configuration.public AbstractBatch createBatch(int batchSize, long batchTimeout)
Please be sure to call AbstractBatch.destroy() before closing the session with the database
createBatch in interface DatabaseEnginebatchSize - The batch size.batchTimeout - If inserts do not occur after the specified time, a flush will be performed.public AbstractBatch createBatch(int batchSize, long batchTimeout, String batchName)
DatabaseEngineAbstractBatch.destroy() before closing the session with the database.createBatch in interface DatabaseEnginebatchSize - The batch size.batchTimeout - If inserts do not occur after the specified time, a flush will be performed.batchName - The batch name.public AbstractBatch createBatch(int batchSize, long batchTimeout, String batchName, FailureListener failureListener)
DatabaseEngine
If desired you may provide an Optional FailureListener that will be invoked when the batch
fails to persist data.
AbstractBatch.destroy() before closing the session with the database.createBatch in interface DatabaseEnginebatchSize - The batch size.batchTimeout - If inserts do not occur after the specified time, a flush will be performed.batchName - The batch name.failureListener - Failure listener to execute custom behavior when the batch fails to persist.public AbstractBatch createBatch(int batchSize, long batchTimeout, String batchName, @Nullable BatchListener batchListener)
DatabaseEngine
If desired you may provide a BatchListener that will be invoked when a batch operation
fails or succeeds to persist data.
AbstractBatch.destroy() before closing the session with the database.createBatch in interface DatabaseEnginebatchSize - The batch size.batchTimeout - If inserts do not occur after the specified time, a flush will be performed.batchName - The batch name.batchListener - Batch listener to execute custom behavior when the batch fails or succeeds to persist.public AbstractBatch createBatch(int batchSize, long batchTimeout, String batchName, @Nullable BatchListener batchListener, @Nullable org.slf4j.Logger confidentialLogger)
DatabaseEngineAbstractBatch.destroy() before closing the session with the database.
The default implementation of this method throws an UnsupportedOperationException
for backward-compatibility reasons. If this method is supposed to be called, it must be explicitly overridden.createBatch in interface DatabaseEnginebatchSize - The batch size.batchTimeout - If inserts do not occur after the specified time, a flush will be performed.batchName - The batch name.batchListener - Batch listener to execute custom behavior when the batch fails or succeeds to persist.confidentialLogger - The confidential logger.protected boolean checkConnection(Connection conn)
conn - The connection to test.public boolean checkConnection(boolean forceReconnect)
checkConnection in interface DatabaseEngineforceReconnect - True to force the connection in case of failure.public boolean checkConnection()
checkConnection in interface DatabaseEnginepublic void addBatch(String name, EntityEntry entry) throws DatabaseEngineException
addBatch in interface DatabaseEnginename - The entity name.entry - The entry to persist.DatabaseEngineException - If something goes wrong while persisting data.protected int entityToPreparedStatementForBatch(DbEntity entity, PreparedStatement ps, EntityEntry entry, boolean useAutoInc) throws DatabaseEngineException
This can be overridden on engines where a distinct treatment is required for these situations, if it isn't
possible to accommodate that behaviour by overriding setPreparedStatementValue(java.sql.PreparedStatement, int, com.feedzai.commons.sql.abstraction.ddl.DbColumn, java.lang.Object, boolean).
entity - The entity.ps - The prepared statement.entry - The entry.useAutoInc - Whether to use autoinc (auto incrementation of values for columns that support it).DatabaseEngineException - if something occurs during the translation.protected int entityToPreparedStatement(DbEntity entity, PreparedStatement ps, EntityEntry entry, boolean useAutoInc) throws DatabaseEngineException
This can be overridden on engines where a distinct treatment is required for these situations, if it isn't
possible to accommodate that behaviour by overriding setPreparedStatementValue(java.sql.PreparedStatement, int, com.feedzai.commons.sql.abstraction.ddl.DbColumn, java.lang.Object, boolean).
entity - The entity.ps - The prepared statement.entry - The entry.useAutoInc - Whether to use autoinc (auto incrementation of values for columns that support it).DatabaseEngineException - If something wrong occurs during the translation.protected int entityToPreparedStatementInternal(DbEntity entity, PreparedStatement ps, EntityEntry entry, boolean useAutoInc, boolean fromBatch) throws DatabaseEngineException
This can be overridden on engines where a distinct treatment is required for these situations, if it isn't
possible to accommodate that behaviour by overriding setPreparedStatementValue(java.sql.PreparedStatement, int, com.feedzai.commons.sql.abstraction.ddl.DbColumn, java.lang.Object, boolean).
entity - The entity.ps - The prepared statement.entry - The entry.useAutoInc - Whether to use autoinc (auto incrementation of values for columns that support it).fromBatch - Whether this translation is to be done in the context of a batch update.DatabaseEngineException - If something wrong occurs during the translation.protected void setPreparedStatementValue(PreparedStatement ps, int index, DbColumn dbColumn, Object value, boolean fromBatch) throws Exception
ps - The prepared statement.index - The index of the value to set in the prepared statement.dbColumn - The DbColumn for which to set the value in the prepared statement.value - The value to set.fromBatch - Whether this translation is to be done in the context of a batch update.Exception - If something wrong occurs setting the value.public List<Map<String,ResultColumn>> query(Expression query) throws DatabaseEngineException
query in interface DatabaseEnginequery - The query to execute.DatabaseEngineException - If something goes wrong executing the query.public List<Map<String,ResultColumn>> query(Expression query, int readTimeoutOverride) throws DatabaseEngineException
DatabaseEnginePdbProperties.getSelectQueryTimeout())
if the underlying engine supports query timeouts.query in interface DatabaseEnginequery - The query to execute.readTimeoutOverride - The query timeout to use.DatabaseEngineException - If something goes wrong executing the query.public List<Map<String,ResultColumn>> query(String query) throws DatabaseEngineException
query in interface DatabaseEnginequery - The query to execute.DatabaseEngineException - If something goes wrong executing the query.public List<Map<String,ResultColumn>> query(String query, int readTimeoutOverride) throws DatabaseEngineException
DatabaseEnginePdbProperties.getSelectQueryTimeout()
if the underlying engine supports query timeouts.query in interface DatabaseEnginequery - The query to execute.readTimeoutOverride - The query timeout to use.DatabaseEngineException - If something goes wrong executing the query.protected List<Map<String,ResultColumn>> processResultIterator(ResultIterator it) throws DatabaseEngineException
ResultIterator.it - The iterator.Map.DatabaseEngineException - If a database access error occurs.public ResultIterator iterator(String query) throws DatabaseEngineException
DatabaseEngineiterator in interface DatabaseEnginequery - The query.DatabaseEngineException - If a database access error occurs.public ResultIterator iterator(Expression query) throws DatabaseEngineException
DatabaseEngineiterator in interface DatabaseEnginequery - The expression that represents the query.DatabaseEngineException - If a database access error occurs.public ResultIterator iterator(String query, int fetchSize) throws DatabaseEngineException
DatabaseEngineiterator in interface DatabaseEnginequery - The query.fetchSize - The number of rows to fetch each time.DatabaseEngineException - If a database access error occurs.public ResultIterator iterator(Expression query, int fetchSize) throws DatabaseEngineException
DatabaseEngineiterator in interface DatabaseEnginequery - The expression that represents the query.fetchSize - The number of rows to fetch each time.DatabaseEngineException - If a database access error occurs.public ResultIterator iterator(Expression query, int fetchSize, int readTimeoutOverride) throws DatabaseEngineException
DatabaseEnginePdbProperties.getSelectQueryTimeout()) if the underlying engine
supports query timeouts.iterator in interface DatabaseEnginequery - The expression that represents the query.fetchSize - The number of rows to fetch each time.readTimeoutOverride - The query timeout to use.DatabaseEngineException - If a database access error occurs.public ResultIterator iterator(String query, int fetchSize, int readTimeoutOverride) throws DatabaseEngineException
DatabaseEnginePdbProperties.getSelectQueryTimeout()) if the underlying engine
supports query timeouts.iterator in interface DatabaseEnginequery - The query.fetchSize - The number of rows to fetch each time.readTimeoutOverride - The query timeout to use.DatabaseEngineException - If a database access error occurs.protected abstract ResultIterator createResultIterator(Statement statement, String sql) throws DatabaseEngineException
ResultIterator given the engine implementation.statement - The statement.sql - The SQL sentence.DatabaseEngineException - If a database access error occurs.protected abstract ResultIterator createResultIterator(PreparedStatement ps) throws DatabaseEngineException
ResultIterator for the engine in place given a prepared statement.ps - The prepared statement.DatabaseEngineException - If a database access error occurs.protected abstract void createTable(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong while creating the table.protected abstract void addPrimaryKey(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong while creating the table.protected abstract void addIndexes(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong while creating the table.protected abstract void addSequences(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong while creating the table.protected abstract void dropSequences(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong dropping the sequences.protected abstract void dropTable(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong dropping the sequences.protected abstract void dropColumn(DbEntity entity, String... columns) throws DatabaseEngineException
entity - The entity.columns - The column name to drop.DatabaseEngineException - If something goes wrong dropping the sequences.protected abstract void addColumn(DbEntity entity, DbColumn... columns) throws DatabaseEngineException
entity - The entity that represents the table.columns - The db column to add.DatabaseEngineException - If something goes wrong adding columns.protected void addFks(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong creating the FKs.protected void addFks(DbEntity entity, Set<DbFk> fks) throws DatabaseEngineException
entity - The entity.fks - The foreign keys to be added.DatabaseEngineException - If something goes wrong creating the FKs.protected abstract MappedEntity createPreparedStatementForInserts(DbEntity entity) throws DatabaseEngineException
entity - The entity.DatabaseEngineException - If something goes wrong while creating the table.protected String translateType(DbColumn column) throws DatabaseEngineException
column - The column.DatabaseEngineException - If the type cannot be found.protected void dropFks(String table) throws DatabaseEngineException
table - The table name.DatabaseEngineException - If something goes wrong dropping the FKs.protected String dropFkQuery(String table, String fkName)
table - The table name.fkName - The foreign key name.protected void dropFks(String table, Set<String> fks) throws DatabaseEngineException
table - The table.fks - The foreign key names to be dropped.DatabaseEngineException - If a foreign key can't be dropped.public Map<String,DbEntityType> getEntities() throws DatabaseEngineException
DatabaseEnginegetEntities in interface DatabaseEngineDatabaseEngineException - If something occurs getting the existing tables.public Map<String,DbEntityType> getEntities(String schemaPattern) throws DatabaseEngineException
DatabaseEnginegetEntities in interface DatabaseEngineschemaPattern - A schema name pattern; must match the schema name as it is stored in the database;
"" retrieves those without a schema; null means that the schema name
should not be used to narrow the search.DatabaseEngineException - If something occurs getting the existing tables.protected void executeUpdateSilently(String statement)
If the statement for some reason fails to execute, the error is logged but no exception is thrown.
statement - The statement.public String getSchema() throws DatabaseEngineException
connection.null if there is none.DatabaseEngineException - If a database access error occurs or this method is called on a closed connection.protected void setSchema(String schema) throws DatabaseEngineException
connection.DatabaseEngineException - If schema doesn't exist, a database access error occurs or this method
is called on a closed connection.public Map<String,DbColumnType> getMetadata(String tableNamePattern) throws DatabaseEngineException
DatabaseEnginegetMetadata in interface DatabaseEnginetableNamePattern - A table name pattern; must match the table name as it is stored in the database.DatabaseEngineException - If something occurs getting the metadata.public Map<String,DbColumnType> getMetadata(String schemaPattern, String tableNamePattern) throws DatabaseEngineException
DatabaseEnginegetMetadata in interface DatabaseEngineschemaPattern - A schema name pattern; must match the schema name as it is stored in the database;
"" retrieves those without a schema; null means that the schema name
should not be used to narrow the search.tableNamePattern - A table name pattern; must match the table name as it is stored in the database.DatabaseEngineException - If something occurs getting the metadata.public Map<String,DbColumnType> getQueryMetadata(Expression query) throws DatabaseEngineException
getQueryMetadata in interface DatabaseEnginequery - The query to retrieve the metadata from.DatabaseEngineException - If something occurs getting the metadata.public Map<String,DbColumnType> getQueryMetadata(String query) throws DatabaseEngineException
getQueryMetadata in interface DatabaseEnginequery - The query to retrieve the metadata from.DatabaseEngineException - If something occurs getting the metadata.protected DbColumnType toPdbType(int type, String typeName)
DbColumnType. If there's no mapping a DbColumnType.UNMAPPED is returned.type - The SQL type from Types.typeName - The native database type name. It provides additional information for
derived classes to resolve types unmapped here.DbColumnType.public DatabaseEngine duplicate(Properties mergeProperties, boolean copyEntities) throws DuplicateEngineException
duplicate in interface DatabaseEnginemergeProperties - Merge properties with the ones already existing.copyEntities - True to include the entities in the new connection, false otherwise.DuplicateEngineException - If policy is set to other than 'create' or 'none' or duplication fails for some reason.public PdbProperties getProperties()
DatabaseEnginegetProperties in interface DatabaseEnginepublic void createPreparedStatement(String name, Expression query) throws NameAlreadyExistsException, DatabaseEngineException
DatabaseEnginecreatePreparedStatement in interface DatabaseEnginename - The prepared statement name.query - The query.NameAlreadyExistsException - If the name already exists.DatabaseEngineException - If something goes wrong creating the statement.public void createPreparedStatement(String name, String query) throws NameAlreadyExistsException, DatabaseEngineException
DatabaseEnginecreatePreparedStatement in interface DatabaseEnginename - The prepared statement name.query - The query.NameAlreadyExistsException - If the name already exists.DatabaseEngineException - If something goes wrong creating the statement.public void createPreparedStatement(String name, Expression query, int timeout) throws NameAlreadyExistsException, DatabaseEngineException
DatabaseEnginecreatePreparedStatement in interface DatabaseEnginename - The prepared statement name.query - The query.timeout - The timeout (in seconds) for the query to execute.NameAlreadyExistsException - If the name already exists.DatabaseEngineException - If something goes wrong creating the statement.public void createPreparedStatement(String name, String query, int timeout) throws NameAlreadyExistsException, DatabaseEngineException
DatabaseEnginecreatePreparedStatement in interface DatabaseEnginename - The prepared statement name.query - The query.timeout - The timeout (in seconds) for the query to execute.NameAlreadyExistsException - If the name already exists.DatabaseEngineException - If something goes wrong creating the statement.public void removePreparedStatement(String name)
DatabaseEngineremovePreparedStatement in interface DatabaseEnginename - The prepared statement name.public List<Map<String,ResultColumn>> getPSResultSet(String name) throws DatabaseEngineException, ConnectionResetException
getPSResultSet in interface DatabaseEnginename - The prepared statement name.DatabaseEngineException - If something occurs getting the result.ConnectionResetException - If the first Result Iterated fails to create.public ResultIterator getPSIterator(String name) throws DatabaseEngineException, ConnectionResetException
DatabaseEnginePreparedStatement bound to the given name.getPSIterator in interface DatabaseEnginename - The name of the prepared statement.DatabaseEngineException - If a database access error occurs.ConnectionResetExceptionpublic ResultIterator getPSIterator(String name, int fetchSize) throws DatabaseEngineException, ConnectionResetException
DatabaseEnginePreparedStatement bound to the given name.getPSIterator in interface DatabaseEnginename - The name of the prepared statement.fetchSize - The number of rows to fetch each time.DatabaseEngineException - If a database access error occurs.ConnectionResetExceptionpublic void setParameters(String name, Object... params) throws DatabaseEngineException, ConnectionResetException
DatabaseEnginesetParameters in interface DatabaseEnginename - The prepared statement name.params - The parameters to set.DatabaseEngineException - If something occurs setting the parameters.ConnectionResetException - If the connection was reset while trying to set parameters.public void setParameter(String name, int index, Object param) throws DatabaseEngineException, ConnectionResetException
DatabaseEnginesetParameter in interface DatabaseEnginename - The prepared statement name.index - The index to set.param - The parameter to set.DatabaseEngineException - If something occurs setting the parameters.ConnectionResetException - If the connection was reset while trying to set the parameter.public void setParameter(String name, int index, Object param, DbColumnType paramType) throws DatabaseEngineException, ConnectionResetException
DatabaseEnginesetParameter in interface DatabaseEnginename - The prepared statement name.index - The index to set.param - The parameter to set.paramType - The type of the parameter being set.DatabaseEngineException - If something occurs setting the parameters.ConnectionResetException - If the connection was reset while trying to set the parameter.public void executePS(String name) throws DatabaseEngineException, ConnectionResetException
executePS in interface DatabaseEnginename - The prepared statement name.DatabaseEngineException - If something goes wrong while executing.ConnectionResetException - If the connection is down and reestablishment occurs. If this happens, the user must reset the parameters and re-execute
the query.public void clearParameters(String name) throws DatabaseEngineException, ConnectionResetException
clearParameters in interface DatabaseEnginename - The prepared statement name.DatabaseEngineException - If something occurs while clearing the parameters.ConnectionResetException - If the connection was reset.public boolean preparedStatementExists(String name)
preparedStatementExists in interface DatabaseEnginename - The name to test.public Integer executePSUpdate(String name) throws DatabaseEngineException, ConnectionResetException
executePSUpdate in interface DatabaseEnginename - The prepared statement name.DatabaseEngineException - If the prepared statement does not exist or something goes wrong while executing.ConnectionResetException - If the connection is down and reestablishment occurs. If this happens, the user must reset the parameters and re-execute
the query.public String commentCharacter()
commentCharacter in interface DatabaseEnginepublic String escapeCharacter()
escapeCharacter in interface DatabaseEnginepublic void setExceptionHandler(ExceptionHandler eh)
DatabaseEnginesetExceptionHandler in interface DatabaseEngineeh - The reference for exception callbacks.protected void handleOperation(OperationFault opFault, Exception exception) throws DatabaseEngineException
setExceptionHandler(ExceptionHandler) method to provide a
specific implementation.opFault - The operation that originated the exception.exception - The exception.DatabaseEngineException - If the faulty operation must stop the execution.protected final byte[] objectToArray(Object val) throws IOException
val - The object to convert.IOException - If the buffer is not enough to make the conversion.public boolean hasIdentityColumn(DbEntity entity)
entity - The entity to check.protected void inject(Expression... objs)
protected void setParameterValues(PreparedStatement ps, int index, Object param) throws SQLException
index to the value provided in param.ps - The PreparedStatement to insert the association between index and the param.index - The index to set the value to.param - The value to be set at the provided index.SQLException - If something goes wrong accessing the database.protected QueryExceptionHandler getQueryExceptionHandler()
QueryExceptionHandler to be used in disambiguating SQL exceptions.QueryExceptionHandler.protected void reconnectExceptionally(String message) throws DatabaseEngineException
getConnection().message - The exception message.DatabaseEngineException - if an error occurs while reestablishing the connection.Copyright © 2023 Feedzai. All rights reserved.