Java Code Examples for org.hibernate.mapping.Column

The following are top voted examples for showing how to use org.hibernate.mapping.Column. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Equella   File: ExtendedOracle10gDialect.java   View source code 6 votes vote down vote up
@Override
public String getModifyColumnSql(Mapping mapping, Column column, boolean changeNotNull, boolean changeType)
{
	String columnName = column.getQuotedName(this);

	String nullStr = "";
	if( changeNotNull )
	{
		nullStr = column.isNullable() ? " NULL" : " NOT NULL";
	}
	String typeStr = "";
	if( changeType )
	{
		typeStr = ' ' + column.getSqlType(this, mapping);
	}

	return "MODIFY (" + columnName + typeStr + nullStr + ")";
}
 
Example 2
Project: Equella   File: ExtendedPostgresDialect.java   View source code 6 votes vote down vote up
@Override
public String getModifyColumnSql(Mapping mapping, Column column, boolean changeNotNull, boolean changeType)
{
	StringBuilder sbuf = new StringBuilder();
	String columnName = column.getQuotedName(this);

	if( changeNotNull )
	{
		sbuf.append("ALTER COLUMN ");
		sbuf.append(columnName).append(' ');
		sbuf.append(column.isNullable() ? "DROP" : "SET");
		sbuf.append(" NOT NULL");
	}
	if( changeType )
	{
		if( changeNotNull )
		{
			sbuf.append(", ");
		}
		sbuf.append("ALTER COLUMN ");
		sbuf.append(columnName).append(" TYPE ").append(column.getSqlType(this, mapping));
	}
	return sbuf.toString();
}
 
Example 3
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void addIndexSQL(List<String> sqlStrings, Table table, Set<Column> colSet)
{
	Iterator<Index> indexIterator = table.getIndexIterator();
	while( indexIterator.hasNext() )
	{
		Index index = indexIterator.next();
		Iterator<Column> colIter = index.getColumnIterator();
		boolean found = false;
		while( colIter.hasNext() )
		{
			Column col = colIter.next();
			if( colSet.contains(col) )
			{
				found = true;
				break;
			}
		}
		if( found && (!extDialect.supportsAutoIndexForUniqueColumn() || !hasUniqueIndex(index, table)) )
		{
			sqlStrings.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
		}
	}
}
 
Example 4
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean hasUniqueIndex(Index index, Table table)
{
	HashSet<Column> indexCols = new HashSet<Column>();
	Iterator<Column> icolIter = index.getColumnIterator();
	while( icolIter.hasNext() )
	{
		Column col = icolIter.next();
		indexCols.add(col);
		if( index.getColumnSpan() == 1 && table.getColumn(col).isUnique() )
		{
			return true;
		}
	}
	Iterator<UniqueKey> iter = table.getUniqueKeyIterator();
	while( iter.hasNext() )
	{
		UniqueKey uk = iter.next();
		if( uk.getColumnSpan() == indexCols.size() && indexCols.containsAll(uk.getColumns()) )
		{
			return true;
		}
	}
	return false;
}
 
Example 5
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
/**
 * @param tableName
 * @param columnName
 * @param changeNotNull
 * @param nullable Pass in null to use the annotation on the column. This is
 *            not always possible (see Redmine #3329).
 * @param changeType
 * @return
 */
public List<String> getModifyColumnSQL(String tableName, String columnName, boolean changeNotNull,
	boolean changeType)
{
	List<String> sqlStrings = new ArrayList<String>();

	Table table = findTable(tableName);
	Column column = table.getColumn(new Column(columnName));

	StringBuffer alter = new StringBuffer("alter table ")
		.append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ')
		.append(extDialect.getModifyColumnSql(mapping, column, changeNotNull, changeType));

	sqlStrings.add(alter.toString());
	return sqlStrings;
}
 
Example 6
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
public List<String> getDropColumnSQL(String tableName, String... columns)
{
	List<String> sqlStrings = new ArrayList<String>();

	Table table = findTable(tableName);
	for( String columnName : columns )
	{
		Column column = table.getColumn(new Column(columnName));
		if( column == null )
		{
			throw new RuntimeException("Could not find column " + columnName + " on table " + tableName);
		}
		sqlStrings.add(extDialect.getDropColumnSql(table.getQualifiedName(dialect, defaultCatalog, defaultSchema),
			column));
	}
	return sqlStrings;
}
 
Example 7
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
public List<String> getAddNotNullSQL(String tableName, String... columns)
{
	List<String> sqlStrings = new ArrayList<String>();

	Table table = findTable(tableName);
	for( String columnName : columns )
	{
		Column column = table.getColumn(new Column(columnName));

		StringBuffer alter = new StringBuffer("alter table ")
			.append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ')
			.append(extDialect.getAddNotNullSql(mapping, column));
		sqlStrings.add(alter.toString());
	}
	return sqlStrings;
}
 
Example 8
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
public Collection<? extends String> getAddIndexesRawIfRequired(Session session, String tableName,
	String[]... indexes)
{
	List<String> sqlStrings = new ArrayList<String>();
	final Table table = findTable(tableName);
	Map<Set<String>, String> revIndexMap = getExistingIndexes(table, session);
	for( String[] index : indexes )
	{
		Index indexObj = new Index();
		indexObj.setTable(table);
		indexObj.setName(index[0]);
		for( int i = 1; i < index.length; i++ )
		{
			Column col = new Column(index[i]);
			indexObj.addColumn(col);
		}
		processIndex(table, indexObj, revIndexMap, sqlStrings);
	}
	return sqlStrings;
}
 
Example 9
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
public Collection<? extends String> getAddIndexesRaw(String tableName, String[]... indexes)
{
	List<String> sqlStrings = new ArrayList<String>();
	final Table table = findTable(tableName);
	for( String[] index : indexes )
	{
		Index indexObj = new Index();
		indexObj.setTable(table);
		indexObj.setName(index[0]);
		for( int i = 1; i < index.length; i++ )
		{
			Column col = new Column(index[i]);
			indexObj.addColumn(col);
		}
		sqlStrings.add(indexObj.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
	}
	return sqlStrings;
}
 
Example 10
Project: Equella   File: HibernateMigrationHelper.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void processIndex(Table table, Index index, Map<Set<String>, String> revIndexMap, List<String> sqlStrings)
{
	Iterator<Column> colIter = index.getColumnIterator();
	Set<String> indexCols = new HashSet<String>();
	while( colIter.hasNext() )
	{
		Column col = colIter.next();
		indexCols.add(col.getName().toLowerCase());
	}
	String existingIndex = revIndexMap.get(indexCols);
	if( existingIndex != null )
	{
		if( existingIndex.equalsIgnoreCase(index.getName()) )
		{
			return;
		}
		else
		{
			sqlStrings.add(extDialect.getDropIndexSql(table.getName(), '`' + existingIndex + '`'));
		}
	}
	sqlStrings.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
}
 
Example 11
Project: lams   File: IndexOrUniqueKeySecondPass.java   View source code 6 votes vote down vote up
private void addConstraintToColumn(final String columnName ) {
	Column column = table.getColumn(
			new Column(
					mappings.getPhysicalColumnName( columnName, table )
			)
	);
	if ( column == null ) {
		throw new AnnotationException(
				"@Index references a unknown column: " + columnName
		);
	}
	if ( unique )
		table.getOrCreateUniqueKey( indexName ).addColumn( column );
	else
		table.getOrCreateIndex( indexName ).addColumn( column );
}
 
Example 12
Project: lams   File: Configuration.java   View source code 6 votes vote down vote up
private void bindLogicalToPhysical(String logicalName, Column physicalColumn) throws DuplicateMappingException {
	final String logicalKey = logicalName.toLowerCase();
	final String physicalName = physicalColumn.getQuotedName();
	final String existingPhysicalName = ( String ) logicalToPhysical.put( logicalKey, physicalName );
	if ( existingPhysicalName != null ) {
		boolean areSamePhysicalColumn = physicalColumn.isQuoted()
				? existingPhysicalName.equals( physicalName )
				: existingPhysicalName.equalsIgnoreCase( physicalName );
		if ( ! areSamePhysicalColumn ) {
			throw new DuplicateMappingException(
					" Table [" + tableName + "] contains logical column name [" + logicalName
							+ "] referenced by multiple physical column names: [" + existingPhysicalName
							+ "], [" + physicalName + "]",
					"column-binding",
					tableName + "." + logicalName
			);
		}
	}
}
 
Example 13
Project: lams   File: BinderHelper.java   View source code 6 votes vote down vote up
private static void matchColumnsByProperty(Property property, Map<Column, Set<Property>> columnsToProperty) {
		if ( property == null ) return;
		if ( "noop".equals( property.getPropertyAccessorName() )
				|| "embedded".equals( property.getPropertyAccessorName() ) ) {
			return;
		}
// FIXME cannot use subproperties becasue the caller needs top level properties
//		if ( property.isComposite() ) {
//			Iterator subProperties = ( (Component) property.getValue() ).getPropertyIterator();
//			while ( subProperties.hasNext() ) {
//				matchColumnsByProperty( (Property) subProperties.next(), columnsToProperty );
//			}
//		}
		else {
			Iterator columnIt = property.getColumnIterator();
			while ( columnIt.hasNext() ) {
				Object column = columnIt.next(); //can be a Formula so we don't cast
				//noinspection SuspiciousMethodCalls
				if ( columnsToProperty.containsKey( column ) ) {
					columnsToProperty.get( column ).add( property );
				}
			}
		}
	}
 
Example 14
Project: lams   File: Ejb3JoinColumn.java   View source code 6 votes vote down vote up
public void linkValueUsingDefaultColumnNaming(
		Column referencedColumn,
		PersistentClass referencedEntity,
		SimpleValue value) {
	String columnName;
	String logicalReferencedColumn = getMappings().getLogicalColumnName(
			referencedColumn.getQuotedName(), referencedEntity.getTable()
	);
	columnName = buildDefaultColumnName( referencedEntity, logicalReferencedColumn );
	//yuk side effect on an implicit column
	setLogicalColumnName( columnName );
	setReferencedColumn( logicalReferencedColumn );
	initMappingColumn(
			columnName,
			null, referencedColumn.getLength(),
			referencedColumn.getPrecision(),
			referencedColumn.getScale(),
			getMappingColumn() != null ? getMappingColumn().isNullable() : false,
			referencedColumn.getSqlType(),
			getMappingColumn() != null ? getMappingColumn().isUnique() : false,
		    false
	);
	linkWithValue( value );
}
 
Example 15
Project: lams   File: Ejb3JoinColumn.java   View source code 6 votes vote down vote up
/**
 * Called to apply column definitions from the referenced FK column to this column.
 *
 * @param column the referenced column.
 */
public void overrideFromReferencedColumnIfNecessary(org.hibernate.mapping.Column column) {
	if (getMappingColumn() != null) {
		// columnDefinition can also be specified using @JoinColumn, hence we have to check
		// whether it is set or not
		if ( StringHelper.isEmpty( sqlType ) ) {
			sqlType = column.getSqlType();
			getMappingColumn().setSqlType( sqlType );
		}

		// these properties can only be applied on the referenced column - we can just take them over
		getMappingColumn().setLength(column.getLength());
		getMappingColumn().setPrecision(column.getPrecision());
		getMappingColumn().setScale(column.getScale());
	}
}
 
Example 16
Project: lams   File: TableBinder.java   View source code 6 votes vote down vote up
public static void linkJoinColumnWithValueOverridingNameIfImplicit(
		PersistentClass referencedEntity,
		Iterator columnIterator,
		Ejb3JoinColumn[] columns,
		SimpleValue value) {
	for (Ejb3JoinColumn joinCol : columns) {
		Column synthCol = (Column) columnIterator.next();
		if ( joinCol.isNameDeferred() ) {
			//this has to be the default value
			joinCol.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value );
		}
		else {
			joinCol.linkWithValue( value );
			joinCol.overrideFromReferencedColumnIfNecessary( synthCol );
		}
	}
}
 
Example 17
Project: lams   File: ForeignKeyMetadata.java   View source code 6 votes vote down vote up
public boolean matches(ForeignKey fk) {
	if ( refTable.equalsIgnoreCase( fk.getReferencedTable().getName() ) ) {
		if ( fk.getColumnSpan() == references.size() ) {
			List fkRefs;
			if ( fk.isReferenceToPrimaryKey() ) {
				fkRefs = fk.getReferencedTable().getPrimaryKey().getColumns();
			}
			else {
				fkRefs = fk.getReferencedColumns();
			}
			for ( int i = 0; i < fk.getColumnSpan(); i++ ) {
				Column column = fk.getColumn( i );
				Column ref = ( Column ) fkRefs.get( i );
				if ( !hasReference( column, ref ) ) {
					return false;
				}
			}
			return true;
		}
	}
	return false;
}
 
Example 18
Project: lams   File: PersistentTableBulkIdStrategy.java   View source code 6 votes vote down vote up
protected Table generateIdTableDefinition(PersistentClass entityMapping) {
	Table idTable = new Table( entityMapping.getTemporaryIdTableName() );
	if ( catalog != null ) {
		idTable.setCatalog( catalog );
	}
	if ( schema != null ) {
		idTable.setSchema( schema );
	}
	Iterator itr = entityMapping.getTable().getPrimaryKey().getColumnIterator();
	while( itr.hasNext() ) {
		Column column = (Column) itr.next();
		idTable.addColumn( column.clone()  );
	}
	Column sessionIdColumn = new Column( "hib_sess_id" );
	sessionIdColumn.setSqlType( "CHAR(36)" );
	sessionIdColumn.setComment( "Used to hold the Hibernate Session identifier" );
	idTable.addColumn( sessionIdColumn );

	idTable.setComment( "Used to hold id values for the " + entityMapping.getEntityName() + " class" );
	return idTable;
}
 
Example 19
Project: hibernate-ogm-ignite   File: IgniteCacheInitializer.java   View source code 6 votes vote down vote up
private String fieldType(Column currentColumn) {
	TypeTranslator translator = serviceRegistry.getService( TypeTranslator.class );
	Type valueType = currentColumn.getValue().getType();
	GridType gridType = translator.getType( valueType );
	if ( gridType instanceof EnumType ) {
		return enumFieldType( (EnumType) gridType );
	}
	if ( gridType instanceof YesNoType ) {
		return STRING_CLASS_NAME;
	}
	if ( gridType instanceof NumericBooleanType ) {
		return INTEGER_CLASS_NAME;
	}
	Class<?> returnedClass = valueType.getReturnedClass();
	if ( Character.class.equals( returnedClass ) ) {
		return STRING_CLASS_NAME;
	}
	return returnedClass.getName();
}
 
Example 20
Project: cacheonix-core   File: HbmBinder.java   View source code 6 votes vote down vote up
public static void bindColumn(Element node, Column column, boolean isNullable) {
	Attribute lengthNode = node.attribute( "length" );
	if ( lengthNode != null ) column.setLength( Integer.parseInt( lengthNode.getValue() ) );
	Attribute scalNode = node.attribute( "scale" );
	if ( scalNode != null ) column.setScale( Integer.parseInt( scalNode.getValue() ) );
	Attribute precNode = node.attribute( "precision" );
	if ( precNode != null ) column.setPrecision( Integer.parseInt( precNode.getValue() ) );

	Attribute nullNode = node.attribute( "not-null" );
	column.setNullable( nullNode == null ? isNullable : nullNode.getValue().equals( "false" ) );

	Attribute unqNode = node.attribute( "unique" );
	if ( unqNode != null ) column.setUnique( unqNode.getValue().equals( "true" ) );

	column.setCheckConstraint( node.attributeValue( "check" ) );
	column.setDefaultValue( node.attributeValue( "default" ) );

	Attribute typeNode = node.attribute( "sql-type" );
	if ( typeNode != null ) column.setSqlType( typeNode.getValue() );

	Element comment = node.element("comment");
	if (comment!=null) column.setComment( comment.getTextTrim() );

}
 
Example 21
Project: cacheonix-core   File: PropertyRefTest.java   View source code 6 votes vote down vote up
public void testForeignKeyCreation() {
	PersistentClass classMapping = getCfg().getClassMapping("org.hibernate.test.propertyref.basic.Account");
	
	Iterator foreignKeyIterator = classMapping.getTable().getForeignKeyIterator();
	boolean found = false;
	while ( foreignKeyIterator.hasNext() ) {
		ForeignKey element = (ForeignKey) foreignKeyIterator.next();
		if(element.getReferencedEntityName().equals(Person.class.getName() ) ) {
			
			if(!element.isReferenceToPrimaryKey() ) {
				List referencedColumns = element.getReferencedColumns();
				Column column = (Column) referencedColumns.get(0);
				if(column.getName().equals("person_userid") ) {
					found = true; // extend test to include the columns
				}				
			}
		}
	}
	
	assertTrue("Property ref foreign key not found",found);
}
 
Example 22
Project: greenpepper   File: AbstractDBUnitHibernateMemoryTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected String[] getColumnNames( Class peristentClass, String[] includedFields )
        throws MappingException
{
    Collection columns = new ArrayList();
    for ( int i = 0; i < includedFields.length; i++ )
    {
        String propertyName = includedFields[i];
        Property property = getMapping( peristentClass ).getProperty( propertyName );

        for ( Iterator it = property.getColumnIterator(); it.hasNext(); )
        {
            Column col = ( Column ) it.next();
            columns.add( col.getName() );
        }
    }
    return ( String[] ) columns.toArray( new String[columns.size()] );
}
 
Example 23
Project: Portofino   File: HibernateConfig.java   View source code 6 votes vote down vote up
protected void setPKColumnGenerator(Mappings mappings, RootClass clazz, Table tab, com.manydesigns.portofino.model.database.Column column, SimpleValue id, Generator generator) {
    if (column.isAutoincrement()) {
        manageIdentityGenerator(mappings, tab, id);
    } else if (generator != null) {
        if (generator instanceof SequenceGenerator) {
            manageSequenceGenerator(mappings, tab, id, (SequenceGenerator) generator);
        } else if (generator instanceof
                            com.manydesigns.portofino.model.database.TableGenerator) {
            manageTableGenerator(mappings, tab, id,
                    (com.manydesigns.portofino.model.database.TableGenerator) generator);
        } else if (generator instanceof
                            com.manydesigns.portofino.model.database.IncrementGenerator){
            manageIncrementGenerator(mappings, tab, id, clazz.getEntityName());
        }
    }
}
 
Example 24
Project: high-performance-java-persistence   File: MetadataTest.java   View source code 6 votes vote down vote up
@Test
public void testEntityToDatabaseBindingMetadata() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();

    for ( PersistentClass persistentClass : metadata.getEntityBindings()) {
        Table table = persistentClass.getTable();
        LOGGER.info( "Entity: {} is mapped to table: {}",
                     persistentClass.getClassName(),
                     table.getName()
        );

        for(Iterator propertyIterator =
                persistentClass.getPropertyIterator(); propertyIterator.hasNext(); ) {
            Property property = (Property) propertyIterator.next();
            for(Iterator columnIterator =
                    property.getColumnIterator(); columnIterator.hasNext(); ) {
                Column column = (Column) columnIterator.next();
                LOGGER.info( "Property: {} is mapped on table column: {} of type: {}",
                             property.getName(),
                             column.getName(),
                             column.getSqlType()
                );
            }
        }
    }
}
 
Example 25
Project: hibernate-conventions   File: MappingConventions.java   View source code 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private void normalizeColumns(Table table, String entityName) {

	Iterator iterator = table.getColumnIterator();
	while (iterator.hasNext()) {

		Column column = (Column) iterator.next();

		String name = strategy.columnName(column.getName());
		String sqlType = strategy.sqlType(table.getName(), column.getSqlType());
		int sqlPrecision = strategy.sqlPrecision(table.getName(), column.getSqlType(), column.getPrecision());
		int sqlScale = strategy.sqlScale(table.getName(), column.getSqlType(), column.getScale());

		column.setName(name);
		column.setSqlType(sqlType);
		column.setPrecision(sqlPrecision);
		column.setScale(sqlScale);

	}

}
 
Example 26
Project: greenpepper3   File: AbstractDBUnitHibernateMemoryTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected String[] getColumnNames( Class peristentClass, String[] includedFields )
        throws MappingException
{
    Collection columns = new ArrayList();
    for ( int i = 0; i < includedFields.length; i++ )
    {
        String propertyName = includedFields[i];
        Property property = getMapping( peristentClass ).getProperty( propertyName );

        for ( Iterator it = property.getColumnIterator(); it.hasNext(); )
        {
            Column col = ( Column ) it.next();
            columns.add( col.getName() );
        }
    }
    return ( String[] ) columns.toArray( new String[columns.size()] );
}
 
Example 27
Project: manydesigns.cn   File: HibernateConfig.java   View source code 6 votes vote down vote up
protected void setPKColumnGenerator(Mappings mappings, RootClass clazz, Table tab, com.manydesigns.portofino.model.database.Column column, SimpleValue id, Generator generator) {
    if (column.isAutoincrement()) {
        manageIdentityGenerator(mappings, tab, id);
    } else if (generator != null) {
        if (generator instanceof SequenceGenerator) {
            manageSequenceGenerator(mappings, tab, id, (SequenceGenerator) generator);
        } else if (generator instanceof
                            com.manydesigns.portofino.model.database.TableGenerator) {
            manageTableGenerator(mappings, tab, id,
                    (com.manydesigns.portofino.model.database.TableGenerator) generator);
        } else if (generator instanceof
                            com.manydesigns.portofino.model.database.IncrementGenerator){
            manageIncrementGenerator(mappings, tab, id, clazz.getEntityName());
        }
    }
}
 
Example 28
Project: ODataSync   File: ForeignKeyMetadata.java   View source code 6 votes vote down vote up
public boolean matches(ForeignKey fk) {
    if (refTable.equalsIgnoreCase(fk.getReferencedTable().getName())) {
        if (fk.getColumnSpan() == references.size()) {
            List fkRefs;
            if (fk.isReferenceToPrimaryKey()) {
                fkRefs = fk.getReferencedTable().getPrimaryKey().getColumns();
            } else {
                fkRefs = fk.getReferencedColumns();
            }

            for (int i = 0; i < fk.getColumnSpan(); i++) {
                Column column = fk.getColumn(i);
                Column ref = (Column)fkRefs.get(i);
                if (!hasReference(column, ref)) {
                    return false;
                }
            }

            return false;
        }
    }

    return false;
}
 
Example 29
Project: debop4j   File: DatastoreProviderGeneratingSchema.java   View source code 6 votes vote down vote up
@Override
public void start(Configuration configuration, SessionFactoryImplementor sessionFactoryImplementor) {
    Iterator<Table> tables = configuration.getTableMappings();
    while (tables.hasNext()) {
        Table table = tables.next();
        if (table.isPhysicalTable()) {
            String tableName = table.getQuotedName();
            // do something with table
            Iterator<Column> columns = (Iterator<Column>) table.getColumnIterator();
            while (columns.hasNext()) {
                Column column = columns.next();
                String columnName = column.getCanonicalName();
                // do something with column
            }
            //TODO handle unique constraints?
        }
    }
    throw new RuntimeException("STARTED!");
}
 
Example 30
Project: Equella   File: SQLServerDialect.java   View source code 5 votes vote down vote up
@Override
public String getModifyColumnSql(Mapping mapping, Column column, boolean changeNotNull, boolean changeType)
{
	String columnName = column.getQuotedName(this);
	String nullStr = column.isNullable() ? " NULL" : " NOT NULL";
	String typeStr = ' ' + column.getSqlType(this, mapping);
	return "ALTER COLUMN " + columnName + typeStr + nullStr;
}
 
Example 31
Project: Equella   File: SQLServerDialect.java   View source code 5 votes vote down vote up
@Override
public String getAddNotNullSql(Mapping mapping, Column column)
{
	String columnName = column.getQuotedName(this);

	String typeStr = ' ' + column.getSqlType(this, mapping);
	return "ALTER COLUMN " + columnName + typeStr + " NOT NULL";
}
 
Example 32
Project: Equella   File: SQLServerDialect.java   View source code 5 votes vote down vote up
@Override
public String getDropColumnSql(String table, Column column)
{
	String dropSQL = dropConstraintsSQL.replaceAll("\\$table", Matcher.quoteReplacement(table));
	dropSQL = dropSQL.replaceAll("\\$column", Matcher.quoteReplacement(column.getName()));
	return dropSQL + "\nalter table " + table + " drop column " + column.getQuotedName(this);
}
 
Example 33
Project: Equella   File: HibernateMigrationHelper.java   View source code 5 votes vote down vote up
public List<String> getAddColumnsSQL(String tableName, String... columnNames)
{
	List<String> sqlStrings = new ArrayList<String>();

	Table table = findTable(tableName);
	for( String columnName : columnNames )
	{
		Column column = table.getColumn(new Column(columnName));

		StringBuffer alter = new StringBuffer("alter table ")
			.append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ')
			.append(dialect.getAddColumnString());
		alter.append(' ').append(column.getQuotedName(dialect)).append(' ')
			.append(column.getSqlType(dialect, mapping));

		boolean useUniqueConstraint = extDialect.supportsModifyWithConstraints() && column.isUnique()
			&& dialect.supportsUnique() && (!column.isNullable() || dialect.supportsNotNullUnique());
		if( useUniqueConstraint )
		{
			alter.append(" unique");
		}
		if( column.hasCheckConstraint() && dialect.supportsColumnCheck() )
		{
			alter.append(" check(").append(column.getCheckConstraint()).append(")");
		}

		String columnComment = column.getComment();
		if( columnComment != null )
		{
			alter.append(dialect.getColumnComment(columnComment));
		}
		sqlStrings.add(alter.toString());
	}
	return sqlStrings;
}
 
Example 34
Project: Equella   File: HibernateMigrationHelper.java   View source code 5 votes vote down vote up
public List<String> getAddIndexesForColumns(String tableName, String... columnNames)
{
	Set<Column> colSet = new HashSet<Column>();
	for( String columnName : columnNames )
	{
		colSet.add(new Column(columnName));
	}
	List<String> sqlStrings = new ArrayList<String>();

	Table table = findTable(tableName);
	addIndexSQL(sqlStrings, table, colSet);
	return sqlStrings;
}
 
Example 35
Project: Equella   File: HibernateMigrationHelper.java   View source code 5 votes vote down vote up
public String getAddNamedIndex(String tableName, String indexName, String... columnNames)
{
	Index index = new Index();
	index.setName(indexName);
	index.setTable(findTable(tableName));
	for( String columnName : columnNames )
	{
		index.addColumn(new Column(columnName));
	}
	return index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema);
}
 
Example 36
Project: Equella   File: HibernateMigrationHelper.java   View source code 5 votes vote down vote up
public List<String> getRenameColumnSQL(String tableName, String columnName, String newColumnName)
{
	List<String> sqlStrings = new ArrayList<String>();

	Table table = findTable(tableName);

	Column column = table.getColumn(new Column(columnName));
	String alter = null;
	alter = extDialect.getRenameColumnSql(table.getQualifiedName(dialect, defaultCatalog, defaultSchema), column,
		newColumnName);
	sqlStrings.add(alter);

	return sqlStrings;
}
 
Example 37
Project: Equella   File: HibernateMigrationHelper.java   View source code 5 votes vote down vote up
public List<String> getAddNotNullSQLIfRequired(Session session, String tableName, String... columns)
{
	final Table table = findTable(tableName);

	final List<String> sqlStrings = new ArrayList<String>();
	final Set<String> colset = new HashSet<String>(Arrays.asList(columns));
	session.doWork(new Work()
	{
		@Override
		public void execute(Connection connection) throws SQLException
		{
			ResultSet colresult = connection.getMetaData().getColumns(getDefaultCatalog(),
				extDialect.getNameForMetadataQuery(getDefaultSchema(), false),
				extDialect.getNameForMetadataQuery(table.getName(), table.isQuoted()), "%");
			try
			{
				while( colresult.next() )
				{
					String columnName = colresult.getString("COLUMN_NAME").toLowerCase();
					if( colset.contains(columnName)
						&& "yes".equals(colresult.getString("IS_NULLABLE").toLowerCase()) )
					{
						Column column = table.getColumn(new Column(columnName));

						StringBuffer alter = new StringBuffer("alter table ")
							.append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ')
							.append(extDialect.getAddNotNullSql(mapping, column));
						sqlStrings.add(alter.toString());
					}
				}
			}
			finally
			{
				colresult.close();
			}
		}
	});
	return sqlStrings;
}
 
Example 38
Project: lams   File: HbmBinder.java   View source code 5 votes vote down vote up
private static void bindIndex(Attribute indexAttribute, Table table, Column column, Mappings mappings) {
	if ( indexAttribute != null && table != null ) {
		StringTokenizer tokens = new StringTokenizer( indexAttribute.getValue(), ", " );
		while ( tokens.hasMoreTokens() ) {
			table.getOrCreateIndex( tokens.nextToken() ).addColumn( column );
		}
	}
}
 
Example 39
Project: lams   File: HbmBinder.java   View source code 5 votes vote down vote up
private static void bindUniqueKey(Attribute uniqueKeyAttribute, Table table, Column column, Mappings mappings) {
	if ( uniqueKeyAttribute != null && table != null ) {
		StringTokenizer tokens = new StringTokenizer( uniqueKeyAttribute.getValue(), ", " );
		while ( tokens.hasMoreTokens() ) {
			table.getOrCreateUniqueKey( tokens.nextToken() ).addColumn( column );
		}
	}
}
 
Example 40
Project: lams   File: HbmBinder.java   View source code 5 votes vote down vote up
public static void bindColumn(Element node, Column column, boolean isNullable) throws MappingException {
	Attribute lengthNode = node.attribute( "length" );
	if ( lengthNode != null ) column.setLength( Integer.parseInt( lengthNode.getValue() ) );
	Attribute scalNode = node.attribute( "scale" );
	if ( scalNode != null ) column.setScale( Integer.parseInt( scalNode.getValue() ) );
	Attribute precNode = node.attribute( "precision" );
	if ( precNode != null ) column.setPrecision( Integer.parseInt( precNode.getValue() ) );

	Attribute nullNode = node.attribute( "not-null" );
	column.setNullable( nullNode == null ? isNullable : nullNode.getValue().equals( "false" ) );

	Attribute unqNode = node.attribute( "unique" );
	if ( unqNode != null ) column.setUnique( unqNode.getValue().equals( "true" ) );

	column.setCheckConstraint( node.attributeValue( "check" ) );
	column.setDefaultValue( node.attributeValue( "default" ) );

	Attribute typeNode = node.attribute( "sql-type" );
	if ( typeNode != null ) column.setSqlType( typeNode.getValue() );

	String customWrite = node.attributeValue( "write" );
	if(customWrite != null && !customWrite.matches("[^?]*\\?[^?]*")) {
		throw new MappingException("write expression must contain exactly one value placeholder ('?') character");
	}
	column.setCustomWrite( customWrite );
	column.setCustomRead( node.attributeValue( "read" ) );

	Element comment = node.element("comment");
	if (comment!=null) column.setComment( comment.getTextTrim() );

}