Search in sources :

Example 11 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException in project orientdb by orientechnologies.

the class OCommandExecutorSQLInsert method execute.

/**
   * Execute the INSERT and return the ODocument object created.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (newRecords == null && content == null && subQuery == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    final OCommandParameters commandParameters = new OCommandParameters(iArgs);
    if (indexName != null) {
        if (newRecords == null)
            throw new OCommandExecutionException("No key/value found");
        final OIndex<?> index = getDatabase().getMetadata().getIndexManager().getIndex(indexName);
        if (index == null)
            throw new OCommandExecutionException("Target index '" + indexName + "' not found");
        // BIND VALUES
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map<String, Object> candidate : newRecords) {
            Object indexKey = getIndexKeyValue(commandParameters, candidate);
            OIdentifiable indexValue = getIndexValue(commandParameters, candidate);
            index.put(indexKey, indexValue);
            result.put(KEYWORD_KEY, indexKey);
            result.put(KEYWORD_RID, indexValue);
        }
        // RETURN LAST ENTRY
        return prepareReturnItem(new ODocument(result));
    } else {
        // CREATE NEW DOCUMENTS
        final List<ODocument> docs = new ArrayList<ODocument>();
        if (newRecords != null) {
            for (Map<String, Object> candidate : newRecords) {
                final ODocument doc = className != null ? new ODocument(className) : new ODocument();
                OSQLHelper.bindParameters(doc, candidate, commandParameters, context);
                saveRecord(doc);
                docs.add(doc);
            }
            if (docs.size() == 1)
                return prepareReturnItem(docs.get(0));
            else
                return prepareReturnResult(docs);
        } else if (content != null) {
            final ODocument doc = className != null ? new ODocument(className) : new ODocument();
            doc.merge(content, true, false);
            saveRecord(doc);
            return prepareReturnItem(doc);
        } else if (subQuery != null) {
            subQuery.execute();
            if (queryResult != null)
                return prepareReturnResult(queryResult);
            return saved.longValue();
        }
    }
    return null;
}
Also used : OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 12 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException in project orientdb by orientechnologies.

the class OCommandExecutorSQLCreateIndex method parse.

public OCommandExecutorSQLCreateIndex parse(final OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    String queryText = textRequest.getText();
    String originalQuery = queryText;
    try {
        queryText = preParse(queryText, iRequest);
        textRequest.setText(queryText);
        init((OCommandRequestText) iRequest);
        final StringBuilder word = new StringBuilder();
        int oldPos = 0;
        int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
        if (pos == -1 || !word.toString().equals(KEYWORD_CREATE))
            throw new OCommandSQLParsingException("Keyword " + KEYWORD_CREATE + " not found. Use " + getSyntax(), parserText, oldPos);
        oldPos = pos;
        pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
        if (pos == -1 || !word.toString().equals(KEYWORD_INDEX))
            throw new OCommandSQLParsingException("Keyword " + KEYWORD_INDEX + " not found. Use " + getSyntax(), parserText, oldPos);
        oldPos = pos;
        pos = nextWord(parserText, parserTextUpperCase, oldPos, word, false);
        if (pos == -1)
            throw new OCommandSQLParsingException("Expected index name. Use " + getSyntax(), parserText, oldPos);
        indexName = decodeClassName(word.toString());
        oldPos = pos;
        pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
        if (pos == -1)
            throw new OCommandSQLParsingException("Index type requested. Use " + getSyntax(), parserText, oldPos + 1);
        if (word.toString().equals(KEYWORD_ON)) {
            oldPos = pos;
            pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
            if (pos == -1)
                throw new OCommandSQLParsingException("Expected class name. Use " + getSyntax(), parserText, oldPos);
            oldPos = pos;
            oClass = findClass(decodeClassName(word.toString()));
            if (oClass == null)
                throw new OCommandExecutionException("Class " + word + " not found");
            pos = parserTextUpperCase.indexOf(")");
            if (pos == -1) {
                throw new OCommandSQLParsingException("No right bracket found. Use " + getSyntax(), parserText, oldPos);
            }
            final String props = parserText.substring(oldPos, pos).trim().substring(1);
            List<String> propList = new ArrayList<String>();
            Collections.addAll(propList, OPatternConst.PATTERN_COMMA_SEPARATED.split(props.trim()));
            fields = new String[propList.size()];
            propList.toArray(fields);
            for (int i = 0; i < fields.length; i++) {
                final String fieldName = fields[i];
                final int collatePos = fieldName.toUpperCase().indexOf(" COLLATE ");
                if (collatePos > 0) {
                    if (collates == null)
                        collates = new String[fields.length];
                    collates[i] = fieldName.substring(collatePos + " COLLATE ".length()).toLowerCase().trim();
                    fields[i] = fieldName.substring(0, collatePos);
                } else {
                    if (collates != null)
                        collates[i] = null;
                }
                fields[i] = decodeClassName(fields[i]);
            }
            for (String propToIndex : fields) {
                checkMapIndexSpecifier(propToIndex, parserText, oldPos);
                propList.add(propToIndex);
            }
            oldPos = pos + 1;
            pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
            if (pos == -1)
                throw new OCommandSQLParsingException("Index type requested. Use " + getSyntax(), parserText, oldPos + 1);
        } else {
            if (indexName.indexOf('.') > 0) {
                final String[] parts = indexName.split("\\.");
                oClass = findClass(parts[0]);
                if (oClass == null)
                    throw new OCommandExecutionException("Class " + parts[0] + " not found");
                fields = new String[] { parts[1] };
            }
        }
        indexType = OClass.INDEX_TYPE.valueOf(word.toString());
        if (indexType == null)
            throw new OCommandSQLParsingException("Index type is null", parserText, oldPos);
        oldPos = pos;
        pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
        if (word.toString().equals(KEYWORD_ENGINE)) {
            oldPos = pos;
            pos = nextWord(parserText, parserTextUpperCase, oldPos, word, false);
            oldPos = pos;
            engine = word.toString().toUpperCase();
        } else
            parserGoBack();
        final int configPos = parserTextUpperCase.indexOf(KEYWORD_METADATA, oldPos);
        if (configPos > -1) {
            final String configString = parserText.substring(configPos + KEYWORD_METADATA.length()).trim();
            metadataDoc = new ODocument().fromJSON(configString);
        }
        pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
        if (pos != -1 && !word.toString().equalsIgnoreCase("NULL") && !word.toString().equalsIgnoreCase(KEYWORD_METADATA)) {
            final String typesString;
            if (configPos > -1)
                typesString = parserTextUpperCase.substring(oldPos, configPos).trim();
            else
                typesString = parserTextUpperCase.substring(oldPos).trim();
            if (word.toString().equalsIgnoreCase("RUNTIME")) {
                oldPos = pos;
                pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
                serializerKeyId = Byte.parseByte(word.toString());
            } else {
                ArrayList<OType> keyTypeList = new ArrayList<OType>();
                for (String typeName : OPatternConst.PATTERN_COMMA_SEPARATED.split(typesString)) {
                    keyTypeList.add(OType.valueOf(typeName));
                }
                keyTypes = new OType[keyTypeList.size()];
                keyTypeList.toArray(keyTypes);
                if (fields != null && fields.length != 0 && fields.length != keyTypes.length) {
                    throw new OCommandSQLParsingException("Count of fields does not match with count of property types. " + "Fields: " + Arrays.toString(fields) + "; Types: " + Arrays.toString(keyTypes), parserText, oldPos);
                }
            }
        }
    } finally {
        textRequest.setText(originalQuery);
    }
    return this;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) ArrayList(java.util.ArrayList) OType(com.orientechnologies.orient.core.metadata.schema.OType) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 13 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException in project orientdb by orientechnologies.

the class OCommandExecutorSQLCreateIndex method execute.

/**
   * Execute the CREATE INDEX.
   */
@SuppressWarnings("rawtypes")
public Object execute(final Map<Object, Object> iArgs) {
    if (indexName == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    final ODatabaseDocument database = getDatabase();
    final OIndex<?> idx;
    List<OCollate> collatesList = null;
    if (collates != null) {
        collatesList = new ArrayList<OCollate>();
        for (String collate : collates) {
            if (collate != null) {
                final OCollate col = OSQLEngine.getCollate(collate);
                collatesList.add(col);
            } else
                collatesList.add(null);
        }
    }
    if (fields == null || fields.length == 0) {
        OIndexFactory factory = OIndexes.getFactory(indexType.toString(), null);
        if (keyTypes != null)
            idx = database.getMetadata().getIndexManager().createIndex(indexName, indexType.toString(), new OSimpleKeyIndexDefinition(keyTypes, collatesList, factory.getLastVersion()), null, null, metadataDoc, engine);
        else if (serializerKeyId != 0) {
            idx = database.getMetadata().getIndexManager().createIndex(indexName, indexType.toString(), new ORuntimeKeyIndexDefinition(serializerKeyId, factory.getLastVersion()), null, null, metadataDoc, engine);
        } else {
            OLogManager.instance().warn(this, "Key type is not provided for '%s' index. Untyped indexes are deprecated and considered unstable." + " Please specify a key type.", indexName);
            idx = database.getMetadata().getIndexManager().createIndex(indexName, indexType.toString(), null, null, null, metadataDoc, engine);
        }
    } else {
        if ((keyTypes == null || keyTypes.length == 0) && collates == null) {
            idx = oClass.createIndex(indexName, indexType.toString(), null, metadataDoc, engine, fields);
        } else {
            final List<OType> fieldTypeList;
            if (keyTypes == null) {
                for (final String fieldName : fields) {
                    if (!fieldName.equals("@rid") && !oClass.existsProperty(fieldName))
                        throw new OIndexException("Index with name : '" + indexName + "' cannot be created on class : '" + oClass.getName() + "' because field: '" + fieldName + "' is absent in class definition.");
                }
                fieldTypeList = ((OClassImpl) oClass).extractFieldTypes(fields);
            } else
                fieldTypeList = Arrays.asList(keyTypes);
            final OIndexDefinition idxDef = OIndexDefinitionFactory.createIndexDefinition(oClass, Arrays.asList(fields), fieldTypeList, collatesList, indexType.toString(), null);
            idx = database.getMetadata().getIndexManager().createIndex(indexName, indexType.name(), idxDef, oClass.getPolymorphicClusterIds(), null, metadataDoc, engine);
        }
    }
    if (idx != null)
        return idx.getSize();
    return null;
}
Also used : OType(com.orientechnologies.orient.core.metadata.schema.OType) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OCollate(com.orientechnologies.orient.core.collate.OCollate)

Example 14 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException in project orientdb by orientechnologies.

the class OCommandExecutorSQLTransactional method execute.

@Override
public Object execute(Map<Object, Object> iArgs) {
    final ODatabaseDocument database = getDatabase();
    boolean txbegun = database.getTransaction() == null || !database.getTransaction().isActive();
    if (txbegun)
        database.begin();
    try {
        final Object result = super.execute(iArgs);
        if (txbegun)
            database.commit();
        return result;
    } catch (Exception e) {
        if (txbegun)
            database.rollback();
        throw OException.wrapException(new OCommandExecutionException("Transactional command failed"), e);
    }
}
Also used : ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OException(com.orientechnologies.common.exception.OException)

Example 15 with OCommandExecutionException

use of com.orientechnologies.orient.core.exception.OCommandExecutionException 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)

Aggregations

OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)82 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)20 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)19 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)16 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)15 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)14 OException (com.orientechnologies.common.exception.OException)9 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)9 OSQLSynchQuery (com.orientechnologies.orient.core.sql.query.OSQLSynchQuery)6 IOException (java.io.IOException)6 OCommandRequestText (com.orientechnologies.orient.core.command.OCommandRequestText)5 OType (com.orientechnologies.orient.core.metadata.schema.OType)5 OQueryParsingException (com.orientechnologies.orient.core.exception.OQueryParsingException)4 OSchema (com.orientechnologies.orient.core.metadata.schema.OSchema)4 ORecord (com.orientechnologies.orient.core.record.ORecord)4 OHazelcastPlugin (com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin)4 OrientVertex (com.tinkerpop.blueprints.impls.orient.OrientVertex)4 ArrayList (java.util.ArrayList)4 ORID (com.orientechnologies.orient.core.id.ORID)3 ORecordId (com.orientechnologies.orient.core.id.ORecordId)3