Search in sources :

Example 1 with OSQLAsynchQuery

use of com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery in project jnosql-diana-driver by eclipse.

the class QueryOSQLFactory method toAsync.

static QueryResult toAsync(DocumentQuery documentQuery, Consumer<List<ODocument>> callBack) {
    Query query = QueryOSQLConverter.select(documentQuery);
    return new QueryResult(new OSQLAsynchQuery<>(query.getQuery(), new OCommandResultListener() {

        private List<ODocument> documents = new ArrayList<>();

        @Override
        public boolean result(Object iRecord) {
            ODocument document = (ODocument) iRecord;
            documents.add(document);
            return true;
        }

        @Override
        public void end() {
            callBack.accept(documents);
        }

        @Override
        public Object getResult() {
            return null;
        }
    }), query.getParams());
}
Also used : Query(org.jnosql.diana.orientdb.document.QueryOSQLConverter.Query) OSQLQuery(com.orientechnologies.orient.core.sql.query.OSQLQuery) OSQLSynchQuery(com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) OLiveQuery(com.orientechnologies.orient.core.sql.query.OLiveQuery) OSQLAsynchQuery(com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery) DocumentQuery(org.jnosql.diana.api.document.DocumentQuery) OCommandResultListener(com.orientechnologies.orient.core.command.OCommandResultListener) List(java.util.List) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 2 with OSQLAsynchQuery

use of com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery in project orientdb by orientechnologies.

the class OCommandExecutorSQLResultsetAbstract method parse.

/**
 * Compile the filter conditions only the first time.
 */
public OCommandExecutorSQLResultsetAbstract parse(final OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    init(textRequest);
    if (iRequest instanceof OSQLSynchQuery) {
        request = (OSQLSynchQuery<ODocument>) iRequest;
    } else if (iRequest instanceof OSQLAsynchQuery)
        request = (OSQLAsynchQuery<ODocument>) iRequest;
    else {
        // BUILD A QUERY OBJECT FROM THE COMMAND REQUEST
        request = new OSQLSynchQuery<ODocument>(textRequest.getText());
        if (textRequest.getResultListener() != null)
            request.setResultListener(textRequest.getResultListener());
    }
    return this;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) OSQLSynchQuery(com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) OSQLAsynchQuery(com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 3 with OSQLAsynchQuery

use of com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery 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 4 with OSQLAsynchQuery

use of com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery in project orientdb by orientechnologies.

the class SQLSelectTest method queryAsynchHalfForheFirstQuery.

@Test
public void queryAsynchHalfForheFirstQuery() {
    final String sqlOne = "select * from company where id between 4 and 7";
    final String sqlTwo = "select $names let $names = (select EXPAND( addresses.city ) as city from Account where addresses.size() > 0 )";
    final List<ODocument> synchResultOne = database.command(new OSQLSynchQuery<ODocument>(sqlOne)).execute();
    final List<ODocument> synchResultTwo = database.command(new OSQLSynchQuery<ODocument>(sqlTwo)).execute();
    Assert.assertTrue(synchResultOne.size() > 0);
    Assert.assertTrue(synchResultTwo.size() > 0);
    final List<ODocument> asynchResultOne = new ArrayList<ODocument>();
    final List<ODocument> asynchResultTwo = new ArrayList<ODocument>();
    final AtomicBoolean endOneCalled = new AtomicBoolean();
    final AtomicBoolean endTwoCalled = new AtomicBoolean();
    database.command(new OSQLAsynchQuery<ODocument>(sqlOne, new OCommandResultListener() {

        @Override
        public boolean result(Object iRecord) {
            asynchResultOne.add((ODocument) iRecord);
            return asynchResultOne.size() < synchResultOne.size() / 2;
        }

        @Override
        public void end() {
            endOneCalled.set(true);
            database.command(new OSQLAsynchQuery<ODocument>(sqlTwo, new OCommandResultListener() {

                @Override
                public boolean result(Object iRecord) {
                    asynchResultTwo.add((ODocument) iRecord);
                    return true;
                }

                @Override
                public void end() {
                    endTwoCalled.set(true);
                }

                @Override
                public Object getResult() {
                    return null;
                }
            })).execute();
        }

        @Override
        public Object getResult() {
            return null;
        }
    })).execute();
    Assert.assertTrue(endOneCalled.get());
    Assert.assertTrue(endTwoCalled.get());
    Assert.assertTrue(ODocumentHelper.compareCollections(database, synchResultOne.subList(0, synchResultOne.size() / 2), database, asynchResultOne, null));
    Assert.assertTrue(ODocumentHelper.compareCollections(database, synchResultTwo, database, asynchResultTwo, null));
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OSQLSynchQuery(com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) OCommandResultListener(com.orientechnologies.orient.core.command.OCommandResultListener) OSQLAsynchQuery(com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.testng.annotations.Test)

Example 5 with OSQLAsynchQuery

use of com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery in project orientdb by orientechnologies.

the class OCommandExecutorSQLUpdate method parse.

@SuppressWarnings("unchecked")
public OCommandExecutorSQLUpdate parse(final OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    String queryText = textRequest.getText();
    String originalQuery = queryText;
    try {
        queryText = preParse(queryText, iRequest);
        if (isUpdateEdge()) {
            // work-around to use UPDATE syntax without having to
            queryText = queryText.replaceFirst("EDGE ", "");
        }
        textRequest.setText(queryText);
        final ODatabaseDocument database = getDatabase();
        init((OCommandRequestText) iRequest);
        setEntries.clear();
        addEntries.clear();
        putEntries.clear();
        removeEntries.clear();
        incrementEntries.clear();
        content = null;
        merge = null;
        query = null;
        parserRequiredKeyword(KEYWORD_UPDATE);
        subjectName = parserRequiredWord(false, "Invalid target", " =><,\r\n");
        if (subjectName == null) {
            throwSyntaxErrorException("Invalid subject name. Expected cluster, class, index or sub-query");
        }
        if (subjectName.equalsIgnoreCase("EDGE")) {
            updateEdge = true;
            subjectName = parserRequiredWord(false, "Invalid target", " =><,\r\n");
        }
        clazz = extractClassFromTarget(subjectName);
        String word = parserNextWord(true);
        if (parserIsEnded() || (!word.equals(KEYWORD_SET) && !word.equals(KEYWORD_ADD) && !word.equals(KEYWORD_PUT) && !word.equals(KEYWORD_REMOVE) && !word.equals(KEYWORD_INCREMENT) && !word.equals(KEYWORD_CONTENT) && !word.equals(KEYWORD_MERGE) && !word.equals(KEYWORD_LOCK) && !word.equals(KEYWORD_RETURN) && !word.equals(KEYWORD_UPSERT) && !word.equals(KEYWORD_EDGE)))
            throwSyntaxErrorException("Expected keyword " + KEYWORD_SET + "," + KEYWORD_ADD + "," + KEYWORD_CONTENT + "," + KEYWORD_MERGE + "," + KEYWORD_PUT + "," + KEYWORD_REMOVE + "," + KEYWORD_INCREMENT + "," + KEYWORD_LOCK + " or " + KEYWORD_RETURN + " or " + KEYWORD_UPSERT + " or " + KEYWORD_EDGE);
        while ((!parserIsEnded() && !parserGetLastWord().equals(OCommandExecutorSQLAbstract.KEYWORD_WHERE)) || parserGetLastWord().equals(KEYWORD_UPSERT)) {
            word = parserGetLastWord();
            if (word.equals(KEYWORD_CONTENT))
                parseContent();
            else if (word.equals(KEYWORD_MERGE))
                parseMerge();
            else if (word.equals(KEYWORD_SET))
                parseSetFields(clazz, setEntries);
            else if (word.equals(KEYWORD_ADD))
                parseAddFields(clazz);
            else if (word.equals(KEYWORD_PUT))
                parsePutFields();
            else if (word.equals(KEYWORD_REMOVE))
                parseRemoveFields();
            else if (word.equals(KEYWORD_INCREMENT))
                parseIncrementFields();
            else if (word.equals(KEYWORD_LOCK))
                lockStrategy = parseLock();
            else if (word.equals(KEYWORD_UPSERT))
                upsertMode = true;
            else if (word.equals(KEYWORD_RETURN))
                parseReturn();
            else if (word.equals(KEYWORD_RETRY)) {
                OLogManager.instance().warn(this, "RETRY keyword will be ignored in " + originalQuery);
                parseRetry();
            } else
                break;
            parserNextWord(true);
        }
        final String additionalStatement = parserGetLastWord();
        if (subjectName.startsWith("(")) {
            subjectName = subjectName.trim();
            query = database.command(new OSQLAsynchQuery<ODocument>(subjectName.substring(1, subjectName.length() - 1), this).setContext(context));
            if (additionalStatement.equals(OCommandExecutorSQLAbstract.KEYWORD_WHERE) || additionalStatement.equals(OCommandExecutorSQLAbstract.KEYWORD_LIMIT))
                compiledFilter = OSQLEngine.getInstance().parseCondition(parserText.substring(parserGetCurrentPosition()), getContext(), KEYWORD_WHERE);
        } else if (additionalStatement.equals(OCommandExecutorSQLAbstract.KEYWORD_WHERE) || additionalStatement.equals(OCommandExecutorSQLAbstract.KEYWORD_LIMIT) || additionalStatement.equals(OCommandExecutorSQLAbstract.KEYWORD_LET) || additionalStatement.equals(KEYWORD_LOCK)) {
            if (this.preParsedStatement != null) {
                Map<Object, Object> params = ((OCommandRequestText) iRequest).getParameters();
                OUpdateStatement updateStm = (OUpdateStatement) preParsedStatement;
                StringBuilder selectString = new StringBuilder();
                selectString.append("select from ");
                updateStm.target.toString(params, selectString);
                if (updateStm.let != null) {
                    selectString.append(" ");
                    updateStm.let.toString(params, selectString);
                }
                if (updateStm.whereClause != null) {
                    selectString.append(" WHERE ");
                    updateStm.whereClause.toString(params, selectString);
                }
                if (updateStm.limit != null) {
                    selectString.append(" ");
                    updateStm.limit.toString(params, selectString);
                }
                if (updateStm.timeout != null) {
                    selectString.append(" ");
                    updateStm.timeout.toString(params, selectString);
                }
                if (updateStm.lockRecord != null) {
                    selectString.append(" LOCK ");
                    switch(updateStm.lockRecord) {
                        case DEFAULT:
                            selectString.append("DEFAULT");
                            break;
                        case EXCLUSIVE_LOCK:
                            selectString.append("RECORD");
                            break;
                        case SHARED_LOCK:
                            selectString.append("SHARED");
                            break;
                        case NONE:
                            selectString.append("NONE");
                            break;
                    }
                }
                query = new OSQLAsynchQuery<ODocument>(selectString.toString(), this);
            } else {
                query = new OSQLAsynchQuery<ODocument>("select from " + getSelectTarget() + " " + additionalStatement + " " + parserText.substring(parserGetCurrentPosition()), this);
            }
            isUpsertAllowed = (((OMetadataInternal) getDatabase().getMetadata()).getImmutableSchemaSnapshot().getClass(subjectName) != null);
        } else if (!additionalStatement.isEmpty())
            throwSyntaxErrorException("Invalid keyword " + additionalStatement);
        else
            query = new OSQLAsynchQuery<ODocument>("select from " + getSelectTarget(), this);
        if (upsertMode && !isUpsertAllowed)
            throwSyntaxErrorException("Upsert only works with class names ");
        if (upsertMode && !additionalStatement.equals(OCommandExecutorSQLAbstract.KEYWORD_WHERE))
            throwSyntaxErrorException("Upsert only works with WHERE keyword");
        if (upsertMode && updateEdge)
            throwSyntaxErrorException("Upsert is not supported with UPDATE EDGE");
    } finally {
        textRequest.setText(originalQuery);
    }
    return this;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OSQLAsynchQuery(com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) OUpdateStatement(com.orientechnologies.orient.core.sql.parser.OUpdateStatement)

Aggregations

OSQLAsynchQuery (com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery)12 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)8 OSQLSynchQuery (com.orientechnologies.orient.core.sql.query.OSQLSynchQuery)6 OCommandRequestText (com.orientechnologies.orient.core.command.OCommandRequestText)4 OCommandResultListener (com.orientechnologies.orient.core.command.OCommandResultListener)4 OCommandSQLParsingException (com.orientechnologies.orient.core.sql.OCommandSQLParsingException)3 ORecordId (com.orientechnologies.orient.core.id.ORecordId)2 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Test (org.testng.annotations.Test)2 OException (com.orientechnologies.common.exception.OException)1 OIOException (com.orientechnologies.common.io.OIOException)1 OModifiableBoolean (com.orientechnologies.common.types.OModifiableBoolean)1 OCommandCache (com.orientechnologies.orient.core.cache.OCommandCache)1 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)1 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)1 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)1 ORID (com.orientechnologies.orient.core.id.ORID)1 OMetadataInternal (com.orientechnologies.orient.core.metadata.OMetadataInternal)1 ORecord (com.orientechnologies.orient.core.record.ORecord)1