Search in sources :

Example 1 with OSQLFunctionRuntime

use of com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime in project orientdb by orientechnologies.

the class OCommandExecutorSQLSelect method applyExpand.

/**
   * Extract the content of collections and/or links and put it as result
   */
private void applyExpand() {
    if (expandTarget == null) {
        return;
    }
    final long startExpand = System.currentTimeMillis();
    try {
        if (tempResult == null) {
            tempResult = new ArrayList<OIdentifiable>();
            if (expandTarget instanceof OSQLFilterItemVariable) {
                Object r = ((OSQLFilterItemVariable) expandTarget).getValue(null, null, context);
                if (r != null) {
                    if (r instanceof OIdentifiable) {
                        ((Collection<OIdentifiable>) tempResult).add((OIdentifiable) r);
                    } else if (r instanceof Iterator || OMultiValue.isMultiValue(r)) {
                        for (Object o : OMultiValue.getMultiValueIterable(r)) {
                            ((Collection<OIdentifiable>) tempResult).add((OIdentifiable) o);
                        }
                    }
                }
            } else if (expandTarget instanceof OSQLFunctionRuntime && !hasFieldItemParams((OSQLFunctionRuntime) expandTarget)) {
                if (((OSQLFunctionRuntime) expandTarget).aggregateResults()) {
                    throw new OCommandExecutionException("Unsupported operation: aggregate function in expand(" + expandTarget + ")");
                } else {
                    Object r = ((OSQLFunctionRuntime) expandTarget).execute(null, null, null, context);
                    if (r instanceof OIdentifiable) {
                        ((Collection<OIdentifiable>) tempResult).add((OIdentifiable) r);
                    } else if (r instanceof Iterator || OMultiValue.isMultiValue(r)) {
                        for (Object o : OMultiValue.getMultiValueIterable(r)) {
                            ((Collection<OIdentifiable>) tempResult).add((OIdentifiable) o);
                        }
                    }
                }
            }
        } else {
            if (tempResult == null) {
                tempResult = new ArrayList<OIdentifiable>();
            }
            final OMultiCollectionIterator<OIdentifiable> finalResult = new OMultiCollectionIterator<OIdentifiable>();
            if (orderedFields == null || orderedFields.size() == 0) {
                // expand is applied before sorting, so limiting the result set here would give wrong results
                int iteratorLimit = 0;
                if (limit < 0) {
                    iteratorLimit = -1;
                } else {
                    iteratorLimit += limit;
                }
                finalResult.setLimit(iteratorLimit);
                finalResult.setSkip(skip);
            }
            for (OIdentifiable id : tempResult) {
                final Object fieldValue;
                if (expandTarget instanceof OSQLFilterItem) {
                    fieldValue = ((OSQLFilterItem) expandTarget).getValue(id.getRecord(), null, context);
                } else if (expandTarget instanceof OSQLFunctionRuntime) {
                    fieldValue = ((OSQLFunctionRuntime) expandTarget).getResult();
                } else {
                    fieldValue = expandTarget.toString();
                }
                if (fieldValue != null) {
                    if (fieldValue instanceof ODocument) {
                        ArrayList<ODocument> partial = new ArrayList<ODocument>();
                        partial.add((ODocument) fieldValue);
                        finalResult.add(partial);
                    } else if (fieldValue instanceof Collection<?> || fieldValue.getClass().isArray() || fieldValue instanceof Iterator<?> || fieldValue instanceof OIdentifiable || fieldValue instanceof ORidBag) {
                        finalResult.add(fieldValue);
                    } else if (fieldValue instanceof Map<?, ?>) {
                        finalResult.add(((Map<?, OIdentifiable>) fieldValue).values());
                    }
                }
            }
            tempResult = finalResult;
        }
    } finally {
        context.setVariable("expandElapsed", (System.currentTimeMillis() - startExpand));
    }
}
Also used : OSQLFunctionRuntime(com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime) ORidBag(com.orientechnologies.orient.core.db.record.ridbag.ORidBag) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OMultiCollectionIterator(com.orientechnologies.common.collection.OMultiCollectionIterator) OIdentifiableIterator(com.orientechnologies.orient.core.iterator.OIdentifiableIterator) OMultiCollectionIterator(com.orientechnologies.common.collection.OMultiCollectionIterator) OSortedMultiIterator(com.orientechnologies.common.collection.OSortedMultiIterator) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 2 with OSQLFunctionRuntime

use of com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime in project orientdb by orientechnologies.

the class OCommandExecutorSQLSelect method isIndexSizeQuery.

private boolean isIndexSizeQuery() {
    if (!(aggregate && projections.entrySet().size() == 1)) {
        return false;
    }
    final Object projection = projections.values().iterator().next();
    if (!(projection instanceof OSQLFunctionRuntime)) {
        return false;
    }
    final OSQLFunctionRuntime f = (OSQLFunctionRuntime) projection;
    return f.getRoot().equals(OSQLFunctionCount.NAME) && ((f.configuredParameters == null || f.configuredParameters.length == 0) || (f.configuredParameters.length == 1 && f.configuredParameters[0].equals("*")));
}
Also used : OSQLFunctionRuntime(com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime)

Example 3 with OSQLFunctionRuntime

use of com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime in project orientdb by orientechnologies.

the class OCommandExecutorSQLSelect method optimizeExecution.

protected boolean optimizeExecution() {
    if (compiledFilter != null) {
        mergeRangeConditionsToBetweenOperators(compiledFilter);
    }
    if ((compiledFilter == null || (compiledFilter.getRootCondition() == null)) && groupByFields == null && projections != null && projections.size() == 1) {
        final long startOptimization = System.currentTimeMillis();
        try {
            final Entry<String, Object> entry = projections.entrySet().iterator().next();
            if (entry.getValue() instanceof OSQLFunctionRuntime) {
                final OSQLFunctionRuntime rf = (OSQLFunctionRuntime) entry.getValue();
                if (rf.function instanceof OSQLFunctionCount && rf.configuredParameters.length == 1 && "*".equals(rf.configuredParameters[0])) {
                    final boolean restrictedClasses = isUsingRestrictedClasses();
                    if (!restrictedClasses) {
                        long count = 0;
                        if (parsedTarget.getTargetClasses() != null) {
                            final String className = parsedTarget.getTargetClasses().keySet().iterator().next();
                            final OClass cls = getDatabase().getMetadata().getSchema().getClass(className);
                            count = cls.count();
                        } else if (parsedTarget.getTargetClusters() != null) {
                            for (String cluster : parsedTarget.getTargetClusters().keySet()) {
                                count += getDatabase().countClusterElements(cluster);
                            }
                        } else if (parsedTarget.getTargetIndex() != null) {
                            count += getDatabase().getMetadata().getIndexManager().getIndex(parsedTarget.getTargetIndex()).getSize();
                        } else {
                            final Iterable<? extends OIdentifiable> recs = parsedTarget.getTargetRecords();
                            if (recs != null) {
                                if (recs instanceof Collection<?>)
                                    count += ((Collection<?>) recs).size();
                                else {
                                    for (Object o : recs) count++;
                                }
                            }
                        }
                        if (tempResult == null)
                            tempResult = new ArrayList<OIdentifiable>();
                        ((Collection<OIdentifiable>) tempResult).add(new ODocument().field(entry.getKey(), count));
                        return true;
                    }
                }
            }
        } finally {
            context.setVariable("optimizationElapsed", (System.currentTimeMillis() - startOptimization));
        }
    }
    return false;
}
Also used : OSQLFunctionRuntime(com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OSQLFunctionCount(com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionCount) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 4 with OSQLFunctionRuntime

use of com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime in project orientdb by orientechnologies.

the class OCommandExecutorSQLCreateEdge method execute.

/**
   * Execute the command and return the ODocument object created.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (clazz == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    return OGraphCommandExecutorSQLFactory.runInConfiguredTxMode(new OGraphCommandExecutorSQLFactory.GraphCallBack<List<Object>>() {

        @Override
        public List<Object> call(OrientBaseGraph graph) {
            final Set<OIdentifiable> fromIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), from, context, iArgs);
            final Set<OIdentifiable> toIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), to, context, iArgs);
            // CREATE EDGES
            final List<Object> edges = new ArrayList<Object>();
            for (OIdentifiable from : fromIds) {
                final OrientVertex fromVertex = graph.getVertex(from);
                if (fromVertex == null)
                    throw new OCommandExecutionException("Source vertex '" + from + "' not exists");
                for (OIdentifiable to : toIds) {
                    final OrientVertex toVertex;
                    if (from.equals(to)) {
                        toVertex = fromVertex;
                    } else {
                        toVertex = graph.getVertex(to);
                    }
                    if (fields != null)
                        // EVALUATE FIELDS
                        for (final OPair<String, Object> f : fields) {
                            if (f.getValue() instanceof OSQLFunctionRuntime) {
                                f.setValue(((OSQLFunctionRuntime) f.getValue()).getValue(to, null, context));
                            } else if (f.getValue() instanceof OSQLFilterItem) {
                                f.setValue(((OSQLFilterItem) f.getValue()).getValue(to, null, context));
                            }
                        }
                    OrientEdge edge = null;
                    if (content != null) {
                        if (fields != null)
                            // MERGE CONTENT WITH FIELDS
                            fields.addAll(OPair.convertFromMap(content.toMap()));
                        else
                            fields = OPair.convertFromMap(content.toMap());
                    }
                    edge = fromVertex.addEdge(null, toVertex, edgeLabel, clusterName, fields);
                    if (fields != null && !fields.isEmpty()) {
                        if (edge.isLightweight())
                            edge.convertToDocument();
                        OSQLHelper.bindParameters(edge.getRecord(), fields, new OCommandParameters(iArgs), context);
                    }
                    edge.save(clusterName);
                    edges.add(edge);
                    if (batch > 0 && edges.size() % batch == 0) {
                        graph.commit();
                        graph.begin();
                    }
                }
            }
            if (edges.isEmpty()) {
                if (fromIds.isEmpty())
                    throw new OCommandExecutionException("No edge has been created because no source vertices");
                else if (toIds.isEmpty())
                    throw new OCommandExecutionException("No edge has been created because no target vertices");
                throw new OCommandExecutionException("No edge has been created between " + fromIds + " and " + toIds);
            }
            return edges;
        }
    });
}
Also used : OSQLFunctionRuntime(com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OSQLFilterItem(com.orientechnologies.orient.core.sql.filter.OSQLFilterItem) OrientBaseGraph(com.tinkerpop.blueprints.impls.orient.OrientBaseGraph) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OrientEdge(com.tinkerpop.blueprints.impls.orient.OrientEdge) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException)

Example 5 with OSQLFunctionRuntime

use of com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime in project orientdb by orientechnologies.

the class OCommandExecutorSQLMoveVertex method execute.

/**
   * Executes the command and return the ODocument object created.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (className == null && clusterName == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    OModifiableBoolean shutdownGraph = new OModifiableBoolean();
    final boolean txAlreadyBegun = getDatabase().getTransaction().isActive();
    final OrientGraph graph = OGraphCommandExecutorSQLFactory.getGraph(true, shutdownGraph);
    try {
        final Set<OIdentifiable> sourceRIDs = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), source, context, iArgs);
        // CREATE EDGES
        final List<ODocument> result = new ArrayList<ODocument>(sourceRIDs.size());
        for (OIdentifiable from : sourceRIDs) {
            final OrientVertex fromVertex = graph.getVertex(from);
            if (fromVertex == null)
                continue;
            final ORID oldVertex = fromVertex.getIdentity().copy();
            final ORID newVertex = fromVertex.moveTo(className, clusterName);
            final ODocument newVertexDoc = newVertex.getRecord();
            if (fields != null) {
                // EVALUATE FIELDS
                for (final OPair<String, Object> f : fields) {
                    if (f.getValue() instanceof OSQLFunctionRuntime)
                        f.setValue(((OSQLFunctionRuntime) f.getValue()).getValue(newVertex.getRecord(), null, context));
                }
                OSQLHelper.bindParameters(newVertexDoc, fields, new OCommandParameters(iArgs), context);
            }
            if (merge != null)
                newVertexDoc.merge(merge, true, false);
            // SAVE CHANGES
            newVertexDoc.save();
            // PUT THE MOVE INTO THE RESULT
            result.add(new ODocument().setTrackingChanges(false).field("old", oldVertex, OType.LINK).field("new", newVertex, OType.LINK));
            if (batch > 0 && result.size() % batch == 0) {
                graph.commit();
                if (!graph.isAutoStartTx())
                    graph.begin();
            }
        }
        graph.commit();
        return result;
    } finally {
        if (!txAlreadyBegun)
            graph.commit();
        if (shutdownGraph.getValue())
            graph.shutdown(false);
    }
}
Also used : OSQLFunctionRuntime(com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime) OrientGraph(com.tinkerpop.blueprints.impls.orient.OrientGraph) ArrayList(java.util.ArrayList) OCommandParameters(com.orientechnologies.orient.core.sql.OCommandParameters) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ORID(com.orientechnologies.orient.core.id.ORID) OModifiableBoolean(com.orientechnologies.common.types.OModifiableBoolean) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OSQLFunctionRuntime (com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime)17 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)7 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)5 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)5 ORID (com.orientechnologies.orient.core.id.ORID)3 ORecord (com.orientechnologies.orient.core.record.ORecord)3 OrientVertex (com.tinkerpop.blueprints.impls.orient.OrientVertex)3 ORidBag (com.orientechnologies.orient.core.db.record.ridbag.ORidBag)2 OCommandParameters (com.orientechnologies.orient.core.sql.OCommandParameters)2 OSQLFilterItemField (com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField)2 OSQLFunctionCount (com.orientechnologies.orient.core.sql.functions.misc.OSQLFunctionCount)2 OrientBaseGraph (com.tinkerpop.blueprints.impls.orient.OrientBaseGraph)2 ArrayList (java.util.ArrayList)2 OMultiCollectionIterator (com.orientechnologies.common.collection.OMultiCollectionIterator)1 OSortedMultiIterator (com.orientechnologies.common.collection.OSortedMultiIterator)1 OException (com.orientechnologies.common.exception.OException)1 OProfiler (com.orientechnologies.common.profiler.OProfiler)1 OModifiableBoolean (com.orientechnologies.common.types.OModifiableBoolean)1 OPair (com.orientechnologies.common.util.OPair)1 OResettable (com.orientechnologies.common.util.OResettable)1