use of com.orientechnologies.orient.core.db.document.ODatabaseDocument 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();
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;
}
use of com.orientechnologies.orient.core.db.document.ODatabaseDocument in project orientdb by orientechnologies.
the class OStorageRemote method command.
/**
* Execute the command remotely and get the results back.
*/
public Object command(final OCommandRequestText iCommand) {
if (!(iCommand instanceof OSerializableStream))
throw new OCommandExecutionException("Cannot serialize the command to be executed to the server side.");
final boolean live = iCommand instanceof OLiveQuery;
final ODatabaseDocument database = ODatabaseRecordThreadLocal.INSTANCE.get();
return networkOperation(new OStorageRemoteOperation<Object>() {
@Override
public Object execute(final OChannelBinaryAsynchClient network, OStorageRemoteSession session) throws IOException {
Object result = null;
session.commandExecuting = true;
try {
final boolean asynch = iCommand instanceof OCommandRequestAsynch && ((OCommandRequestAsynch) iCommand).isAsynchronous();
try {
beginRequest(network, OChannelBinaryProtocol.REQUEST_COMMAND, session);
if (live) {
network.writeByte((byte) 'l');
} else {
// ASYNC / SYNC
network.writeByte((byte) (asynch ? 'a' : 's'));
}
network.writeBytes(OStreamSerializerAnyStreamable.INSTANCE.toStream(iCommand));
} finally {
endRequest(network);
}
try {
beginResponse(network, session);
// Collection of prefetched temporary record (nested projection record), to refer for avoid garbage collection.
List<ORecord> temporaryResults = new ArrayList<ORecord>();
boolean addNextRecord = true;
if (asynch) {
byte status;
// ASYNCH: READ ONE RECORD AT TIME
while ((status = network.readByte()) > 0) {
final ORecord record = (ORecord) OChannelBinaryProtocol.readIdentifiable(network);
if (record == null)
continue;
switch(status) {
case 1:
// PUT AS PART OF THE RESULT SET. INVOKE THE LISTENER
if (addNextRecord) {
addNextRecord = iCommand.getResultListener().result(record);
database.getLocalCache().updateRecord(record);
}
break;
case 2:
if (record.getIdentity().getClusterId() == -2)
temporaryResults.add(record);
// PUT IN THE CLIENT LOCAL CACHE
database.getLocalCache().updateRecord(record);
}
}
} else {
result = readSynchResult(network, database, temporaryResults);
if (live) {
final ODocument doc = ((List<ODocument>) result).get(0);
final Integer token = doc.field("token");
final Boolean unsubscribe = doc.field("unsubscribe");
if (token != null) {
if (Boolean.TRUE.equals(unsubscribe)) {
if (OStorageRemote.this.asynchEventListener != null)
OStorageRemote.this.asynchEventListener.unregisterLiveListener(token);
} else {
final OLiveResultListener listener = (OLiveResultListener) iCommand.getResultListener();
ODatabaseDocumentInternal current = ODatabaseRecordThreadLocal.INSTANCE.get();
final ODatabaseDocument dbCopy = current.copy();
ORemoteConnectionPool pool = OStorageRemote.this.connectionManager.getPool(network.getServerURL());
OStorageRemote.this.asynchEventListener.registerLiveListener(pool, token, new OLiveResultListener() {
@Override
public void onUnsubscribe(int iLiveToken) {
listener.onUnsubscribe(iLiveToken);
dbCopy.close();
}
@Override
public void onLiveResult(int iLiveToken, ORecordOperation iOp) throws OException {
dbCopy.activateOnCurrentThread();
listener.onLiveResult(iLiveToken, iOp);
}
@Override
public void onError(int iLiveToken) {
listener.onError(iLiveToken);
dbCopy.close();
}
});
}
} else {
throw new OStorageException("Cannot execute live query, returned null token");
}
}
}
if (!temporaryResults.isEmpty()) {
if (result instanceof OBasicResultSet<?>) {
((OBasicResultSet<?>) result).setTemporaryRecordCache(temporaryResults);
}
}
return result;
} finally {
endResponse(network);
}
} finally {
session.commandExecuting = false;
if (iCommand.getResultListener() != null && !live)
iCommand.getResultListener().end();
}
}
}, "Error on executing command: " + iCommand);
}
use of com.orientechnologies.orient.core.db.document.ODatabaseDocument in project orientdb by orientechnologies.
the class RemoteConnetWrongUrlTest method testConnectWrongUrl.
@Test(expectedExceptions = OStorageException.class)
public void testConnectWrongUrl() {
ODatabaseDocument doc = new ODatabaseDocumentTx("remote:wrong:2424/test");
doc.open("user", "user");
}
use of com.orientechnologies.orient.core.db.document.ODatabaseDocument in project orientdb by orientechnologies.
the class OCommandExecutorSQLRevoke method parse.
@SuppressWarnings("unchecked")
public OCommandExecutorSQLRevoke 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);
privilege = ORole.PERMISSION_NONE;
resource = null;
role = null;
StringBuilder word = new StringBuilder();
int oldPos = 0;
int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_REVOKE))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_REVOKE + " not found. Use " + getSyntax(), parserText, oldPos);
pos = nextWord(parserText, parserTextUpperCase, pos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Invalid privilege", parserText, oldPos);
parsePrivilege(word, oldPos);
pos = nextWord(parserText, parserTextUpperCase, pos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_ON))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_ON + " not found. Use " + getSyntax(), parserText, oldPos);
pos = nextWord(parserText, parserText, pos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Invalid resource", parserText, oldPos);
resource = word.toString();
pos = nextWord(parserText, parserTextUpperCase, pos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_FROM))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_FROM + " not found. Use " + getSyntax(), parserText, oldPos);
pos = nextWord(parserText, parserText, pos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Invalid role", parserText, oldPos);
final String roleName = word.toString();
role = database.getMetadata().getSecurity().getRole(roleName);
if (role == null)
throw new OCommandSQLParsingException("Invalid role: " + roleName);
} finally {
textRequest.setText(originalQuery);
}
return this;
}
use of com.orientechnologies.orient.core.db.document.ODatabaseDocument in project orientdb by orientechnologies.
the class OCommandExecutorSQLInsert method parse.
@SuppressWarnings("unchecked")
public OCommandExecutorSQLInsert 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);
final ODatabaseDocument database = getDatabase();
init((OCommandRequestText) iRequest);
className = null;
newRecords = null;
content = null;
if (parserTextUpperCase.endsWith(KEYWORD_UNSAFE)) {
unsafe = true;
parserText = parserText.substring(0, parserText.length() - KEYWORD_UNSAFE.length() - 1);
parserTextUpperCase = parserTextUpperCase.substring(0, parserTextUpperCase.length() - KEYWORD_UNSAFE.length() - 1);
}
parserRequiredKeyword("INSERT");
parserRequiredKeyword("INTO");
String subjectName = parserRequiredWord(true, "Invalid subject name. Expected cluster, class or index");
if (subjectName.startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX)) {
// CLUSTER
clusterName = subjectName.substring(OCommandExecutorSQLAbstract.CLUSTER_PREFIX.length());
try {
int clusterId = Integer.parseInt(clusterName);
clusterName = database.getClusterNameById(clusterId);
} catch (Exception e) {
//not an integer
}
} else if (subjectName.startsWith(OCommandExecutorSQLAbstract.INDEX_PREFIX))
// INDEX
indexName = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_PREFIX.length());
else {
// CLASS
if (subjectName.startsWith(OCommandExecutorSQLAbstract.CLASS_PREFIX))
subjectName = subjectName.substring(OCommandExecutorSQLAbstract.CLASS_PREFIX.length());
final OClass cls = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(subjectName);
if (cls == null)
throwParsingException("Class " + subjectName + " not found in database");
if (!unsafe && cls.isSubClassOf("E"))
// FOUND EDGE
throw new OCommandExecutionException("'INSERT' command cannot create Edges. Use 'CREATE EDGE' command instead, or apply the 'UNSAFE' keyword to force it");
className = cls.getName();
clazz = database.getMetadata().getSchema().getClass(className);
if (clazz == null)
throw new OQueryParsingException("Class '" + className + "' was not found");
}
if (clusterName != null && className == null) {
ODatabaseDocumentInternal db = getDatabase();
OCluster cluster = db.getStorage().getClusterByName(clusterName);
if (cluster != null) {
clazz = db.getMetadata().getSchema().getClassByClusterId(cluster.getId());
if (clazz != null) {
className = clazz.getName();
}
}
}
parserSkipWhiteSpaces();
if (parserIsEnded())
throwSyntaxErrorException("Set of fields is missed. Example: (name, surname) or SET name = 'Bill'");
final String temp = parseOptionalWord(true);
if (parserGetLastWord().equalsIgnoreCase("cluster")) {
clusterName = parserRequiredWord(false);
parserSkipWhiteSpaces();
if (parserIsEnded())
throwSyntaxErrorException("Set of fields is missed. Example: (name, surname) or SET name = 'Bill'");
} else
parserGoBack();
newRecords = new ArrayList<Map<String, Object>>();
Boolean sourceClauseProcessed = false;
if (parserGetCurrentChar() == '(') {
parseValues();
parserNextWord(true, " \r\n");
sourceClauseProcessed = true;
} else {
parserNextWord(true, " ,\r\n");
if (parserGetLastWord().equals(KEYWORD_CONTENT)) {
newRecords = null;
parseContent();
sourceClauseProcessed = true;
} else if (parserGetLastWord().equals(KEYWORD_SET)) {
final List<OPair<String, Object>> fields = new ArrayList<OPair<String, Object>>();
parseSetFields(clazz, fields);
newRecords.add(OPair.convertToMap(fields));
sourceClauseProcessed = true;
}
}
if (sourceClauseProcessed)
parserNextWord(true, " \r\n");
// it has to be processed before KEYWORD_FROM in order to not be taken as part of SELECT
if (parserGetLastWord().equals(KEYWORD_RETURN)) {
parseReturn(!sourceClauseProcessed);
parserNextWord(true, " \r\n");
}
if (!sourceClauseProcessed) {
if (parserGetLastWord().equals(KEYWORD_FROM)) {
newRecords = null;
subQuery = new OSQLAsynchQuery<OIdentifiable>(parserText.substring(parserGetCurrentPosition()), this);
}
}
} finally {
textRequest.setText(originalQuery);
}
return this;
}
Aggregations