Package org.apache.openjpa.jdbc.schema

Examples of org.apache.openjpa.jdbc.schema.ForeignKey


                constant = true;
        }

        // if this is not a constant join, look for existing foreign key
        // on local columns
        ForeignKey exist = null;
        if (!constant && local.getForeignKeys().length > 0) {
            Column[] cols = new Column[joins.length];
            Column[] pks = new Column[joins.length];
            for (int i = 0; i < joins.length; i++) {
                cols[i] = (Column) joins[i][0];
                pks[i] = (Column) joins[i][1];
            }

            ForeignKey[] fks = local.getForeignKeys();
            for (int i = 0; i < fks.length; i++) {
                if (fks[i].getConstantColumns().length == 0
                    && fks[i].getConstantPrimaryKeyColumns().length == 0
                    && fks[i].columnsMatch(cols, pks)) {
                    exist = fks[i];
                    break;
                }
            }
        }

        MappingRepository repos = (MappingRepository) context.getRepository();
        DBDictionary dict = repos.getDBDictionary();
        if (exist != null) {
            // make existing key logical?
            if (!_canFK) {
                if (exist.getDeleteAction() != exist.ACTION_NONE && !adapt)
                    throw new MetaDataException(_loc.get(prefix
                        + "-fk-exists", context));
                exist.setDeleteAction(exist.ACTION_NONE);
            }

            if (_fk != null && _fk.isDeferred() && !exist.isDeferred()) {
                Log log = repos.getLog();
                if (log.isWarnEnabled())
                    log.warn(_loc.get(prefix + "-defer-fk", context));
            }

            // allow user-given info to override existing key if we're adapting;
            // template info cannot override existing key
            if (adapt && _fk != null) {
                if (_fk.getUpdateAction() != ForeignKey.ACTION_NONE)
                    exist.setUpdateAction(_fk.getUpdateAction());
                if (_fk.getDeleteAction() != ForeignKey.ACTION_NONE)
                    exist.setDeleteAction(_fk.getDeleteAction());
            }
            setIOFromJoins(exist, joins);
            return exist;
        }

        String name = null;
        int delAction = ForeignKey.ACTION_NONE;
        int upAction = ForeignKey.ACTION_NONE;
        boolean deferred = false;
        boolean fill = repos.getMappingDefaults().defaultMissingInfo();
        ForeignKey tmplate = (def == null) ? null
            : def.get(local, foreign, _join == JOIN_INVERSE);
        if (_fk != null && (tmplate == null || (!adapt && !fill))) {
            // if not adapting or no template info use given data
            name = _fk.getName();
            delAction = _fk.getDeleteAction();
            upAction = _fk.getUpdateAction();
            deferred = _fk.isDeferred();
        } else if (_canFK && (adapt || fill)) {
            if (_fk == null && tmplate != null) {
                // no user given info; use template data
                name = tmplate.getName();
                delAction = tmplate.getDeleteAction();
                upAction = tmplate.getUpdateAction();
                deferred = tmplate.isDeferred();
            } else if (_fk != null && tmplate != null) {
                // merge user and template data, always letting user info win
                name = _fk.getName();
                if (name == null && tmplate.getName() != null)
                    name = tmplate.getName();
                delAction = _fk.getDeleteAction();
                if (delAction == ForeignKey.ACTION_NONE)
                    delAction = tmplate.getDeleteAction();
                upAction = _fk.getUpdateAction();
                if (upAction == ForeignKey.ACTION_NONE)
                    upAction = tmplate.getUpdateAction();
                deferred = _fk.isDeferred();
            }
        }

        if (!dict.supportsDeleteAction(delAction)
            || !dict.supportsUpdateAction(upAction)) {
            Log log = repos.getLog();
            if (log.isWarnEnabled())
                log.warn(_loc.get(prefix + "-unsupported-fk-action", context));
            delAction = ForeignKey.ACTION_NONE;
            upAction = ForeignKey.ACTION_NONE;
        }
        if (deferred && !dict.supportsDeferredConstraints) {
            Log log = repos.getLog();
            if (log.isWarnEnabled())
                log.warn(_loc.get(prefix + "-create-defer-fk",
                    context, dict.platform));
            deferred = false;
        }

        // create foreign key with merged info
        ForeignKey fk = local.addForeignKey(name);
        fk.setDeleteAction(delAction);
        fk.setUpdateAction(upAction);
        fk.setDeferred(deferred);

        // add joins to key
        Column col;
        for (int i = 0; i < joins.length; i++) {
            col = (Column) joins[i][0];
            if (joins[i][1]instanceof Column)
                fk.join(col, (Column) joins[i][1]);
            else if ((joins[i][2] == Boolean.TRUE) != (_join == JOIN_INVERSE))
                fk.joinConstant(joins[i][1], col);
            else
                fk.joinConstant(col, joins[i][1]);
        }
        setIOFromJoins(fk, joins);
        return fk;
    }
View Full Code Here


    /**
     * Use the given join instance to create SQL joining its tables in
     * the traditional style.
     */
    public SQLBuffer toTraditionalJoin(Join join) {
        ForeignKey fk = join.getForeignKey();
        if (fk == null)
            return null;

        boolean inverse = join.isForeignKeyInversed();
        Column[] from = (inverse) ? fk.getPrimaryKeyColumns()
            : fk.getColumns();
        Column[] to = (inverse) ? fk.getColumns()
            : fk.getPrimaryKeyColumns();

        // do column joins
        SQLBuffer buf = new SQLBuffer(this);
        int count = 0;
        for (int i = 0; i < from.length; i++, count++) {
            if (count > 0)
                buf.append(" AND ");
            buf.append(join.getAlias1()).append(".").append(from[i]);
            buf.append(" = ");
            buf.append(join.getAlias2()).append(".").append(to[i]);
        }

        // do constant joins
        Column[] constCols = fk.getConstantColumns();
        for (int i = 0; i < constCols.length; i++, count++) {
            if (count > 0)
                buf.append(" AND ");
            if (inverse)
                buf.appendValue(fk.getConstant(constCols[i]), constCols[i]);
            else
                buf.append(join.getAlias1()).append(".").
                    append(constCols[i]);
            buf.append(" = ");

            if (inverse)
                buf.append(join.getAlias2()).append(".").
                    append(constCols[i]);
            else
                buf.appendValue(fk.getConstant(constCols[i]), constCols[i]);
        }

        Column[] constColsPK = fk.getConstantPrimaryKeyColumns();
        for (int i = 0; i < constColsPK.length; i++, count++) {
            if (count > 0)
                buf.append(" AND ");
            if (inverse)
                buf.append(join.getAlias1()).append(".").
                    append(constColsPK[i]);
            else
                buf.appendValue(fk.getPrimaryKeyConstant(constColsPK[i]),
                    constColsPK[i]);
            buf.append(" = ");

            if (inverse)
                buf.appendValue(fk.getPrimaryKeyConstant(constColsPK[i]),
                    constColsPK[i]);
            else
                buf.append(join.getAlias2()).append(".").
                    append(constColsPK[i]);
        }
View Full Code Here

    /**
     * Create a new foreign key from the information in the schema metadata.
     */
    protected ForeignKey newForeignKey(ResultSet fkMeta)
        throws SQLException {
        ForeignKey fk = new ForeignKey();
        fk.setSchemaName(fkMeta.getString("FKTABLE_SCHEM"));
        fk.setTableName(fkMeta.getString("FKTABLE_NAME"));
        fk.setColumnName(fkMeta.getString("FKCOLUMN_NAME"));
        fk.setName(fkMeta.getString("FK_NAME"));
        fk.setPrimaryKeySchemaName(fkMeta.getString("PKTABLE_SCHEM"));
        fk.setPrimaryKeyTableName(fkMeta.getString("PKTABLE_NAME"));
        fk.setPrimaryKeyColumnName(fkMeta.getString("PKCOLUMN_NAME"));
        fk.setKeySequence(fkMeta.getInt("KEY_SEQ"));
        fk.setDeferred(fkMeta.getInt("DEFERRABILITY")
            == DatabaseMetaData.importedKeyInitiallyDeferred);

        int del = fkMeta.getInt("DELETE_RULE");
        switch (del) {
            case DatabaseMetaData.importedKeySetNull:
                fk.setDeleteAction(ForeignKey.ACTION_NULL);
                break;
            case DatabaseMetaData.importedKeySetDefault:
                fk.setDeleteAction(ForeignKey.ACTION_DEFAULT);
                break;
            case DatabaseMetaData.importedKeyCascade:
                fk.setDeleteAction(ForeignKey.ACTION_CASCADE);
                break;
            default:
                fk.setDeleteAction(ForeignKey.ACTION_RESTRICT);
                break;
        }
        return fk;
    }
View Full Code Here

        if (fk.isLogical())
            _fk = null;
        else {
            _canFK = true;
            _fk = new ForeignKey();
            _fk.setName(fk.getName());
            _fk.setDeleteAction(fk.getDeleteAction());
            _fk.setUpdateAction(fk.getUpdateAction());
            _fk.setDeferred(fk.isDeferred());
        }
View Full Code Here

        return res.load(elem, store, fetch, joins);
    }

    protected Joins join(Joins joins, ClassMapping elem) {
        ValueMapping vm = field.getElementMapping();
        ForeignKey fk = vm.getForeignKey(elem);
        ClassMapping owner = field.getDefiningMapping();
        while (fk.getPrimaryKeyTable() != owner.getTable()) {
            joins = owner.joinSuperclass(joins, false);
            owner = owner.getJoinablePCSuperclassMapping();
            if (owner == null)
                throw new InternalException();
        }
View Full Code Here

            field.setOrderColumnIO(finfo.getColumnIO());
            return;
        }

        // map inverse foreign key in related table
        ForeignKey fk = vinfo.getInverseTypeJoin(elem, field.getName(), adapt);
        elem.setForeignKey(fk);
        elem.setColumnIO(vinfo.getColumnIO());
        elem.setColumns(elem.getTypeMapping().getPrimaryKeyColumns());
        elem.setJoinDirection(ValueMapping.JOIN_EXPECTED_INVERSE);
        elem.setUseClassCriteria(criteria);
        elem.mapConstraints(field.getName(), adapt);

        field.setOrderColumn(finfo.getOrderColumn(field, fk.getTable(),
            adapt));
        field.setOrderColumnIO(finfo.getColumnIO());
    }
View Full Code Here

        ValueMapping elem = field.getElementMapping();
        Log log = field.getRepository().getLog();
        if (field.getMappedBy() == null
            && elem.getUseClassCriteria() && log.isWarnEnabled()) {
            ForeignKey fk = elem.getForeignKey();
            if (elem.getColumnIO().isAnyUpdatable(fk, false))
                log.warn(_loc.get("class-crit-owner", field));
        }
    }
View Full Code Here

            return;

        // if nullable, null any existing inverse columns that refer to this obj
        ValueMapping elem = field.getElementMapping();
        ColumnIO io = elem.getColumnIO();
        ForeignKey fk = elem.getForeignKey();
        if (!elem.getUseClassCriteria() && io.isAnyUpdatable(fk, true)) {
            assertInversable();
            Row row = rm.getAllRows(fk.getTable(), Row.ACTION_UPDATE);
            row.setForeignKey(fk, io, null);
            row.whereForeignKey(fk, sm);
            rm.flushAllRows(row);
            return;
        }
View Full Code Here

            ctx);
        if (invsm == null)
            return;

        ValueMapping elem = field.getElementMapping();
        ForeignKey fk = elem.getForeignKey();
        ColumnIO io = elem.getColumnIO();
        Column order = field.getOrderColumn();

        int action;
        boolean writeable;
        boolean orderWriteable;
        if (invsm.isNew() && !invsm.isFlushed()) {
            // no need to null inverse columns of new instance
            if (sm == null || sm.isDeleted())
                return;
            writeable = io.isAnyInsertable(fk, false);
            orderWriteable = _orderInsert;
            action = Row.ACTION_INSERT;
        } else if (invsm.isDeleted()) {
            // no need to null inverse columns of deleted instance
            if (invsm.isFlushed() || sm == null || !sm.isDeleted())
                return;
            writeable = true;
            orderWriteable = false;
            action = Row.ACTION_DELETE;
        } else {
            if (sm != null && sm.isDeleted())
                sm = null;
            writeable = io.isAnyUpdatable(fk, sm == null);
            orderWriteable = field.getOrderColumnIO().isUpdatable
                (order, sm == null);
            action = Row.ACTION_UPDATE;
        }
        if (!writeable && !orderWriteable)
            return;

        assertInversable();

        // if this is an update, this might be the only mod to the row, so
        // make sure the where condition is set
        Row row = rm.getRow(fk.getTable(), action, invsm, true);
        if (action == Row.ACTION_UPDATE)
            row.wherePrimaryKey(invsm);

        // update the inverse pointer with our oid value
        if (writeable)
View Full Code Here

            field.getMappingInfo().setColumns(null);
        }

        field.mapJoin(adapt, false);
        if (field.getTypeMapping().isMapped()) {
            ForeignKey fk = vinfo.getTypeJoin(field, field.getName(), true,
                adapt);
            field.setForeignKey(fk);
            field.setColumnIO(vinfo.getColumnIO());
            if (vinfo.getJoinDirection() == vinfo.JOIN_INVERSE)
                field.setJoinDirection(field.JOIN_INVERSE);
View Full Code Here

TOP

Related Classes of org.apache.openjpa.jdbc.schema.ForeignKey

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.