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));
}
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"), "'';");
}
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;
}
}
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;
}
use of com.orientechnologies.orient.core.command.script.OCommandScript in project orientdb by orientechnologies.
the class TestGraphTransactionOnBatch method testDuplicateEdgeAlreadyPresentRollback.
@Test
public void testDuplicateEdgeAlreadyPresentRollback() {
OClass clazz = db.getMetadata().getSchema().createClass("Test");
clazz.setSuperClass(E);
clazz.createProperty("aKey", OType.STRING).createIndex(INDEX_TYPE.UNIQUE);
db.command(new OCommandScript("sql", "BEGIN \n LET a = create vertex V \n LET b = create vertex V \n LET c =create edge Test from $a to $b SET aKey = \"12345\" \n commit \n" + " RETURN $c")).execute();
try {
db.command(new OCommandScript("sql", "BEGIN \n LET a = create vertex V \n LET b = create vertex V \n LET c =create edge Test from $a to $b SET aKey = \"12345\"\n COMMIT \n" + " RETURN $c")).execute();
Assert.fail("expected record duplicate exception");
} catch (ORecordDuplicatedException ex) {
}
List<ODocument> res = db.query(new OSQLSynchQuery("select from Test"));
Assert.assertEquals(1, res.size());
}
Aggregations