Search in sources :

Example 1 with OCommandSQLParsingException

use of com.orientechnologies.orient.core.sql.OCommandSQLParsingException 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 2 with OCommandSQLParsingException

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

the class OCommandExecutorScript method executeSQLScript.

protected Object executeSQLScript(final String iText, final ODatabaseDocument db) throws IOException {
    Object lastResult = null;
    int maxRetry = 1;
    context.setVariable("transactionRetries", 0);
    context.setVariable("parentQuery", this);
    for (int retry = 1; retry <= maxRetry; retry++) {
        try {
            try {
                int txBegunAtLine = -1;
                int txBegunAtPart = -1;
                lastResult = null;
                int nestedLevel = 0;
                int skippingScriptsAtNestedLevel = -1;
                final BufferedReader reader = new BufferedReader(new StringReader(iText));
                int line = 0;
                int linePart = 0;
                String lastLine;
                boolean txBegun = false;
                for (; line < txBegunAtLine; ++line) // SKIP PREVIOUS COMMAND AND JUMP TO THE BEGIN IF ANY
                reader.readLine();
                for (; (lastLine = reader.readLine()) != null; ++line) {
                    lastLine = lastLine.trim();
                    // this block is here (and not below, with the other conditions)
                    // just because of the smartSprit() that does not parse correctly a single bracket
                    // final List<String> lineParts = OStringSerializerHelper.smartSplit(lastLine, ';', true);
                    final List<String> lineParts = splitBySemicolon(lastLine);
                    if (line == txBegunAtLine)
                        // SKIP PREVIOUS COMMAND PART AND JUMP TO THE BEGIN IF ANY
                        linePart = txBegunAtPart;
                    else
                        linePart = 0;
                    boolean breakReturn = false;
                    for (; linePart < lineParts.size(); ++linePart) {
                        final String lastCommand = lineParts.get(linePart);
                        if (isIfCondition(lastCommand)) {
                            nestedLevel++;
                            if (skippingScriptsAtNestedLevel >= 0) {
                                // I'm in an (outer) IF that did not match the condition
                                continue;
                            }
                            boolean ifResult = evaluateIfCondition(lastCommand);
                            if (!ifResult) {
                                // if does not match the condition, skip all the inner statements
                                skippingScriptsAtNestedLevel = nestedLevel;
                            }
                            continue;
                        } else if (lastCommand.equals("}")) {
                            nestedLevel--;
                            if (skippingScriptsAtNestedLevel > nestedLevel) {
                                skippingScriptsAtNestedLevel = -1;
                            }
                            continue;
                        } else if (skippingScriptsAtNestedLevel >= 0) {
                            // I'm in an IF that did not match the condition
                            continue;
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "let ")) {
                            lastResult = executeLet(lastCommand, db);
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "begin")) {
                            if (txBegun)
                                throw new OCommandSQLParsingException("Transaction already begun");
                            if (db.getTransaction().isActive())
                                // COMMIT ANY ACTIVE TX
                                db.commit();
                            txBegun = true;
                            txBegunAtLine = line;
                            txBegunAtPart = linePart;
                            db.begin();
                            if (lastCommand.length() > "begin ".length()) {
                                String next = lastCommand.substring("begin ".length()).trim();
                                if (OStringSerializerHelper.startsWithIgnoreCase(next, "isolation ")) {
                                    next = next.substring("isolation ".length()).trim();
                                    db.getTransaction().setIsolationLevel(OTransaction.ISOLATION_LEVEL.valueOf(next.toUpperCase(Locale.ENGLISH)));
                                }
                            }
                        } else if ("rollback".equalsIgnoreCase(lastCommand)) {
                            if (!txBegun)
                                throw new OCommandSQLParsingException("Transaction not begun");
                            db.rollback();
                            txBegun = false;
                            txBegunAtLine = -1;
                            txBegunAtPart = -1;
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "commit")) {
                            if (txBegunAtLine < 0)
                                throw new OCommandSQLParsingException("Transaction not begun");
                            if (retry == 1 && lastCommand.length() > "commit ".length()) {
                                // FIRST CYCLE: PARSE RETRY TIMES OVERWRITING DEFAULT = 1
                                String next = lastCommand.substring("commit ".length()).trim();
                                if (OStringSerializerHelper.startsWithIgnoreCase(next, "retry ")) {
                                    next = next.substring("retry ".length()).trim();
                                    maxRetry = Integer.parseInt(next);
                                }
                            }
                            db.commit();
                            txBegun = false;
                            txBegunAtLine = -1;
                            txBegunAtPart = -1;
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "sleep ")) {
                            executeSleep(lastCommand);
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "console.log ")) {
                            executeConsoleLog(lastCommand, db);
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "console.output ")) {
                            executeConsoleOutput(lastCommand, db);
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "console.error ")) {
                            executeConsoleError(lastCommand, db);
                        } else if (OStringSerializerHelper.startsWithIgnoreCase(lastCommand, "return ")) {
                            lastResult = getValue(lastCommand.substring("return ".length()), db);
                            // END OF SCRIPT
                            breakReturn = true;
                            break;
                        } else if (lastCommand != null && lastCommand.length() > 0)
                            lastResult = executeCommand(lastCommand, db);
                    }
                    if (breakReturn) {
                        break;
                    }
                }
            } catch (RuntimeException ex) {
                if (db.getTransaction().isActive())
                    db.rollback();
                throw ex;
            }
            // COMPLETED
            break;
        } catch (OTransactionException e) {
            // THIS CASE IS ON UPSERT
            context.setVariable("retries", retry);
            getDatabase().getLocalCache().clear();
            if (retry >= maxRetry)
                throw e;
            waitForNextRetry();
        } catch (ORecordDuplicatedException e) {
            // THIS CASE IS ON UPSERT
            context.setVariable("retries", retry);
            getDatabase().getLocalCache().clear();
            if (retry >= maxRetry)
                throw e;
            waitForNextRetry();
        } catch (ORecordNotFoundException e) {
            // THIS CASE IS ON UPSERT
            context.setVariable("retries", retry);
            getDatabase().getLocalCache().clear();
            if (retry >= maxRetry)
                throw e;
        } catch (ONeedRetryException e) {
            context.setVariable("retries", retry);
            getDatabase().getLocalCache().clear();
            if (retry >= maxRetry)
                throw e;
            waitForNextRetry();
        }
    }
    return lastResult;
}
Also used : OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) ONeedRetryException(com.orientechnologies.common.concur.ONeedRetryException) ORecordDuplicatedException(com.orientechnologies.orient.core.storage.ORecordDuplicatedException) OTransactionException(com.orientechnologies.orient.core.exception.OTransactionException) ORecordNotFoundException(com.orientechnologies.orient.core.exception.ORecordNotFoundException)

Example 3 with OCommandSQLParsingException

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

the class OSQLMethodRuntime method setRoot.

@Override
protected void setRoot(final OBaseParser iQueryToParse, final String iText) {
    final int beginParenthesis = iText.indexOf('(');
    // SEARCH FOR THE FUNCTION
    final String funcName = iText.substring(0, beginParenthesis);
    final List<String> funcParamsText = OStringSerializerHelper.getParameters(iText);
    method = OSQLEngine.getInstance().getMethod(funcName);
    if (method == null)
        throw new OCommandSQLParsingException("Unknown method " + funcName + "()");
    // PARSE PARAMETERS
    this.configuredParameters = new Object[funcParamsText.size()];
    for (int i = 0; i < funcParamsText.size(); ++i) this.configuredParameters[i] = funcParamsText.get(i);
    setParameters(configuredParameters, true);
}
Also used : OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException)

Example 4 with OCommandSQLParsingException

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

the class OCommandExecutorSQLCreateVertex method parse.

@SuppressWarnings("unchecked")
public OCommandExecutorSQLCreateVertex parse(final OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    String queryText = textRequest.getText();
    String originalQuery = queryText;
    try {
        queryText = preParse(queryText, iRequest);
        textRequest.setText(queryText);
        final ODatabaseDocument database = getDatabase();
        init((OCommandRequestText) iRequest);
        String className = null;
        parserRequiredKeyword("CREATE");
        parserRequiredKeyword("VERTEX");
        String temp = parseOptionalWord(true);
        while (temp != null) {
            if (temp.equals("CLUSTER")) {
                clusterName = parserRequiredWord(false);
            } else if (temp.equals(KEYWORD_SET)) {
                fields = new ArrayList<OPair<String, Object>>();
                parseSetFields(clazz, fields);
            } else if (temp.equals(KEYWORD_CONTENT)) {
                parseContent();
            } else if (className == null && temp.length() > 0) {
                className = temp;
                if (className == null)
                    // ASSIGN DEFAULT CLASS
                    className = OrientVertexType.CLASS_NAME;
                // GET/CHECK CLASS NAME
                clazz = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(className);
                if (clazz == null)
                    throw new OCommandSQLParsingException("Class '" + className + "' was not found");
            }
            temp = parserOptionalWord(true);
            if (parserIsEnded())
                break;
        }
        if (className == null) {
            // ASSIGN DEFAULT CLASS
            className = OrientVertexType.CLASS_NAME;
            // GET/CHECK CLASS NAME
            clazz = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(className);
            if (clazz == null)
                throw new OCommandSQLParsingException("Class '" + className + "' was not found");
        }
    } finally {
        textRequest.setText(originalQuery);
    }
    return this;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) OMetadataInternal(com.orientechnologies.orient.core.metadata.OMetadataInternal)

Example 5 with OCommandSQLParsingException

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

the class OCommandExecutorSQLDeleteVertex method parse.

@SuppressWarnings("unchecked")
public OCommandExecutorSQLDeleteVertex 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);
        database = getDatabase();
        init((OCommandRequestText) iRequest);
        parserRequiredKeyword("DELETE");
        parserRequiredKeyword("VERTEX");
        OClass clazz = null;
        String where = null;
        int limit = -1;
        String word = parseOptionalWord(true);
        while (word != null) {
            if (word.startsWith("#")) {
                rid = new ORecordId(word);
            } else if (word.equalsIgnoreCase("from")) {
                final StringBuilder q = new StringBuilder();
                final int newPos = OStringSerializerHelper.getEmbedded(parserText, parserGetCurrentPosition(), -1, q);
                query = database.command(new OSQLAsynchQuery<ODocument>(q.toString(), this));
                parserSetCurrentPosition(newPos);
            } else if (word.equals(KEYWORD_WHERE)) {
                if (clazz == null)
                    // ASSIGN DEFAULT CLASS
                    clazz = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(OrientVertexType.CLASS_NAME);
                where = parserGetCurrentPosition() > -1 ? " " + parserText.substring(parserGetPreviousPosition()) : "";
                query = database.command(new OSQLAsynchQuery<ODocument>("select from `" + clazz.getName() + "`" + where, this));
                break;
            } else if (word.equals(KEYWORD_LIMIT)) {
                word = parseOptionalWord(true);
                try {
                    limit = Integer.parseInt(word);
                } catch (Exception e) {
                    throw OException.wrapException(new OCommandSQLParsingException("Invalid LIMIT: " + word), e);
                }
            } else if (word.equals(KEYWORD_RETURN)) {
                returning = parseReturn();
            } else if (word.equals(KEYWORD_BATCH)) {
                word = parserNextWord(true);
                if (word != null)
                    batch = Integer.parseInt(word);
            } else if (word.length() > 0) {
                // GET/CHECK CLASS NAME
                clazz = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(word);
                if (clazz == null)
                    throw new OCommandSQLParsingException("Class '" + word + "' was not found");
            }
            word = parseOptionalWord(true);
            if (parserIsEnded())
                break;
        }
        if (where == null)
            where = "";
        else
            where = " WHERE " + where;
        if (query == null && rid == null) {
            StringBuilder queryString = new StringBuilder();
            queryString.append("select from `");
            if (clazz == null) {
                queryString.append(OrientVertexType.CLASS_NAME);
            } else {
                queryString.append(clazz.getName());
            }
            queryString.append("`");
            queryString.append(where);
            if (limit > -1) {
                queryString.append(" LIMIT ").append(limit);
            }
            query = database.command(new OSQLAsynchQuery<ODocument>(queryString.toString(), this));
        }
    } finally {
        textRequest.setText(originalQuery);
    }
    return this;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) OMetadataInternal(com.orientechnologies.orient.core.metadata.OMetadataInternal) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OSQLAsynchQuery(com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery) ORecordId(com.orientechnologies.orient.core.id.ORecordId) OException(com.orientechnologies.common.exception.OException) OCommandSQLParsingException(com.orientechnologies.orient.core.sql.OCommandSQLParsingException) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OCommandSQLParsingException (com.orientechnologies.orient.core.sql.OCommandSQLParsingException)9 OSQLAsynchQuery (com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery)3 OException (com.orientechnologies.common.exception.OException)2 OCommandRequestText (com.orientechnologies.orient.core.command.OCommandRequestText)2 ORecordId (com.orientechnologies.orient.core.id.ORecordId)2 OMetadataInternal (com.orientechnologies.orient.core.metadata.OMetadataInternal)2 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)2 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)2 ONeedRetryException (com.orientechnologies.common.concur.ONeedRetryException)1 OModifiableBoolean (com.orientechnologies.common.types.OModifiableBoolean)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 OQueryParsingException (com.orientechnologies.orient.core.exception.OQueryParsingException)1 ORecordNotFoundException (com.orientechnologies.orient.core.exception.ORecordNotFoundException)1 OTransactionException (com.orientechnologies.orient.core.exception.OTransactionException)1 ORID (com.orientechnologies.orient.core.id.ORID)1 OIndexManagerProxy (com.orientechnologies.orient.core.index.OIndexManagerProxy)1 OSimpleKeyIndexDefinition (com.orientechnologies.orient.core.index.OSimpleKeyIndexDefinition)1 OSQLSynchQuery (com.orientechnologies.orient.core.sql.query.OSQLSynchQuery)1