- All Known Implementing Classes:
AbstractBackend,AbstractSql2003Backend,AbstractSql2008Backend,AbstractSql92Backend,Db2,H2,Informix,MariaDb,MsSql,MySql,Oracle,Oracle8,Postgres
public interface Backend
A database backend.
Defines the backend specifics.
There is only one instance per database type.
Implementations must not maintain any state except for the whole of all connections to the specific kind of database.
Defines the backend specifics.
There is only one instance per database type.
Implementations must not maintain any state except for the whole of all connections to the specific kind of database.
- Author:
- harald
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final String'*' all string.static final StringSQL ALTER COLUMN fragment.static final StringSQL ALTER INDEX intro.static final StringSQL ALTER TABLE intro.static final StringAND string.static final StringAND NOT string.static final StringALL array operator string.static final StringParameter ALL array operator string.static final StringANY array operator string.static final StringParameter ANY array operator string.static final StringIN array operator string.static final StringParameter IN array operator string.static final StringNOT IN array operator string.static final StringParameter NOT IN array operator string.static final StringArray parameter (?).static final Stringcomma separator.static final StringParameter ,? string.static final StringDELETE string.static final Stringdot all columns.static final String= operator string.static final StringParameter =? string.static final StringParameter =?, string.static final String=0 string.static final StringSQL EXISTS clause with SELECT 1 and opening left parenthesis.static final StringFROM string.static final String> operator string.static final StringParameter >? string.static final String>= operator string.static final StringParameter ≥? string.static final StringGROUP BY string.static final StringSQL IF EXISTS fragment.static final StringINSERT INTO string.static final String(VALUES) string for insert.static final StringIS NOT NULL string.static final StringIS NULL string.static final Stringopening bracket.static final String< operator string.static final StringParameter <? string.static final String<= operator string.static final StringParameter <=? string.static final StringLIKE operator string.static final StringParameter LIKE ? string.static final StringMAX function name.static final StringMAX function name.static final StringNOT string.static final String<> operator string.static final StringParameter <>? string.static final String<>0 string.static final StringNOT LIKE operator string.static final StringParameter NOT LIKE ? string.static final StringOR string.static final StringORDER BY string.static final StringOR NOT string.static final String? string.static final StringParameter ?, string.static final String+1 string.static final Stringclosing bracket.static final StringSELECT string.static final StringSELECT * FROM string.static final StringSET string.static final Stringsort ASC string.static final Stringsort DESC string.static final StringUPDATE string.static final StringWHERE string.static final String"WHERE 1=1" allows AND to be added.static final StringSQL_WHEREALL + AND will be replaced by...static final String"WHERE 1=0" to select nothing.static final StringSQL_WHEREALL + OR will be replaced by... -
Method Summary
Modifier and TypeMethodDescriptionvoidassertValidName(SqlNameType nameType, String name) Asserts that given string is a valid name and usage.voidbuildSelectSql(StringBuilder sqlBuilder, boolean writeLock, int limit, int offset) Creates a select statement string from an inner sql string.buildSelectSql(String sql, boolean writeLock, int limit, int offset) Creates a select statement string from an inner sql string.columnTypeNullDefaultToString(String columnName, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Converts an sqltype, size, scale, nullable and default value to a database type declaration.columnTypeToString(SqlType sqlType, int size, int scale) Converts an sqltype, size and scale to a database type declaration.createColumnMetaData(TableMetaData tableMetaData) Creates a column meta data instance.createConnection(String url, String username, char[] password) Creates a jdbc connection.createIndexColumnMetaData(IndexMetaData indexMetaData) Creates an index column meta data instance.createIndexMetaData(TableMetaData tableMetaData) Creates an index meta data instance.createScriptRunner(Connection connection) Creates a script runner instance.createTableMetaData(ModelMetaData metaData, String tableName) Creates a meta data instance.getBackendId(Connection connection) Determines the unique id or name used by the backend for a given connection.Gets the string to begin a block comment in generated code.String[]Gets all strings that begin a block comment.Gets the string to end a block comment in generated code.String[]Gets all strings that end a block comment.Gets the keyword for the COALESCE function.Gets the default schema name.
Some backends store the objects in a default schema, if no explicit schema is given.intgetDefaultSize(SqlType sqlType) Gets the default size if no size given in model.Gets the JDBC driver class name.Gets the dummy select to keep/test connections alive.
Most databases just require a"SELECT 1".Gets the empty string.
Some dbms (most famous: Oracle) handle empty strings as null.intgetMaxScale(SqlType sqlType, int size) Returns the maximum scale for a given SQL-type and size.intgetMaxSize(SqlType sqlType) Returns the maximum size for a given SQL-type.getMetaData(BackendInfo backendInfo) Gets the metadata from the backend.getMigrationStrategy(ColumnMetaData column, String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Determines the best migration strategy.getModelMetaData(DatabaseMetaData[] metaData, String[] schemas, String... tableNames) Retrieves the metadata.getName()Gets the name of the backend.Gets the list of reserved words for this backend.Gets the string to begin a single line comment in generated code.String[]Gets all strings that begin a single line comment.The SQL statement separator used in generated code.String[]The all SQL statement separators.getTableHeaders(DatabaseMetaData metaData) Gets all table headers for a given metadata.getTableMetaData(ModelMetaData modelMetaData, String tableName) Gets the table metadata for a given table name.booleanReturns whether backend requires an alias for a sub-select.booleanisArrayOperatorSupported(String operator) Returns whether the backend supports given array operator.booleanReturns whether the backend support CLOB types.
If not, it will be emulated as VARCHAR with the maximum possible size.booleanDetermines whether exception is a communication error.booleanDetermines whether exception is a constraint violation.booleanisDatabaseInMemory(String url) Returns whether the URL denotes an in-memory database.
Used by test suites to decide whether to populate the database before running the tests.booleanisDefaultEqual(ColumnMetaData column, SqlType sqlType, Object defaultValue) Checks whether the column's default corresponds to the model's default value.booleanReturns whether this backend is deprecated and superseded by a newer implementation.
Deprecated backends are omitted fromBackendFactory.getAllBackends().booleanReturns whether backend should addIF EXISTSfor generated DROPs.booleanDetermines whether backend allows expressions referring to tables being updated.booleanAccording to the JDBC-specsConnection.setAutoCommit(boolean)(true) should commit, but some backends require an extraConnection.commit().booleanReturns whether backend supports filtered indexes.booleanReturns whether function based indexes are supported.booleanisMatchingName(String name) Checks whether the backend belongs to the given name.booleanisMatchingUrl(String url) Checks whether the backend belongs to the given jdbc url.
If multiple backend implementations are provided for the same database type, only one backend should match the URL.booleanReturns whether the backend supports posix-style escapes via backslash.booleanReturns whether the backend supports releasing savepoints explicitly.booleanisReservedSchemaName(String name) Checks whether this is a reserved schema name for this backend.booleanisReservedTableName(String name) Checks whether this a reserved table name for this backend.
Applies only to tables.booleanReturns whether the backend supports schemas.booleanTrue if backend provides locking-free sequences.
Sequences must not take part in transactions, i.e.booleanisTemporaryName(String name) Checks whether this is a temporary name.
Returns whether an entity-, attribute- or index-name is temporary and should not be taken into account for migration or even used in the model.
Depending on the backend, temporary names start with an underscore or some other lead string.booleanDetermines whether exception is transient and retrying the transaction may succeed.
Typical transient exceptions are thrown when a deadlock is detected or when serialized transaction isolation is used.booleanChecks for the (postgres) bug that fetch-size is ignored if not within a new transaction.booleanReturns whether the backend supports theUUIDnatively via JDBC setObject/getObject.SqlType[]jdbcTypeToSqlType(int jdbcType, int size, int scale) Converts the JDBC data type integer to a tentackle backend SqlTypes.optimizeSql(String sql) Optimize SQL code.
Replace WHERE 1=1 AND/OR to WHERE.voidsetArray(PreparedStatement statement, int pos, SqlType type, Collection<?> elements, String operator) Sets an array parameter in a prepared statement.voidsetDropIfExistsEnabled(boolean dropIfExists) Some database support drop index/constraint/columnIF EXISTS.
This may be useful if migration scripts are generated against non-production databases that contain test indexes etc...
Notice, that those temporary DDL changes should better use the temporary prefix (seeisTemporaryName(String)) in order to be ignored by the migrator.intsetLeadingSelectParameters(BackendPreparedStatement stmt, int limit, int offset) Sets optional parameters before applying the original parameters.intsetTrailingSelectParameters(BackendPreparedStatement stmt, int index, int limit, int offset) Sets optional parameters after applying the original parameters.sqlAddColumn(String tableName, String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Generates sql code to add a column.sqlAlterColumnComment(String tableName, String columnName, String comment) Generates SQL code to alter the comment for an attribute.sqlAlterColumnDefault(String tableName, String columnName, SqlType sqlType, Object defaultValue) Generates sql code to change the default value a column.sqlAlterColumnNullConstraint(String tableName, String columnName, boolean nullable) Generates sql code to change the null-constraint of a column.sqlAlterColumnType(String tableName, String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Generates sql code to change the datatype of a column.sqlAlterTableComment(String tableName, String comment) Generates SQL code to alter the comment for a table.Gets the string before the table alias.
In most databases the " AS " is optional and some don't accept it all.sqlComment(String text) Create comment sql code that is interpreted as a comment by the backend.sqlCreateColumn(String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue, boolean primaryKey, boolean withTrailingComma) Generates the attribute definition of a CREATE TABLE statement.sqlCreateColumnComment(String tableName, String columnName, String comment) Generates SQL code to create the comment for an attribute.sqlCreateForeignKey(String referencingTableName, String referencingColumnName, String referencedTableName, String referencedColumnName, String foreignKeyName, boolean composite) Generates the ALTER TABLE statement to add a foreign key constraint.sqlCreateIndex(String tableName, String indexName, boolean unique, String filterCondition, String... columnNames) Generates the CREATE INDEX statement.sqlCreateSchema(String name) Creates the SQL string to create a schema.sqlCreateSequence(String name, Long start, Long increment) Creates the SQL string to create a sequence.sqlCreateSequenceComment(String name, String comment) Creates the SQL string to comment a sequence.sqlCreateTableClosing(String tableName, String comment) Generates the last line of a CREATE TABLE statement.sqlCreateTableComment(String tableName, String comment) Generates SQL code to create the comment for a table.sqlCreateTableIntro(String tableName, String comment) Generates the first line of a CREATE TABLE statement.sqlDropColumn(String tableName, String columnName) Generates sql code to drop a column.sqlDropForeignKey(String referencingTableName, String foreignKeyName) Generates the sql statement to drop a foreign key constraint.sqlDropIndex(String schemaName, String tableNameWithoutSchema, String indexName) Generates the DROP INDEX statement.sqlDropTable(String schemaName, String tableNameWithoutSchema) Generates the DROP TABLE statement.sqlFunction(String functionName, String expression) Creates an sql function expression.Creates a join clause.voidsqlJoinSelects(JoinType type, boolean addColumns, StringBuilder select, String joinSelect, String joinSelectIdAlias, String joinAlias, String join) Generate SQL-code for joining a table to an existing select.sqlJoinSelects(JoinType type, boolean addColumns, String select, String joinSelect, String joinSelectIdAlias, String joinAlias, String join) Generate SQL-code for joining a table to an existing select.sqlNextFromSequence(String name) Creates the SQL string to retrieve the next id from a sequence.sqlRenameAndAlterColumnType(String tableName, String oldColumnName, String newColumnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Generates sql code to rename a column.sqlRenameColumn(String tableName, String oldColumnName, String newColumnName) Generates sql code to rename a column.sqlRenameIndex(String tableName, String oldIndexName, String newIndexName) Generates sql code to rename an index.sqlRenameTable(String tableName, String newTableName) Generate sql code to rename a table.sqlTypeToString(SqlType sqlType, int size) Converts the java SQL-type to the database type name.sqlUpdateToNotNull(String tableName, String columnName, SqlType sqlType, Object defaultValue, boolean migrated) Generates code to update a column to a non-null value.toInternalType(String sqlTypeName) Converts a backend specific type name to an internal name used by driver specific methods.toQuotedString(String str) Converts a string to a string enclosed in single quotes.voidvalidateVersion(int databaseMajorVersion, int databaseMinorVersion) Verifies that the major and minor version of the connection's metadata is compatible with this backend.
If the latest backend is not compatible, the URL may be post-fixed with a backend type for an older version, for example:valueToLiteral(SqlType sqlType, Object value) Converts a type and value to a literal string.
-
Field Details
-
SQL_WHERE
WHERE string.- See Also:
-
SQL_SELECT
SELECT string.- See Also:
-
SQL_SELECT_ALL_FROM
SELECT * FROM string.- See Also:
-
SQL_DELETE
DELETE string.- See Also:
-
SQL_UPDATE
UPDATE string.- See Also:
-
SQL_INSERT_INTO
INSERT INTO string.- See Also:
-
SQL_LEFT_PARENTHESIS
opening bracket.- See Also:
-
SQL_RIGHT_PARENTHESIS
closing bracket.- See Also:
-
SQL_DOT_STAR
dot all columns.- See Also:
-
SQL_INSERT_VALUES
(VALUES) string for insert.- See Also:
-
SQL_SET
SET string.- See Also:
-
SQL_FROM
FROM string.- See Also:
-
SQL_AND
AND string.- See Also:
-
SQL_OR
OR string.- See Also:
-
SQL_NOT
NOT string.- See Also:
-
SQL_ANDNOT
AND NOT string.- See Also:
-
SQL_ORNOT
OR NOT string.- See Also:
-
SQL_COMMA
comma separator.- See Also:
-
SQL_PAR
? string.- See Also:
-
SQL_ARRAY_PAR
Array parameter (?).- See Also:
-
SQL_EQUAL
= operator string.- See Also:
-
SQL_NOTEQUAL
<> operator string.- See Also:
-
SQL_LESS
< operator string.- See Also:
-
SQL_GREATER
> operator string.- See Also:
-
SQL_LESSOREQUAL
<= operator string.- See Also:
-
SQL_GREATEROREQUAL
>= operator string.- See Also:
-
SQL_LIKE
LIKE operator string.- See Also:
-
SQL_NOTLIKE
NOT LIKE operator string.- See Also:
-
SQL_ARRAY_IN
IN array operator string.- See Also:
-
SQL_ARRAY_NOT_IN
NOT IN array operator string.- See Also:
-
SQL_ARRAY_ANY
ANY array operator string.- See Also:
-
SQL_ARRAY_ALL
ALL array operator string.- See Also:
-
SQL_EQUAL_ZERO
=0 string.- See Also:
-
SQL_NOTEQUAL_ZERO
<>0 string.- See Also:
-
SQL_COMMA_PAR
Parameter ,? string.- See Also:
-
SQL_PAR_COMMA
Parameter ?, string.- See Also:
-
SQL_EQUAL_PAR
Parameter =? string.- See Also:
-
SQL_EQUAL_PAR_COMMA
Parameter =?, string.- See Also:
-
SQL_NOTEQUAL_PAR
Parameter <>? string.- See Also:
-
SQL_GREATER_PAR
Parameter >? string.- See Also:
-
SQL_GREATEROREQUAL_PAR
Parameter ≥? string.- See Also:
-
SQL_LESS_PAR
Parameter <? string.- See Also:
-
SQL_LESSOREQUAL_PAR
Parameter <=? string.- See Also:
-
SQL_LIKE_PAR
Parameter LIKE ? string.- See Also:
-
SQL_NOTLIKE_PAR
Parameter NOT LIKE ? string.- See Also:
-
SQL_ARRAY_IN_PAR
Parameter IN array operator string.- See Also:
-
SQL_ARRAY_NOT_IN_PAR
Parameter NOT IN array operator string.- See Also:
-
SQL_ARRAY_ANY_PAR
Parameter ANY array operator string.- See Also:
-
SQL_ARRAY_ALL_PAR
Parameter ALL array operator string.- See Also:
-
SQL_ALLSTAR
'*' all string.- See Also:
-
SQL_PLUS_ONE
+1 string.- See Also:
-
SQL_WHEREALL
"WHERE 1=1" allows AND to be added.- See Also:
-
SQL_WHERENOTHING
"WHERE 1=0" to select nothing.- See Also:
-
SQL_WHEREAND
SQL_WHEREALL + AND will be replaced by... SQL_WHERE.- See Also:
-
SQL_WHEREOR
SQL_WHEREALL + OR will be replaced by... SQL_WHERE.- See Also:
-
SQL_ISNULL
IS NULL string.- See Also:
-
SQL_ISNOTNULL
IS NOT NULL string.- See Also:
-
SQL_ORDERBY
ORDER BY string.- See Also:
-
SQL_SORTASC
sort ASC string.- See Also:
-
SQL_SORTDESC
sort DESC string.- See Also:
-
SQL_GROUPBY
GROUP BY string.- See Also:
-
SQL_MAX
MAX function name.- See Also:
-
SQL_MIN
MAX function name.- See Also:
-
SQL_EXISTS
SQL EXISTS clause with SELECT 1 and opening left parenthesis.- See Also:
-
SQL_ALTER_TABLE
SQL ALTER TABLE intro.- See Also:
-
SQL_ALTER_INDEX
SQL ALTER INDEX intro.- See Also:
-
SQL_ALTER_COLUMN
SQL ALTER COLUMN fragment.- See Also:
-
SQL_IF_EXISTS
SQL IF EXISTS fragment.- See Also:
-
-
Method Details
-
isMatchingUrl
Checks whether the backend belongs to the given jdbc url.
If multiple backend implementations are provided for the same database type, only one backend should match the URL. The others must be selected via name.- Parameters:
url- the jdbc url- Returns:
- true if matches
-
isMatchingName
Checks whether the backend belongs to the given name.- Parameters:
name- the backend's name- Returns:
- true if matches
-
isDeprecated
boolean isDeprecated()Returns whether this backend is deprecated and superseded by a newer implementation.
Deprecated backends are omitted fromBackendFactory.getAllBackends().- Returns:
- true if deprecated
-
validateVersion
void validateVersion(int databaseMajorVersion, int databaseMinorVersion) Verifies that the major and minor version of the connection's metadata is compatible with this backend.
If the latest backend is not compatible, the URL may be post-fixed with a backend type for an older version, for example:jdbc:oracle:thin:@//localhost:1521/xe|Oracle8
Throws
BackendExceptionif incompatible.- Parameters:
databaseMajorVersion- the major versiondatabaseMinorVersion- the minor version- See Also:
-
getName
String getName()Gets the name of the backend.- Returns:
- the name
-
getDriverClassName
String getDriverClassName()Gets the JDBC driver class name.- Returns:
- the class name
-
createConnection
Creates a jdbc connection.- Parameters:
url- the jdbc urlusername- the usernamepassword- the password- Returns:
- the created connection
- Throws:
SQLException- if connection could not be established
-
getMetaData
Gets the metadata from the backend.Important: the connection of the metadata is open!
- Parameters:
backendInfo- the backend info- Returns:
- the metadata, may be more than one if schemas set in backendInfo
- Throws:
SQLException- if failed
-
getTableHeaders
Gets all table headers for a given metadata.- Parameters:
metaData- the database metadata- Returns:
- the list of table headers
- Throws:
SQLException- if failed
-
isTemporaryName
Checks whether this is a temporary name.
Returns whether an entity-, attribute- or index-name is temporary and should not be taken into account for migration or even used in the model.
Depending on the backend, temporary names start with an underscore or some other lead string.- Parameters:
name- the name- Returns:
- true temporary (invalid) name
-
isReservedTableName
Checks whether this a reserved table name for this backend.
Applies only to tables. Not to be mixed up withgetReservedWords().
Useful to avoid conflicts with naming conventions for backend specific things, such as snapshots.- Parameters:
name- the table name- Returns:
- true if reserved by backend
-
isReservedSchemaName
Checks whether this is a reserved schema name for this backend.- Parameters:
name- the schema name- Returns:
- true if reserved by backend
-
buildSelectSql
Creates a select statement string from an inner sql string.sqlBuilderis anything as[SELECT] FROM... WHERE... ORDER BY....
It is decorated with a leadingSELECT, if missing, plus optional clauses like for the given parameters.- Parameters:
sqlBuilder- the sql builder, initially containing the inner sql without leadingSELECT.writeLock- true select should write locklimit- the limit value, ≤ 0 if no limit clauseoffset- the offset value, ≤ 0 if no offset clause
-
buildSelectSql
Creates a select statement string from an inner sql string.Same as
buildSelectSql(StringBuilder, boolean, int, int), but for strings.- Parameters:
sql- the sql without leadingSELECT.writeLock- true select should write locklimit- the limit value, ≤ 0 if no limit clauseoffset- the offset value, ≤ 0 if no offset clause- Returns:
- the select statement
-
setLeadingSelectParameters
Sets optional parameters before applying the original parameters.- Parameters:
stmt- the prepared statementlimit- the limit value, ≤ 0 if no limit clauseoffset- the offset value, ≤ 0 if no offset clause- Returns:
- the next parameter index
-
setTrailingSelectParameters
Sets optional parameters after applying the original parameters.- Parameters:
stmt- the prepared statementindex- the first parameter indexlimit- the limit value, ≤ 0 if no limit clauseoffset- the offset value, ≤ 0 if no offset clause- Returns:
- the next parameter index
-
getEmptyString
String getEmptyString()Gets the empty string.
Some dbms (most famous: Oracle) handle empty strings as null. In such cases the empty string (e.g. Oracle) may consist of a single blank, or whatever.- Returns:
- the empty string (never null)
-
getDummySelect
String getDummySelect()Gets the dummy select to keep/test connections alive.
Most databases just require a"SELECT 1".- Returns:
- the select string
-
isExtraCommitRequired
boolean isExtraCommitRequired()According to the JDBC-specsConnection.setAutoCommit(boolean)(true) should commit, but some backends require an extraConnection.commit().- Returns:
- true if the database needs an extra commit
-
getCoalesceKeyword
String getCoalesceKeyword()Gets the keyword for the COALESCE function.- Returns:
- the keyword
-
isExpressionReferringToTableBeingUpdatedSupported
boolean isExpressionReferringToTableBeingUpdatedSupported()Determines whether backend allows expressions referring to tables being updated.- Returns:
- true if allowed
-
isSequenceSupported
boolean isSequenceSupported()True if backend provides locking-free sequences.
Sequences must not take part in transactions, i.e. no read- or write-locks!- Returns:
- true if database supports sequences
-
sqlAsBeforeTableAlias
String sqlAsBeforeTableAlias()Gets the string before the table alias.
In most databases the " AS " is optional and some don't accept it all.- Returns:
- the as-string
-
isAliasRequiredForSubSelect
boolean isAliasRequiredForSubSelect()Returns whether backend requires an alias for a sub-select.- Returns:
- true if sub-select needs an alias.
-
sqlCreateSequence
Creates the SQL string to create a sequence.- Parameters:
name- the sequence namestart- the optional start value, defaults to 1increment- the optional increment, defaults to 1- Returns:
- the SQL code
-
sqlCreateSequenceComment
Creates the SQL string to comment a sequence.- Parameters:
name- the sequence namecomment- the comment- Returns:
- the SQL code
-
sqlNextFromSequence
Creates the SQL string to retrieve the next id from a sequence.- Parameters:
name- the name of the sequence- Returns:
- the SQL code
-
sqlCreateSchema
Creates the SQL string to create a schema.- Parameters:
name- the schema name- Returns:
- the SQL code
- See Also:
-
sqlComment
Create comment sql code that is interpreted as a comment by the backend.- Parameters:
text- any text, single or multiline- Returns:
- the comment, null if text was null
-
sqlJoin
Creates a join clause.- Parameters:
type- the join typejoinedTableName- the joined tablenamejoinedTableAlias- the joined table alias, null if nonejoin- the join expression- Returns:
- the sql code
-
sqlFunction
Creates an sql function expression.Example:
sqlFunction("max", CN_ID) --> "MAX(id)"- Parameters:
functionName- the function name, will be translated to uppercaseexpression- the expression, may be null- Returns:
- the sql code
-
isTxRequiredForFetchsize
boolean isTxRequiredForFetchsize()Checks for the (postgres) bug that fetch-size is ignored if not within a new transaction.- Returns:
- true if start tx
-
isConstraintException
Determines whether exception is a constraint violation.- Parameters:
ex- the exception- Returns:
- true if constraint violation
-
isCommunicationLinkException
Determines whether exception is a communication error.- Parameters:
ex- the exception- Returns:
- true if comlink down or alike
-
isTransientTransactionException
Determines whether exception is transient and retrying the transaction may succeed.
Typical transient exceptions are thrown when a deadlock is detected or when serialized transaction isolation is used.Other transient errors are not covered by this method (e.g. connection timeouts, etc...).
- Parameters:
ex- the exception- Returns:
- true if retrying the transaction may succeed
-
getMaxSize
Returns the maximum size for a given SQL-type.- Parameters:
sqlType- the SQL-type- Returns:
- the maximum size, 0 if unlimited, -1 if type without size
-
getMaxScale
Returns the maximum scale for a given SQL-type and size.- Parameters:
sqlType- the SQL-typesize- the size, 0 if unlimited- Returns:
- the maximum scale, 0 if unlimited
-
getDefaultSize
Gets the default size if no size given in model.- Parameters:
sqlType- the SQL-type- Returns:
- the default size, 0 if no default size
-
getDefaultSchema
String getDefaultSchema()Gets the default schema name.
Some backends store the objects in a default schema, if no explicit schema is given.- Returns:
- the default schema, null if none
-
getReservedWords
Gets the list of reserved words for this backend.- Returns:
- the set of reserved words
-
assertValidName
Asserts that given string is a valid name and usage.- Parameters:
nameType- the type/usage of the namename- the name- Throws:
BackendException- if invalid name
-
getBackendId
Determines the unique id or name used by the backend for a given connection.Useful to figure out the corresponding
ManagedConnectionfrom the backend's logfiles.- Parameters:
connection- the jdbc connection- Returns:
- the backend id, null if none
-
getModelMetaData
Retrieves the metadata.- Parameters:
metaData- the metadata for the whole databaseschemas- the optional schemas to filter tables, null if no filtertableNames- the tables of the model- Returns:
- the metadata, null if no such table
-
createColumnMetaData
Creates a column meta data instance.- Parameters:
tableMetaData- the table metadata this column belongs to- Returns:
- the meta data
-
createTableMetaData
Creates a meta data instance.- Parameters:
metaData- the whole metadatatableName- the model's table name- Returns:
- the meta data
-
createIndexMetaData
Creates an index meta data instance.- Parameters:
tableMetaData- the table metadata this index belongs to- Returns:
- the meta data
-
createIndexColumnMetaData
Creates an index column meta data instance.- Parameters:
indexMetaData- the meta meta data this column belongs to- Returns:
- the meta data
-
sqlTypeToString
Converts the java SQL-type to the database type name.- Parameters:
sqlType- the java sql typesize- the column's size- Returns:
- the corresponding type string
-
columnTypeToString
Converts an sqltype, size and scale to a database type declaration.- Parameters:
sqlType- the SQL typesize- the sizescale- the scale- Returns:
- the type definition
-
columnTypeNullDefaultToString
String columnTypeNullDefaultToString(String columnName, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Converts an sqltype, size, scale, nullable and default value to a database type declaration.- Parameters:
columnName- the database column namesqlType- the JDBC sql typesize- the optional sizescale- the optional scalenullable- true if NULL, else NOT NULLdefaultValue- the optional default value- Returns:
- the SQL code
-
valueToLiteral
Converts a type and value to a literal string.- Parameters:
sqlType- the sql typevalue- the value- Returns:
- the constant
-
getStatementSeparators
String[] getStatementSeparators()The all SQL statement separators.- Returns:
- the separators, usually
";"
-
getStatementSeparator
String getStatementSeparator()The SQL statement separator used in generated code.- Returns:
- the separator, usually
";"
-
getSingleLineComments
String[] getSingleLineComments()Gets all strings that begin a single line comment.- Returns:
- the single line comment strings, usually
"--"
-
getSingleLineComment
String getSingleLineComment()Gets the string to begin a single line comment in generated code.- Returns:
- the single line comment string, usually
"--"
-
getBlockCommentBegins
String[] getBlockCommentBegins()Gets all strings that begin a block comment.- Returns:
- the strings to begin a block comment, usually
"/*"
-
getBlockCommentBegin
String getBlockCommentBegin()Gets the string to begin a block comment in generated code.- Returns:
- the string to begin a block comment, usually
"/*"
-
getBlockCommentEnds
String[] getBlockCommentEnds()Gets all strings that end a block comment.- Returns:
- the strings to end a block comment, usually
"*/"
-
getBlockCommentEnd
String getBlockCommentEnd()Gets the string to end a block comment in generated code.- Returns:
- the string to end a block comment, usually
"*/"
-
sqlCreateTableIntro
Generates the first line of a CREATE TABLE statement.- Parameters:
tableName- the tablename with optional schema separated by a dotcomment- optional comment, null if none- Returns:
- the SQL code including the opening bracket
-
sqlCreateTableClosing
Generates the last line of a CREATE TABLE statement.- Parameters:
tableName- the tablename with optional schema separated by a dotcomment- optional comment, null if none- Returns:
- the SQL code including the closing bracket
-
sqlCreateTableComment
Generates SQL code to create the comment for a table.- Parameters:
tableName- the table namecomment- optional comment, null if none- Returns:
- the SQL code, empty string if comment is created via
sqlCreateTableIntro(java.lang.String, java.lang.String)orsqlCreateTableClosing(java.lang.String, java.lang.String)
-
sqlAlterTableComment
Generates SQL code to alter the comment for a table.- Parameters:
tableName- the table namecomment- optional comment, null to clear- Returns:
- the SQL code
-
sqlCreateColumn
String sqlCreateColumn(String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue, boolean primaryKey, boolean withTrailingComma) Generates the attribute definition of a CREATE TABLE statement.- Parameters:
columnName- the database column namecomment- optional comment, null if nonesqlType- the JDBC sql typesize- the optional sizescale- the optional scalenullable- true if NULL, else NOT NULLdefaultValue- the optional default valueprimaryKey- true if this is a primary keywithTrailingComma- true if append a comma- Returns:
- the SQL code
-
isDefaultEqual
Checks whether the column's default corresponds to the model's default value.- Parameters:
column- the column to inspectsqlType- the sql typedefaultValue- the model's default value- Returns:
- true if same
-
getMigrationStrategy
MigrationStrategy[] getMigrationStrategy(ColumnMetaData column, String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Determines the best migration strategy.- Parameters:
column- old column meta datacolumnName- new column namecomment- new commentsqlType- new sql typesize- new sizescale- new scalenullable- new nullabledefaultValue- new default- Returns:
- the strategies in order to achieve the migration
-
sqlRenameTable
Generate sql code to rename a table.- Parameters:
tableName- the old tablename (with leading schema, if any)newTableName- the new tablename (without schema)- Returns:
- the SQL code
-
sqlRenameColumn
Generates sql code to rename a column.- Parameters:
tableName- the tablenameoldColumnName- the old column namenewColumnName- the new column name- Returns:
- the SQL code, null if full spec sqlRenameAndAlterColumnType below is necessary
-
sqlRenameIndex
Generates sql code to rename an index.- Parameters:
tableName- the tablenameoldIndexName- the old column namenewIndexName- the new column name- Returns:
- the SQL code, null if not supported by the backend, and we need to drop and create
-
sqlRenameAndAlterColumnType
String sqlRenameAndAlterColumnType(String tableName, String oldColumnName, String newColumnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Generates sql code to rename a column.- Parameters:
tableName- the tablenameoldColumnName- the old column namenewColumnName- the new column namecomment- optional comment, null if nonesqlType- the JDBC sql typesize- the optional sizescale- the optional scalenullable- true if NULL, else NOT NULLdefaultValue- the optional default value- Returns:
- the SQL code
-
sqlAddColumn
String sqlAddColumn(String tableName, String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Generates sql code to add a column.- Parameters:
tableName- the tablenamecolumnName- the new column namecomment- optional comment, null if nonesqlType- the JDBC sql typesize- the optional sizescale- the optional scalenullable- true if NULL, else NOT NULLdefaultValue- the optional default value- Returns:
- the SQL code
-
sqlDropColumn
Generates sql code to drop a column.- Parameters:
tableName- the tablenamecolumnName- the new column name- Returns:
- the SQL code
-
sqlAlterColumnType
String sqlAlterColumnType(String tableName, String columnName, String comment, SqlType sqlType, int size, int scale, boolean nullable, Object defaultValue) Generates sql code to change the datatype of a column.- Parameters:
tableName- the tablenamecolumnName- the new column namecomment- optional comment, null if nonesqlType- the JDBC sql typesize- the optional sizescale- the optional scalenullable- true if NULL, else NOT NULLdefaultValue- the optional default value- Returns:
- the SQL code
-
sqlUpdateToNotNull
String sqlUpdateToNotNull(String tableName, String columnName, SqlType sqlType, Object defaultValue, boolean migrated) Generates code to update a column to a non-null value.- Parameters:
tableName- the tablenamecolumnName- the column namesqlType- the sql typedefaultValue- the optional default value if defined in the modelmigrated- true if column is migrated, false if added- Returns:
- the SQL code
-
sqlAlterColumnNullConstraint
Generates sql code to change the null-constraint of a column.- Parameters:
tableName- the tablenamecolumnName- the new column namenullable- true if NULL, else NOT NULL- Returns:
- the SQL code, null if need
sqlAlterColumnType(java.lang.String, java.lang.String, java.lang.String, org.tentackle.sql.SqlType, int, int, boolean, java.lang.Object)
-
sqlAlterColumnDefault
String sqlAlterColumnDefault(String tableName, String columnName, SqlType sqlType, Object defaultValue) Generates sql code to change the default value a column.- Parameters:
tableName- the tablenamecolumnName- the new column namesqlType- the JDBC sql typedefaultValue- the optional default value- Returns:
- the SQL code, null if need
sqlAlterColumnType(java.lang.String, java.lang.String, java.lang.String, org.tentackle.sql.SqlType, int, int, boolean, java.lang.Object)
-
sqlCreateColumnComment
Generates SQL code to create the comment for an attribute.- Parameters:
tableName- the table namecolumnName- the column namecomment- optional comment, null if none- Returns:
- the SQL code, empty string if comment is created via
sqlCreateColumn(java.lang.String, java.lang.String, org.tentackle.sql.SqlType, int, int, boolean, java.lang.Object, boolean, boolean)
-
sqlCreateIndex
String sqlCreateIndex(String tableName, String indexName, boolean unique, String filterCondition, String... columnNames) Generates the CREATE INDEX statement.- Parameters:
tableName- the table nameindexName- the name of the indexunique- true if index is uniquefilterCondition- the filter condition (null if none)columnNames- the column names (with a leading '-' if descending). Simple function-based indexes are also supported.- Returns:
- the SQL code
-
sqlDropIndex
Generates the DROP INDEX statement.- Parameters:
schemaName- the optional schema, null if nonetableNameWithoutSchema- the table name without the schemaindexName- the name of the index- Returns:
- the SQL code
-
sqlDropTable
Generates the DROP TABLE statement.- Parameters:
schemaName- the optional schema, null if nonetableNameWithoutSchema- the table name without the schema- Returns:
- the SQL code
-
sqlCreateForeignKey
String sqlCreateForeignKey(String referencingTableName, String referencingColumnName, String referencedTableName, String referencedColumnName, String foreignKeyName, boolean composite) Generates the ALTER TABLE statement to add a foreign key constraint.- Parameters:
referencingTableName- the referencing foreign table namereferencingColumnName- the referencing foreign column namereferencedTableName- the referenced primary table namereferencedColumnName- the referenced primary column nameforeignKeyName- the name of the foreign keycomposite- true if referencing table is a component of the referenced table- Returns:
- the SQL code
-
sqlDropForeignKey
Generates the sql statement to drop a foreign key constraint.- Parameters:
referencingTableName- the referencing foreign table nameforeignKeyName- the name of the foreign key- Returns:
- the SQL code
-
sqlAlterColumnComment
Generates SQL code to alter the comment for an attribute.- Parameters:
tableName- the table namecolumnName- the column namecomment- optional comment, null to clear- Returns:
- the SQL code, null if
sqlRenameAndAlterColumnType(java.lang.String, java.lang.String, java.lang.String, java.lang.String, org.tentackle.sql.SqlType, int, int, boolean, java.lang.Object)must be used instead
-
sqlJoinSelects
void sqlJoinSelects(JoinType type, boolean addColumns, StringBuilder select, String joinSelect, String joinSelectIdAlias, String joinAlias, String join) Generate SQL-code for joining a table to an existing select.- Parameters:
type- the join typeaddColumns- true if columns of joined table should be added to the result setselect- the original select statementjoinSelect- the select to join with the original sql or just a tablenamejoinSelectIdAlias- extra id alias to add to the joined select, null if nonejoinAlias- the alias of the joined selectjoin- the join clause
-
sqlJoinSelects
String sqlJoinSelects(JoinType type, boolean addColumns, String select, String joinSelect, String joinSelectIdAlias, String joinAlias, String join) Generate SQL-code for joining a table to an existing select.- Parameters:
type- the join typeaddColumns- true if columns of joined table should be added to the result setselect- the original select statementjoinSelect- the select to join with the original sql or just a tablenamejoinSelectIdAlias- extra id alias to add to the joined select, null if nonejoinAlias- the alias of the joined selectjoin- the join clause- Returns:
- the select statement
-
jdbcTypeToSqlType
Converts the JDBC data type integer to a tentackle backend SqlTypes.There may be more than one sqltype returned!
- Parameters:
jdbcType- the jdbc data typesize- the column sizescale- the column's scale- Returns:
- the SqlTypes, empty array if no mapping available or no exact match (not generated by TT)
- See Also:
-
getTableMetaData
Gets the table metadata for a given table name.- Parameters:
modelMetaData- the model the table belongs totableName- the model's table name- Returns:
- the table data
-
toQuotedString
Converts a string to a string enclosed in single quotes.- Parameters:
str- the string- Returns:
- the quoted string
-
optimizeSql
Optimize SQL code.
Replace WHERE 1=1 AND/OR to WHERE. Any remaining WHERE 1=1 will be removed too. If you don't want your statements getting optimized, use lowercase for those keywords.- Parameters:
sql- the original sql code- Returns:
- the optimized sql code
-
isReleaseSavepointSupported
boolean isReleaseSavepointSupported()Returns whether the backend supports releasing savepoints explicitly. If not, the savepoints are released when the transaction finishs.- Returns:
- true if release is supported, else false
-
isClobSupported
boolean isClobSupported()Returns whether the backend support CLOB types.
If not, it will be emulated as VARCHAR with the maximum possible size.- Returns:
- true if supported, false if treat as varchar
-
isUUIDSupported
boolean isUUIDSupported()Returns whether the backend supports theUUIDnatively via JDBC setObject/getObject.- Returns:
- true if supported, false if mapped to VARCHAR(36)
-
isFunctionBasedIndexSupported
boolean isFunctionBasedIndexSupported()Returns whether function based indexes are supported.- Returns:
- true if supported
-
isFilteredIndexSupported
boolean isFilteredIndexSupported()Returns whether backend supports filtered indexes.- Returns:
- true if supported, false if model will raise an error if filtered index is used
-
setDropIfExistsEnabled
void setDropIfExistsEnabled(boolean dropIfExists) Some database support drop index/constraint/columnIF EXISTS.
This may be useful if migration scripts are generated against non-production databases that contain test indexes etc...
Notice, that those temporary DDL changes should better use the temporary prefix (seeisTemporaryName(String)) in order to be ignored by the migrator.- Parameters:
dropIfExists- true ifIF EXISTSshould be used
-
isDropIfExistsEnabled
boolean isDropIfExistsEnabled()Returns whether backend should addIF EXISTSfor generated DROPs.- Returns:
- true if
IF EXISTSis turned on and supported, false if not supported or turned off
-
toInternalType
Converts a backend specific type name to an internal name used by driver specific methods.- Parameters:
sqlTypeName- the original type used in SQL scripts- Returns:
- the JDBC internal name
-
isArrayOperatorSupported
Returns whether the backend supports given array operator.- Parameters:
operator- the array operator- Returns:
- true if supported
-
setArray
void setArray(PreparedStatement statement, int pos, SqlType type, Collection<?> elements, String operator) throws SQLException Sets an array parameter in a prepared statement.- Parameters:
statement- the prepared statementpos- the parameter position (starting at 1)type- the element's SQL typeelements- the elements to be converted to an array parameteroperator- the array operator- Throws:
SQLException
-
isSchemaSupported
boolean isSchemaSupported()Returns whether the backend supports schemas.- Returns:
- true if supported
- See Also:
-
isPosixEscapeSyntaxSupported
boolean isPosixEscapeSyntaxSupported()Returns whether the backend supports posix-style escapes via backslash.- Returns:
- true if supported
-
createScriptRunner
Creates a script runner instance.- Parameters:
connection- the SQL-connection
-
isDatabaseInMemory
Returns whether the URL denotes an in-memory database.
Used by test suites to decide whether to populate the database before running the tests.- Parameters:
url- the JDBC url- Returns:
- true if in-memory
-