Search in sources :

Example 51 with OProperty

use of com.orientechnologies.orient.core.metadata.schema.OProperty in project orientdb by orientechnologies.

the class ORecordSerializerSchemaAware2CSV method fromString.

@Override
public ORecord fromString(String iContent, final ORecord iRecord, final String[] iFields) {
    iContent = iContent.trim();
    if (iContent.length() == 0)
        return iRecord;
    // UNMARSHALL THE CLASS NAME
    final ODocument record = (ODocument) iRecord;
    int pos;
    final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
    final int posFirstValue = iContent.indexOf(OStringSerializerHelper.ENTRY_SEPARATOR);
    pos = iContent.indexOf(OStringSerializerHelper.CLASS_SEPARATOR);
    if (pos > -1 && (pos < posFirstValue || posFirstValue == -1)) {
        if ((record.getIdentity().getClusterId() < 0 || database == null || !database.getStorageVersions().classesAreDetectedByClusterId()))
            ODocumentInternal.fillClassNameIfNeeded(((ODocument) iRecord), iContent.substring(0, pos));
        iContent = iContent.substring(pos + 1);
    } else
        record.setClassNameIfExists(null);
    if (iFields != null && iFields.length == 1 && iFields[0].equals("@class"))
        // ONLY THE CLASS NAME HAS BEEN REQUESTED: RETURN NOW WITHOUT UNMARSHALL THE ENTIRE RECORD
        return iRecord;
    final List<String> fields = OStringSerializerHelper.smartSplit(iContent, OStringSerializerHelper.RECORD_SEPARATOR, true, true);
    String fieldName = null;
    String fieldValue;
    OType type;
    OClass linkedClass;
    OType linkedType;
    OProperty prop;
    final Set<String> fieldSet;
    if (iFields != null && iFields.length > 0) {
        fieldSet = new HashSet<String>(iFields.length);
        for (String f : iFields) fieldSet.add(f);
    } else
        fieldSet = null;
    // UNMARSHALL ALL THE FIELDS
    for (String fieldEntry : fields) {
        fieldEntry = fieldEntry.trim();
        boolean uncertainType = false;
        try {
            pos = fieldEntry.indexOf(FIELD_VALUE_SEPARATOR);
            if (pos > -1) {
                // GET THE FIELD NAME
                fieldName = fieldEntry.substring(0, pos);
                // CHECK IF THE FIELD IS REQUESTED TO BEING UNMARSHALLED
                if (fieldSet != null && !fieldSet.contains(fieldName))
                    continue;
                if (record.containsField(fieldName))
                    // ALREADY UNMARSHALLED: DON'T OVERWRITE IT
                    continue;
                // GET THE FIELD VALUE
                fieldValue = fieldEntry.length() > pos + 1 ? fieldEntry.substring(pos + 1) : null;
                boolean setFieldType = false;
                // SEARCH FOR A CONFIGURED PROPERTY
                prop = ODocumentInternal.getImmutableSchemaClass(record) != null ? ODocumentInternal.getImmutableSchemaClass(record).getProperty(fieldName) : null;
                if (prop != null && prop.getType() != OType.ANY) {
                    // RECOGNIZED PROPERTY
                    type = prop.getType();
                    linkedClass = prop.getLinkedClass();
                    linkedType = prop.getLinkedType();
                } else {
                    // SCHEMA PROPERTY NOT FOUND FOR THIS FIELD: TRY TO AUTODETERMINE THE BEST TYPE
                    type = record.fieldType(fieldName);
                    if (type == OType.ANY)
                        type = null;
                    if (type != null)
                        setFieldType = true;
                    linkedClass = null;
                    linkedType = null;
                    // NOT FOUND: TRY TO DETERMINE THE TYPE FROM ITS CONTENT
                    if (fieldValue != null && type == null) {
                        if (fieldValue.length() > 1 && fieldValue.charAt(0) == '"' && fieldValue.charAt(fieldValue.length() - 1) == '"') {
                            type = OType.STRING;
                        } else if (fieldValue.startsWith(OStringSerializerHelper.LINKSET_PREFIX)) {
                            type = OType.LINKSET;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN && fieldValue.charAt(fieldValue.length() - 1) == OStringSerializerHelper.LIST_END || fieldValue.charAt(0) == OStringSerializerHelper.SET_BEGIN && fieldValue.charAt(fieldValue.length() - 1) == OStringSerializerHelper.SET_END) {
                            // EMBEDDED LIST/SET
                            type = fieldValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN ? OType.EMBEDDEDLIST : OType.EMBEDDEDSET;
                            final String value = fieldValue.substring(1, fieldValue.length() - 1);
                            if (!value.isEmpty()) {
                                if (value.charAt(0) == OStringSerializerHelper.LINK) {
                                    // TODO replace with regex
                                    // ASSURE ALL THE ITEMS ARE RID
                                    int max = value.length();
                                    boolean allLinks = true;
                                    boolean checkRid = true;
                                    for (int i = 0; i < max; ++i) {
                                        char c = value.charAt(i);
                                        if (checkRid) {
                                            if (c != '#') {
                                                allLinks = false;
                                                break;
                                            }
                                            checkRid = false;
                                        } else if (c == ',')
                                            checkRid = true;
                                    }
                                    if (allLinks) {
                                        type = fieldValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN ? OType.LINKLIST : OType.LINKSET;
                                        linkedType = OType.LINK;
                                    }
                                } else if (value.charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) {
                                    linkedType = OType.EMBEDDED;
                                } else if (value.charAt(0) == OStringSerializerHelper.CUSTOM_TYPE) {
                                    linkedType = OType.CUSTOM;
                                } else if (Character.isDigit(value.charAt(0)) || value.charAt(0) == '+' || value.charAt(0) == '-') {
                                    String[] items = value.split(",");
                                    linkedType = getType(items[0]);
                                } else if (value.charAt(0) == '\'' || value.charAt(0) == '"')
                                    linkedType = OType.STRING;
                            } else
                                uncertainType = true;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.MAP_BEGIN && fieldValue.charAt(fieldValue.length() - 1) == OStringSerializerHelper.MAP_END) {
                            type = OType.EMBEDDEDMAP;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.LINK)
                            type = OType.LINK;
                        else if (fieldValue.charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) {
                            // TEMPORARY PATCH
                            if (fieldValue.startsWith("(ORIDs"))
                                type = OType.LINKSET;
                            else
                                type = OType.EMBEDDED;
                        } else if (fieldValue.charAt(0) == OStringSerializerHelper.BAG_BEGIN) {
                            type = OType.LINKBAG;
                        } else if (fieldValue.equals("true") || fieldValue.equals("false"))
                            type = OType.BOOLEAN;
                        else
                            type = getType(fieldValue);
                    }
                }
                final Object value = fieldFromStream(iRecord, type, linkedClass, linkedType, fieldName, fieldValue);
                if ("@class".equals(fieldName)) {
                    ODocumentInternal.fillClassNameIfNeeded(((ODocument) iRecord), value.toString());
                } else {
                    record.field(fieldName, value, type);
                }
                if (uncertainType)
                    record.setFieldType(fieldName, null);
            }
        } catch (Exception e) {
            throw OException.wrapException(new OSerializationException("Error on unmarshalling field '" + fieldName + "' in record " + iRecord.getIdentity() + " with value: " + fieldEntry), e);
        }
    }
    return iRecord;
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OType(com.orientechnologies.orient.core.metadata.schema.OType) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) OException(com.orientechnologies.common.exception.OException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 52 with OProperty

use of com.orientechnologies.orient.core.metadata.schema.OProperty in project orientdb by orientechnologies.

the class ORecordSerializerSchemaAware2CSV method toString.

@Override
protected StringBuilder toString(ORecord iRecord, final StringBuilder iOutput, final String iFormat, OUserObject2RecordHandler iObjHandler, final boolean iOnlyDelta, final boolean autoDetectCollectionType) {
    if (iRecord == null)
        throw new OSerializationException("Expected a record but was null");
    if (!(iRecord instanceof ODocument))
        throw new OSerializationException("Cannot marshall a record of type " + iRecord.getClass().getSimpleName());
    final ODocument record = (ODocument) iRecord;
    if (!iOnlyDelta && ODocumentInternal.getImmutableSchemaClass(record) != null) {
        iOutput.append(ODocumentInternal.getImmutableSchemaClass(record).getStreamableName());
        iOutput.append(OStringSerializerHelper.CLASS_SEPARATOR);
    }
    OProperty prop;
    OType type;
    OClass linkedClass;
    OType linkedType;
    String fieldClassName;
    int i = 0;
    final String[] fieldNames = iOnlyDelta && record.isTrackingChanges() ? record.getDirtyFields() : record.fieldNames();
    // MARSHALL ALL THE FIELDS OR DELTA IF TRACKING IS ENABLED
    for (String fieldName : fieldNames) {
        Object fieldValue = record.rawField(fieldName);
        if (i > 0)
            iOutput.append(OStringSerializerHelper.RECORD_SEPARATOR);
        // SEARCH FOR A CONFIGURED PROPERTY
        prop = ODocumentInternal.getImmutableSchemaClass(record) != null ? ODocumentInternal.getImmutableSchemaClass(record).getProperty(fieldName) : null;
        fieldClassName = getClassName(fieldValue);
        type = record.fieldType(fieldName);
        if (type == OType.ANY)
            type = null;
        linkedClass = null;
        linkedType = null;
        if (prop != null && prop.getType() != OType.ANY) {
            // RECOGNIZED PROPERTY
            type = prop.getType();
            linkedClass = prop.getLinkedClass();
            linkedType = prop.getLinkedType();
        } else if (fieldValue != null) {
            // NOT FOUND: TRY TO DETERMINE THE TYPE FROM ITS CONTENT
            if (type == null) {
                if (fieldValue.getClass() == byte[].class)
                    type = OType.BINARY;
                else if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && fieldValue instanceof ORecord) {
                    if (type == null)
                        // DETERMINE THE FIELD TYPE
                        if (fieldValue instanceof ODocument && ((ODocument) fieldValue).hasOwners())
                            type = OType.EMBEDDED;
                        else
                            type = OType.LINK;
                    linkedClass = getLinkInfo(ODatabaseRecordThreadLocal.INSTANCE.get(), fieldClassName);
                } else if (fieldValue instanceof ORID)
                    // DETERMINE THE FIELD TYPE
                    type = OType.LINK;
                else if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner() instanceof ODatabaseObject && ((ODatabaseObject) ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner()).getEntityManager().getEntityClass(fieldClassName) != null) {
                    // DETERMINE THE FIELD TYPE
                    type = OType.LINK;
                    linkedClass = getLinkInfo(ODatabaseRecordThreadLocal.INSTANCE.get(), fieldClassName);
                } else if (fieldValue instanceof Date)
                    type = OType.DATETIME;
                else if (fieldValue instanceof String)
                    type = OType.STRING;
                else if (fieldValue instanceof Integer || fieldValue instanceof BigInteger)
                    type = OType.INTEGER;
                else if (fieldValue instanceof Long)
                    type = OType.LONG;
                else if (fieldValue instanceof Float)
                    type = OType.FLOAT;
                else if (fieldValue instanceof Short)
                    type = OType.SHORT;
                else if (fieldValue instanceof Byte)
                    type = OType.BYTE;
                else if (fieldValue instanceof Double)
                    type = OType.DOUBLE;
                else if (fieldValue instanceof BigDecimal)
                    type = OType.DECIMAL;
                else if (fieldValue instanceof ORidBag)
                    type = OType.LINKBAG;
                if (fieldValue instanceof OMultiCollectionIterator<?>) {
                    type = ((OMultiCollectionIterator<?>) fieldValue).isEmbedded() ? OType.EMBEDDEDLIST : OType.LINKLIST;
                    linkedType = ((OMultiCollectionIterator<?>) fieldValue).isEmbedded() ? OType.EMBEDDED : OType.LINK;
                } else if (fieldValue instanceof Collection<?> || fieldValue.getClass().isArray()) {
                    final int size = OMultiValue.getSize(fieldValue);
                    Boolean autoConvertLinks = null;
                    if (fieldValue instanceof ORecordLazyMultiValue) {
                        autoConvertLinks = ((ORecordLazyMultiValue) fieldValue).isAutoConvertToRecord();
                        if (autoConvertLinks)
                            // DISABLE AUTO CONVERT
                            ((ORecordLazyMultiValue) fieldValue).setAutoConvertToRecord(false);
                    }
                    if (autoDetectCollectionType)
                        if (size > 0) {
                            final Object firstValue = OMultiValue.getFirstValue(fieldValue);
                            if (firstValue != null) {
                                if (firstValue instanceof ORID) {
                                    linkedClass = null;
                                    linkedType = OType.LINK;
                                    if (fieldValue instanceof Set<?>)
                                        type = OType.LINKSET;
                                    else
                                        type = OType.LINKLIST;
                                } else if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && (firstValue instanceof ODocument && !((ODocument) firstValue).isEmbedded()) && (firstValue instanceof ORecord || (ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner() instanceof ODatabaseObject && ((ODatabaseObject) ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner()).getEntityManager().getEntityClass(getClassName(firstValue)) != null))) {
                                    linkedClass = getLinkInfo(ODatabaseRecordThreadLocal.INSTANCE.get(), getClassName(firstValue));
                                    if (type == null) {
                                        // LINK: GET THE CLASS
                                        linkedType = OType.LINK;
                                        if (fieldValue instanceof Set<?>)
                                            type = OType.LINKSET;
                                        else
                                            type = OType.LINKLIST;
                                    } else
                                        linkedType = OType.EMBEDDED;
                                } else {
                                    // EMBEDDED COLLECTION
                                    if (firstValue instanceof ODocument && ((((ODocument) firstValue).hasOwners()) || type == OType.EMBEDDEDSET || type == OType.EMBEDDEDLIST || type == OType.EMBEDDEDMAP))
                                        linkedType = OType.EMBEDDED;
                                    else if (firstValue instanceof Enum<?>)
                                        linkedType = OType.STRING;
                                    else {
                                        linkedType = OType.getTypeByClass(firstValue.getClass());
                                        if (linkedType != OType.LINK)
                                            // EMBEDDED FOR SURE DON'T USE THE LINKED TYPE
                                            linkedType = null;
                                    }
                                    if (type == null)
                                        if (fieldValue instanceof ORecordLazySet)
                                            type = OType.LINKSET;
                                        else if (fieldValue instanceof Set<?>)
                                            type = OType.EMBEDDEDSET;
                                        else
                                            type = OType.EMBEDDEDLIST;
                                }
                            }
                        } else if (type == null)
                            type = OType.EMBEDDEDLIST;
                    if (fieldValue instanceof ORecordLazyMultiValue && autoConvertLinks) {
                        // REPLACE PREVIOUS SETTINGS
                        ((ORecordLazyMultiValue) fieldValue).setAutoConvertToRecord(true);
                    }
                } else if (fieldValue instanceof Map<?, ?> && type == null) {
                    final int size = OMultiValue.getSize(fieldValue);
                    Boolean autoConvertLinks = null;
                    if (fieldValue instanceof ORecordLazyMap) {
                        autoConvertLinks = ((ORecordLazyMap) fieldValue).isAutoConvertToRecord();
                        if (autoConvertLinks)
                            // DISABLE AUTO CONVERT
                            ((ORecordLazyMap) fieldValue).setAutoConvertToRecord(false);
                    }
                    if (size > 0) {
                        final Object firstValue = OMultiValue.getFirstValue(fieldValue);
                        if (firstValue != null) {
                            if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && (firstValue instanceof ODocument && !((ODocument) firstValue).isEmbedded()) && (firstValue instanceof ORecord || (ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner() instanceof ODatabaseObject && ((ODatabaseObject) ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner()).getEntityManager().getEntityClass(getClassName(firstValue)) != null))) {
                                linkedClass = getLinkInfo(ODatabaseRecordThreadLocal.INSTANCE.get(), getClassName(firstValue));
                                // LINK: GET THE CLASS
                                linkedType = OType.LINK;
                                type = OType.LINKMAP;
                            }
                        }
                    }
                    if (type == null)
                        type = OType.EMBEDDEDMAP;
                    if (fieldValue instanceof ORecordLazyMap && autoConvertLinks)
                        // REPLACE PREVIOUS SETTINGS
                        ((ORecordLazyMap) fieldValue).setAutoConvertToRecord(true);
                }
            }
        }
        if (type == OType.TRANSIENT)
            // TRANSIENT FIELD
            continue;
        if (type == null)
            type = OType.EMBEDDED;
        iOutput.append(fieldName);
        iOutput.append(FIELD_VALUE_SEPARATOR);
        fieldToStream(record, iOutput, iObjHandler, type, linkedClass, linkedType, fieldName, fieldValue, true);
        i++;
    }
    // GET THE OVERSIZE IF ANY
    final float overSize;
    if (ODocumentInternal.getImmutableSchemaClass(record) != null)
        // GET THE CONFIGURED OVERSIZE SETTED PER CLASS
        overSize = ODocumentInternal.getImmutableSchemaClass(record).getOverSize();
    else
        overSize = 0;
    // APPEND BLANKS IF NEEDED
    final int newSize;
    if (record.hasOwners())
        // EMBEDDED: GET REAL SIZE
        newSize = iOutput.length();
    else if (record.getSize() == iOutput.length())
        // IDENTICAL! DO NOTHING
        newSize = record.getSize();
    else if (record.getSize() > iOutput.length() && !OGlobalConfiguration.RECORD_DOWNSIZING_ENABLED.getValueAsBoolean()) {
        // APPEND EXTRA SPACES TO FILL ALL THE AVAILABLE SPACE AND AVOID FRAGMENTATION
        newSize = record.getSize();
    } else if (overSize > 0) {
        // APPEND EXTRA SPACES TO GET A LARGER iOutput
        newSize = (int) (iOutput.length() * overSize);
    } else
        // NO OVERSIZE
        newSize = iOutput.length();
    if (newSize > iOutput.length()) {
        iOutput.ensureCapacity(newSize);
        for (int b = iOutput.length(); b < newSize; ++b) iOutput.append(' ');
    }
    return iOutput;
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) HashSet(java.util.HashSet) Set(java.util.Set) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) ORidBag(com.orientechnologies.orient.core.db.record.ridbag.ORidBag) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) ORID(com.orientechnologies.orient.core.id.ORID) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) OType(com.orientechnologies.orient.core.metadata.schema.OType) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) Date(java.util.Date) BigDecimal(java.math.BigDecimal) ORecordLazyMap(com.orientechnologies.orient.core.db.record.ORecordLazyMap) ORecordLazyMultiValue(com.orientechnologies.orient.core.db.record.ORecordLazyMultiValue) BigInteger(java.math.BigInteger) ORecord(com.orientechnologies.orient.core.record.ORecord) BigInteger(java.math.BigInteger) ODatabaseObject(com.orientechnologies.orient.core.db.object.ODatabaseObject) ORecordLazyMap(com.orientechnologies.orient.core.db.record.ORecordLazyMap) Map(java.util.Map)

Example 53 with OProperty

use of com.orientechnologies.orient.core.metadata.schema.OProperty in project orientdb by orientechnologies.

the class OCommandExecutorSQLCreateLink method execute.

/**
   * Execute the CREATE LINK.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (destField == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    final ODatabaseDocumentInternal database = getDatabase();
    if (!(database.getDatabaseOwner() instanceof ODatabaseDocument))
        throw new OCommandSQLParsingException("This command supports only the database type ODatabaseDocumentTx and type '" + database.getClass() + "' was found");
    final ODatabaseDocument db = (ODatabaseDocument) database.getDatabaseOwner();
    final OClass sourceClass = database.getMetadata().getSchema().getClass(sourceClassName);
    if (sourceClass == null)
        throw new OCommandExecutionException("Source class '" + sourceClassName + "' not found");
    final OClass destClass = database.getMetadata().getSchema().getClass(destClassName);
    if (destClass == null)
        throw new OCommandExecutionException("Destination class '" + destClassName + "' not found");
    Object value;
    String cmd = "select from ";
    if (!ODocumentHelper.ATTRIBUTE_RID.equals(destField)) {
        cmd = "select from " + destClassName + " where " + destField + " = ";
    }
    List<ODocument> result;
    ODocument target;
    Object oldValue;
    long total = 0;
    if (linkName == null)
        // NO LINK NAME EXPRESSED: OVERWRITE THE SOURCE FIELD
        linkName = sourceField;
    boolean multipleRelationship;
    if (linkType != null)
        // DETERMINE BASED ON FORCED TYPE
        multipleRelationship = linkType == OType.LINKSET || linkType == OType.LINKLIST;
    else
        multipleRelationship = false;
    long totRecords = db.countClass(sourceClass.getName());
    long currRecord = 0;
    if (progressListener != null)
        progressListener.onBegin(this, totRecords, false);
    database.declareIntent(new OIntentMassiveInsert());
    try {
        // BROWSE ALL THE RECORDS OF THE SOURCE CLASS
        for (ODocument doc : db.browseClass(sourceClass.getName())) {
            value = doc.field(sourceField);
            if (value != null) {
                if (value instanceof ODocument || value instanceof ORID) {
                // ALREADY CONVERTED
                } else if (value instanceof Collection<?>) {
                // TODO
                } else {
                    // SEARCH THE DESTINATION RECORD
                    target = null;
                    if (!ODocumentHelper.ATTRIBUTE_RID.equals(destField) && value instanceof String)
                        if (((String) value).length() == 0)
                            value = null;
                        else
                            value = "'" + value + "'";
                    result = database.<OCommandRequest>command(new OSQLSynchQuery<ODocument>(cmd + value)).execute();
                    if (result == null || result.size() == 0)
                        value = null;
                    else if (result.size() > 1)
                        throw new OCommandExecutionException("Cannot create link because multiple records was found in class '" + destClass.getName() + "' with value " + value + " in field '" + destField + "'");
                    else {
                        target = result.get(0);
                        value = target;
                    }
                    if (target != null && inverse) {
                        // INVERSE RELATIONSHIP
                        oldValue = target.field(linkName);
                        if (oldValue != null) {
                            if (!multipleRelationship)
                                multipleRelationship = true;
                            Collection<ODocument> coll;
                            if (oldValue instanceof Collection) {
                                // ADD IT IN THE EXISTENT COLLECTION
                                coll = (Collection<ODocument>) oldValue;
                                target.setDirty();
                            } else {
                                // CREATE A NEW COLLECTION FOR BOTH
                                coll = new ArrayList<ODocument>(2);
                                target.field(linkName, coll);
                                coll.add((ODocument) oldValue);
                            }
                            coll.add(doc);
                        } else {
                            if (linkType != null)
                                if (linkType == OType.LINKSET) {
                                    value = new ORecordLazySet(target);
                                    ((Set<OIdentifiable>) value).add(doc);
                                } else if (linkType == OType.LINKLIST) {
                                    value = new ORecordLazyList(target);
                                    ((ORecordLazyList) value).add(doc);
                                } else
                                    // IGNORE THE TYPE, SET IT AS LINK
                                    value = doc;
                            else
                                value = doc;
                            target.field(linkName, value);
                        }
                        target.save();
                    } else {
                        // SET THE REFERENCE
                        doc.field(linkName, value);
                        doc.save();
                    }
                    total++;
                }
            }
            if (progressListener != null)
                progressListener.onProgress(this, currRecord, currRecord * 100f / totRecords);
        }
        if (total > 0) {
            if (inverse) {
                // REMOVE THE OLD PROPERTY IF ANY
                OProperty prop = destClass.getProperty(linkName);
                if (prop != null)
                    destClass.dropProperty(linkName);
                if (linkType == null)
                    linkType = multipleRelationship ? OType.LINKSET : OType.LINK;
                // CREATE THE PROPERTY
                destClass.createProperty(linkName, linkType, sourceClass);
            } else {
                // REMOVE THE OLD PROPERTY IF ANY
                OProperty prop = sourceClass.getProperty(linkName);
                if (prop != null)
                    sourceClass.dropProperty(linkName);
                // CREATE THE PROPERTY
                sourceClass.createProperty(linkName, OType.LINK, destClass);
            }
        }
        if (progressListener != null)
            progressListener.onCompletition(this, true);
    } catch (Exception e) {
        if (progressListener != null)
            progressListener.onCompletition(this, false);
        throw OException.wrapException(new OCommandExecutionException("Error on creation of links"), e);
    } finally {
        database.declareIntent(null);
    }
    return total;
}
Also used : ORecordLazyList(com.orientechnologies.orient.core.db.record.ORecordLazyList) OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) Set(java.util.Set) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) OSQLSynchQuery(com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) ArrayList(java.util.ArrayList) ORecordLazySet(com.orientechnologies.orient.core.db.record.ORecordLazySet) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) OIntentMassiveInsert(com.orientechnologies.orient.core.intent.OIntentMassiveInsert) OException(com.orientechnologies.common.exception.OException) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) Collection(java.util.Collection) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ORID(com.orientechnologies.orient.core.id.ORID) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 54 with OProperty

use of com.orientechnologies.orient.core.metadata.schema.OProperty in project orientdb by orientechnologies.

the class OSQLHelper method bindParameters.

public static ODocument bindParameters(final ODocument iDocument, final List<OPair<String, Object>> iFields, final OCommandParameters iArguments, final OCommandContext iContext) {
    if (iFields == null)
        return null;
    // BIND VALUES
    for (OPair<String, Object> field : iFields) {
        final String fieldName = field.getKey();
        Object fieldValue = field.getValue();
        if (fieldValue != null) {
            if (fieldValue instanceof OCommandSQL) {
                final OCommandSQL cmd = (OCommandSQL) fieldValue;
                cmd.getContext().setParent(iContext);
                fieldValue = ODatabaseRecordThreadLocal.INSTANCE.get().command(cmd).execute();
                // CHECK FOR CONVERSIONS
                OImmutableClass immutableClass = ODocumentInternal.getImmutableSchemaClass(iDocument);
                if (immutableClass != null) {
                    final OProperty prop = immutableClass.getProperty(fieldName);
                    if (prop != null) {
                        if (prop.getType() == OType.LINK) {
                            if (OMultiValue.isMultiValue(fieldValue)) {
                                final int size = OMultiValue.getSize(fieldValue);
                                if (size == 1)
                                    // GET THE FIRST ITEM AS UNIQUE LINK
                                    fieldValue = OMultiValue.getFirstValue(fieldValue);
                                else if (size == 0)
                                    // NO ITEMS, SET IT AS NULL
                                    fieldValue = null;
                            }
                        }
                    } else if (immutableClass.isEdgeType() && ("out".equals(fieldName) || "in".equals(fieldName)) && (fieldValue instanceof List)) {
                        List lst = (List) fieldValue;
                        if (lst.size() == 1) {
                            fieldValue = lst.get(0);
                        }
                    }
                }
                if (OMultiValue.isMultiValue(fieldValue)) {
                    final List<Object> tempColl = new ArrayList<Object>(OMultiValue.getSize(fieldValue));
                    String singleFieldName = null;
                    for (Object o : OMultiValue.getMultiValueIterable(fieldValue, false)) {
                        if (o instanceof OIdentifiable && !((OIdentifiable) o).getIdentity().isPersistent()) {
                            // TEMPORARY / EMBEDDED
                            final ORecord rec = ((OIdentifiable) o).getRecord();
                            if (rec != null && rec instanceof ODocument) {
                                // CHECK FOR ONE FIELD ONLY
                                final ODocument doc = (ODocument) rec;
                                if (doc.fields() == 1) {
                                    singleFieldName = doc.fieldNames()[0];
                                    tempColl.add(doc.field(singleFieldName));
                                } else {
                                    // TRANSFORM IT IN EMBEDDED
                                    doc.getIdentity().reset();
                                    ODocumentInternal.addOwner(doc, iDocument);
                                    ODocumentInternal.addOwner(doc, iDocument);
                                    tempColl.add(doc);
                                }
                            }
                        } else
                            tempColl.add(o);
                    }
                    fieldValue = tempColl;
                }
            }
        }
        iDocument.field(fieldName, resolveFieldValue(iDocument, fieldName, fieldValue, iArguments, iContext));
    }
    return iDocument;
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) ArrayList(java.util.ArrayList) OImmutableClass(com.orientechnologies.orient.core.metadata.schema.OImmutableClass) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ORecord(com.orientechnologies.orient.core.record.ORecord) ArrayList(java.util.ArrayList) List(java.util.List) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 55 with OProperty

use of com.orientechnologies.orient.core.metadata.schema.OProperty in project orientdb by orientechnologies.

the class OSQLFilterItemField method getCollate.

/**
   * get the collate of this expression, based on the fully evaluated field chain starting from the passed object.
   *
   * @param doc the root element (document?) of this field chain
   * @return the collate, null if no collate is defined
   */
public OCollate getCollate(Object doc) {
    if (collate != null || operationsChain == null || !isFieldChain()) {
        return collate;
    }
    if (!(doc instanceof OIdentifiable)) {
        return null;
    }
    FieldChain chain = getFieldChain();
    ODocument lastDoc = ((OIdentifiable) doc).getRecord();
    for (int i = 0; i < chain.getItemCount() - 1; i++) {
        if (lastDoc == null) {
            return null;
        }
        Object nextDoc = lastDoc.field(chain.getItemName(i));
        if (nextDoc == null || !(nextDoc instanceof OIdentifiable)) {
            return null;
        }
        lastDoc = ((OIdentifiable) nextDoc).getRecord();
    }
    if (lastDoc == null) {
        return null;
    }
    OClass schemaClass = lastDoc.getSchemaClass();
    if (schemaClass == null) {
        return null;
    }
    OProperty property = schemaClass.getProperty(chain.getItemName(chain.getItemCount() - 1));
    if (property == null) {
        return null;
    }
    return property.getCollate();
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OProperty (com.orientechnologies.orient.core.metadata.schema.OProperty)87 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)69 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)32 Test (org.testng.annotations.Test)30 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)25 OSchema (com.orientechnologies.orient.core.metadata.schema.OSchema)23 OType (com.orientechnologies.orient.core.metadata.schema.OType)14 OSQLSynchQuery (com.orientechnologies.orient.core.sql.query.OSQLSynchQuery)11 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)9 OIndex (com.orientechnologies.orient.core.index.OIndex)7 ODatabaseObject (com.orientechnologies.orient.core.db.object.ODatabaseObject)6 OCommandSQL (com.orientechnologies.orient.core.sql.OCommandSQL)6 Map (java.util.Map)6 Set (java.util.Set)6 OIndexDefinition (com.orientechnologies.orient.core.index.OIndexDefinition)5 Collection (java.util.Collection)5 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)4 Field (java.lang.reflect.Field)4 Test (org.junit.Test)4 OException (com.orientechnologies.common.exception.OException)3