use of com.orientechnologies.orient.core.metadata.schema.OType in project orientdb by orientechnologies.
the class OCommandExecutorSQLSelect method searchInIndex.
private void searchInIndex() {
final OIndex<Object> index = (OIndex<Object>) getDatabase().getMetadata().getIndexManager().getIndex(parsedTarget.getTargetIndex());
if (index == null) {
throw new OCommandExecutionException("Target index '" + parsedTarget.getTargetIndex() + "' not found");
}
boolean ascOrder = true;
if (!orderedFields.isEmpty()) {
if (orderedFields.size() != 1) {
throw new OCommandExecutionException("Index can be ordered only by key field");
}
final String fieldName = orderedFields.get(0).getKey();
if (!fieldName.equalsIgnoreCase("key")) {
throw new OCommandExecutionException("Index can be ordered only by key field");
}
final String order = orderedFields.get(0).getValue();
ascOrder = order.equalsIgnoreCase(KEYWORD_ASC);
}
// nothing was added yet, so index definition for manual index was not calculated
if (index.getDefinition() == null) {
return;
}
if (compiledFilter != null && compiledFilter.getRootCondition() != null) {
if (!"KEY".equalsIgnoreCase(compiledFilter.getRootCondition().getLeft().toString())) {
throw new OCommandExecutionException("'Key' field is required for queries against indexes");
}
final OQueryOperator indexOperator = compiledFilter.getRootCondition().getOperator();
if (indexOperator instanceof OQueryOperatorBetween) {
final Object[] values = (Object[]) compiledFilter.getRootCondition().getRight();
final OIndexCursor cursor = index.iterateEntriesBetween(getIndexKey(index.getDefinition(), values[0], context), true, getIndexKey(index.getDefinition(), values[2], context), true, ascOrder);
fetchEntriesFromIndexCursor(cursor);
} else if (indexOperator instanceof OQueryOperatorMajor) {
final Object value = compiledFilter.getRootCondition().getRight();
final OIndexCursor cursor = index.iterateEntriesMajor(getIndexKey(index.getDefinition(), value, context), false, ascOrder);
fetchEntriesFromIndexCursor(cursor);
} else if (indexOperator instanceof OQueryOperatorMajorEquals) {
final Object value = compiledFilter.getRootCondition().getRight();
final OIndexCursor cursor = index.iterateEntriesMajor(getIndexKey(index.getDefinition(), value, context), true, ascOrder);
fetchEntriesFromIndexCursor(cursor);
} else if (indexOperator instanceof OQueryOperatorMinor) {
final Object value = compiledFilter.getRootCondition().getRight();
OIndexCursor cursor = index.iterateEntriesMinor(getIndexKey(index.getDefinition(), value, context), false, ascOrder);
fetchEntriesFromIndexCursor(cursor);
} else if (indexOperator instanceof OQueryOperatorMinorEquals) {
final Object value = compiledFilter.getRootCondition().getRight();
OIndexCursor cursor = index.iterateEntriesMinor(getIndexKey(index.getDefinition(), value, context), true, ascOrder);
fetchEntriesFromIndexCursor(cursor);
} else if (indexOperator instanceof OQueryOperatorIn) {
final List<Object> origValues = (List<Object>) compiledFilter.getRootCondition().getRight();
final List<Object> values = new ArrayList<Object>(origValues.size());
for (Object val : origValues) {
if (index.getDefinition() instanceof OCompositeIndexDefinition) {
throw new OCommandExecutionException("Operator IN not supported yet.");
}
val = getIndexKey(index.getDefinition(), val, context);
values.add(val);
}
OIndexCursor cursor = index.iterateEntries(values, true);
fetchEntriesFromIndexCursor(cursor);
} else {
final Object right = compiledFilter.getRootCondition().getRight();
Object keyValue = getIndexKey(index.getDefinition(), right, context);
if (keyValue == null) {
return;
}
final Object res;
if (index.getDefinition().getParamCount() == 1) {
// CONVERT BEFORE SEARCH IF NEEDED
final OType type = index.getDefinition().getTypes()[0];
keyValue = OType.convert(keyValue, type.getDefaultJavaType());
res = index.get(keyValue);
} else {
final Object secondKey = getIndexKey(index.getDefinition(), right, context);
if (keyValue instanceof OCompositeKey && secondKey instanceof OCompositeKey && ((OCompositeKey) keyValue).getKeys().size() == index.getDefinition().getParamCount() && ((OCompositeKey) secondKey).getKeys().size() == index.getDefinition().getParamCount()) {
res = index.get(keyValue);
} else {
OIndexCursor cursor = index.iterateEntriesBetween(keyValue, true, secondKey, true, true);
fetchEntriesFromIndexCursor(cursor);
return;
}
}
if (res != null) {
if (res instanceof Collection<?>) {
// MULTI VALUES INDEX
for (final OIdentifiable r : (Collection<OIdentifiable>) res) {
final ODocument record = createIndexEntryAsDocument(keyValue, r.getIdentity());
applyGroupBy(record, context);
if (!handleResult(record, context)) // LIMIT REACHED
{
break;
}
}
} else {
// SINGLE VALUE INDEX
final ODocument record = createIndexEntryAsDocument(keyValue, ((OIdentifiable) res).getIdentity());
applyGroupBy(record, context);
handleResult(record, context);
}
}
}
} else {
if (isIndexSizeQuery()) {
getProjectionGroup(null, context).applyValue(projections.keySet().iterator().next(), index.getSize());
return;
}
if (isIndexKeySizeQuery()) {
getProjectionGroup(null, context).applyValue(projections.keySet().iterator().next(), index.getKeySize());
return;
}
final OIndexInternal<?> indexInternal = index.getInternal();
if (indexInternal instanceof OSharedResource) {
((OSharedResource) indexInternal).acquireExclusiveLock();
}
try {
// ADD ALL THE ITEMS AS RESULT
if (ascOrder) {
final OIndexCursor cursor = index.cursor();
fetchEntriesFromIndexCursor(cursor);
} else {
final OIndexCursor cursor = index.descCursor();
fetchEntriesFromIndexCursor(cursor);
}
} finally {
if (indexInternal instanceof OSharedResource) {
((OSharedResource) indexInternal).releaseExclusiveLock();
}
}
}
}
use of com.orientechnologies.orient.core.metadata.schema.OType in project orientdb by orientechnologies.
the class ORecordSerializerCSVAbstract method embeddedCollectionFromStream.
public Object embeddedCollectionFromStream(final ODocument iDocument, final OType iType, OClass iLinkedClass, final OType iLinkedType, final String iValue) {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END COLLECTIONS CHARACTERS IF IT'S A COLLECTION
final String value = iValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN || iValue.charAt(0) == OStringSerializerHelper.SET_BEGIN ? iValue.substring(1, iValue.length() - 1) : iValue;
Collection<?> coll;
if (iLinkedType == OType.LINK) {
if (iDocument != null)
coll = (Collection<?>) (iType == OType.EMBEDDEDLIST ? new ORecordLazyList(iDocument).setStreamedContent(new StringBuilder(value)) : unserializeSet(iDocument, value));
else {
if (iType == OType.EMBEDDEDLIST)
coll = (Collection<?>) new ORecordLazyList().setStreamedContent(new StringBuilder(value));
else {
return unserializeSet(iDocument, value);
}
}
} else
coll = iType == OType.EMBEDDEDLIST ? new OTrackedList<Object>(iDocument) : new OTrackedSet<Object>(iDocument);
if (value.length() == 0)
return coll;
OType linkedType;
if (coll instanceof ORecordElement)
((ORecordElement) coll).setInternalStatus(STATUS.UNMARSHALLING);
final List<String> items = OStringSerializerHelper.smartSplit(value, OStringSerializerHelper.RECORD_SEPARATOR, true, false);
for (String item : items) {
Object objectToAdd = null;
linkedType = null;
if (item.equals("null"))
// NULL VALUE
objectToAdd = null;
else if (item.length() > 2 && item.charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) {
// REMOVE EMBEDDED BEGIN/END CHARS
item = item.substring(1, item.length() - 1);
if (!item.isEmpty()) {
// EMBEDDED RECORD, EXTRACT THE CLASS NAME IF DIFFERENT BY THE PASSED (SUB-CLASS OR IT WAS PASSED NULL)
iLinkedClass = OStringSerializerHelper.getRecordClassName(item, iLinkedClass);
if (iLinkedClass != null) {
ODocument doc = new ODocument();
objectToAdd = fromString(item, doc, null);
ODocumentInternal.fillClassNameIfNeeded(doc, iLinkedClass.getName());
} else
// EMBEDDED OBJECT
objectToAdd = fieldTypeFromStream(iDocument, OType.EMBEDDED, item);
}
} else {
if (linkedType == null) {
final char begin = item.length() > 0 ? item.charAt(0) : OStringSerializerHelper.LINK;
// AUTO-DETERMINE LINKED TYPE
if (begin == OStringSerializerHelper.LINK)
linkedType = OType.LINK;
else
linkedType = getType(item);
if (linkedType == null)
throw new IllegalArgumentException("Linked type cannot be null. Probably the serialized type has not stored the type along with data");
}
if (iLinkedType == OType.CUSTOM)
item = item.substring(1, item.length() - 1);
objectToAdd = fieldTypeFromStream(iDocument, linkedType, item);
}
if (objectToAdd != null && objectToAdd instanceof ODocument && coll instanceof ORecordElement)
ODocumentInternal.addOwner((ODocument) objectToAdd, (ORecordElement) coll);
((Collection<Object>) coll).add(objectToAdd);
}
if (coll instanceof ORecordElement)
((ORecordElement) coll).setInternalStatus(STATUS.LOADED);
return coll;
}
use of com.orientechnologies.orient.core.metadata.schema.OType in project orientdb by orientechnologies.
the class ORecordSerializerCSVAbstract method embeddedMapFromStream.
public Map<String, Object> embeddedMapFromStream(final ODocument iSourceDocument, final OType iLinkedType, final String iValue, final String iName) {
if (iValue.length() == 0)
return null;
// REMOVE BEGIN & END MAP CHARACTERS
String value = iValue.substring(1, iValue.length() - 1);
@SuppressWarnings("rawtypes") Map map;
if (iLinkedType == OType.LINK || iLinkedType == OType.EMBEDDED)
map = new ORecordLazyMap(iSourceDocument, ODocument.RECORD_TYPE);
else
map = new OTrackedMap<Object>(iSourceDocument);
if (value.length() == 0)
return map;
final List<String> items = OStringSerializerHelper.smartSplit(value, OStringSerializerHelper.RECORD_SEPARATOR, true, false);
if (map instanceof ORecordElement)
((ORecordElement) map).setInternalStatus(STATUS.UNMARSHALLING);
for (String item : items) {
if (item != null && !item.isEmpty()) {
final List<String> entries = OStringSerializerHelper.smartSplit(item, OStringSerializerHelper.ENTRY_SEPARATOR, true, false);
if (!entries.isEmpty()) {
final Object mapValueObject;
if (entries.size() > 1) {
String mapValue = entries.get(1);
final OType linkedType;
if (iLinkedType == null)
if (!mapValue.isEmpty()) {
linkedType = getType(mapValue);
if ((iName == null || iSourceDocument.fieldType(iName) == null || iSourceDocument.fieldType(iName) != OType.EMBEDDEDMAP) && isConvertToLinkedMap(map, linkedType)) {
// CONVERT IT TO A LAZY MAP
map = new ORecordLazyMap(iSourceDocument, ODocument.RECORD_TYPE);
((ORecordElement) map).setInternalStatus(STATUS.UNMARSHALLING);
} else if (map instanceof ORecordLazyMap && linkedType != OType.LINK) {
map = new OTrackedMap<Object>(iSourceDocument, map, null);
}
} else
linkedType = OType.EMBEDDED;
else
linkedType = iLinkedType;
if (linkedType == OType.EMBEDDED && mapValue.length() >= 2)
mapValue = mapValue.substring(1, mapValue.length() - 1);
mapValueObject = fieldTypeFromStream(iSourceDocument, linkedType, mapValue);
if (mapValueObject != null && mapValueObject instanceof ODocument)
ODocumentInternal.addOwner((ODocument) mapValueObject, iSourceDocument);
} else
mapValueObject = null;
final Object key = fieldTypeFromStream(iSourceDocument, OType.STRING, entries.get(0));
try {
map.put(key, mapValueObject);
} catch (ClassCastException e) {
throw OException.wrapException(new OSerializationException("Cannot load map because the type was not the expected: key=" + key + "(type " + key.getClass().toString() + "), value=" + mapValueObject + "(type " + key.getClass() + ")"), e);
}
}
}
}
if (map instanceof ORecordElement)
((ORecordElement) map).setInternalStatus(STATUS.LOADED);
return map;
}
use of com.orientechnologies.orient.core.metadata.schema.OType 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;
}
use of com.orientechnologies.orient.core.metadata.schema.OType 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