Java Code Examples for org.hibernate.boot.model.naming.Identifier

The following examples show how to use org.hibernate.boot.model.naming.Identifier. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: lams   Source File: StandardTableExporter.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public String[] getSqlDropStrings(Table table, Metadata metadata) {
	StringBuilder buf = new StringBuilder( "drop table " );
	if ( dialect.supportsIfExistsBeforeTableName() ) {
		buf.append( "if exists " );
	}

	final QualifiedName tableName = new QualifiedNameParser.NameParts(
			Identifier.toIdentifier( table.getCatalog(), table.isCatalogQuoted() ),
			Identifier.toIdentifier( table.getSchema(), table.isSchemaQuoted() ),
			table.getNameIdentifier()
	);
	final JdbcEnvironment jdbcEnvironment = metadata.getDatabase().getJdbcEnvironment();
	buf.append( jdbcEnvironment.getQualifiedObjectNameFormatter().format( tableName, jdbcEnvironment.getDialect() ) )
			.append( dialect.getCascadeConstraintsString() );

	if ( dialect.supportsIfExistsAfterTableName() ) {
		buf.append( " if exists" );
	}

	return new String[] { buf.toString() };
}
 
Example 2
private void bindLogicalToPhysical(Identifier logicalName, String physicalName) throws DuplicateMappingException {
	final String existingPhysicalNameMapping = logicalToPhysical.put( logicalName, physicalName );
	if ( existingPhysicalNameMapping != null ) {
		final boolean areSame = logicalName.isQuoted()
				? physicalName.equals( existingPhysicalNameMapping )
				: physicalName.equalsIgnoreCase( existingPhysicalNameMapping );
		if ( !areSame ) {
			throw new DuplicateMappingException(
					String.format(
							Locale.ENGLISH,
							"Table [%s] contains logical column name [%s] referring to multiple physical " +
									"column names: [%s], [%s]",
							tableName,
							logicalName,
							existingPhysicalNameMapping,
							physicalName
					),
					DuplicateMappingException.Type.COLUMN_BINDING,
					tableName + "." + logicalName
			);
		}
	}
}
 
Example 3
private void bindPhysicalToLogical(Identifier logicalName, String physicalName) throws DuplicateMappingException {
	final Identifier existingLogicalName = physicalToLogical.put( physicalName, logicalName );
	if ( existingLogicalName != null && ! existingLogicalName.equals( logicalName ) ) {
		throw new DuplicateMappingException(
				String.format(
						Locale.ENGLISH,
						"Table [%s] contains physical column name [%s] referred to by multiple physical " +
								"column names: [%s], [%s]",
						tableName,
						physicalName,
						logicalName,
						existingLogicalName
				),
				DuplicateMappingException.Type.COLUMN_BINDING,
				tableName + "." + physicalName
		);
	}
}
 
Example 4
@Override
public Table resolveTable(Identifier tableName) {
	if ( tableName == null ) {
		return primaryTable;
	}

	if ( Identifier.areEqual( primaryTableLogicalName, tableName ) ) {
		return primaryTable;
	}

	Join secondaryTableJoin = null;
	if ( secondaryTableJoinMap != null ) {
		//secondaryTableJoin = secondaryTableJoinMap.get( tableName );
		secondaryTableJoin = secondaryTableJoinMap.get( tableName.getCanonicalName() );
	}

	if ( secondaryTableJoin != null ) {
		return secondaryTableJoin.getTable();
	}

	if ( superEntityTableXref != null ) {
		return superEntityTableXref.resolveTable( tableName );
	}

	return null;
}
 
Example 5
@Override
public String format(Identifier catalog, Identifier schema, Identifier name, Dialect dialect) {
	StringBuilder buff = new StringBuilder();

	if ( catalog != null ) {
		buff.append( render( catalog, dialect ) ).append( catalogSeparator );
	}

	buff.append( render( name, dialect ) );

	return buff.toString();
}
 
Example 6
@Override
public String getLogicalColumnName(Table table, Identifier physicalName) throws MappingException {
	final String physicalNameString = physicalName.render( getDatabase().getJdbcEnvironment().getDialect() );
	Identifier logicalName = null;

	Table currentTable = table;
	while ( currentTable != null ) {
		final TableColumnNameBinding binding = columnNameBindingByTableMap.get( currentTable );

		if ( binding != null ) {
			logicalName = binding.physicalToLogical.get( physicalNameString );
			if ( logicalName != null ) {
				break;
			}
		}

		if ( DenormalizedTable.class.isInstance( currentTable ) ) {
			currentTable = ( (DenormalizedTable) currentTable ).getIncludedTable();
		}
		else {
			currentTable = null;
		}
	}

	if ( logicalName == null ) {
		throw new MappingException(
				"Unable to find column with physical name " + physicalNameString + " in table " + table.getName()
		);
	}
	return logicalName.render();
}
 
Example 7
private Identifier getIdentifier(Identifier name) {
    if (name == null) {
        return null;
    }
    return new Identifier(
            NamingStrategy.DEFAULT.mappedName(name.getText()),
            name.isQuoted()
    );
}
 
Example 8
Source Project: cia   Source File: LegacyNamingStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/**
* Convert.
*
* @param identifier
*            the identifier
* @return the identifier
*/
  private static Identifier convert(final Identifier identifier) {
  	if (identifier == null || StringUtils.isBlank(identifier.getText())) {
          return identifier;
      } else {
      	return Identifier.toIdentifier(identifier.getText().replaceAll(REG_EXPR, REPLACEMENT_PATTERN).toLowerCase(Locale.ENGLISH));
      }
  }
 
Example 9
Source Project: lams   Source File: ModelBinder.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void bindCollectionIdentifier() {
	final CollectionIdSource idSource = getPluralAttributeSource().getCollectionIdSource();
	if ( idSource != null ) {
		final IdentifierCollection idBagBinding = (IdentifierCollection) getCollectionBinding();
		final SimpleValue idBinding = new SimpleValue(
				mappingDocument,
				idBagBinding.getCollectionTable()
		);

		bindSimpleValueType(
				mappingDocument,
				idSource.getTypeInformation(),
				idBinding
		);

		relationalObjectBinder.bindColumn(
				mappingDocument,
				idSource.getColumnSource(),
				idBinding,
				false,
				new RelationalObjectBinder.ColumnNamingDelegate() {
					@Override
					public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
						return database.toIdentifier( IdentifierCollection.DEFAULT_IDENTIFIER_COLUMN_NAME );
					}
				}
		);

		idBagBinding.setIdentifier( idBinding );

		makeIdentifier(
				mappingDocument,
				new IdentifierGeneratorDefinition( idSource.getGeneratorName(), idSource.getParameters() ),
				null,
				idBinding
		);
	}
}
 
Example 10
private Identifier formatIdentifier(Identifier identifier) {
    if (identifier != null) {
        String name = identifier.getText();

        String formattedName = name.replaceAll(CAMEL_CASE_REGEX, SNAKE_CASE_PATTERN).toLowerCase();

        return !formattedName.equals(name) ?
                Identifier.toIdentifier(formattedName, identifier.isQuoted()) :
                identifier;
    } else {
        return null;
    }

}
 
Example 11
@Override
public boolean catalogExists(Identifier catalog) {
	try {
		final ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getCatalogs();

		try {
			while ( resultSet.next() ) {
				final String existingCatalogName = resultSet.getString( "TABLE_CAT" );

				// todo : hmm.. case sensitive or insensitive match...
				// for now, match any case...

				if ( catalog.getText().equalsIgnoreCase( existingCatalogName ) ) {
					return true;
				}
			}

			return false;
		}
		finally {
			try {
				resultSet.close();
			}
			catch (SQLException ignore) {
			}
		}
	}
	catch (SQLException sqlException) {
		throw convertSQLException( sqlException, "Unable to query DatabaseMetaData for existing catalogs" );
	}
}
 
Example 12
private Identifier formatIdentifier(Identifier identifier) {
    if (identifier != null) {
        String name = identifier.getText();

        String formattedName = name.replaceAll(CAMEL_CASE_REGEX, SNAKE_CASE_PATTERN).toLowerCase();

        return !formattedName.equals(name) ?
                Identifier.toIdentifier(formattedName, identifier.isQuoted()) :
                identifier;
    } else {
        return null;
    }

}
 
Example 13
public DuplicateSecondaryTableException(Identifier tableName) {
	super(
			String.format(
					Locale.ENGLISH,
					"Table with that name [%s] already associated with entity",
					tableName.render()
			)
	);
	this.tableName = tableName;
}
 
Example 14
Source Project: lams   Source File: Namespace.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a mapping Table instance.
 *
 * @param logicalTableName The logical table name
 *
 * @return the created table.
 */
public Table createTable(Identifier logicalTableName, boolean isAbstract) {
	final Table existing = tables.get( logicalTableName );
	if ( existing != null ) {
		return existing;
	}

	final Identifier physicalTableName = database.getPhysicalNamingStrategy().toPhysicalTableName( logicalTableName, database.getJdbcEnvironment() );
	Table table = new Table( this, physicalTableName, isAbstract );
	tables.put( logicalTableName, table );
	return table;
}
 
Example 15
@Override
public Table addTable(
		String schemaName,
		String catalogName,
		String name,
		String subselectFragment,
		boolean isAbstract) {
	final Namespace namespace = getDatabase().locateNamespace(
			getDatabase().toIdentifier( catalogName ),
			getDatabase().toIdentifier( schemaName )
	);

	// annotation binding depends on the "table name" for @Subselect bindings
	// being set into the generated table (mainly to avoid later NPE), but for now we need to keep that :(
	final Identifier logicalName;
	if ( name != null ) {
		logicalName = getDatabase().toIdentifier( name );
	}
	else {
		logicalName = null;
	}

	if ( subselectFragment != null ) {
		return new Table( namespace, logicalName, subselectFragment, isAbstract );
	}
	else {
		Table table = namespace.locateTable( logicalName );
		if ( table != null ) {
			if ( !isAbstract ) {
				table.setAbstract( false );
			}
			return table;
		}
		return namespace.createTable( logicalName, isAbstract );
	}
}
 
Example 16
@Override
public String format(Identifier catalog, Identifier schema, Identifier name, Dialect dialect) {
	StringBuilder buff = new StringBuilder();
	if ( schema != null ) {
		buff.append( render( schema, dialect ) ).append( '.' );
	}

	buff.append( render( name, dialect ) );

	if ( catalog != null ) {
		buff.append( catalogSeparator ).append( render( catalog, dialect ) );
	}

	return buff.toString();
}
 
Example 17
Source Project: lams   Source File: Database.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Namespace locateNamespace(Identifier catalogName, Identifier schemaName) {
	if ( catalogName == null && schemaName == null ) {
		return getDefaultNamespace();
	}

	final Namespace.Name name = new Namespace.Name( catalogName, schemaName );
	Namespace namespace = namespaceMap.get( name );
	if ( namespace == null ) {
		namespace = makeNamespace( name );
	}
	return namespace;
}
 
Example 18
Source Project: lams   Source File: Ejb3JoinColumn.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void setJoinAnnotation(JoinColumn annJoin, String defaultName) {
	if ( annJoin == null ) {
		setImplicit( true );
	}
	else {
		setImplicit( false );
		if ( !BinderHelper.isEmptyAnnotationValue( annJoin.columnDefinition() ) ) {
			setSqlType( getBuildingContext().getObjectNameNormalizer().applyGlobalQuoting( annJoin.columnDefinition() ) );
		}
		if ( !BinderHelper.isEmptyAnnotationValue( annJoin.name() ) ) {
			setLogicalColumnName( annJoin.name() );
		}
		setNullable( annJoin.nullable() );
		setUnique( annJoin.unique() );
		setInsertable( annJoin.insertable() );
		setUpdatable( annJoin.updatable() );
		setReferencedColumn( annJoin.referencedColumnName() );

		if ( BinderHelper.isEmptyAnnotationValue( annJoin.table() ) ) {
			setExplicitTableName( "" );
		}
		else {
			final Identifier logicalIdentifier = getBuildingContext().getMetadataCollector()
					.getDatabase()
					.toIdentifier( annJoin.table() );
			final Identifier physicalIdentifier = getBuildingContext().getBuildingOptions()
					.getPhysicalNamingStrategy()
					.toPhysicalTableName( logicalIdentifier, getBuildingContext().getMetadataCollector().getDatabase().getJdbcEnvironment() );
			setExplicitTableName(
					physicalIdentifier.render( getBuildingContext().getMetadataCollector().getDatabase().getDialect() )
			);
		}
	}
}
 
Example 19
public ImprovedExtractionContextImpl(
		ServiceRegistry serviceRegistry,
		JdbcEnvironment jdbcEnvironment,
		DdlTransactionIsolator ddlTransactionIsolator,
		Identifier defaultCatalog,
		Identifier defaultSchema,
		DatabaseObjectAccess databaseObjectAccess) {
	this.serviceRegistry = serviceRegistry;
	this.jdbcEnvironment = jdbcEnvironment;
	this.ddlTransactionIsolator = ddlTransactionIsolator;
	this.defaultCatalog = defaultCatalog;
	this.defaultSchema = defaultSchema;
	this.databaseObjectAccess = databaseObjectAccess;
}
 
Example 20
@Override
public String getLogicalTableName(Table ownerTable) {
	final Identifier logicalName = physicalToLogicalTableNameMap.get( ownerTable.getNameIdentifier() );
	if ( logicalName == null ) {
		throw new MappingException( "Unable to find physical table: " + ownerTable.getName() );
	}
	return logicalName.render();
}
 
Example 21
Source Project: lams   Source File: TableStructure.java    License: GNU General Public License v2.0 5 votes vote down vote up
public TableStructure(
		JdbcEnvironment jdbcEnvironment,
		QualifiedName qualifiedTableName,
		Identifier valueColumnNameIdentifier,
		int initialValue,
		int incrementSize,
		Class numberType) {
	this.logicalQualifiedTableName = qualifiedTableName;
	this.logicalValueColumnNameIdentifier = valueColumnNameIdentifier;

	this.initialValue = initialValue;
	this.incrementSize = incrementSize;
	this.numberType = numberType;
}
 
Example 22
Source Project: lams   Source File: DatabaseInformationImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public SequenceInformation getSequenceInformation(
		Identifier catalogName,
		Identifier schemaName,
		Identifier sequenceName) {
	return getSequenceInformation( new QualifiedSequenceName( catalogName, schemaName, sequenceName ) );
}
 
Example 23
Source Project: lams   Source File: AbstractSchemaMigrator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if the ForeignKey already exists. First check based on definition and if that is not matched check if a key
 * with the exact same name exists. Keys with the same name are presumed to be functional equal.
 * 
 * @param foreignKey - ForeignKey, new key to be created
 * @param tableInformation - TableInformation, information of existing keys
 * @return boolean, true if key already exists
 */
private boolean checkForExistingForeignKey(ForeignKey foreignKey, TableInformation tableInformation) {
	if ( foreignKey.getName() == null || tableInformation == null ) {
		return false;
	}

	final String referencingColumn = foreignKey.getColumn( 0 ).getName();
	final String referencedTable = foreignKey.getReferencedTable().getName();

	/*
	 * Find existing keys based on referencing column and referencedTable. "referencedColumnName" is not checked
	 * because that always is the primary key of the "referencedTable".
	 */
	Predicate<ColumnReferenceMapping> mappingPredicate = m -> {
		String existingReferencingColumn = m.getReferencingColumnMetadata().getColumnIdentifier().getText();
		String existingReferencedTable = m.getReferencedColumnMetadata().getContainingTableInformation().getName().getTableName().getCanonicalName();
		return referencingColumn.equals( existingReferencingColumn ) && referencedTable.equals( existingReferencedTable );
	};
	Stream<ForeignKeyInformation> keyStream = StreamSupport.stream( tableInformation.getForeignKeys().spliterator(), false );
	Stream<ColumnReferenceMapping> mappingStream = keyStream.flatMap( k -> StreamSupport.stream( k.getColumnReferenceMappings().spliterator(), false ) );
	boolean found = mappingStream.anyMatch( mappingPredicate );
	if ( found ) {
		return true;
	}

	// And at the end just compare the name of the key. If a key with the same name exists we assume the function is
	// also the same...
	return tableInformation.getForeignKey( Identifier.toIdentifier( foreignKey.getName() ) ) != null;
}
 
Example 24
Source Project: lams   Source File: EntityBinder.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Identifier handleExplicitName(String explicitName, MetadataBuildingContext buildingContext) {
	return buildingContext.getMetadataCollector()
			.getDatabase()
			.getJdbcEnvironment()
			.getIdentifierHelper()
			.toIdentifier( explicitName );
}
 
Example 25
Source Project: lams   Source File: Ejb3Column.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void addColumnBinding(SimpleValue value) {
	final String logicalColumnName;
	if ( StringHelper.isNotEmpty( this.logicalColumnName ) ) {
		logicalColumnName = this.logicalColumnName;
	}
	else {
		final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer();
		final Database database = context.getMetadataCollector().getDatabase();
		final ImplicitNamingStrategy implicitNamingStrategy = context.getBuildingOptions()
				.getImplicitNamingStrategy();

		final Identifier implicitName = normalizer.normalizeIdentifierQuoting(
				implicitNamingStrategy.determineBasicColumnName(
						new ImplicitBasicColumnNameSource() {
							@Override
							public AttributePath getAttributePath() {
								return AttributePath.parse( propertyName );
							}

							@Override
							public boolean isCollectionElement() {
								return false;
							}

							@Override
							public MetadataBuildingContext getBuildingContext() {
								return context;
							}
						}
				)
		);
		logicalColumnName = implicitName.render( database.getDialect() );
	}
	context.getMetadataCollector().addColumnNameBinding( value.getTable(), logicalColumnName, getMappingColumn() );
}
 
Example 26
Source Project: lams   Source File: TableInformationImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public IndexInformation getIndex(Identifier indexName) {
	return indexes().get( new Identifier(
			identifierHelper.toMetaDataObjectName( indexName ),
			false
	) );
}
 
Example 27
Source Project: lams   Source File: TableGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine the table name to use for the generator values.
 * <p/>
 * Called during {@link #configure configuration}.
 *
 * @see #getTableName()
 * @param params The params supplied in the generator config (plus some standard useful extras).
 * @param jdbcEnvironment The JDBC environment
 * @return The table name to use.
 */
@SuppressWarnings({"UnusedParameters", "WeakerAccess"})
protected QualifiedName determineGeneratorTableName(Properties params, JdbcEnvironment jdbcEnvironment, ServiceRegistry serviceRegistry) {

	String fallbackTableName = DEF_TABLE;

	final Boolean preferGeneratorNameAsDefaultName = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( AvailableSettings.PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME, StandardConverters.BOOLEAN, true );
	if ( preferGeneratorNameAsDefaultName ) {
		final String generatorName = params.getProperty( IdentifierGenerator.GENERATOR_NAME );
		if ( StringHelper.isNotEmpty( generatorName ) ) {
			fallbackTableName = generatorName;
		}
	}


	String tableName = ConfigurationHelper.getString( TABLE_PARAM, params, fallbackTableName );

	if ( tableName.contains( "." ) ) {
		return QualifiedNameParser.INSTANCE.parse( tableName );
	}
	else {
		// todo : need to incorporate implicit catalog and schema names
		final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( CATALOG, params )
		);
		final Identifier schema = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( SCHEMA, params )
		);
		return new QualifiedNameParser.NameParts(
				catalog,
				schema,
				jdbcEnvironment.getIdentifierHelper().toIdentifier( tableName )
		);
	}
}
 
Example 28
Source Project: lams   Source File: Table.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean equals(Table table) {
	if (null == table) {
		return false;
	}
	if (this == table) {
		return true;
	}

	return Identifier.areEqual( name, table.name )
			&& Identifier.areEqual( schema, table.schema )
			&& Identifier.areEqual( catalog, table.catalog );
}
 
Example 29
private String determineCatalogFilter(Identifier catalog) throws SQLException {
	Identifier identifierToUse = catalog;
	if ( identifierToUse == null ) {
		identifierToUse = extractionContext.getDefaultCatalog();
	}

	return extractionContext.getJdbcEnvironment().getIdentifierHelper().toMetaDataCatalogName( identifierToUse );
}
 
Example 30
Source Project: WeBASE-Collect-Bee   Source File: DatabaseNamingStrategy.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Identifier toPhysicalCatalogName(Identifier identifier, JdbcEnvironment jdbcEnvironment) {
    return identifier;
}