Search in sources :

Example 46 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class OCommandExecutorSQLSelect method executeSearchRecord.

protected boolean executeSearchRecord(final OIdentifiable id, final OCommandContext iContext, boolean callHooks) {
    if (id == null)
        return false;
    final ORID identity = id.getIdentity();
    if (uniqueResult != null) {
        if (uniqueResult.containsKey(identity))
            return true;
        if (identity.isValid())
            uniqueResult.put(identity, identity);
    }
    if (!checkInterruption())
        return false;
    final LOCKING_STRATEGY contextLockingStrategy = iContext.getVariable("$locking") != null ? (LOCKING_STRATEGY) iContext.getVariable("$locking") : null;
    final LOCKING_STRATEGY localLockingStrategy = contextLockingStrategy != null ? contextLockingStrategy : lockingStrategy;
    if (localLockingStrategy != null && !(localLockingStrategy == LOCKING_STRATEGY.DEFAULT || localLockingStrategy == LOCKING_STRATEGY.NONE || localLockingStrategy == LOCKING_STRATEGY.EXCLUSIVE_LOCK || localLockingStrategy == LOCKING_STRATEGY.SHARED_LOCK))
        throw new IllegalStateException("Unsupported locking strategy " + localLockingStrategy);
    if (localLockingStrategy == LOCKING_STRATEGY.SHARED_LOCK) {
        id.lock(false);
        if (id instanceof ORecord) {
            final ORecord record = (ORecord) id;
            record.reload(null, true, false);
        }
    } else if (localLockingStrategy == LOCKING_STRATEGY.EXCLUSIVE_LOCK) {
        id.lock(true);
        if (id instanceof ORecord) {
            final ORecord record = (ORecord) id;
            record.reload(null, true, false);
        }
    }
    ORecord record = null;
    try {
        if (!(id instanceof ORecord)) {
            record = getDatabase().load(id.getIdentity(), null, !isUseCache());
            if (id instanceof OContextualRecordId && ((OContextualRecordId) id).getContext() != null) {
                Map<String, Object> ridContext = ((OContextualRecordId) id).getContext();
                for (String key : ridContext.keySet()) {
                    context.setVariable(key, ridContext.get(key));
                }
            }
        } else {
            record = (ORecord) id;
        }
        iContext.updateMetric("recordReads", +1);
        if (record == null)
            // SKIP IT
            return true;
        if (ORecordInternal.getRecordType(record) != ODocument.RECORD_TYPE && checkSkipBlob())
            // SKIP binary records in case of projection.
            return true;
        iContext.updateMetric("documentReads", +1);
        iContext.setVariable("current", record);
        if (filter(record, iContext)) {
            if (callHooks) {
                ((ODatabaseDocumentInternal) getDatabase()).callbackHooks(ORecordHook.TYPE.BEFORE_READ, record);
                ((ODatabaseDocumentInternal) getDatabase()).callbackHooks(ORecordHook.TYPE.AFTER_READ, record);
            }
            if (parallel) {
                try {
                    applyGroupBy(record, iContext);
                    resultQueue.put(new AsyncResult(record, iContext));
                } catch (InterruptedException e) {
                    Thread.interrupted();
                    return false;
                }
                tmpQueueOffer.incrementAndGet();
            } else {
                applyGroupBy(record, iContext);
                if (!handleResult(record, iContext)) {
                    // LIMIT REACHED
                    return false;
                }
            }
        }
    } finally {
        if (localLockingStrategy != null && record != null && record.isLocked()) {
            // CONTEXT LOCK: lock must be released (no matter if filtered or not)
            if (localLockingStrategy == LOCKING_STRATEGY.EXCLUSIVE_LOCK || localLockingStrategy == LOCKING_STRATEGY.SHARED_LOCK) {
                record.unlock();
            }
        }
    }
    return true;
}
Also used : OContextualRecordId(com.orientechnologies.orient.core.id.OContextualRecordId) ORecord(com.orientechnologies.orient.core.record.ORecord) LOCKING_STRATEGY(com.orientechnologies.orient.core.storage.OStorage.LOCKING_STRATEGY) ORID(com.orientechnologies.orient.core.id.ORID) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Example 47 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class OCommandExecutorSQLSetAware method extractClassFromTarget.

protected OClass extractClassFromTarget(String iTarget) {
    // CLASS
    if (!iTarget.toUpperCase().startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX) && !iTarget.startsWith(OCommandExecutorSQLAbstract.INDEX_PREFIX)) {
        if (iTarget.toUpperCase().startsWith(OCommandExecutorSQLAbstract.CLASS_PREFIX))
            // REMOVE CLASS PREFIX
            iTarget = iTarget.substring(OCommandExecutorSQLAbstract.CLASS_PREFIX.length());
        if (iTarget.charAt(0) == ORID.PREFIX)
            return getDatabase().getMetadata().getSchema().getClassByClusterId(new ORecordId(iTarget).getClusterId());
        return getDatabase().getMetadata().getSchema().getClass(iTarget);
    }
    //CLUSTER
    if (iTarget.toUpperCase().startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX)) {
        String clusterName = iTarget.substring(OCommandExecutorSQLAbstract.CLUSTER_PREFIX.length()).trim();
        ODatabaseDocumentInternal db = getDatabase();
        if (clusterName.startsWith("[") && clusterName.endsWith("]")) {
            String[] clusterNames = clusterName.substring(1, clusterName.length() - 1).split(",");
            OClass candidateClass = null;
            for (String cName : clusterNames) {
                OCluster aCluster = db.getStorage().getClusterByName(cName.trim());
                if (aCluster == null) {
                    return null;
                }
                OClass aClass = db.getMetadata().getSchema().getClassByClusterId(aCluster.getId());
                if (aClass == null) {
                    return null;
                }
                if (candidateClass == null || candidateClass.equals(aClass) || candidateClass.isSubClassOf(aClass)) {
                    candidateClass = aClass;
                } else if (!candidateClass.isSuperClassOf(aClass)) {
                    return null;
                }
            }
            return candidateClass;
        } else {
            OCluster cluster = db.getStorage().getClusterByName(clusterName);
            if (cluster != null) {
                return db.getMetadata().getSchema().getClassByClusterId(cluster.getId());
            }
        }
    }
    return null;
}
Also used : OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OCluster(com.orientechnologies.orient.core.storage.OCluster) ORecordId(com.orientechnologies.orient.core.id.ORecordId) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Example 48 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class OCommandExecutorSQLDeleteEdge method parse.

@SuppressWarnings("unchecked")
public OCommandExecutorSQLDeleteEdge parse(final OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    String queryText = textRequest.getText();
    String originalQuery = queryText;
    try {
        // System.out.println("NEW PARSER FROM: " + queryText);
        queryText = preParse(queryText, iRequest);
        // System.out.println("NEW PARSER TO: " + queryText);
        textRequest.setText(queryText);
        init((OCommandRequestText) iRequest);
        parserRequiredKeyword("DELETE");
        parserRequiredKeyword("EDGE");
        OClass clazz = null;
        String where = null;
        String temp = parseOptionalWord(true);
        String originalTemp = null;
        int limit = -1;
        if (temp != null && !parserIsEnded())
            originalTemp = parserText.substring(parserGetPreviousPosition(), parserGetCurrentPosition()).trim();
        final OModifiableBoolean shutdownFlag = new OModifiableBoolean();
        ODatabaseDocumentInternal curDb = ODatabaseRecordThreadLocal.INSTANCE.get();
        final OrientGraph graph = OGraphCommandExecutorSQLFactory.getGraph(false, shutdownFlag);
        try {
            while (temp != null) {
                if (temp.equals("FROM")) {
                    fromExpr = parserRequiredWord(false, "Syntax error", " =><,\r\n");
                    if (rids != null)
                        throwSyntaxErrorException("FROM '" + fromExpr + "' is not allowed when specify a RIDs (" + rids + ")");
                } else if (temp.equals("TO")) {
                    toExpr = parserRequiredWord(false, "Syntax error", " =><,\r\n");
                    if (rids != null)
                        throwSyntaxErrorException("TO '" + toExpr + "' is not allowed when specify a RID (" + rids + ")");
                } else if (temp.startsWith("#")) {
                    rids = new ArrayList<ORecordId>();
                    rids.add(new ORecordId(temp));
                    if (fromExpr != null || toExpr != null)
                        throwSyntaxErrorException("Specifying the RID " + rids + " is not allowed with FROM/TO");
                } else if (temp.startsWith("[") && temp.endsWith("]")) {
                    temp = temp.substring(1, temp.length() - 1);
                    rids = new ArrayList<ORecordId>();
                    for (String rid : temp.split(",")) {
                        rid = rid.trim();
                        if (!rid.startsWith("#")) {
                            throwSyntaxErrorException("Not a valid RID: " + rid);
                        }
                        rids.add(new ORecordId(rid));
                    }
                } else if (temp.equals(KEYWORD_WHERE)) {
                    if (clazz == null)
                        // ASSIGN DEFAULT CLASS
                        clazz = graph.getEdgeType(OrientEdgeType.CLASS_NAME);
                    where = parserGetCurrentPosition() > -1 ? " " + parserText.substring(parserGetCurrentPosition()) : "";
                    if (this.preParsedStatement != null) {
                        StringBuilder builder = new StringBuilder();
                        ((ODeleteEdgeStatement) this.preParsedStatement).getWhereClause().toString(parameters, builder);
                        where = builder.toString();
                    }
                    compiledFilter = OSQLEngine.getInstance().parseCondition(where, getContext(), KEYWORD_WHERE);
                    break;
                } else if (temp.equals(KEYWORD_BATCH)) {
                    temp = parserNextWord(true);
                    if (temp != null)
                        batch = Integer.parseInt(temp);
                } else if (temp.equals(KEYWORD_LIMIT)) {
                    temp = parserNextWord(true);
                    if (temp != null)
                        limit = Integer.parseInt(temp);
                } else if (temp.length() > 0) {
                    // GET/CHECK CLASS NAME
                    label = originalTemp;
                    clazz = graph.getEdgeType(temp);
                    if (clazz == null)
                        throw new OCommandSQLParsingException("Class '" + temp + "' was not found");
                }
                temp = parseOptionalWord(true);
                if (parserIsEnded())
                    break;
            }
            if (where == null)
                if (limit > -1) {
                    where = " LIMIT " + limit;
                } else {
                    where = "";
                }
            else
                where = " WHERE " + where;
            if (fromExpr == null && toExpr == null && rids == null)
                if (clazz == null)
                    // DELETE ALL THE EDGES
                    query = graph.getRawGraph().command(new OSQLAsynchQuery<ODocument>("select from E" + where, this));
                else
                    // DELETE EDGES OF CLASS X
                    query = graph.getRawGraph().command(new OSQLAsynchQuery<ODocument>("select from " + clazz.getName() + where, this));
            return this;
        } finally {
            if (shutdownFlag.getValue())
                graph.shutdown(false, false);
            ODatabaseRecordThreadLocal.INSTANCE.set(curDb);
        }
    } finally {
        textRequest.setText(originalQuery);
    }
}
Also used : OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) ORecordId(com.orientechnologies.orient.core.id.ORecordId) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OSQLAsynchQuery(com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery) OModifiableBoolean(com.orientechnologies.common.types.OModifiableBoolean)

Example 49 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class OrientEdgeIterator method createGraphElement.

@Override
public OrientEdge createGraphElement(final Object iObject) {
    if (iObject instanceof OrientEdge)
        return (OrientEdge) iObject;
    final OIdentifiable rec = (OIdentifiable) iObject;
    if (rec == null) {
        // SKIP IT
        OLogManager.instance().warn(this, "Record (%s) is null", iObject);
        return null;
    }
    final ORecord record = rec.getRecord();
    if (record == null) {
        // SKIP IT
        OLogManager.instance().warn(this, "Record (%s) is null", rec);
        return null;
    }
    if (!(record instanceof ODocument)) {
        // SKIP IT
        OLogManager.instance().warn(this, "Found a record (%s) that is not an edge. Source vertex : %s, Target vertex : %s, Database : %s", rec, sourceVertex != null ? sourceVertex.getIdentity() : null, targetVertex != null ? targetVertex.getIdentity() : null, record.getDatabase().getURL());
        return null;
    }
    final ODocument value = rec.getRecord();
    if (value == null) {
        return null;
    }
    OImmutableClass immutableSchema = ODocumentInternal.getImmutableSchemaClass(value);
    if (immutableSchema == null) {
        ODatabaseDocument db = value.getDatabaseIfDefined();
        if (db == null) {
            return null;
        }
        db.getMetadata().reload();
        immutableSchema = ODocumentInternal.getImmutableSchemaClass(value);
        if (immutableSchema == null) {
            return null;
        }
    }
    final OrientEdge edge;
    if (immutableSchema.isVertexType()) {
        // DIRECT VERTEX, CREATE DUMMY EDGE
        OrientBaseGraph graph = this.sourceVertex.getGraph();
        boolean newGraph = false;
        if (graph == null) {
            newGraph = true;
            ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
            if (db != null) {
                graph = new OrientGraphNoTx((ODatabaseDocumentTx) db);
            }
        }
        if (connection.getKey() == Direction.OUT) {
            edge = graph.getEdgeInstance(this.sourceVertex.getIdentity(), rec.getIdentity(), connection.getValue());
        } else {
            edge = graph.getEdgeInstance(rec.getIdentity(), this.sourceVertex.getIdentity(), connection.getValue());
        }
        if (newGraph) {
            graph.shutdown(false, false);
        }
    } else if (immutableSchema.isEdgeType()) {
        // EDGE
        edge = new OrientEdge(this.sourceVertex.getGraph(), rec.getIdentity(), connection.getValue());
    } else
        throw new IllegalStateException("Invalid content found while iterating edges, value '" + value + "' is not an edge");
    if (this.sourceVertex.settings.isUseVertexFieldsForEdgeLabels() || edge.isLabeled(labels))
        return edge;
    return null;
}
Also used : ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) ORecord(com.orientechnologies.orient.core.record.ORecord) OImmutableClass(com.orientechnologies.orient.core.metadata.schema.OImmutableClass) ODatabaseDocumentTx(com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 50 with ODatabaseDocumentInternal

use of com.orientechnologies.orient.core.db.ODatabaseDocumentInternal in project orientdb by orientechnologies.

the class OClassImpl method addSuperClass.

@Override
public OClass addSuperClass(final OClass superClass) {
    getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
    checkParametersConflict(superClass);
    acquireSchemaWriteLock();
    try {
        final ODatabaseDocumentInternal database = getDatabase();
        final OStorage storage = database.getStorage();
        if (storage instanceof OStorageProxy) {
            final String cmd = String.format("alter class `%s` superclass +`%s`", name, superClass != null ? superClass.getName() : null);
            database.command(new OCommandSQL(cmd)).execute();
        } else if (isDistributedCommand()) {
            final String cmd = String.format("alter class `%s` superclass +`%s`", name, superClass != null ? superClass.getName() : null);
            final OCommandSQL commandSQL = new OCommandSQL(cmd);
            commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
            database.command(commandSQL).execute();
            addSuperClassInternal(superClass);
        } else
            addSuperClassInternal(superClass);
    } finally {
        releaseSchemaWriteLock();
    }
    return this;
}
Also used : OCommandSQL(com.orientechnologies.orient.core.sql.OCommandSQL) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Aggregations

ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)139 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)42 OStorage (com.orientechnologies.orient.core.storage.OStorage)31 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)26 OStorageProxy (com.orientechnologies.orient.core.storage.OStorageProxy)20 OAutoshardedStorage (com.orientechnologies.orient.core.storage.OAutoshardedStorage)18 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)17 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)16 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)14 ORID (com.orientechnologies.orient.core.id.ORID)13 IOException (java.io.IOException)13 OException (com.orientechnologies.common.exception.OException)12 ORecordId (com.orientechnologies.orient.core.id.ORecordId)11 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)10 OSchemaException (com.orientechnologies.orient.core.exception.OSchemaException)10 ORecord (com.orientechnologies.orient.core.record.ORecord)7 OMetadataInternal (com.orientechnologies.orient.core.metadata.OMetadataInternal)6 OCommandRequestText (com.orientechnologies.orient.core.command.OCommandRequestText)5 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)5 ODatabaseException (com.orientechnologies.orient.core.exception.ODatabaseException)5