Search in sources :

Example 21 with ORecord

use of com.orientechnologies.orient.core.record.ORecord in project orientdb by orientechnologies.

the class OObjectLazyMap method convert.

/**
 * Assure that the requested key is converted.
 */
private void convert(final String iKey) {
    if (converted || !convertToRecord)
        return;
    if (super.containsKey(iKey))
        return;
    final ORecord record = (ORecord) underlying.get(iKey);
    if (record == null)
        return;
    TYPE o = getDatabase().getUserObjectByRecord(record, null);
    ((OObjectProxyMethodHandler) (((ProxyObject) o)).getHandler()).setParentObject(sourceRecord);
    super.put(iKey, o);
}
Also used : ProxyObject(javassist.util.proxy.ProxyObject) ORecord(com.orientechnologies.orient.core.record.ORecord) OObjectProxyMethodHandler(com.orientechnologies.orient.object.enhancement.OObjectProxyMethodHandler)

Example 22 with ORecord

use of com.orientechnologies.orient.core.record.ORecord in project orientdb by orientechnologies.

the class HookTxTest method testHookCannotBeginTx.

@Test(dependsOnMethods = "testHookCallsDelete")
public void testHookCannotBeginTx() throws IOException {
    final AtomicBoolean exc = new AtomicBoolean(false);
    database.activateOnCurrentThread();
    database.registerHook(new ORecordHookAbstract() {

        @Override
        public RESULT onRecordBeforeCreate(ORecord iRecord) {
            try {
                database.activateOnCurrentThread();
                database.begin();
            } catch (IllegalStateException e) {
                exc.set(true);
            }
            return null;
        }

        @Override
        public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() {
            return DISTRIBUTED_EXECUTION_MODE.BOTH;
        }
    });
    Assert.assertFalse(exc.get());
    new ODocument().field("test-hook", true).save();
    Assert.assertTrue(exc.get());
    database.activateOnCurrentThread();
    database.close();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ORecord(com.orientechnologies.orient.core.record.ORecord) ORecordHookAbstract(com.orientechnologies.orient.core.hook.ORecordHookAbstract) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.testng.annotations.Test)

Example 23 with ORecord

use of com.orientechnologies.orient.core.record.ORecord in project orientdb by orientechnologies.

the class OCommandCacheSoftRefs method get.

@Override
public Object get(final OSecurityUser iUser, final String queryText, final int iLimit) {
    if (!enable)
        return null;
    OCachedResult result;
    synchronized (this) {
        final String key = getKey(iUser, queryText, iLimit);
        result = cache.get(key);
        if (result != null) {
            // SERIALIZE ALL THE RECORDS IN LOCK TO AVOID CONCURRENT ACCESS. ONCE SERIALIZED CAN ARE THREAD-SAFE
            int resultsetSize = 1;
            if (result.result instanceof ORecord)
                ((ORecord) result.result).toStream();
            else if (OMultiValue.isMultiValue(result.result)) {
                resultsetSize = OMultiValue.getSize(result.result);
                for (Object rc : OMultiValue.getMultiValueIterable(result.result)) {
                    if (rc != null && rc instanceof ORecord) {
                        ((ORecord) rc).toStream();
                    }
                }
            }
            if (OLogManager.instance().isDebugEnabled())
                OLogManager.instance().debug(this, "Reused cached resultset size=%d", resultsetSize);
        }
    }
    final OProfiler profiler = Orient.instance().getProfiler();
    if (profiler.isRecording()) {
        // UPDATE PROFILER
        if (result != null) {
            profiler.updateCounter(profiler.getDatabaseMetric(databaseName, "queryCache.hit"), "Results returned by Query Cache", +1);
        } else {
            profiler.updateCounter(profiler.getDatabaseMetric(databaseName, "queryCache.miss"), "Results not returned by Query Cache", +1);
        }
    }
    return result != null ? result.result : null;
}
Also used : OProfiler(com.orientechnologies.common.profiler.OProfiler) ORecord(com.orientechnologies.orient.core.record.ORecord)

Example 24 with ORecord

use of com.orientechnologies.orient.core.record.ORecord in project orientdb by orientechnologies.

the class OLocalRecordCache method findRecord.

/**
 * Looks up for record in cache by it's identifier. Optionally look up in secondary cache and update primary with found record
 *
 * @param rid
 *          unique identifier of record
 * @return record stored in cache if any, otherwise - {@code null}
 */
public ORecord findRecord(final ORID rid) {
    ORecord record;
    record = underlying.get(rid);
    if (record != null)
        Orient.instance().getProfiler().updateCounter(CACHE_HIT, "Record found in Level1 Cache", 1L, "db.*.cache.level1.cache.found");
    else
        Orient.instance().getProfiler().updateCounter(CACHE_MISS, "Record not found in Level1 Cache", 1L, "db.*.cache.level1.cache.notFound");
    return record;
}
Also used : ORecord(com.orientechnologies.orient.core.record.ORecord)

Example 25 with ORecord

use of com.orientechnologies.orient.core.record.ORecord in project orientdb by orientechnologies.

the class OAbstractPaginatedStorage method commit.

public List<ORecordOperation> commit(final OTransaction clientTx, Runnable callback) {
    try {
        checkOpeness();
        checkLowDiskSpaceFullCheckpointRequestsAndBackgroundDataFlushExceptions();
        txBegun.incrementAndGet();
        final ODatabaseDocumentInternal databaseRecord = (ODatabaseDocumentInternal) clientTx.getDatabase();
        final OIndexManagerProxy indexManager = databaseRecord.getMetadata().getIndexManager();
        final TreeMap<String, OTransactionIndexChanges> indexesToCommit = getSortedIndexEntries(clientTx);
        final Map<ORecordOperation, Integer> clusterOverrides = new IdentityHashMap<ORecordOperation, Integer>();
        databaseRecord.getMetadata().makeThreadLocalSchemaSnapshot();
        if (OLogManager.instance().isDebugEnabled())
            OLogManager.instance().debug(this, "Committing transaction %d on database '%s' (items=%d thread=%d)...", clientTx.getId(), databaseRecord.getName(), clientTx.getEntryCount(), Thread.currentThread().getId());
        final Iterable<ORecordOperation> entries = (Iterable<ORecordOperation>) clientTx.getAllRecordEntries();
        final TreeMap<Integer, OCluster> clustersToLock = new TreeMap<Integer, OCluster>();
        final Set<ORecordOperation> newRecords = new TreeSet<ORecordOperation>(new Comparator<ORecordOperation>() {

            @Override
            public int compare(final ORecordOperation o1, final ORecordOperation o2) {
                return o1.getRecord().getIdentity().compareTo(o2.getRecord().getIdentity());
            }
        });
        for (ORecordOperation txEntry : entries) {
            if (txEntry.type == ORecordOperation.CREATED || txEntry.type == ORecordOperation.RECYCLED || txEntry.type == ORecordOperation.UPDATED) {
                final ORecord record = txEntry.getRecord();
                if (record instanceof ODocument)
                    ((ODocument) record).validate();
            }
            if (txEntry.type == ORecordOperation.UPDATED || txEntry.type == ORecordOperation.DELETED) {
                final int clusterId = txEntry.getRecord().getIdentity().getClusterId();
                clustersToLock.put(clusterId, getClusterById(clusterId));
            } else if (txEntry.type == ORecordOperation.CREATED || txEntry.type == ORecordOperation.RECYCLED) {
                newRecords.add(txEntry);
                final ORecord record = txEntry.getRecord();
                final ORID rid = record.getIdentity();
                int clusterId = rid.getClusterId();
                if (record.isDirty() && clusterId == ORID.CLUSTER_ID_INVALID && record instanceof ODocument) {
                    // TRY TO FIX CLUSTER ID TO THE DEFAULT CLUSTER ID DEFINED IN SCHEMA CLASS
                    final OImmutableClass class_ = ODocumentInternal.getImmutableSchemaClass(((ODocument) record));
                    if (class_ != null) {
                        clusterId = class_.getClusterForNewInstance((ODocument) record);
                        clusterOverrides.put(txEntry, clusterId);
                    }
                }
                clustersToLock.put(clusterId, getClusterById(clusterId));
            }
        }
        final List<ORecordOperation> result = new ArrayList<ORecordOperation>();
        final List<Lock[]> indexKeyLockList = new ArrayList<Lock[]>(indexesToCommit.size());
        stateLock.acquireReadLock();
        try {
            try {
                try {
                    checkOpeness();
                    lockIndexKeys(indexManager, indexesToCommit, indexKeyLockList);
                    makeStorageDirty();
                    startStorageTx(clientTx);
                    lockClusters(clustersToLock);
                    lockRidBags(clustersToLock, indexesToCommit);
                    lockIndexes(indexesToCommit);
                    Map<ORecordOperation, OPhysicalPosition> positions = new IdentityHashMap<ORecordOperation, OPhysicalPosition>();
                    for (ORecordOperation txEntry : newRecords) {
                        ORecord rec = txEntry.getRecord();
                        ORecordId rid = (ORecordId) rec.getIdentity().copy();
                        ORecordId oldRID = rid.copy();
                        final Integer clusterOverride = clusterOverrides.get(txEntry);
                        final int clusterId = clusterOverride == null ? rid.getClusterId() : clusterOverride;
                        final OCluster cluster = getClusterById(clusterId);
                        final OPaginatedCluster.RECORD_STATUS recordStatus = rid.getClusterPosition() > -1 ? ((OPaginatedCluster) cluster).getRecordStatus(rid.getClusterPosition()) : OPaginatedCluster.RECORD_STATUS.NOT_EXISTENT;
                        OPhysicalPosition ppos = new OPhysicalPosition(rid.getClusterPosition());
                        if (recordStatus == OPaginatedCluster.RECORD_STATUS.NOT_EXISTENT) {
                            ppos = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
                            if (rid.getClusterPosition() > -1) {
                                // RECORD HAVING A HIGHER CLUSTER POSITION
                                while (rid.getClusterPosition() > ppos.clusterPosition) {
                                    ppos = cluster.allocatePosition(ORecordInternal.getRecordType(rec));
                                }
                                if (rid.getClusterPosition() != ppos.clusterPosition)
                                    throw new OConcurrentCreateException(rid, new ORecordId(rid.getClusterId(), ppos.clusterPosition));
                            }
                        } else if (recordStatus == OPaginatedCluster.RECORD_STATUS.REMOVED) {
                            // RECYCLE THE RID AND OVERWRITE IT WITH THE NEW CONTENT
                            final ORecord record = txEntry.getRecord();
                            record.setDirty();
                            recyclePosition(rid, record.toStream(), record.getVersion(), ORecordInternal.getRecordType(record));
                        }
                        positions.put(txEntry, ppos);
                        rid.setClusterId(cluster.getId());
                        rid.setClusterPosition(ppos.clusterPosition);
                        if (!oldRID.equals(rid))
                            clientTx.updateIdentityAfterCommit(oldRID, rid);
                    }
                    for (ORecordOperation txEntry : entries) {
                        commitEntry(txEntry, positions.get(txEntry));
                        result.add(txEntry);
                    }
                    commitIndexes(indexesToCommit);
                    endStorageTx();
                    OTransactionAbstract.updateCacheFromEntries(clientTx, entries, true);
                    txCommit.incrementAndGet();
                } catch (IOException ioe) {
                    makeRollback(clientTx, ioe);
                } catch (RuntimeException e) {
                    makeRollback(clientTx, e);
                } finally {
                    unlockIndexKeys(indexesToCommit, indexKeyLockList);
                    transaction.set(null);
                }
            } finally {
                databaseRecord.getMetadata().clearThreadLocalSchemaSnapshot();
            }
        } finally {
            stateLock.releaseReadLock();
        }
        if (OLogManager.instance().isDebugEnabled())
            OLogManager.instance().debug(this, "Committed transaction %d on database '%s' (result=%s thread=%d)", clientTx.getId(), databaseRecord.getName(), result, Thread.currentThread().getId());
        return result;
    } catch (RuntimeException e) {
        throw logAndPrepareForRethrow(e);
    } catch (Error e) {
        throw logAndPrepareForRethrow(e);
    } catch (Throwable t) {
        throw logAndPrepareForRethrow(t);
    }
}
Also used : ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) ORecordOperation(com.orientechnologies.orient.core.db.record.ORecordOperation) ORID(com.orientechnologies.orient.core.id.ORID) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) OImmutableClass(com.orientechnologies.orient.core.metadata.schema.OImmutableClass) ORecordId(com.orientechnologies.orient.core.id.ORecordId) Lock(java.util.concurrent.locks.Lock) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ORecord(com.orientechnologies.orient.core.record.ORecord)

Aggregations

ORecord (com.orientechnologies.orient.core.record.ORecord)194 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)91 ORecordId (com.orientechnologies.orient.core.id.ORecordId)40 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)36 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)27 ORID (com.orientechnologies.orient.core.id.ORID)27 IOException (java.io.IOException)21 OException (com.orientechnologies.common.exception.OException)17 Test (org.junit.Test)16 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)15 ORecordOperation (com.orientechnologies.orient.core.db.record.ORecordOperation)15 ORecordNotFoundException (com.orientechnologies.orient.core.exception.ORecordNotFoundException)15 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)14 OConcurrentModificationException (com.orientechnologies.orient.core.exception.OConcurrentModificationException)10 ArrayList (java.util.ArrayList)9 Map (java.util.Map)9 ONeedRetryException (com.orientechnologies.common.concur.ONeedRetryException)8 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)8 Test (org.testng.annotations.Test)8 OIOException (com.orientechnologies.common.io.OIOException)7