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;
}
use of com.orientechnologies.orient.core.db.document.ODatabaseDocument 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;
}
Aggregations