HHH-14921 Delay generation of SQL strings by identifier generators until schema export or session factory creation

This commit is contained in:
Yoann Rodière 2021-11-04 17:55:55 +01:00
parent 9a14200ca2
commit 5b83edfd49
45 changed files with 529 additions and 210 deletions

View File

@ -42,11 +42,37 @@ public interface AuxiliaryDatabaseObject extends Exportable, Serializable {
/**
* Gets the SQL strings for creating the database object.
*
* @param dialect The dialect for which to generate the SQL creation strings
* @param context A context to help generate the SQL creation strings
*
* @return the SQL strings for creating the database object.
*/
public String[] sqlCreateStrings(Dialect dialect);
default String[] sqlCreateStrings(SqlStringGenerationContext context) {
return sqlCreateStrings( context.getDialect() );
}
/**
* Gets the SQL strings for creating the database object.
*
* @param dialect The dialect for which to generate the SQL creation strings
*
* @return the SQL strings for creating the database object.
* @deprecated Implement {@link #sqlCreateStrings(SqlStringGenerationContext)} instead.
*/
@Deprecated
default String[] sqlCreateStrings(Dialect dialect) {
throw new IllegalStateException( this + " does not implement sqlCreateStrings(...)" );
}
/**
* Gets the SQL strings for dropping the database object.
*
* @param context A context to help generate the SQL drop strings
*
* @return the SQL strings for dropping the database object.
*/
default String[] sqlDropStrings(SqlStringGenerationContext context) {
return sqlDropStrings( context.getDialect() );
}
/**
* Gets the SQL strings for dropping the database object.
@ -54,8 +80,12 @@ public interface AuxiliaryDatabaseObject extends Exportable, Serializable {
* @param dialect The dialect for which to generate the SQL drop strings
*
* @return the SQL strings for dropping the database object.
* @deprecated Implement {@link #sqlDropStrings(SqlStringGenerationContext)} instead.
*/
public String[] sqlDropStrings(Dialect dialect);
@Deprecated
default String[] sqlDropStrings(Dialect dialect) {
throw new IllegalStateException( this + " does not implement sqlDropStrings(...)" );
}
/**
* Additional, optional interface for AuxiliaryDatabaseObject that want to allow

View File

@ -0,0 +1,48 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.boot.model.relational;
import org.hibernate.dialect.Dialect;
/**
* A context provided to methods responsible for generating SQL strings on startup.
*/
public interface SqlStringGenerationContext {
/**
* @return The database dialect, to generate SQL fragments that are specific to each vendor.
*/
Dialect getDialect();
/**
* Render a formatted a table name
*
* @param qualifiedName The table name
*
* @return The formatted name,
*/
String format(QualifiedTableName qualifiedName);
/**
* Render a formatted sequence name
*
* @param qualifiedName The sequence name
*
* @return The formatted name
*/
String format(QualifiedSequenceName qualifiedName);
/**
* Render a formatted non-table and non-sequence qualified name
*
* @param qualifiedName The name
*
* @return The formatted name
*/
String format(QualifiedName qualifiedName);
}

View File

@ -0,0 +1,52 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.boot.model.relational.internal;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.QualifiedSequenceName;
import org.hibernate.boot.model.relational.QualifiedTableName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.env.spi.QualifiedObjectNameFormatter;
public class SqlStringGenerationContextImpl
implements SqlStringGenerationContext {
public static SqlStringGenerationContext forTests(JdbcEnvironment jdbcEnvironment) {
return new SqlStringGenerationContextImpl( jdbcEnvironment );
}
private final Dialect dialect;
private final QualifiedObjectNameFormatter qualifiedObjectNameFormatter;
public SqlStringGenerationContextImpl(JdbcEnvironment jdbcEnvironment) {
this.dialect = jdbcEnvironment.getDialect();
this.qualifiedObjectNameFormatter = jdbcEnvironment.getQualifiedObjectNameFormatter();
}
@Override
public Dialect getDialect() {
return dialect;
}
@Override
public String format(QualifiedTableName qualifiedName) {
return qualifiedObjectNameFormatter.format( qualifiedName, dialect );
}
@Override
public String format(QualifiedSequenceName qualifiedName) {
return qualifiedObjectNameFormatter.format( qualifiedName, dialect );
}
@Override
public String format(QualifiedName qualifiedName) {
return qualifiedObjectNameFormatter.format( qualifiedName, dialect );
}
}

View File

@ -11,6 +11,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGeneratorHelper;
@ -37,7 +38,7 @@ public class GetGeneratedKeysDelegate
}
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert(SqlStringGenerationContext context) {
IdentifierGeneratingInsert insert = new IdentifierGeneratingInsert( dialect );
insert.addIdentityColumn( persister.getRootTableKeyColumnNames()[0] );
return insert;

View File

@ -30,6 +30,7 @@ import org.hibernate.SessionFactoryObserver;
import org.hibernate.StatelessSession;
import org.hibernate.StatelessSessionBuilder;
import org.hibernate.TypeHelper;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.spi.CacheImplementor;
import org.hibernate.cfg.Settings;
@ -244,6 +245,11 @@ public class SessionFactoryDelegatingImpl implements SessionFactoryImplementor,
return delegate.getJdbcServices();
}
@Override
public SqlStringGenerationContext getSqlStringGenerationContext() {
return delegate.getSqlStringGenerationContext();
}
@Override
public Dialect getDialect() {
return delegate.getDialect();

View File

@ -21,6 +21,7 @@ import org.hibernate.Metamodel;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.spi.CacheImplementor;
import org.hibernate.cfg.Settings;
@ -298,6 +299,8 @@ public interface SessionFactoryImplementor extends Mapping, SessionFactory, Quer
return getJdbcServices().getDialect();
}
SqlStringGenerationContext getSqlStringGenerationContext();
/**
* Retrieves the SQLExceptionConverter in effect for this SessionFactory.
*

View File

@ -897,7 +897,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par
}
final String fragment = capableGenerator.determineBulkInsertionIdentifierGenerationSelectFragment(
sessionFactoryHelper.getFactory().getDialect()
sessionFactoryHelper.getFactory().getSqlStringGenerationContext()
);
if ( fragment != null ) {
// we got a fragment from the generator, so alter the sql tree...

View File

@ -8,6 +8,7 @@ package org.hibernate.id;
import java.io.Serializable;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
@ -29,7 +30,7 @@ public abstract class AbstractPostInsertGenerator
}
@Override
public String determineBulkInsertionIdentifierGenerationSelectFragment(Dialect dialect) {
public String determineBulkInsertionIdentifierGenerationSelectFragment(SqlStringGenerationContext context) {
return null;
}
}

View File

@ -6,7 +6,7 @@
*/
package org.hibernate.id;
import org.hibernate.dialect.Dialect;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
/**
* Specialized contract for {@link IdentifierGenerator} implementations capable of being used in conjunction
@ -32,5 +32,5 @@ public interface BulkInsertionCapableIdentifierGenerator extends IdentifierGener
*
* @return The identifier value generation fragment (SQL). {@code null} indicates that no fragment is needed.
*/
public String determineBulkInsertionIdentifierGenerationSelectFragment(Dialect dialect);
public String determineBulkInsertionIdentifierGenerationSelectFragment(SqlStringGenerationContext context);
}

View File

@ -9,11 +9,15 @@ package org.hibernate.id;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
/**
* For composite identifiers, defines a number of "nested" generations that
@ -67,6 +71,16 @@ public class CompositeNestedGeneratedValueGenerator implements IdentifierGenerat
* determined {@link GenerationContextLocator#locateGenerationContext context}
*/
public interface GenerationPlan extends ExportableProducer {
/**
* Initializes this instance, in particular pre-generates SQL as necessary.
* <p>
* This method is called after {@link #registerExportables(Database)}, before first use.
*
* @param context A context to help generate SQL strings
*/
void initialize(SqlStringGenerationContext context);
/**
* Execute the value generation.
*
@ -106,4 +120,11 @@ public class CompositeNestedGeneratedValueGenerator implements IdentifierGenerat
plan.registerExportables( database );
}
}
@Override
public void initialize(SqlStringGenerationContext context) {
for (GenerationPlan plan : generationPlans) {
plan.initialize( context );
}
}
}

View File

@ -14,6 +14,7 @@ import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
@ -79,6 +80,16 @@ public interface IdentifierGenerator extends Configurable, ExportableProducer {
default void registerExportables(Database database) {
}
/**
* Initializes this instance, in particular pre-generates SQL as necessary.
* <p>
* This method is called after {@link #registerExportables(Database)}, before first use.
*
* @param context A context to help generate SQL strings
*/
default void initialize(SqlStringGenerationContext context) {
}
/**
* Generate a new identifier.
*

View File

@ -13,6 +13,7 @@ import java.sql.SQLException;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.insert.AbstractReturningDelegate;
@ -67,7 +68,7 @@ public class IdentityGenerator extends AbstractPostInsertGenerator {
}
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert(SqlStringGenerationContext context) {
InsertSelectIdentityInsert insert = new InsertSelectIdentityInsert( dialect );
insert.addIdentityColumn( persister.getRootTableKeyColumnNames()[0] );
return insert;
@ -120,7 +121,7 @@ public class IdentityGenerator extends AbstractPostInsertGenerator {
}
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert(SqlStringGenerationContext context) {
IdentifierGeneratingInsert insert = new IdentifierGeneratingInsert( dialect );
insert.addIdentityColumn( persister.getRootTableKeyColumnNames()[0] );
return insert;

View File

@ -10,11 +10,17 @@ import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ObjectNameNormalizer;
import org.hibernate.boot.model.relational.QualifiedTableName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.jdbc.env.spi.IdentifierHelper;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreLogging;
@ -42,6 +48,8 @@ public class IncrementGenerator implements IdentifierGenerator {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IncrementGenerator.class );
private Class returnClass;
private String column;
private List<QualifiedTableName> physicalTableNames;
private String sql;
private IntegralDataTypeHolder previousValueHolder;
@ -62,17 +70,13 @@ public class IncrementGenerator implements IdentifierGenerator {
final ObjectNameNormalizer normalizer =
(ObjectNameNormalizer) params.get( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER );
String column = params.getProperty( "column" );
column = params.getProperty( "column" );
if ( column == null ) {
column = params.getProperty( PersistentIdentifierGenerator.PK );
}
column = normalizer.normalizeIdentifierQuoting( column ).render( jdbcEnvironment.getDialect() );
String tableList = params.getProperty( "tables" );
if ( tableList == null ) {
tableList = params.getProperty( PersistentIdentifierGenerator.TABLES );
}
String[] tables = StringHelper.split( ", ", tableList );
IdentifierHelper identifierHelper = jdbcEnvironment.getIdentifierHelper();
final String schema = normalizer.toDatabaseIdentifierText(
params.getProperty( PersistentIdentifierGenerator.SCHEMA )
@ -81,23 +85,40 @@ public class IncrementGenerator implements IdentifierGenerator {
params.getProperty( PersistentIdentifierGenerator.CATALOG )
);
String tableList = params.getProperty( "tables" );
if ( tableList == null ) {
tableList = params.getProperty( PersistentIdentifierGenerator.TABLES );
}
physicalTableNames = new ArrayList<>();
for ( String tableName : StringHelper.split( ", ", tableList ) ) {
physicalTableNames.add( new QualifiedTableName( identifierHelper.toIdentifier( catalog ),
identifierHelper.toIdentifier( schema ), identifierHelper.toIdentifier( tableName ) ) );
}
}
@Override
public void initialize(SqlStringGenerationContext context) {
StringBuilder buf = new StringBuilder();
for ( int i = 0; i < tables.length; i++ ) {
final String tableName = normalizer.toDatabaseIdentifierText( tables[i] );
if ( tables.length > 1 ) {
for ( int i = 0; i < physicalTableNames.size(); i++ ) {
final String tableName = context.format( physicalTableNames.get( i ) );
if ( physicalTableNames.size() > 1 ) {
buf.append( "select max(" ).append( column ).append( ") as mx from " );
}
buf.append( Table.qualify( catalog, schema, tableName ) );
if ( i < tables.length - 1 ) {
buf.append( tableName );
if ( i < physicalTableNames.size() - 1 ) {
buf.append( " union " );
}
}
if ( tables.length > 1 ) {
String maxColumn;
if ( physicalTableNames.size() > 1 ) {
buf.insert( 0, "( " ).append( " ) ids_" );
column = "ids_.mx";
maxColumn = "ids_.mx";
}
else {
maxColumn = column;
}
sql = "select max(" + column + ") from " + buf.toString();
sql = "select max(" + maxColumn + ") from " + buf.toString();
}
private void initializePreviousValueHolder(SharedSessionContractImplementor session) {

View File

@ -21,6 +21,7 @@ import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.QualifiedNameParser;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.internal.FormatStyle;
import org.hibernate.engine.jdbc.spi.JdbcServices;
@ -91,7 +92,7 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
private static final String DEFAULT_VALUE_COLUMN = "sequence_next_hi_value";
private QualifiedName qualifiedTableName;
private String tableName;
private QualifiedName physicalTableName;
private String segmentColumnName;
private String segmentName;
private String valueColumnName;
@ -175,7 +176,7 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
rows = executeUpdate( updatePreparedStatement, statsCollector );
}
catch (SQLException sqle) {
LOG.error( LOG.unableToUpdateHiValue( tableName ), sqle );
LOG.error( LOG.unableToUpdateHiValue( physicalTableName.render() ), sqle );
throw sqle;
}
finally {
@ -340,23 +341,23 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
table.addColumn( valueColumn );
}
final JdbcEnvironment jdbcEnvironment = database.getJdbcEnvironment();
// allow physical naming strategies a chance to kick in
tableName = jdbcEnvironment.getQualifiedObjectNameFormatter().format(
table.getQualifiedTableName(),
jdbcEnvironment.getDialect()
);
physicalTableName = table.getQualifiedTableName();
}
@Override
public void initialize(SqlStringGenerationContext context) {
String formattedPhysicalTableName = context.format( physicalTableName );
query = "select " +
valueColumnName +
" from " +
jdbcEnvironment.getDialect().appendLockHint( LockMode.PESSIMISTIC_WRITE, tableName ) +
context.getDialect().appendLockHint( LockMode.PESSIMISTIC_WRITE, formattedPhysicalTableName ) +
" where " + segmentColumnName + " = '" + segmentName + "'" +
jdbcEnvironment.getDialect().getForUpdateString();
context.getDialect().getForUpdateString();
update = "update " +
tableName +
formattedPhysicalTableName +
" set " +
valueColumnName +
" = ? where " +
@ -367,7 +368,7 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
segmentName
+ "'";
insert = "insert into " + tableName +
insert = "insert into " + formattedPhysicalTableName +
"(" + segmentColumnName + ", " + valueColumnName + ") " +
"values('" + segmentName + "', ?)";

View File

@ -7,6 +7,7 @@
package org.hibernate.id;
import org.hibernate.HibernateException;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.id.insert.InsertGeneratedIdentifierDelegate;

View File

@ -14,6 +14,7 @@ import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.insert.AbstractSelectingDelegate;
@ -39,6 +40,7 @@ public class SelectGenerator extends AbstractPostInsertGenerator {
uniqueKeyPropertyName = params.getProperty( "key" );
}
@Override
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
PostInsertIdentityPersister persister,
Dialect dialect,
@ -102,7 +104,8 @@ public class SelectGenerator extends AbstractPostInsertGenerator {
idType = persister.getIdentifierType();
}
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert(SqlStringGenerationContext context) {
return new IdentifierGeneratingInsert( dialect );
}

View File

@ -12,7 +12,6 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.boot.model.naming.ObjectNameNormalizer;
import org.hibernate.boot.model.relational.Database;
@ -20,8 +19,7 @@ import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.QualifiedNameParser;
import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.log.DeprecationLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
@ -65,7 +63,7 @@ public class SequenceGenerator
public static final String PARAMETERS = "parameters";
private QualifiedName logicalQualifiedSequenceName;
private String sequenceName;
private QualifiedName physicalSequenceName;
private Type identifierType;
private String sql;
@ -73,8 +71,8 @@ public class SequenceGenerator
return identifierType;
}
public String getSequenceName() {
return sequenceName;
public QualifiedName getPhysicalSequenceName() {
return physicalSequenceName;
}
@Override
@ -146,8 +144,8 @@ public class SequenceGenerator
}
@Override
public String determineBulkInsertionIdentifierGenerationSelectFragment(Dialect dialect) {
return dialect.getSelectSequenceNextValString( getSequenceName() );
public String determineBulkInsertionIdentifierGenerationSelectFragment(SqlStringGenerationContext context) {
return context.getDialect().getSelectSequenceNextValString( context.format( getPhysicalSequenceName() ) );
}
@Override
@ -167,14 +165,12 @@ public class SequenceGenerator
1
);
}
this.physicalSequenceName = sequence.getName();
}
final JdbcEnvironment jdbcEnvironment = database.getJdbcEnvironment();
final Dialect dialect = jdbcEnvironment.getDialect();
this.sequenceName = jdbcEnvironment.getQualifiedObjectNameFormatter().format(
sequence.getName(),
dialect
);
this.sql = jdbcEnvironment.getDialect().getSequenceNextValString( sequenceName );
@Override
public void initialize(SqlStringGenerationContext context) {
String formattedPhysicalSequenceName = context.format( physicalSequenceName );
this.sql = context.getDialect().getSequenceNextValString( formattedPhysicalSequenceName );
}
}

View File

@ -13,6 +13,8 @@ import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.insert.AbstractReturningDelegate;
@ -55,7 +57,7 @@ public class SequenceIdentityGenerator
PostInsertIdentityPersister persister,
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException {
return new Delegate( persister, dialect, getSequenceName() );
return new Delegate( persister, getPhysicalSequenceName() );
}
@Override
@ -64,22 +66,23 @@ public class SequenceIdentityGenerator
}
public static class Delegate extends AbstractReturningDelegate {
private final Dialect dialect;
private final String sequenceNextValFragment;
private final QualifiedName physicalSequenceName;
private final String[] keyColumns;
public Delegate(PostInsertIdentityPersister persister, Dialect dialect, String sequenceName) {
public Delegate(PostInsertIdentityPersister persister, QualifiedName physicalSequenceName) {
super( persister );
this.dialect = dialect;
this.sequenceNextValFragment = dialect.getSelectSequenceNextValString( sequenceName );
this.physicalSequenceName = physicalSequenceName;
this.keyColumns = getPersister().getRootTableKeyColumnNames();
if ( keyColumns.length > 1 ) {
throw new HibernateException( "sequence-identity generator cannot be used with with multi-column keys" );
}
}
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert(SqlStringGenerationContext context) {
Dialect dialect = context.getDialect();
NoCommentsInsert insert = new NoCommentsInsert( dialect );
String sequenceNextValFragment = dialect.getSelectSequenceNextValString( context.format( physicalSequenceName ) );
insert.addColumn( getPersister().getRootTableKeyColumnNames()[0], sequenceNextValFragment );
return insert;
}

View File

@ -6,7 +6,10 @@
*/
package org.hibernate.id.enhanced;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
/**
@ -17,10 +20,14 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor;
*/
public interface DatabaseStructure extends ExportableProducer {
/**
* The name of the database structure (table or sequence).
* The physical name of the database structure (table or sequence).
* <p>
* Only available after {@link #registerExportables(Database)}
* has been called.
*
* @return The structure name.
*/
String getName();
QualifiedName getPhysicalName();
/**
* How many times has this structure been accessed through this reference?
@ -54,8 +61,45 @@ public interface DatabaseStructure extends ExportableProducer {
* but before first use.
*
* @param optimizer The optimizer being applied to the generator.
*
* @deprecated Use {@link #configure(Optimizer)} instead.
*/
void prepare(Optimizer optimizer);
@Deprecated
default void prepare(Optimizer optimizer) {
}
/**
* Configures this structure with the given arguments.
* <p>
* Called just after instantiation, before {@link #initialize(SqlStringGenerationContext)}
*
* @param optimizer The optimizer being applied to the generator.
*/
default void configure(Optimizer optimizer) {
prepare( optimizer );
}
/**
* Register database objects involved in this structure, e.g. sequences, tables, etc.
* <p>
* This method is called just once, after {@link #configure(Optimizer)},
* but before {@link #initialize(SqlStringGenerationContext)}.
*
* @param database The database instance
*/
@Override
void registerExportables(Database database);
/**
* Initializes this structure, in particular pre-generates SQL as necessary.
* <p>
* This method is called just once, after {@link #registerExportables(Database)},
* before first use.
*
* @param context A context to help generate SQL strings
*/
default void initialize(SqlStringGenerationContext context) {
}
/**
* Is the structure physically a sequence?

View File

@ -15,6 +15,7 @@ import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGeneratorHelper;
@ -42,7 +43,7 @@ public class SequenceStructure implements DatabaseStructure {
private String sql;
private boolean applyIncrementSizeToSourceValues;
private int accessCounter;
protected String sequenceName;
protected QualifiedName physicalSequenceName;
public SequenceStructure(
JdbcEnvironment jdbcEnvironment,
@ -58,8 +59,8 @@ public class SequenceStructure implements DatabaseStructure {
}
@Override
public String getName() {
return sequenceName;
public QualifiedName getPhysicalName() {
return physicalSequenceName;
}
@Override
@ -132,14 +133,18 @@ public class SequenceStructure implements DatabaseStructure {
}
@Override
public void prepare(Optimizer optimizer) {
public void configure(Optimizer optimizer) {
applyIncrementSizeToSourceValues = optimizer.applyIncrementSizeToSourceValues();
}
@Override
public void registerExportables(Database database) {
buildSequence( database );
this.sql = database.getJdbcEnvironment().getDialect().getSequenceNextValString( sequenceName );
}
@Override
public void initialize(SqlStringGenerationContext context) {
this.sql = context.getDialect().getSequenceNextValString( context.format( physicalSequenceName ) );
}
@Override
@ -170,9 +175,6 @@ public class SequenceStructure implements DatabaseStructure {
sequence = namespace.createSequence( logicalQualifiedSequenceName.getObjectName(), initialValue, sourceIncrementSize );
}
this.sequenceName = database.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
sequence.getName(),
database.getJdbcEnvironment().getDialect()
);
this.physicalSequenceName = sequence.getName();
}
}

View File

@ -16,6 +16,7 @@ import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.QualifiedNameParser;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService;
@ -297,7 +298,17 @@ public class SequenceStyleGenerator
incrementSize,
ConfigurationHelper.getInt( INITIAL_PARAM, params, -1 )
);
this.databaseStructure.prepare( optimizer );
this.databaseStructure.configure( optimizer );
}
@Override
public void registerExportables(Database database) {
databaseStructure.registerExportables( database );
}
@Override
public void initialize(SqlStringGenerationContext context) {
this.databaseStructure.initialize( context );
}
/**
@ -535,13 +546,8 @@ public class SequenceStyleGenerator
}
@Override
public String determineBulkInsertionIdentifierGenerationSelectFragment(Dialect dialect) {
return dialect.getSelectSequenceNextValString( getDatabaseStructure().getName() );
}
@Override
public void registerExportables(Database database) {
databaseStructure.registerExportables( database );
public String determineBulkInsertionIdentifierGenerationSelectFragment(SqlStringGenerationContext context) {
return context.getDialect().getSelectSequenceNextValString( context.format( getDatabaseStructure().getPhysicalName() ) );
}
/**

View File

@ -25,6 +25,7 @@ import org.hibernate.boot.model.relational.InitCommand;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.QualifiedNameParser;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService;
@ -231,7 +232,7 @@ public class TableGenerator implements PersistentIdentifierGenerator {
private Type identifierType;
private QualifiedName qualifiedTableName;
private String renderedTableName;
private QualifiedName physicalTableName;
private String segmentColumnName;
private String segmentValue;
@ -518,30 +519,31 @@ public class TableGenerator implements PersistentIdentifierGenerator {
}
@SuppressWarnings({"unchecked", "WeakerAccess"})
protected String buildSelectQuery(Dialect dialect) {
protected String buildSelectQuery(String formattedPhysicalTableName, SqlStringGenerationContext context) {
final String alias = "tbl";
final String query = "select " + StringHelper.qualify( alias, valueColumnName ) +
" from " + renderedTableName + ' ' + alias +
" from " + formattedPhysicalTableName + ' ' + alias +
" where " + StringHelper.qualify( alias, segmentColumnName ) + "=?";
final LockOptions lockOptions = new LockOptions( LockMode.PESSIMISTIC_WRITE );
lockOptions.setAliasSpecificLockMode( alias, LockMode.PESSIMISTIC_WRITE );
final Map updateTargetColumnsMap = Collections.singletonMap( alias, new String[] { valueColumnName } );
return dialect.applyLocksToSql( query, lockOptions, updateTargetColumnsMap );
return context.getDialect().applyLocksToSql( query, lockOptions, updateTargetColumnsMap );
}
@SuppressWarnings("WeakerAccess")
protected String buildUpdateQuery() {
return "update " + renderedTableName +
protected String buildUpdateQuery(String formattedPhysicalTableName, SqlStringGenerationContext context) {
return "update " + formattedPhysicalTableName +
" set " + valueColumnName + "=? " +
" where " + valueColumnName + "=? and " + segmentColumnName + "=?";
}
@SuppressWarnings("WeakerAccess")
protected String buildInsertQuery() {
return "insert into " + renderedTableName + " (" + segmentColumnName + ", " + valueColumnName + ") " + " values (?,?)";
protected String buildInsertQuery(String formattedPhysicalTableName, SqlStringGenerationContext context) {
return "insert into " + formattedPhysicalTableName + " (" + segmentColumnName + ", " + valueColumnName + ") " + " values (?,?)";
}
protected InitCommand generateInsertInitCommand() {
protected InitCommand generateInsertInitCommand(SqlStringGenerationContext context) {
String renderedTableName = context.format( physicalTableName );
int value = initialValue;
if ( storeLastUsedValue ) {
value = initialValue - 1;
@ -639,7 +641,7 @@ public class TableGenerator implements PersistentIdentifierGenerator {
rows = executeUpdate( updatePS, statsCollector );
}
catch (SQLException e) {
LOG.unableToUpdateQueryHiValue( renderedTableName, e );
LOG.unableToUpdateQueryHiValue( physicalTableName.render(), e );
throw e;
}
}
@ -740,14 +742,15 @@ public class TableGenerator implements PersistentIdentifierGenerator {
}
// allow physical naming strategies a chance to kick in
this.renderedTableName = database.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
table.getQualifiedTableName(),
dialect
);
table.addInitCommand( generateInsertInitCommand() );
this.physicalTableName = table.getQualifiedTableName();
table.addInitCommand( this::generateInsertInitCommand );
}
this.selectQuery = buildSelectQuery( dialect );
this.updateQuery = buildUpdateQuery();
this.insertQuery = buildInsertQuery();
@Override
public void initialize(SqlStringGenerationContext context) {
String formattedPhysicalTableName = context.format( physicalTableName );
this.selectQuery = buildSelectQuery( formattedPhysicalTableName, context );
this.updateQuery = buildUpdateQuery( formattedPhysicalTableName, context );
this.insertQuery = buildInsertQuery( formattedPhysicalTableName, context );
}
}

View File

@ -18,6 +18,7 @@ import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.InitCommand;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.internal.FormatStyle;
@ -53,7 +54,7 @@ public class TableStructure implements DatabaseStructure {
private final int incrementSize;
private final Class numberType;
private String tableNameText;
private QualifiedName physicalTableName;
private String valueColumnNameText;
private String selectQuery;
@ -78,8 +79,8 @@ public class TableStructure implements DatabaseStructure {
}
@Override
public String getName() {
return tableNameText;
public QualifiedName getPhysicalName() {
return physicalTableName;
}
@Override
@ -135,7 +136,7 @@ public class TableStructure implements DatabaseStructure {
)) {
final ResultSet selectRS = executeQuery( selectStatement, statsCollector );
if ( !selectRS.next() ) {
final String err = "could not read a hi value - you need to populate the table: " + tableNameText;
final String err = "could not read a hi value - you need to populate the table: " + physicalTableName;
LOG.error( err );
throw new IdentifierGenerationException( err );
}
@ -161,7 +162,7 @@ public class TableStructure implements DatabaseStructure {
rows = executeUpdate( updatePS, statsCollector );
}
catch (SQLException e) {
LOG.unableToUpdateQueryHiValue( tableNameText, e );
LOG.unableToUpdateQueryHiValue( physicalTableName.render(), e );
throw e;
}
} while ( rows == 0 );
@ -239,22 +240,9 @@ public class TableStructure implements DatabaseStructure {
table = namespace.createTable( logicalQualifiedTableName.getObjectName(), false );
tableCreated = true;
}
this.physicalTableName = table.getQualifiedTableName();
this.tableNameText = jdbcEnvironment.getQualifiedObjectNameFormatter().format(
table.getQualifiedTableName(),
dialect
);
this.valueColumnNameText = logicalValueColumnNameIdentifier.render( dialect );
this.selectQuery = "select " + valueColumnNameText + " as id_val" +
" from " + dialect.appendLockHint( LockMode.PESSIMISTIC_WRITE, tableNameText ) +
dialect.getForUpdateString();
this.updateQuery = "update " + tableNameText +
" set " + valueColumnNameText + "= ?" +
" where " + valueColumnNameText + "=?";
valueColumnNameText = logicalValueColumnNameIdentifier.render( dialect );
if ( tableCreated ) {
ExportableColumn valueColumn = new ExportableColumn(
database,
@ -265,9 +253,23 @@ public class TableStructure implements DatabaseStructure {
table.addColumn( valueColumn );
table.addInitCommand(
new InitCommand( "insert into " + tableNameText + " values ( " + initialValue + " )" )
);
table.addInitCommand( context -> new InitCommand( "insert into "
+ context.format( physicalTableName ) + " values ( " + initialValue + " )" ) );
}
}
@Override
public void initialize(SqlStringGenerationContext context) {
Dialect dialect = context.getDialect();
String formattedPhysicalTableName = context.format( physicalTableName );
this.selectQuery = "select " + valueColumnNameText + " as id_val" +
" from " + dialect.appendLockHint( LockMode.PESSIMISTIC_WRITE, formattedPhysicalTableName ) +
dialect.getForUpdateString();
this.updateQuery = "update " + formattedPhysicalTableName +
" set " + valueColumnNameText + "= ?" +
" where " + valueColumnNameText + "=?";
}
}

View File

@ -8,6 +8,7 @@ package org.hibernate.id.insert;
import java.io.Serializable;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
/**
@ -25,9 +26,10 @@ public interface InsertGeneratedIdentifierDelegate {
* Build a {@link org.hibernate.sql.Insert} specific to the delegate's mode
* of handling generated key values.
*
* @param context A context to help generate SQL strings
* @return The insert object.
*/
IdentifierGeneratingInsert prepareIdentifierGeneratingInsert();
IdentifierGeneratingInsert prepareIdentifierGeneratingInsert(SqlStringGenerationContext context);
/**
* Perform the indicated insert SQL statement and determine the identifier value

View File

@ -18,7 +18,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
@ -49,6 +48,8 @@ import org.hibernate.StatelessSessionBuilder;
import org.hibernate.TypeHelper;
import org.hibernate.boot.cfgxml.spi.CfgXmlAccessService;
import org.hibernate.boot.cfgxml.spi.LoadedConfig;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.boot.spi.SessionFactoryOptions;
@ -171,6 +172,7 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
private final transient SessionFactoryServiceRegistry serviceRegistry;
private final transient EventEngine eventEngine;
private final transient JdbcServices jdbcServices;
private final transient SqlStringGenerationContext sqlStringGenerationContext;
private final transient SQLFunctionRegistry sqlFunctionRegistry;
@ -231,6 +233,7 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
this.uuid = options.getUuid();
jdbcServices = serviceRegistry.getService( JdbcServices.class );
sqlStringGenerationContext = new SqlStringGenerationContextImpl( jdbcServices.getJdbcEnvironment() );
this.properties = new HashMap<>();
this.properties.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );
@ -302,6 +305,7 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
settings.getDefaultSchemaName(),
(RootClass) model
);
generator.initialize( sqlStringGenerationContext );
identifierGenerators.put( model.getEntityName(), generator );
} );
metadata.validate();
@ -560,6 +564,11 @@ public class SessionFactoryImpl implements SessionFactoryImplementor {
return jdbcServices;
}
@Override
public SqlStringGenerationContext getSqlStringGenerationContext() {
return sqlStringGenerationContext;
}
public IdentifierGeneratorFactory getIdentifierGeneratorFactory() {
return null;
}

View File

@ -16,6 +16,7 @@ import java.util.Map;
import org.hibernate.EntityMode;
import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.boot.spi.MetadataBuildingContext;
@ -513,6 +514,11 @@ public class Component extends SimpleValue implements MetaAttributable {
public void registerExportables(Database database) {
subGenerator.registerExportables( database );
}
@Override
public void initialize(SqlStringGenerationContext context) {
subGenerator.initialize( context );
}
}
}

View File

@ -16,6 +16,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
@ -25,6 +26,7 @@ import org.hibernate.boot.model.relational.Exportable;
import org.hibernate.boot.model.relational.InitCommand;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.QualifiedTableName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.env.spi.QualifiedObjectNameFormatter;
@ -67,7 +69,7 @@ public class Table implements RelationalModel, Serializable, Exportable {
private boolean hasDenormalizedTables;
private String comment;
private List<InitCommand> initCommands;
private List<Function<SqlStringGenerationContext, InitCommand>> initCommandProducers;
public Table() {
}
@ -897,18 +899,30 @@ public class Table implements RelationalModel, Serializable, Exportable {
}
}
/**
* @deprecated Use {@link #addInitCommand(Function)} instead.
*/
@Deprecated
public void addInitCommand(InitCommand command) {
if ( initCommands == null ) {
initCommands = new ArrayList<>();
}
initCommands.add( command );
addInitCommand( ignored -> command );
}
public List<InitCommand> getInitCommands() {
if ( initCommands == null ) {
public void addInitCommand(Function<SqlStringGenerationContext, InitCommand> commandProducer) {
if ( initCommandProducers == null ) {
initCommandProducers = new ArrayList<>();
}
initCommandProducers.add( commandProducer );
}
public List<InitCommand> getInitCommands(SqlStringGenerationContext context) {
if ( initCommandProducers == null ) {
return Collections.emptyList();
}
else {
List<InitCommand> initCommands = new ArrayList<>();
for ( Function<SqlStringGenerationContext, InitCommand> producer : initCommandProducers ) {
initCommands.add( producer.apply( context ) );
}
return Collections.unmodifiableList( initCommands );
}
}

View File

@ -459,6 +459,7 @@ public abstract class AbstractCollectionPersister
factory.getSettings().getDefaultSchemaName(),
null
);
identifierGenerator.initialize( creationContext.getSessionFactory().getSqlStringGenerationContext() );
}
else {
identifierType = null;

View File

@ -37,6 +37,7 @@ import org.hibernate.QueryException;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.bytecode.enhance.spi.LazyPropertyInitializer;
@ -2957,8 +2958,8 @@ public abstract class AbstractEntityPersister
*
* @return The insert SQL statement string
*/
public String generateIdentityInsertString(boolean[] includeProperty) {
Insert insert = identityDelegate.prepareIdentifierGeneratingInsert();
public String generateIdentityInsertString(SqlStringGenerationContext context, boolean[] includeProperty) {
Insert insert = identityDelegate.prepareIdentifierGeneratingInsert( context );
insert.setTableName( getTableName( 0 ) );
// add normal properties except lobs
@ -4396,7 +4397,7 @@ public abstract class AbstractEntityPersister
identityDelegate = ( (PostInsertIdentifierGenerator) getIdentifierGenerator() )
.getInsertGeneratedIdentifierDelegate( this, getFactory().getDialect(), useGetGeneratedKeys() );
sqlIdentityInsertString = customSQLInsert[0] == null
? generateIdentityInsertString( getPropertyInsertability() )
? generateIdentityInsertString( factory.getSqlStringGenerationContext(), getPropertyInsertability() )
: substituteBrackets( customSQLInsert[0] );
}
else {

View File

@ -22,6 +22,8 @@ import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.Exportable;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService;
@ -187,7 +189,8 @@ public class SchemaDropperImpl implements SchemaDropper {
Formatter formatter,
GenerationTarget... targets) {
final Database database = metadata.getDatabase();
final JdbcEnvironment jdbcEnvironment = database.getJdbcEnvironment();
SqlStringGenerationContext sqlStringGenerationContext =
new SqlStringGenerationContextImpl( metadata.getDatabase().getJdbcEnvironment() );
boolean tryToDropCatalogs = false;
boolean tryToDropSchemas = false;
@ -259,7 +262,7 @@ public class SchemaDropperImpl implements SchemaDropper {
}
applySqlStrings(
auxiliaryDatabaseObject.sqlDropStrings( jdbcEnvironment.getDialect() ),
auxiliaryDatabaseObject.sqlDropStrings( sqlStringGenerationContext ),
formatter,
options,
targets

View File

@ -8,6 +8,7 @@ package org.hibernate.tool.schema.internal;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.model.relational.AuxiliaryDatabaseObject;
import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl;
import org.hibernate.dialect.Dialect;
import org.hibernate.tool.schema.spi.Exporter;
@ -23,11 +24,11 @@ public class StandardAuxiliaryDatabaseObjectExporter implements Exporter<Auxilia
@Override
public String[] getSqlCreateStrings(AuxiliaryDatabaseObject object, Metadata metadata) {
return object.sqlCreateStrings( dialect );
return object.sqlCreateStrings( new SqlStringGenerationContextImpl( metadata.getDatabase().getJdbcEnvironment() ) );
}
@Override
public String[] getSqlDropStrings(AuxiliaryDatabaseObject object, Metadata metadata) {
return object.sqlDropStrings( dialect );
return object.sqlDropStrings( new SqlStringGenerationContextImpl( metadata.getDatabase().getJdbcEnvironment() ) );
}
}

View File

@ -16,6 +16,8 @@ import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.relational.InitCommand;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.QualifiedNameParser;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.mapping.Column;
@ -152,7 +154,9 @@ public class StandardTableExporter implements Exporter<Table> {
applyComments( table, tableName, sqlStrings );
applyInitCommands( table, sqlStrings );
SqlStringGenerationContext context =
new SqlStringGenerationContextImpl( metadata.getDatabase().getJdbcEnvironment() );
applyInitCommands( table, sqlStrings, context );
return sqlStrings.toArray( new String[ sqlStrings.size() ] );
}
@ -173,8 +177,8 @@ public class StandardTableExporter implements Exporter<Table> {
}
}
protected void applyInitCommands(Table table, List<String> sqlStrings) {
for ( InitCommand initCommand : table.getInitCommands() ) {
protected void applyInitCommands(Table table, List<String> sqlStrings, SqlStringGenerationContext context) {
for ( InitCommand initCommand : table.getInitCommands( context ) ) {
Collections.addAll( sqlStrings, initCommand.getInitCommands() );
}
}

View File

@ -9,6 +9,7 @@ package org.hibernate.tool.schema.spi;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.model.relational.Exportable;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
/**
* Defines a contract for exporting of database objects (tables, sequences, etc) for use in SQL {@code CREATE} and

View File

@ -76,6 +76,7 @@ public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTestCase {
generator.registerExportables( metadata.getDatabase() );
sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
generator.initialize( sessionFactory.getSqlStringGenerationContext() );
sequenceValueExtractor = new SequenceValueExtractor( sessionFactory.getDialect(), TEST_SEQUENCE );
}

View File

@ -71,6 +71,7 @@ public class SequenceHiLoGeneratorTest extends BaseUnitTestCase {
generator.registerExportables( metadata.getDatabase() );
sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
generator.initialize( sessionFactory.getSqlStringGenerationContext() );
sequenceValueExtractor = new SequenceValueExtractor( sessionFactory.getDialect(), TEST_SEQUENCE );
}

View File

@ -74,6 +74,7 @@ public class SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncreme
generator.registerExportables( metadata.getDatabase() );
sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
generator.initialize( sessionFactory.getSqlStringGenerationContext() );
sequenceValueExtractor = new SequenceValueExtractor( sessionFactory.getDialect(), TEST_SEQUENCE );
}

View File

@ -11,6 +11,7 @@ import java.util.Properties;
import org.hibernate.MappingException;
import org.hibernate.boot.internal.MetadataBuilderImpl;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
@ -45,13 +46,14 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( NoopOptimizer.class, generator.getOptimizer().getClass() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME,
generator.getDatabaseStructure().getPhysicalName().render() );
}
}
@ -76,13 +78,14 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( TableStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( NoopOptimizer.class, generator.getOptimizer().getClass() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME,
generator.getDatabaseStructure().getPhysicalName().render() );
}
}
@ -103,13 +106,14 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( TableStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( PooledOptimizer.class, generator.getOptimizer().getClass() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME,
generator.getDatabaseStructure().getPhysicalName().render() );
}
// for dialects which do support pooled sequences, we default to pooled+sequence
@ -121,13 +125,14 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( PooledOptimizer.class, generator.getOptimizer().getClass() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME,
generator.getDatabaseStructure().getPhysicalName().render() );
}
}
@ -146,13 +151,14 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( TableStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( PooledOptimizer.class, generator.getOptimizer().getClass() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME,
generator.getDatabaseStructure().getPhysicalName().render() );
}
}
@ -169,13 +175,14 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( TableStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( NoopOptimizer.class, generator.getOptimizer().getClass() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, generator.getDatabaseStructure().getName() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME,
generator.getDatabaseStructure().getPhysicalName().render() );
}
}
@ -193,9 +200,9 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
props.setProperty( SequenceStyleGenerator.INCREMENT_PARAM, "20" );
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( NoopOptimizer.class, generator.getOptimizer().getClass() );
@ -208,9 +215,8 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
props.setProperty( SequenceStyleGenerator.INCREMENT_PARAM, "20" );
generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( HiLoOptimizer.class, generator.getOptimizer().getClass() );
assertEquals( 20, generator.getOptimizer().getIncrementSize() );
@ -222,9 +228,8 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
props.setProperty( SequenceStyleGenerator.INCREMENT_PARAM, "20" );
generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
// because the dialect reports to not support pooled seqyences, the expectation is that we will
// use a table for the backing structure...
assertClassAssignability( TableStructure.class, generator.getDatabaseStructure().getClass() );
@ -243,27 +248,25 @@ public class SequenceStyleConfigUnitTest extends BaseUnitTestCase {
props.setProperty( SequenceStyleGenerator.INCREMENT_PARAM, "20" );
SequenceStyleGenerator generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
Database database = new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) );
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( PooledOptimizer.class, generator.getOptimizer().getClass() );
props.setProperty( Environment.PREFER_POOLED_VALUES_LO, "true" );
generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( PooledLoOptimizer.class, generator.getOptimizer().getClass() );
props.setProperty( Environment.PREFERRED_POOLED_OPTIMIZER, StandardOptimizerDescriptor.POOLED_LOTL.getExternalName() );
generator = new SequenceStyleGenerator();
generator.configure( StandardBasicTypes.LONG, props, serviceRegistry );
generator.registerExportables(
new Database( new MetadataBuilderImpl.MetadataBuildingOptionsImpl( serviceRegistry ) )
);
generator.registerExportables( database );
generator.initialize( SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() ) );
assertClassAssignability( SequenceStructure.class, generator.getDatabaseStructure().getClass() );
assertClassAssignability( PooledLoThreadLocalOptimizer.class, generator.getOptimizer().getClass() );
}

View File

@ -66,7 +66,8 @@ public class NewGeneratorMappingsTest extends BaseCoreFunctionalTestCase {
IdentifierGenerator generator = persister.getIdentifierGenerator();
assertTrue( SequenceStyleGenerator.class.isInstance( generator ) );
SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
assertEquals( MinimalSequenceEntity.SEQ_NAME, seqGenerator.getDatabaseStructure().getName() );
assertEquals( MinimalSequenceEntity.SEQ_NAME,
seqGenerator.getDatabaseStructure().getPhysicalName().render() );
// 1 is the annotation default
assertEquals( 1, seqGenerator.getDatabaseStructure().getInitialValue() );
// 50 is the annotation default
@ -91,7 +92,8 @@ public class NewGeneratorMappingsTest extends BaseCoreFunctionalTestCase {
IdentifierGenerator generator = persister.getIdentifierGenerator();
assertTrue( SequenceStyleGenerator.class.isInstance( generator ) );
SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, seqGenerator.getDatabaseStructure().getName() );
assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME,
seqGenerator.getDatabaseStructure().getPhysicalName().render() );
assertEquals( SequenceStyleGenerator.DEFAULT_INITIAL_VALUE, seqGenerator.getDatabaseStructure().getInitialValue() );
assertEquals( SequenceStyleGenerator.DEFAULT_INCREMENT_SIZE, seqGenerator.getDatabaseStructure().getIncrementSize() );
}
@ -123,7 +125,7 @@ public class NewGeneratorMappingsTest extends BaseCoreFunctionalTestCase {
SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
assertEquals(
StringHelper.unqualifyEntityName( DedicatedSequenceEntity1.class.getName() ) + DedicatedSequenceEntity1.SEQUENCE_SUFFIX,
seqGenerator.getDatabaseStructure().getName()
seqGenerator.getDatabaseStructure().getPhysicalName().render()
);
// Checking second entity.
@ -133,7 +135,7 @@ public class NewGeneratorMappingsTest extends BaseCoreFunctionalTestCase {
seqGenerator = (SequenceStyleGenerator) generator;
assertEquals(
DedicatedSequenceEntity2.ENTITY_NAME + DedicatedSequenceEntity1.SEQUENCE_SUFFIX,
seqGenerator.getDatabaseStructure().getName()
seqGenerator.getDatabaseStructure().getPhysicalName().render()
);
}
}

View File

@ -12,7 +12,6 @@ import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.enhanced.SequenceStyleGenerator;
@ -57,7 +56,7 @@ public class HibernateSequenceTest extends BaseCoreFunctionalTestCase {
SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
Assert.assertEquals(
Table.qualify( null, SCHEMA_NAME, SequenceStyleGenerator.DEF_SEQUENCE_NAME ),
seqGenerator.getDatabaseStructure().getName()
seqGenerator.getDatabaseStructure().getPhysicalName().render()
);
}

View File

@ -70,9 +70,9 @@ public class NewGeneratorsTests extends BaseUnitTestCase {
final DatabaseStructure databaseStructure = generator.getDatabaseStructure();
// HHH-14491 - what we want to happen
assertThat( databaseStructure.getName(), is( "Entity1_SEQ" ) );
assertThat( databaseStructure.getPhysicalName().render(), is( "Entity1_SEQ" ) );
// or this depending on the discussion (Jira) about using entity name v. table name as the base
assertThat( databaseStructure.getName(), is( "tbl_1_SEQ" ) );
assertThat( databaseStructure.getPhysicalName().render(), is( "tbl_1_SEQ" ) );
// HHH-14491 - this is what we want to have happen
assertThat( databaseStructure.getIncrementSize(), is( 50 ) );

View File

@ -64,7 +64,8 @@ public class BasicSequenceTest extends BaseCoreFunctionalTestCase {
EntityPersister persister = sessionFactory().getEntityPersister( overriddenEntityName );
assertClassAssignability( SequenceStyleGenerator.class, persister.getIdentifierGenerator().getClass() );
SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getIdentifierGenerator();
assertEquals( overriddenEntityName + SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX, generator.getDatabaseStructure().getName() );
assertEquals( overriddenEntityName + SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX,
generator.getDatabaseStructure().getPhysicalName().getObjectName().getText() );
Session s = openSession();
s.beginTransaction();

View File

@ -16,6 +16,7 @@ import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
@ -93,8 +94,8 @@ public class HiLoSequenceMismatchStrategyTest extends BaseCoreFunctionalTestCase
SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getIdentifierGenerator();
assertClassAssignability( HiLoOptimizer.class, generator.getOptimizer().getClass() );
String sequenceName = generator.getDatabaseStructure().getName();
Assert.assertEquals( this.sequenceName, sequenceName );
QualifiedName sequenceName = generator.getDatabaseStructure().getPhysicalName();
Assert.assertEquals( this.sequenceName, sequenceName.render() );
int incrementSize = generator.getOptimizer().getIncrementSize();
Assert.assertNotEquals( 1, incrementSize );

View File

@ -17,6 +17,7 @@ import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
@ -61,13 +62,13 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final SequenceStyleGenerator sequenceStyleGenerator = assertTyping(
SequenceStyleGenerator.class,
generator
);
assertThat( sequenceStyleGenerator.getDatabaseStructure().getName(), is( "my_real_db_sequence" ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_real_db_sequence" ) );
// all the JPA defaults since they were not defined
assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 100 ) );
@ -91,6 +92,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final SequenceStyleGenerator sequenceStyleGenerator = assertTyping(
SequenceStyleGenerator.class,
@ -99,7 +101,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
// PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME == false indicates that the legacy
// default (hibernate_sequence) should be used
assertThat( sequenceStyleGenerator.getDatabaseStructure().getName(), is( "hibernate_sequence" ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "hibernate_sequence" ) );
// the JPA defaults since they were not defined
assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 1 ) );
@ -121,6 +123,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final SequenceStyleGenerator sequenceStyleGenerator = assertTyping(
SequenceStyleGenerator.class,
@ -129,7 +132,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
// PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME == true (the default) indicates that the generator-name
// should be used as the default instead.
assertThat( sequenceStyleGenerator.getDatabaseStructure().getName(), is( "my_db_sequence" ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) );
// the JPA defaults since they were not defined
assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 1 ) );
@ -153,10 +156,11 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final SequenceStyleGenerator sequenceStyleGenerator = assertTyping( SequenceStyleGenerator.class, generator );
// all the JPA defaults since they were not defined
assertThat( sequenceStyleGenerator.getDatabaseStructure().getName(), is( SequenceStyleGenerator.DEF_SEQUENCE_NAME ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( SequenceStyleGenerator.DEF_SEQUENCE_NAME ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 100 ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 500 ) );
}
@ -177,13 +181,14 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final SequenceStyleGenerator sequenceStyleGenerator = assertTyping(
SequenceStyleGenerator.class,
generator
);
// all the JPA defaults since they were not defined
assertThat( sequenceStyleGenerator.getDatabaseStructure().getName(), is( "my_db_sequence" ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getPhysicalName().render(), is( "my_db_sequence" ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is( 100 ) );
assertThat( sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is( 500 ) );
@ -215,6 +220,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator );
@ -240,6 +246,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator );
@ -265,6 +272,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
final TableGenerator tableGenerator = assertTyping( TableGenerator.class, generator );
@ -292,6 +300,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
assertTyping( IncrementGenerator.class, generator );
}
@ -311,6 +320,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
null,
(RootClass) entityMapping
);
generator.initialize( SqlStringGenerationContextImpl.forTests( bootModel.getDatabase().getJdbcEnvironment() ) );
assertTyping( IncrementGenerator.class, generator );
}

View File

@ -16,6 +16,8 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.QualifiedTableName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
@ -34,7 +36,6 @@ import org.hibernate.tool.schema.spi.TargetDescriptor;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@ -77,7 +78,8 @@ public class SchemaUpdateTableBackedSequenceTest extends BaseUnitTestCase {
// lets make sure the InitCommand is there
assertEquals( 1, database.getDefaultNamespace().getTables().size() );
Table table = database.getDefaultNamespace().getTables().iterator().next();
assertEquals( 1, table.getInitCommands().size() );
SqlStringGenerationContext context = SqlStringGenerationContextImpl.forTests( database.getJdbcEnvironment() );
assertEquals( 1, table.getInitCommands( context ).size() );
final TargetImpl target = new TargetImpl();

View File

@ -9,6 +9,7 @@ package org.hibernate.envers.enhanced;
import org.hibernate.boot.model.relational.AuxiliaryDatabaseObject;
import org.hibernate.boot.model.relational.Database;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
@ -38,16 +39,13 @@ public class OrderedSequenceStructure extends SequenceStructure {
@Override
protected void buildSequence(Database database) {
database.addAuxiliaryDatabaseObject( sequenceObject );
this.sequenceName = database.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
getQualifiedName(),
database.getJdbcEnvironment().getDialect()
);
this.physicalSequenceName = getQualifiedName();
}
private class OrderedSequence implements AuxiliaryDatabaseObject {
@Override
public String getExportIdentifier() {
return getName();
return getQualifiedName().render();
}
@Override
@ -63,9 +61,10 @@ public class OrderedSequenceStructure extends SequenceStructure {
}
@Override
public String[] sqlCreateStrings(Dialect dialect) {
public String[] sqlCreateStrings(SqlStringGenerationContext context) {
Dialect dialect = context.getDialect();
final String[] createStrings = dialect.getCreateSequenceStrings(
getName(),
context.format( getPhysicalName() ),
getInitialValue(),
getSourceIncrementSize()
);
@ -80,8 +79,9 @@ public class OrderedSequenceStructure extends SequenceStructure {
}
@Override
public String[] sqlDropStrings(Dialect dialect) {
return dialect.getDropSequenceStrings( getName() );
public String[] sqlDropStrings(SqlStringGenerationContext context) {
Dialect dialect = context.getDialect();
return dialect.getDropSequenceStrings( context.format( getPhysicalName() ) );
}
}
}