Search in sources :

Example 26 with OCommandScript

use of com.orientechnologies.orient.core.command.script.OCommandScript in project orientdb by orientechnologies.

the class OCommandExecutorSQLScriptTest method testReturnExpanded.

@Test
public void testReturnExpanded() throws Exception {
    StringBuilder script = new StringBuilder();
    script.append("let $a = insert into V set test = 'sql script test'\n");
    script.append("return $a.toJSON()\n");
    String qResult = db.command(new OCommandScript("sql", script.toString())).execute();
    Assert.assertNotNull(qResult);
    new ODocument().fromJSON(qResult);
    script = new StringBuilder();
    script.append("let $a = select from V limit 2\n");
    script.append("return $a.toJSON()\n");
    String result = db.command(new OCommandScript("sql", script.toString())).execute();
    Assert.assertNotNull(result);
    result = result.trim();
    Assert.assertTrue(result.startsWith("["));
    Assert.assertTrue(result.endsWith("]"));
    new ODocument().fromJSON(result.substring(1, result.length() - 1));
}
Also used : OCommandScript(com.orientechnologies.orient.core.command.script.OCommandScript) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.testng.annotations.Test)

Example 27 with OCommandScript

use of com.orientechnologies.orient.core.command.script.OCommandScript in project orientdb by orientechnologies.

the class OCommandExecutorSQLScriptTest method testQuotedRegex.

@Test
public void testQuotedRegex() {
    //issue #4996 (simplified)
    db.command(new OCommandSQL("CREATE CLASS QuotedRegex2")).execute();
    String batch = "INSERT INTO QuotedRegex2 SET regexp=\"'';\"";
    db.command(new OCommandScript(batch.toString())).execute();
    List<ODocument> result = db.query(new OSQLSynchQuery<ODocument>("SELECT FROM QuotedRegex2"));
    Assert.assertEquals(result.size(), 1);
    ODocument doc = result.get(0);
    Assert.assertEquals(doc.field("regexp"), "'';");
}
Also used : OCommandScript(com.orientechnologies.orient.core.command.script.OCommandScript) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.testng.annotations.Test)

Example 28 with OCommandScript

use of com.orientechnologies.orient.core.command.script.OCommandScript in project orientdb by orientechnologies.

the class ODistributedStorage method command.

public Object command(final OCommandRequestText iCommand) {
    List<String> servers = (List<String>) iCommand.getContext().getVariable("servers");
    if (servers == null) {
        servers = new ArrayList<String>();
        iCommand.getContext().setVariable("servers", servers);
    }
    final String localNodeName = dManager.getLocalNodeName();
    servers.add(localNodeName);
    if (OScenarioThreadLocal.INSTANCE.isRunModeDistributed())
        // ALREADY DISTRIBUTED
        return wrapped.command(iCommand);
    final ODistributedConfiguration dbCfg = distributedConfiguration;
    if (!dbCfg.isReplicationActive(null, localNodeName))
        // DON'T REPLICATE
        return wrapped.command(iCommand);
    final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand);
    executor.setProgressListener(iCommand.getProgressListener());
    executor.parse(iCommand);
    final OCommandExecutor exec = executor instanceof OCommandExecutorSQLDelegate ? ((OCommandExecutorSQLDelegate) executor).getDelegate() : executor;
    if (exec.isIdempotent() && !dManager.isNodeAvailable(dManager.getLocalNodeName(), getName())) {
        // SPECIAL CASE: NODE IS OFFLINE AND THE COMMAND IS IDEMPOTENT, EXECUTE IT LOCALLY ONLY
        ODistributedServerLog.warn(this, dManager.getLocalNodeName(), null, ODistributedServerLog.DIRECTION.NONE, "Node '%s' is %s, the command '%s' against database '%s' will be executed only on local server with the possibility to have partial result", dManager.getLocalNodeName(), dManager.getDatabaseStatus(dManager.getLocalNodeName(), getName()), iCommand, wrapped.getName());
        return wrapped.command(iCommand);
    }
    checkLocalNodeIsAvailable();
    if (!exec.isIdempotent())
        checkNodeIsMaster(localNodeName, dbCfg);
    try {
        Object result = null;
        OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE executionMode = OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE.LOCAL;
        OCommandDistributedReplicateRequest.DISTRIBUTED_RESULT_MGMT resultMgmt = OCommandDistributedReplicateRequest.DISTRIBUTED_RESULT_MGMT.CHECK_FOR_EQUALS;
        boolean executeOnLocalNodeFirst = true;
        if (OScenarioThreadLocal.INSTANCE.getRunMode() != RUN_MODE.RUNNING_DISTRIBUTED) {
            if (exec instanceof OCommandDistributedReplicateRequest) {
                executionMode = ((OCommandDistributedReplicateRequest) exec).getDistributedExecutionMode();
                resultMgmt = ((OCommandDistributedReplicateRequest) exec).getDistributedResultManagement();
                executeOnLocalNodeFirst = ((OCommandDistributedReplicateRequest) exec).isDistributedExecutingOnLocalNodeFirst();
            }
        }
        switch(executionMode) {
            case LOCAL:
                // CALL IN DEFAULT MODE TO LET OWN COMMAND TO REDISTRIBUTE CHANGES (LIKE INSERT)
                return wrapped.command(iCommand);
            case REPLICATE:
                // REPLICATE IT, GET ALL THE INVOLVED NODES
                final Collection<String> involvedClusters = exec.getInvolvedClusters();
                if (resultMgmt == OCommandDistributedReplicateRequest.DISTRIBUTED_RESULT_MGMT.MERGE) {
                    if (!exec.isIdempotent() && dbCfg.isSharded())
                        throw new ODistributedOperationException("Cannot distribute the command '" + iCommand.getText() + "' because it is not idempotent and a map-reduce has been requested");
                    final Map<String, Collection<String>> nodeClusterMap = dbCfg.getServerClusterMap(involvedClusters, localNodeName, exec.isIdempotent());
                    final Map<String, Object> results;
                    if (exec.isIdempotent() && nodeClusterMap.size() == 1 && nodeClusterMap.keySet().iterator().next().equals(localNodeName)) {
                        // LOCAL NODE, AVOID TO DISTRIBUTE IT
                        // CALL IN DEFAULT MODE TO LET OWN COMMAND TO REDISTRIBUTE CHANGES (LIKE INSERT)
                        result = wrapped.command(iCommand);
                        results = new HashMap<String, Object>(1);
                        results.put(localNodeName, result);
                    } else {
                        // SELECT: SPLIT CLASSES/CLUSTER IF ANY
                        results = executeOnServers(iCommand, exec, involvedClusters, nodeClusterMap);
                    }
                    final OCommandExecutorSQLSelect select = exec instanceof OCommandExecutorSQLSelect ? (OCommandExecutorSQLSelect) exec : null;
                    if (select != null && select.isAnyFunctionAggregates() && !select.hasGroupBy()) {
                        result = mergeResultByAggregation(select, results);
                    } else {
                        // MIX & FILTER RESULT SET AVOIDING DUPLICATES
                        // TODO: ONCE OPTIMIZED (SEE ABOVE) AVOID TO FILTER HERE
                        result = exec.mergeResults(results);
                    }
                    if (result instanceof Throwable && results.containsKey(localNodeName))
                        undoCommandOnLocalServer(iCommand);
                } else {
                    final OAbstractCommandTask task = iCommand instanceof OCommandScript ? new OScriptTask(iCommand) : new OSQLCommandTask(iCommand, new HashSet<String>());
                    task.setResultStrategy(OAbstractRemoteTask.RESULT_STRATEGY.ANY);
                    final Set<String> nodes = dbCfg.getServers(involvedClusters);
                    if (iCommand instanceof ODistributedCommand)
                        nodes.removeAll(((ODistributedCommand) iCommand).nodesToExclude());
                    if (executeOnlyLocally(localNodeName, dbCfg, exec, involvedClusters, nodes))
                        // CALL IN DEFAULT MODE TO LET OWN COMMAND TO REDISTRIBUTE CHANGES (LIKE INSERT)
                        return wrapped.command(iCommand);
                    final Object localResult;
                    final boolean executedLocally = executeOnLocalNodeFirst && nodes.contains(localNodeName);
                    if (exec.involveSchema())
                        // EXECUTE THE COMMAND IN LOCK
                        result = dManager.executeInDistributedDatabaseLock(getName(), 0, dManager.getDatabaseConfiguration(getName()).modify(), new OCallable<Object, OModifiableDistributedConfiguration>() {

                            @Override
                            public Object call(OModifiableDistributedConfiguration iArgument) {
                                return executeCommand(iCommand, localNodeName, involvedClusters, task, nodes, executedLocally);
                            }
                        });
                    else
                        result = executeCommand(iCommand, localNodeName, involvedClusters, task, nodes, executedLocally);
                }
                if (exec.involveSchema())
                    // UPDATE THE SCHEMA
                    dManager.propagateSchemaChanges(ODatabaseRecordThreadLocal.INSTANCE.get());
                break;
        }
        if (result instanceof ONeedRetryException)
            throw (ONeedRetryException) result;
        else if (result instanceof RuntimeException)
            throw (RuntimeException) result;
        else if (result instanceof Exception)
            throw OException.wrapException(new ODistributedException("Error on execution distributed COMMAND"), (Exception) result);
        return result;
    } catch (OConcurrentModificationException e) {
        localDistributedDatabase.getDatabaseRepairer().enqueueRepairRecord((ORecordId) e.getRid());
        throw e;
    } catch (ONeedRetryException e) {
        // PASS THROUGH
        throw e;
    } catch (HazelcastInstanceNotActiveException e) {
        throw new OOfflineNodeException("Hazelcast instance is not available");
    } catch (HazelcastException e) {
        throw new OOfflineNodeException("Hazelcast instance is not available");
    } catch (Exception e) {
        handleDistributedException("Cannot route COMMAND operation to the distributed node", e);
        // UNREACHABLE
        return null;
    }
}
Also used : OOfflineNodeException(com.orientechnologies.common.concur.OOfflineNodeException) OCommandExecutorSQLDelegate(com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate) HazelcastException(com.hazelcast.core.HazelcastException) OCommandExecutorSQLSelect(com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect) HazelcastInstanceNotActiveException(com.hazelcast.core.HazelcastInstanceNotActiveException) OException(com.orientechnologies.common.exception.OException) ONeedRetryException(com.orientechnologies.common.concur.ONeedRetryException) HazelcastException(com.hazelcast.core.HazelcastException) ODistributedRedirectException(com.orientechnologies.orient.enterprise.channel.binary.ODistributedRedirectException) OIOException(com.orientechnologies.common.io.OIOException) OOfflineNodeException(com.orientechnologies.common.concur.OOfflineNodeException) ORecordId(com.orientechnologies.orient.core.id.ORecordId) HazelcastInstanceNotActiveException(com.hazelcast.core.HazelcastInstanceNotActiveException) ONeedRetryException(com.orientechnologies.common.concur.ONeedRetryException) OCommandScript(com.orientechnologies.orient.core.command.script.OCommandScript)

Example 29 with OCommandScript

use of com.orientechnologies.orient.core.command.script.OCommandScript in project orientdb by orientechnologies.

the class OScriptTask method execute.

public Object execute(ODistributedRequestId requestId, final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentInternal database) throws Exception {
    ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "execute command=%s db=%s", text.toString(), database.getName());
    final OCommandRequest cmd = database.command(new OCommandScript(text));
    final Object res;
    if (params != null)
        // EXECUTE WITH PARAMETERS
        res = cmd.execute(params);
    else
        res = cmd.execute();
    return res;
}
Also used : OCommandScript(com.orientechnologies.orient.core.command.script.OCommandScript) OCommandRequest(com.orientechnologies.orient.core.command.OCommandRequest)

Example 30 with OCommandScript

use of com.orientechnologies.orient.core.command.script.OCommandScript in project orientdb by orientechnologies.

the class OScriptImporterListener method executeEvent.

private Object executeEvent(final ODatabaseDocument db, final String iEventName, final OCommandContext iContext) {
    if (events == null)
        return null;
    OCommandScript script = scripts.get(iEventName);
    if (script == null) {
        final String code = events.get(iEventName);
        if (code != null) {
            // CACHE IT
            script = new OCommandScript(code).setLanguage("Javascript");
            scripts.put(iEventName, script);
        }
    }
    if (script != null) {
        final Map<String, Object> pars = new HashMap<String, Object>();
        pars.put("task", iContext);
        pars.put("importer", this);
        return db.command(script).execute(pars);
    }
    return null;
}
Also used : HashMap(java.util.HashMap) OCommandScript(com.orientechnologies.orient.core.command.script.OCommandScript)

Aggregations

OCommandScript (com.orientechnologies.orient.core.command.script.OCommandScript)43 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)21 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)18 Test (org.junit.Test)13 OSQLSynchQuery (com.orientechnologies.orient.core.sql.query.OSQLSynchQuery)11 ORecordDuplicatedException (com.orientechnologies.orient.core.storage.ORecordDuplicatedException)9 InputStream (java.io.InputStream)9 Test (org.testng.annotations.Test)9 Before (org.junit.Before)8 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)6 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)6 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)4 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)4 IOException (java.io.IOException)4 Collection (java.util.Collection)3 List (java.util.List)3 StandardAnalyzer (org.apache.lucene.analysis.standard.StandardAnalyzer)3 ONeedRetryException (com.orientechnologies.common.concur.ONeedRetryException)2 OException (com.orientechnologies.common.exception.OException)2 OCommandRequest (com.orientechnologies.orient.core.command.OCommandRequest)2