Search in sources :

Example 1 with DuplicateColumnException

use of org.datanucleus.store.rdbms.exceptions.DuplicateColumnException in project datanucleus-rdbms by datanucleus.

the class ClassTable method runCallBacks.

/**
 * Execute the callbacks for the classes that this table maps to.
 * @param clr ClassLoader resolver
 */
private void runCallBacks(ClassLoaderResolver clr) {
    // Run callbacks for all classes managed by this table
    Iterator<AbstractClassMetaData> cmdIter = managedClassMetaData.iterator();
    while (cmdIter.hasNext()) {
        AbstractClassMetaData managedCmd = cmdIter.next();
        if (managingClassCurrent != null && managingClassCurrent.equals(managedCmd.getFullClassName())) {
            // We can't run callbacks for this class since it is still being initialised. Mark callbacks to run after it completes
            runCallbacksAfterManageClass = true;
            break;
        }
        Collection processedCallbacks = callbacksAppliedForManagedClass.get(managedCmd.getFullClassName());
        Collection c = (Collection) storeMgr.getSchemaCallbacks().get(managedCmd.getFullClassName());
        if (c != null) {
            if (processedCallbacks == null) {
                processedCallbacks = new HashSet();
                callbacksAppliedForManagedClass.put(managedCmd.getFullClassName(), processedCallbacks);
            }
            for (Iterator it = c.iterator(); it.hasNext(); ) {
                AbstractMemberMetaData callbackMmd = (AbstractMemberMetaData) it.next();
                if (processedCallbacks.contains(callbackMmd)) {
                    continue;
                }
                processedCallbacks.add(callbackMmd);
                if (callbackMmd.getJoinMetaData() == null) {
                    // 1-N FK relationship
                    AbstractMemberMetaData ownerFmd = callbackMmd;
                    if (ownerFmd.getMappedBy() != null) {
                        // Bidirectional (element has a PC mapping to the owner)
                        // Check that the "mapped-by" field in the other class actually exists
                        AbstractMemberMetaData fmd = null;
                        if (ownerFmd.getMappedBy().indexOf('.') > 0) {
                            // TODO Can we just use getRelatedMemberMetaData always?
                            AbstractMemberMetaData[] relMmds = ownerFmd.getRelatedMemberMetaData(clr);
                            fmd = (relMmds != null && relMmds.length > 0) ? relMmds[0] : null;
                        } else {
                            fmd = managedCmd.getMetaDataForMember(ownerFmd.getMappedBy());
                        }
                        if (fmd == null) {
                            throw new NucleusUserException(Localiser.msg("057036", ownerFmd.getMappedBy(), managedCmd.getFullClassName(), ownerFmd.getFullFieldName()));
                        }
                        if (ownerFmd.getMap() != null && storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_RDBMS_UNIQUE_CONSTRAINTS_MAP_INVERSE)) {
                            initializeFKMapUniqueConstraints(ownerFmd);
                        }
                        boolean duplicate = false;
                        JavaTypeMapping fkDiscrimMapping = null;
                        JavaTypeMapping orderMapping = null;
                        if (ownerFmd.hasExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN)) {
                            // Collection has a relation discriminator so we need to share the FK. Check for the required discriminator
                            String colName = ownerFmd.getValueForExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN);
                            if (colName == null) {
                                // No column defined so use a fallback name
                                colName = "RELATION_DISCRIM";
                            }
                            Set fkDiscrimEntries = getExternalFkDiscriminatorMappings().entrySet();
                            Iterator discrimMappingIter = fkDiscrimEntries.iterator();
                            while (discrimMappingIter.hasNext()) {
                                Map.Entry entry = (Map.Entry) discrimMappingIter.next();
                                JavaTypeMapping discrimMapping = (JavaTypeMapping) entry.getValue();
                                String discrimColName = (discrimMapping.getDatastoreMapping(0).getColumn().getColumnMetaData()).getName();
                                if (discrimColName.equalsIgnoreCase(colName)) {
                                    duplicate = true;
                                    fkDiscrimMapping = discrimMapping;
                                    orderMapping = getExternalOrderMappings().get(entry.getKey());
                                    break;
                                }
                            }
                            if (!duplicate) {
                                // Create the relation discriminator column since we dont have this discriminator
                                ColumnMetaData colmd = new ColumnMetaData();
                                colmd.setName(colName);
                                // Allow for elements not in any discriminated collection
                                colmd.setAllowsNull(Boolean.TRUE);
                                // Only support String discriminators currently
                                fkDiscrimMapping = storeMgr.getMappingManager().getMapping(String.class);
                                fkDiscrimMapping.setTable(this);
                                ColumnCreator.createIndexColumn(fkDiscrimMapping, storeMgr, clr, this, colmd, false);
                            }
                            if (fkDiscrimMapping != null) {
                                getExternalFkDiscriminatorMappings().put(ownerFmd, fkDiscrimMapping);
                            }
                        }
                        // Add the order mapping as necessary
                        addOrderMapping(ownerFmd, orderMapping, clr);
                    } else {
                        // Unidirectional (element knows nothing about the owner)
                        String ownerClassName = ownerFmd.getAbstractClassMetaData().getFullClassName();
                        JavaTypeMapping fkMapping = new PersistableMapping();
                        fkMapping.setTable(this);
                        fkMapping.initialize(storeMgr, ownerClassName);
                        JavaTypeMapping fkDiscrimMapping = null;
                        JavaTypeMapping orderMapping = null;
                        boolean duplicate = false;
                        try {
                            // Get the owner id mapping of the "1" end
                            DatastoreClass ownerTbl = storeMgr.getDatastoreClass(ownerClassName, clr);
                            if (ownerTbl == null) {
                                // Class doesn't have its own table (subclass-table) so find where it persists
                                AbstractClassMetaData[] ownerParentCmds = storeMgr.getClassesManagingTableForClass(ownerFmd.getAbstractClassMetaData(), clr);
                                if (ownerParentCmds.length > 1) {
                                    throw new NucleusUserException("Relation (" + ownerFmd.getFullFieldName() + ") with multiple related tables (using subclass-table). Not supported");
                                }
                                ownerClassName = ownerParentCmds[0].getFullClassName();
                                ownerTbl = storeMgr.getDatastoreClass(ownerClassName, clr);
                                if (ownerTbl == null) {
                                    throw new NucleusException("Failed to get owner table at other end of relation for field=" + ownerFmd.getFullFieldName());
                                }
                            }
                            JavaTypeMapping ownerIdMapping = ownerTbl.getIdMapping();
                            ColumnMetaDataContainer colmdContainer = null;
                            if (ownerFmd.hasCollection() || ownerFmd.hasArray()) {
                                // 1-N Collection/array
                                colmdContainer = ownerFmd.getElementMetaData();
                            } else if (ownerFmd.hasMap() && ownerFmd.getKeyMetaData() != null && ownerFmd.getKeyMetaData().getMappedBy() != null) {
                                // 1-N Map with key stored in the value
                                colmdContainer = ownerFmd.getValueMetaData();
                            } else if (ownerFmd.hasMap() && ownerFmd.getValueMetaData() != null && ownerFmd.getValueMetaData().getMappedBy() != null) {
                                // 1-N Map with value stored in the key
                                colmdContainer = ownerFmd.getKeyMetaData();
                            }
                            CorrespondentColumnsMapper correspondentColumnsMapping = new CorrespondentColumnsMapper(colmdContainer, this, ownerIdMapping, true);
                            int countIdFields = ownerIdMapping.getNumberOfDatastoreMappings();
                            for (int i = 0; i < countIdFields; i++) {
                                DatastoreMapping refDatastoreMapping = ownerIdMapping.getDatastoreMapping(i);
                                JavaTypeMapping mapping = storeMgr.getMappingManager().getMapping(refDatastoreMapping.getJavaTypeMapping().getJavaType());
                                ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(refDatastoreMapping.getColumn().getIdentifier());
                                if (colmd == null) {
                                    throw new NucleusUserException(Localiser.msg("057035", refDatastoreMapping.getColumn().getIdentifier(), toString())).setFatal();
                                }
                                DatastoreIdentifier identifier = null;
                                IdentifierFactory idFactory = storeMgr.getIdentifierFactory();
                                if (colmd.getName() == null || colmd.getName().length() < 1) {
                                    // No user provided name so generate one
                                    identifier = idFactory.newForeignKeyFieldIdentifier(ownerFmd, null, refDatastoreMapping.getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(mapping.getJavaType()), FieldRole.ROLE_OWNER);
                                } else {
                                    // User-defined name
                                    identifier = idFactory.newColumnIdentifier(colmd.getName());
                                }
                                Column refColumn = addColumn(mapping.getJavaType().getName(), identifier, mapping, colmd);
                                refDatastoreMapping.getColumn().copyConfigurationTo(refColumn);
                                if ((colmd.getAllowsNull() == null) || (colmd.getAllowsNull() != null && colmd.isAllowsNull())) {
                                    // User either wants it nullable, or haven't specified anything, so make it nullable
                                    refColumn.setNullable(true);
                                }
                                fkMapping.addDatastoreMapping(getStoreManager().getMappingManager().createDatastoreMapping(mapping, refColumn, refDatastoreMapping.getJavaTypeMapping().getJavaType().getName()));
                                ((PersistableMapping) fkMapping).addJavaTypeMapping(mapping);
                            }
                        } catch (DuplicateColumnException dce) {
                            // If the user hasnt specified "relation-discriminator-column" here we dont allow the sharing of columns
                            if (!ownerFmd.hasExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN)) {
                                throw dce;
                            }
                            // Find the FK using this column and use it instead of creating a new one since we're sharing
                            Iterator fkIter = getExternalFkMappings().entrySet().iterator();
                            fkMapping = null;
                            while (fkIter.hasNext()) {
                                Map.Entry entry = (Map.Entry) fkIter.next();
                                JavaTypeMapping existingFkMapping = (JavaTypeMapping) entry.getValue();
                                for (int j = 0; j < existingFkMapping.getNumberOfDatastoreMappings(); j++) {
                                    if (existingFkMapping.getDatastoreMapping(j).getColumn().getIdentifier().toString().equals(dce.getConflictingColumn().getIdentifier().toString())) {
                                        // The FK is shared (and so if it is a List we also share the index)
                                        fkMapping = existingFkMapping;
                                        fkDiscrimMapping = externalFkDiscriminatorMappings.get(entry.getKey());
                                        orderMapping = getExternalOrderMappings().get(entry.getKey());
                                        break;
                                    }
                                }
                            }
                            if (fkMapping == null) {
                                // Should never happen since we know there is a col duplicating ours
                                throw dce;
                            }
                            duplicate = true;
                        }
                        if (!duplicate && ownerFmd.hasExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN)) {
                            // Create the relation discriminator column
                            String colName = ownerFmd.getValueForExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN);
                            if (colName == null) {
                                // No column defined so use a fallback name
                                colName = "RELATION_DISCRIM";
                            }
                            ColumnMetaData colmd = new ColumnMetaData();
                            colmd.setName(colName);
                            // Allow for elements not in any discriminated collection
                            colmd.setAllowsNull(Boolean.TRUE);
                            // Only support String discriminators currently
                            fkDiscrimMapping = storeMgr.getMappingManager().getMapping(String.class);
                            fkDiscrimMapping.setTable(this);
                            ColumnCreator.createIndexColumn(fkDiscrimMapping, storeMgr, clr, this, colmd, false);
                        }
                        // Save the external FK
                        getExternalFkMappings().put(ownerFmd, fkMapping);
                        if (fkDiscrimMapping != null) {
                            getExternalFkDiscriminatorMappings().put(ownerFmd, fkDiscrimMapping);
                        }
                        // Add the order mapping as necessary
                        addOrderMapping(ownerFmd, orderMapping, clr);
                    }
                }
            }
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) DuplicateColumnException(org.datanucleus.store.rdbms.exceptions.DuplicateColumnException) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) MacroString(org.datanucleus.util.MacroString) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ColumnMetaDataContainer(org.datanucleus.metadata.ColumnMetaDataContainer) Iterator(java.util.Iterator) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) HashSet(java.util.HashSet) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) IdentifierFactory(org.datanucleus.store.rdbms.identifier.IdentifierFactory) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) DatastoreMapping(org.datanucleus.store.rdbms.mapping.datastore.DatastoreMapping) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) Collection(java.util.Collection) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) Map(java.util.Map) HashMap(java.util.HashMap) CorrespondentColumnsMapper(org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)

Example 2 with DuplicateColumnException

use of org.datanucleus.store.rdbms.exceptions.DuplicateColumnException in project datanucleus-rdbms by datanucleus.

the class ColumnCreator method createColumnsForField.

/**
 * Method to create the column(s) for a field in either a join table or for a reference field.
 * @param javaType The java type of the field being stored
 * @param mapping The JavaTypeMapping (if existing, otherwise created and returned by this method)
 * @param table The table to insert the columns into (join table, or primary table (if ref field))
 * @param storeMgr Manager for the store
 * @param mmd MetaData for the field (or null if a collection field)
 * @param isPrimaryKey Whether to create the columns as part of the PK
 * @param isNullable Whether the columns should be nullable
 * @param serialised Whether the field is serialised
 * @param embedded Whether the field is embedded
 * @param fieldRole The role of the field (when part of a join table)
 * @param columnMetaData MetaData for the column(s)
 * @param clr ClassLoader resolver
 * @param isReferenceField Whether this field is part of a reference field
 * @param ownerTable Table of the owner of this member (optional, for when the member is embedded)
 * @return The JavaTypeMapping for the table
 */
public static JavaTypeMapping createColumnsForField(Class javaType, JavaTypeMapping mapping, Table table, RDBMSStoreManager storeMgr, AbstractMemberMetaData mmd, boolean isPrimaryKey, boolean isNullable, boolean serialised, boolean embedded, FieldRole fieldRole, ColumnMetaData[] columnMetaData, ClassLoaderResolver clr, boolean isReferenceField, Table ownerTable) {
    IdentifierFactory idFactory = storeMgr.getIdentifierFactory();
    if (mapping instanceof ReferenceMapping || mapping instanceof PersistableMapping) {
        // PC/interface/Object mapping
        JavaTypeMapping container = mapping;
        if (mapping instanceof ReferenceMapping) {
            // Interface/Object has child mappings for each implementation
            container = storeMgr.getMappingManager().getMapping(javaType, serialised, embedded, mmd != null ? mmd.getFullFieldName() : null);
            ((ReferenceMapping) mapping).addJavaTypeMapping(container);
        }
        // Get the table that we want our column to be a FK to. This could be the owner table, element table, key table, value table etc
        DatastoreClass destinationTable = null;
        try {
            destinationTable = storeMgr.getDatastoreClass(javaType.getName(), clr);
        } catch (NoTableManagedException ntme) {
            if (ownerTable != null && ownerTable instanceof DatastoreClass) {
                destinationTable = (DatastoreClass) ownerTable;
            } else {
                throw ntme;
            }
        }
        if (destinationTable == null) {
            // Maybe the owner hasn't got its own table (e.g "subclass-table" or "complete-table"+abstract)
            // Alternate is when we have an embedded type which itself has an embedded collection - not catered for at all currently
            AbstractClassMetaData ownerCmd = storeMgr.getMetaDataManager().getMetaDataForClass(javaType, clr);
            if (ownerCmd.getBaseAbstractClassMetaData().getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
                // COMPLETE-TABLE but abstract root, so find one of the subclasses with a table and use that for now
                Collection<String> ownerSubclassNames = storeMgr.getSubClassesForClass(javaType.getName(), true, clr);
                if (ownerSubclassNames != null && ownerSubclassNames.size() > 0) {
                    for (String ownerSubclassName : ownerSubclassNames) {
                        ownerCmd = storeMgr.getMetaDataManager().getMetaDataForClass(ownerSubclassName, clr);
                        try {
                            destinationTable = storeMgr.getDatastoreClass(ownerSubclassName, clr);
                        } catch (NoTableManagedException ntme) {
                        }
                        if (destinationTable != null) {
                            break;
                        }
                    }
                }
            } else {
                AbstractClassMetaData[] ownerCmds = storeMgr.getClassesManagingTableForClass(ownerCmd, clr);
                if (ownerCmds == null || ownerCmds.length == 0) {
                    throw new NucleusUserException(Localiser.msg("057023", javaType.getName())).setFatal();
                }
                // Use the first one since they should all have the same id column(s)
                destinationTable = storeMgr.getDatastoreClass(ownerCmds[0].getFullClassName(), clr);
            }
        }
        if (destinationTable != null) {
            // Foreign-Key to the destination table ID mapping
            JavaTypeMapping m = destinationTable.getIdMapping();
            // For each column in the destination mapping, add a column here
            ColumnMetaDataContainer columnContainer = null;
            if (columnMetaData != null && columnMetaData.length > 0) {
                columnContainer = (ColumnMetaDataContainer) columnMetaData[0].getParent();
            }
            CorrespondentColumnsMapper correspondentColumnsMapping = new CorrespondentColumnsMapper(columnContainer, table, columnMetaData, m, true);
            for (int i = 0; i < m.getNumberOfDatastoreMappings(); i++) {
                JavaTypeMapping refDatastoreMapping = storeMgr.getMappingManager().getMapping(m.getDatastoreMapping(i).getJavaTypeMapping().getJavaType());
                ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(m.getDatastoreMapping(i).getColumn().getIdentifier());
                try {
                    DatastoreIdentifier identifier = null;
                    if (fieldRole == FieldRole.ROLE_MAP_KEY && columnContainer == null) {
                        // Map KEY field and no metadata defined
                        if (isReferenceField) {
                            // Create reference identifier
                            identifier = idFactory.newReferenceFieldIdentifier(mmd, storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(javaType, clr), m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
                        } else {
                            // Create join table identifier
                            AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                            // TODO If the mmd is an "embedded" type this can create invalid identifiers
                            // TODO Cater for more than 1 related field
                            identifier = idFactory.newJoinTableFieldIdentifier(mmd, relatedMmds != null ? relatedMmds[0] : null, m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
                        }
                    } else {
                        if (colmd.getName() == null) {
                            // User hasn't provided a name, so we use default naming
                            if (isReferenceField) {
                                // Create reference identifier
                                identifier = idFactory.newReferenceFieldIdentifier(mmd, storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(javaType, clr), m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
                            } else {
                                // Create join table identifier
                                AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                                // TODO If the mmd is an "embedded" type this can create invalid identifiers
                                // TODO Cater for more than 1 related field
                                identifier = idFactory.newJoinTableFieldIdentifier(mmd, relatedMmds != null ? relatedMmds[0] : null, m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
                            }
                        } else {
                            // User defined name, so we use that.
                            identifier = idFactory.newColumnIdentifier(colmd.getName());
                        }
                    }
                    // Only add the column if not currently present
                    Column column = table.addColumn(javaType.getName(), identifier, refDatastoreMapping, colmd);
                    m.getDatastoreMapping(i).getColumn().copyConfigurationTo(column);
                    if (isPrimaryKey) {
                        column.setPrimaryKey();
                    }
                    if (isNullable) {
                        column.setNullable(true);
                    }
                    storeMgr.getMappingManager().createDatastoreMapping(refDatastoreMapping, column, m.getDatastoreMapping(i).getJavaTypeMapping().getJavaTypeForDatastoreMapping(i));
                } catch (DuplicateColumnException ex) {
                    throw new NucleusUserException("Cannot create column for field " + mmd.getFullFieldName() + " column metadata " + colmd, ex);
                }
                try {
                    ((PersistableMapping) container).addJavaTypeMapping(refDatastoreMapping);
                } catch (ClassCastException e) {
                    throw new NucleusUserException("Failed to create column for field " + mmd.getFullFieldName() + ". Cannot cast mapping to PersistableMapping.", e);
                }
            }
        }
    } else {
        // Non-PC mapping
        // Add column for the field
        Column column = null;
        ColumnMetaData colmd = null;
        if (columnMetaData != null && columnMetaData.length > 0) {
            colmd = columnMetaData[0];
        }
        DatastoreIdentifier identifier = null;
        if (colmd != null && colmd.getName() != null) {
            // User specified name
            identifier = idFactory.newColumnIdentifier(colmd.getName());
        } else {
            // No user-supplied name so generate one
            identifier = idFactory.newJoinTableFieldIdentifier(mmd, null, null, storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
        }
        column = table.addColumn(javaType.getName(), identifier, mapping, colmd);
        storeMgr.getMappingManager().createDatastoreMapping(mapping, column, mapping.getJavaTypeForDatastoreMapping(0));
        if (isNullable) {
            column.setNullable(true);
        }
    }
    return mapping;
}
Also used : DuplicateColumnException(org.datanucleus.store.rdbms.exceptions.DuplicateColumnException) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) IdentifierFactory(org.datanucleus.store.rdbms.identifier.IdentifierFactory) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) ColumnMetaDataContainer(org.datanucleus.metadata.ColumnMetaDataContainer) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) NoTableManagedException(org.datanucleus.store.rdbms.exceptions.NoTableManagedException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) CorrespondentColumnsMapper(org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)

Example 3 with DuplicateColumnException

use of org.datanucleus.store.rdbms.exceptions.DuplicateColumnException in project datanucleus-rdbms by datanucleus.

the class AbstractTable method addColumn.

/**
 * Creates a new column in the table.
 * Will add the new Column and return it. If the new column clashes in name with an existing column of the
 * required name will throw a DuplicateColumnNameException except when :-
 * <ul>
 * <li>The 2 columns are for same named fields in the class or its subclasses with the subclass(es) using
 * "superclass-table" inheritance strategy. One of the columns has to come from a subclass - cant have
 * both from the same class.</li>
 * </ul>
 * @param storedJavaType the java type of the datastore field
 * @param name the SQL identifier for the column to be added
 * @param mapping the mapping for the column to be added
 * @param colmd ColumnMetaData for the column to be added to the table
 * @return the new Column
 * @throws DuplicateColumnException if a column already exists with same name and not a supported situation.
 */
public synchronized Column addColumn(String storedJavaType, DatastoreIdentifier name, JavaTypeMapping mapping, ColumnMetaData colmd) {
    // TODO If already initialized and this is called we should check if exists in current representation
    // then check if exists in datastore, and then create it if necessary
    boolean duplicateName = false;
    if (hasColumnName(name)) {
        duplicateName = true;
    }
    // Create the column
    Column col = new ColumnImpl(this, storedJavaType, name, colmd);
    if (duplicateName && colmd != null) {
        // Verify if a duplicate column is valid. A duplicate column name is (currently) valid when :-
        // 1. subclasses defining the duplicated column are using "super class table" strategy
        // 
        // Find the MetaData for the existing column
        Column existingCol = columnsByIdentifier.get(name);
        MetaData md = existingCol.getColumnMetaData().getParent();
        while (!(md instanceof AbstractClassMetaData)) {
            if (md == null) {
                // ColumnMetaData for existing column has no parent class somehow!
                throw new NucleusUserException(Localiser.msg("057043", name.getName(), getDatastoreIdentifierFullyQualified()));
            }
            md = md.getParent();
        }
        // Find the MetaData for the column to be added
        MetaData dupMd = colmd.getParent();
        while (!(dupMd instanceof AbstractClassMetaData)) {
            dupMd = dupMd.getParent();
            if (dupMd == null) {
                // ColumnMetaData for required column has no parent class somehow!
                throw new NucleusUserException(Localiser.msg("057044", name.getName(), getDatastoreIdentifierFullyQualified(), colmd.toString()));
            }
        }
        boolean reuseColumns = storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_RDBMS_ALLOW_COLUMN_REUSE);
        if (!reuseColumns) {
            if (((AbstractClassMetaData) md).getFullClassName().equals(((AbstractClassMetaData) dupMd).getFullClassName())) {
                // much sense in most of the cases. (this whole block of duplicated column check, could be optional, like a pmf property)
                throw new DuplicateColumnException(this.toString(), existingCol, col);
            }
            // Make sure the field JavaTypeMappings are compatible
            if (mapping != null && !mapping.getClass().isAssignableFrom(existingCol.getJavaTypeMapping().getClass()) && !existingCol.getJavaTypeMapping().getClass().isAssignableFrom(mapping.getClass())) {
                // the mapping class must be the same (not really required, but to avoid user mistakes)
                throw new DuplicateColumnException(this.toString(), existingCol, col);
            }
        } else {
            if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
                if (mapping != null && mapping.getMemberMetaData() != null) {
                    NucleusLogger.DATASTORE_SCHEMA.debug("Column " + existingCol + " has already been defined but needing to reuse it for " + mapping.getMemberMetaData().getFullFieldName());
                } else {
                    NucleusLogger.DATASTORE_SCHEMA.debug("Column " + existingCol + " has already been defined but needing to reuse it");
                }
            }
        }
        // Make sure the field java types are compatible
        Class fieldStoredJavaTypeClass = null;
        Class existingColStoredJavaTypeClass = null;
        try {
            ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null);
            fieldStoredJavaTypeClass = clr.classForName(storedJavaType);
            existingColStoredJavaTypeClass = clr.classForName(col.getStoredJavaType());
        } catch (RuntimeException cnfe) {
        // Do nothing
        }
        if (fieldStoredJavaTypeClass != null && existingColStoredJavaTypeClass != null && !fieldStoredJavaTypeClass.isAssignableFrom(existingColStoredJavaTypeClass) && !existingColStoredJavaTypeClass.isAssignableFrom(fieldStoredJavaTypeClass)) {
            // the stored java type must be the same (not really required, but to avoid user mistakes)
            throw new DuplicateColumnException(this.toString(), existingCol, col);
        }
    }
    if (!duplicateName) {
        // Only add to our internal list when it is not a dup (since it would try to create a table with the same col twice)
        addColumnInternal(col);
    }
    if (isInitialized()) {
        // Set state to modified
        state = TABLE_STATE_INITIALIZED_MODIFIED;
    }
    return col;
}
Also used : DuplicateColumnException(org.datanucleus.store.rdbms.exceptions.DuplicateColumnException) VersionMetaData(org.datanucleus.metadata.VersionMetaData) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) MetaData(org.datanucleus.metadata.MetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) DiscriminatorMetaData(org.datanucleus.metadata.DiscriminatorMetaData) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData)

Aggregations

NucleusUserException (org.datanucleus.exceptions.NucleusUserException)3 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)3 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)3 ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)3 DuplicateColumnException (org.datanucleus.store.rdbms.exceptions.DuplicateColumnException)3 ColumnMetaDataContainer (org.datanucleus.metadata.ColumnMetaDataContainer)2 DatastoreIdentifier (org.datanucleus.store.rdbms.identifier.DatastoreIdentifier)2 IdentifierFactory (org.datanucleus.store.rdbms.identifier.IdentifierFactory)2 CorrespondentColumnsMapper (org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)2 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)2 PersistableMapping (org.datanucleus.store.rdbms.mapping.java.PersistableMapping)2 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 Set (java.util.Set)1 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)1 NucleusException (org.datanucleus.exceptions.NucleusException)1 DiscriminatorMetaData (org.datanucleus.metadata.DiscriminatorMetaData)1