Package org.apache.openjpa.jdbc.sql

Examples of org.apache.openjpa.jdbc.sql.Select


            if (rops != null) {
                for (int i = 0; i < mappings.length; i++) {
                    if (rops[i] != null)
                        continue;

                    Select sel = _sql.newSelect();
                    sel.setLRS(true);
                    if (_log.isTraceEnabled()) {
                        _log.trace("executeExtent: "+mappings[i].getDescribedType());
                        sel.logEagerRelations();
                    }
                    BitSet paged = selectExtent(sel, mappings[i], jfetch,
                        subclasses);
                    if (paged == null)
                        rops[i] = new InstanceResultObjectProvider(sel,
View Full Code Here


            FieldMapping fms[] = mapping.getFieldMappings();
            for( FieldMapping fm : fms) {
                DBIdentifier secTableName = fm.getMappingInfo().getTableIdentifier();
                if (!DBIdentifier.isNull(secTableName)) {
                    // select only the PK columns, since we just want to lock
                    Select select = factory.newSelect();
                    select.select(fm.getColumns());
                    select.whereForeignKey(fm.getJoinForeignKey(), id, mapping, _store);
                    sqls.add(select.toSelect(true, fetch));
                }
            }
        }
        return sqls;
    }
View Full Code Here

    public boolean checkVersion(OpenJPAStateManager sm, JDBCStore store,
        boolean updateVersion)
        throws SQLException {
        Column[] cols = vers.getColumns();
        Select sel = store.getSQLFactory().newSelect();
        sel.select(cols);
        sel.wherePrimaryKey(sm.getObjectId(), vers.getClassMapping(), store);

        // No need to lock version field (i.e. optimistic), except when version update is required (e.g. refresh)
        JDBCFetchConfiguration fetch = store.getFetchConfiguration();
        if (!updateVersion && fetch.getReadLockLevel() >= MixedLockLevels.LOCK_PESSIMISTIC_READ) {
            fetch = (JDBCFetchConfiguration) fetch.clone();
            fetch.setReadLockLevel(MixedLockLevels.LOCK_NONE);
        }
        Result res = sel.execute(store, fetch);
        try {
            if (!res.next())
                return false;

            Object memVersion = sm.getVersion();
View Full Code Here

    public void customUpdate(OpenJPAStateManager sm, JDBCStore store)
        throws SQLException {
        JDBCFetchConfiguration fetch = store.getFetchConfiguration();
        // select existing value for update
        Column col = field.getColumns()[0];
        Select sel = store.getSQLFactory().newSelect();
        sel.select(col);
        field.wherePrimaryKey(sel, sm, store);
        SQLBuffer sql = sel.toSelect(true, fetch);

        Connection conn = store.getConnection();
        DBDictionary dict = store.getDBDictionary();
        PreparedStatement stmnt = null;
        ResultSet rs = null;
View Full Code Here

    public void load(OpenJPAStateManager sm, JDBCStore store,
        JDBCFetchConfiguration fetch)
        throws SQLException {
        Column col = field.getColumns()[0];
        Select sel = store.getSQLFactory().newSelect();
        sel.select(col);
        field.wherePrimaryKey(sel, sm, store);

        Result res = sel.execute(store, fetch);
        Object val = null;
        try {
            if (res.next())
                val = load(col, res, null);
        } finally {
View Full Code Here

                    toObjectValue(field, ds, sm, store, fetch));
                return;
            }
        }

        Select sel = store.getSQLFactory().newSelect();
        sel.select(_cols);
        field.wherePrimaryKey(sel, sm, store);

        Result res = sel.execute(store, fetch);
        Object val = null;
        try {
            if (res.next())
                val = HandlerStrategies.loadDataStore(field, res, null, _cols);
        } finally {
View Full Code Here

     * @param state will be filled with expression state
     */
    public Select evaluate(ExpContext ctx, Select parent, String alias,
        QueryExpressions exps, QueryExpressionsState state) {
        // already know that this query is equivalent to an extent?
        Select sel;
        if (_extent) {
            sel = ctx.store.getSQLFactory().newSelect();
            sel.setAutoDistinct((exps.distinct & exps.DISTINCT_AUTO) != 0);
            return sel;
        }

        // create a new select and initialize it with the joins needed for
        // the criteria of this query
        sel = newSelect(ctx, parent, alias, exps, state);
        sel.setTablePerClassMeta(ctx.tpcMeta);

        // create where clause; if there are no where conditions and
        // no ordering or projections, we return null to signify that this
        // query should be treated like an extent
        Select inner = sel.getFromSelect();
        SQLBuffer where = buildWhere((inner != null) ? inner : sel, ctx,
            state.filter, exps.filter);
        if (where == null && exps.projections.length == 0
            && exps.ordering.length == 0
            && (sel.getJoins() == null || sel.getJoins().isEmpty())) {
            _extent = true;
            sel.setAutoDistinct((exps.distinct & exps.DISTINCT_AUTO) != 0);
            return sel;
        }

        // now set sql criteria; it goes on the inner select if present
        if (inner != null)
            inner.where(where);
        else
            sel.where(where);

        // apply grouping and having.  this does not select the grouping
        // columns, just builds the GROUP BY clauses.  we don't build the
        // ORDER BY clauses yet because if we decide to add this select
        // to a union, the ORDER BY values get aliased differently
        if (exps.having != null) {
            Exp havingExp = (Exp) exps.having;
            SQLBuffer buf = new SQLBuffer(ctx.store.getDBDictionary());
            havingExp.appendTo(sel, ctx, state.having, buf);
            sel.having(buf);
        }
        for (int i = 0; i < exps.grouping.length; i++)
            ((Val) exps.grouping[i]).groupBy(sel, ctx, state.grouping[i]);
       
        if (exps.projections.length == 1) {
            Val val = (Val) exps.projections[0];
            if (val instanceof Count && ((Count)val).isCountDistinctMultiCols()) {
                Select newSel = ctx.store.getSQLFactory().newSelect();
                newSel.select("COUNT(*)", val);
                newSel.setExpectedResultCount(1, true);
                newSel.setFromSelect(sel);
                sel.setExpectedResultCount(0, true);
                sel = newSel;
            }
        }       
        return sel;
View Full Code Here

    /**
     * Return a new select with expressions initialized.
     */
    private Select newSelect(ExpContext ctx, Select parent,
        String alias, QueryExpressions exps, QueryExpressionsState state) {
        Select subselect = JDBCStoreQuery.getThreadLocalSelect(_subselect);
        Select sel = parent != null ? subselect
            : ctx.store.getSQLFactory().newSelect();
        sel.setAutoDistinct((exps.distinct & exps.DISTINCT_AUTO) != 0);
        sel.setJoinSyntax(ctx.fetch.getJoinSyntax());
        sel.setParent(parent, alias);

        Context[] qryCtx = JDBCStoreQuery.getThreadLocalContext();
        Context lctx = null;
        for (int i = 0; i < qryCtx.length; i++) {
            if (qryCtx[i].cloneFrom == exps.ctx()) {
                lctx = qryCtx[i];
                break;
            }
        }

        if (sel.ctx() == null)
            sel.setContext(lctx);

        if (parent == null && lctx.getSubselContexts() != null) {
            // this is the case subselect was created before parent got created
            List<Context> subselCtxs = lctx.getSubselContexts();
            for (Context subselCtx : subselCtxs) {
                Select subsel = (Select) subselCtx.getSelect();
                Subquery subquery = subselCtx.getSubquery();
                subsel.setParent(sel, subquery.getCandidateAlias());
            }
        }
        if (HasContainsExpressionVisitor.hasContains(exps.filter)) {
            sel.setHasSubselect(true);
        }
        initialize(sel, ctx, exps, state);

        if (!sel.getAutoDistinct()) {
            if ((exps.distinct & exps.DISTINCT_TRUE) != 0)
                sel.setDistinct(true);
            else if ((exps.distinct & exps.DISTINCT_FALSE) != 0)
                sel.setDistinct(false);
        } else if (exps.projections.length > 0) {
            if (!sel.isDistinct() && (exps.distinct & exps.DISTINCT_TRUE) != 0){
                // if the select is not distinct but the query is, force
                // the select to be distinct
                sel.setDistinct(true);
            } else if (sel.isDistinct()) {
                // when aggregating data or making a non-distinct projection
                // from a distinct select, we have to select from a tmp
                // table formed by a distinct subselect in the from clause;
                // this subselect selects the pks of the candidate (to
                // get unique candidate values) and needed field values and
                // applies the where conditions; the outer select applies
                // ordering, grouping, etc
                boolean agg = exps.isAggregate();
                boolean candidate = ProjectionExpressionVisitor.
                    hasCandidateProjections(exps.projections);
                if (agg || (candidate
                    && (exps.distinct & exps.DISTINCT_TRUE) == 0)) {
                    DBDictionary dict = ctx.store.getDBDictionary();
                    dict.assertSupport(dict.supportsSubselect,
                        "SupportsSubselect");

                    Select inner = sel;
                    sel = ctx.store.getSQLFactory().newSelect();
                    sel.setParent(parent, alias);
                    sel.setDistinct(agg
                        && (exps.distinct & exps.DISTINCT_TRUE) != 0);
                    sel.setFromSelect(inner);
View Full Code Here

     * Select the data for this query.
     */
    public void select(Select sel, ExpContext ctx, ClassMapping mapping,
        boolean subclasses, QueryExpressions exps, QueryExpressionsState state,
        int eager) {
        Select inner = sel.getFromSelect();
        Val val;
        Joins joins = null;
        boolean isCountDistinctMultiCols = false;

        if (sel.getSubselectPath() != null)
            joins = sel.newJoins().setSubselect(sel.getSubselectPath());

        // build ordering clauses before select so that any eager join
        // ordering gets applied after query ordering
        for (int i = 0; i < exps.ordering.length; i++)
            ((Val) exps.ordering[i]).orderBy(sel, ctx, state.ordering[i],
                exps.ascending[i]);

        // if no result string set, select matching objects like normal
        if (exps.projections.length == 0 && sel.getParent() == null) {
            int subs = (subclasses) ? Select.SUBS_JOINABLE : Select.SUBS_NONE;
            sel.selectIdentifier(mapping, subs, ctx.store, ctx.fetch, eager);
        } else if (exps.projections.length == 0) {
            // subselect for objects; we really just need the primary key values
            sel.select(mapping.getPrimaryKeyColumns(), joins);
        } else {
            if (exps.projections.length == 1) {
                val = (Val) exps.projections[0];
                if (val instanceof Count && ((Count)val).isCountDistinctMultiCols()) {
                    isCountDistinctMultiCols = true;
                    if (sel.getParent() != null)
                        throw new UnsupportedException(_loc.get("count-distinct-multi-col-subselect-unsupported"));
                }
            }           

            // if we have an inner select, we need to select the candidate
            // class' pk columns to guarantee unique instances
            if (inner != null && !isCountDistinctMultiCols)
                inner.select(mapping.getPrimaryKeyColumns(), joins);

            // select each result value; no need to pass on the eager mode since
            // under projections we always use EAGER_NONE
            boolean pks = sel.getParent() != null;
            for (int i = 0; i < exps.projections.length; i++) {
View Full Code Here

            // if this is ordered we need to know the next seq to use in case
            // objects are added to the collection
            if (field.getOrderColumn() != null) {
                // we don't allow ordering table per class one-many's, so
                // we know we don't need a union
                Select sel = store.getSQLFactory().newSelect();
                sel.setAggregate(true);
                StringBuilder sql = new StringBuilder();
                sql.append("MAX(").
                    append(sel.getColumnAlias(field.getOrderColumn())).
                    append(")");
                sel.select(sql.toString(), field);
                ClassMapping rel = getDefaultElementMapping(false);
                sel.whereForeignKey(getJoinForeignKey(rel),
                    sm.getObjectId(), field.getDefiningMapping(), store);

                Result res = sel.execute(store, fetch);
                try {
                    res.next();
                    pcoll.getChangeTracker().setNextSequence
                        (res.getInt(field) + 1);
                } finally {
View Full Code Here

TOP

Related Classes of org.apache.openjpa.jdbc.sql.Select

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.