Package com.sleepycat.db

Examples of com.sleepycat.db.Transaction


             * Use a single transaction for opening the primary DB and its
             * secondaries.  If opening any secondary fails, abort the
             * transaction and undo the changes to the state of the store.
             * Also support undo if the store is non-transactional.
             */
            Transaction txn = null;
            DatabaseConfig dbConfig = getPrimaryConfig(entityMeta);
            if (dbConfig.getTransactional() &&
    DbCompat.getThreadTransaction(env) == null) {
                txn = env.beginTransaction(null, null);
            }
            PrimaryOpenState priOpenState =
                new PrimaryOpenState(entityClassName);
            boolean success = false;
            try {
       
                /* Open the primary database. */
                String[] fileAndDbNames =
                    parseDbName(storePrefix + entityClassName);
                Database db;
                try {
                    db = DbCompat.openDatabase
                        (env, txn, fileAndDbNames[0], fileAndDbNames[1],
                         dbConfig);
                } catch (FileNotFoundException e) {
                    throw new DatabaseException(e);
                }
                priOpenState.addDatabase(db);

                /* Create index object. */
                priIndex = new PrimaryIndex
                    (db, primaryKeyClass, keyBinding, entityClass,
                     entityBinding);

                /* Update index and database maps. */
                priIndexMap.put(entityClassName, priIndex);
                if (DbCompat.getDeferredWrite(dbConfig)) {
                    deferredWriteDatabases.put(db, null);
                }

                /* If not read-only, open all associated secondaries. */
                if (!dbConfig.getReadOnly()) {
                    openSecondaryIndexes(txn, entityMeta, priOpenState);

                    /*
                     * To enable foreign key contratints, also open all primary
                     * indexes referring to this class via a relatedEntity
                     * property in another entity. [#15358]
                     */
                    Set<String> inverseClassNames =
                        inverseRelatedEntityMap.get(entityClassName);
                    if (inverseClassNames != null) {
                        for (String relatedClsName : inverseClassNames) {
                            getRelatedIndex(relatedClsName);
                        }
                    }
                }
                success = true;
            } finally {
                if (success) {
                    if (txn != null) {
                        txn.commit();
                    }
                } else {
                    if (txn != null) {
                        txn.abort();
                    } else {
                        priOpenState.closeDatabases();
                    }
                    priOpenState.undoState();
                }
View Full Code Here


        EntityBinding binding = index.getEntityBinding();
        DatabaseEntry key = new DatabaseEntry();
        DatabaseEntry data = new DatabaseEntry();

        CursorConfig cursorConfig = null;
        Transaction txn = null;
        if (dbConfig.getTransactional()) {
            txn = env.beginTransaction(null, null);
            cursorConfig = CursorConfig.READ_COMMITTED;
        }

        Cursor cursor = null;
        int nWritten = 0;
        try {
            cursor = db.openCursor(txn, cursorConfig);
            OperationStatus status = cursor.getFirst(key, data, null);
            while (status == OperationStatus.SUCCESS) {
                boolean oneWritten = false;
                if (evolveNeeded(key, data, binding)) {
                    cursor.putCurrent(data);
                    oneWritten = true;
                    nWritten += 1;
                }
                if (listener != null) {
                    EvolveInternal.updateEvent
                        (event, entityClassName, 1, oneWritten ? 1 : 0);
                    if (!listener.evolveProgress(event)) {
                        break;
                    }
                }
                if (txn != null && nWritten >= WRITES_PER_TXN) {
                    cursor.close();
                    cursor = null;
                    txn.commit();
                    txn = null;
                    txn = env.beginTransaction(null, null);
                    cursor = db.openCursor(txn, cursorConfig);
                    DatabaseEntry saveKey = KeyRange.copy(key);
                    status = cursor.getSearchKeyRange(key, data, null);
                    if (status == OperationStatus.SUCCESS &&
                        KeyRange.equalBytes(key, saveKey)) {
                        status = cursor.getNext(key, data, null);
                    }
                } else {
                    status = cursor.getNext(key, data, null);
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (txn != null) {
                if (nWritten > 0) {
                    txn.commit();
                } else {
                    txn.abort();
                }
            }
        }
    }
View Full Code Here

    // Thread method that writes a series of objects
    // to the store using transaction protection.
    // Deadlock handling is demonstrated here.
    public void run () {
        Transaction txn = null;

        // Perform 50 transactions
        for (int i=0; i<50; i++) {

           boolean retry = true;
           int retry_count = 0;
           // while loop is used for deadlock retries
           while (retry) {
                // try block used for deadlock detection and
                // general exception handling
                try {

                    // Get a transaction
                    txn = myEnv.beginTransaction(null, null);

                    // Write 10 PayloadDataEntity objects to the
                    // store for each transaction
                    for (int j = 0; j < 10; j++) {
                        // Instantiate an object
                        PayloadDataEntity pd = new PayloadDataEntity();

                        // Set the Object ID. This is used as the primary key.
                        pd.setID(i + j);

                        // The thread name is used as a secondary key, and
                        // it is retrieved by this class's getName() method.
                        pd.setThreadName(getName());
                       
                        // The last bit of data that we use is a double
                        // that we generate randomly. This data is not
                        // indexed.
                        pd.setDoubleData(generator.nextDouble());

                        // Do the put
                        pdKey.put(txn, pd);
                    }

                    // commit
                    System.out.println(getName() + " : committing txn : " + i);
                    System.out.println(getName() + " : Found " +
                        countObjects(txn) + " objects in the store.");
                    try {
                        txn.commit();
                        txn = null;
                    } catch (DatabaseException e) {
                        System.err.println("Error on txn commit: " +
                            e.toString());
                    }
                    retry = false;

                } catch (DeadlockException de) {
                    System.out.println("################# " + getName() +
                        " : caught deadlock");
                    // retry if necessary
                    if (retry_count < MAX_RETRY) {
                        System.err.println(getName() +
                            " : Retrying operation.");
                        retry = true;
                        retry_count++;
                    } else {
                        System.err.println(getName() +
                            " : out of retries. Giving up.");
                        retry = false;
                    }
                } catch (DatabaseException e) {
                    // abort and don't retry
                    retry = false;
                    System.err.println(getName() +
                        " : caught exception: " + e.toString());
                    System.err.println(getName() +
                        " : errno: " + e.getErrno());
                    e.printStackTrace();
                } finally {
                    if (txn != null) {
                        try {
                            txn.abort();
                        } catch (Exception e) {
                            System.err.println("Error aborting transaction: " +
                                e.toString());
                            e.printStackTrace();
                        }
View Full Code Here

        checkIndex(primaryRaw, expected, rawKeyGetter, rawEntityGetter);

        /* Check primary delete, last key first for variety. */
        for (int priKey = N_RECORDS - 1; priKey >= 0; priKey -= 1) {
            boolean useRaw = ((priKey & 1) != 0);
            Transaction txn = txnBegin();
            if (useRaw) {
                primaryRaw.delete(txn, priKey);
            } else {
                primary.delete(txn, priKey);
            }
            txnCommit(txn);
            expected.remove(priKey);
            checkIndex(primary, expected, keyGetter, entityGetter);
        }
        checkAllEmpty();

        /* Check PrimaryIndex put operations. */
        MyEntity e;
        Transaction txn = txnBegin();
        /* put() */
        e = primary.put(txn, new MyEntity(1));
        assertNull(e);
        e = primary.get(txn, 1, null);
        assertEquals(1, e.key);
View Full Code Here

    }

    private void addEntities(PrimaryIndex<Integer,MyEntity> primary)
        throws DatabaseException {

        Transaction txn = txnBegin();
        for (int priKey = 0; priKey < N_RECORDS; priKey += 1) {
            MyEntity prev = primary.put(txn, new MyEntity(priKey));
            assertNull(prev);
        }
        txnCommit(txn);
View Full Code Here

            Integer delSecKey = expected.firstKey();
            SortedSet<Integer> deletedPriKeys = expected.remove(delSecKey);
            for (SortedSet<Integer> priKeys : expected.values()) {
                priKeys.removeAll(deletedPriKeys);
            }
            Transaction txn = txnBegin();
            boolean deleted = index.delete(txn, delSecKey);
            assertEquals(deleted, !deletedPriKeys.isEmpty());
            deleted = index.delete(txn, delSecKey);
            assertTrue(!deleted);
            assertNull(index.get(txn, delSecKey, null));
            txnCommit(txn);
            checkSecondary(index, indexRaw, expected);
        }

        /*
         * Delete remaining records so that the primary index is empty.  Use
         * the RawStore for variety.
         */
        Transaction txn = txnBegin();
        for (int priKey = 0; priKey < N_RECORDS; priKey += 1) {
            primaryRaw.delete(txn, priKey);
        }
        txnCommit(txn);
        checkAllEmpty();
View Full Code Here

                                  Getter<V> vGetter)
        throws DatabaseException {

        SortedMap<K,V> map = index.sortedMap();

        Transaction txn = txnBegin();
        for (int i : expected.keySet()) {
            K k = kGetter.fromInt(i);
            SortedSet<Integer> dups = expected.get(i);
            if (dups.isEmpty()) {
View Full Code Here

        eventBinding.objectToEntry(new Event(40, "CompanyD"),
                                   data);
        eventDb.put(null, key, data);

        /* Load a whole set of events transactionally. */
        Transaction txn = env.beginTransaction(null, null);
        int maxPrice = 50;
        System.out.println("-> Inserting some randomly generated events");
        for (int i = 0; i < 25; i++) {
            long time = makeDate(rand.nextInt(365));
            Event e = new Event(rand.nextInt(maxPrice),"Company_X");
            if ((i%2) ==0) {
                e.addRep("Jane");
                e.addRep("Nikunj");
            } else {
                e.addRep("Yongmin");
            }
            LongBinding.longToEntry(time, key);
            eventBinding.objectToEntry(e, data);
            eventDb.put(txn, key, data);
        }
        txn.commitWriteNoSync();

        /*
         * Windows of events - display the events between June 1 and Aug 31
         */
        System.out.println("\n-> Display the events between June 1 and Aug 31");
View Full Code Here

        eventByTime.put(new Event(makeDate(2), 2, "Company_B"));
        eventByTime.put(new Event(makeDate(3), 20, "Company_C"));
        eventByTime.put(new Event(makeDate(4), 40, "CompanyD"));

        /* Load a whole set of events transactionally. */
        Transaction txn = env.beginTransaction(null, null);
        int maxPrice = 50;
        System.out.println("-> Inserting some randomly generated events");
        for (int i = 0; i < 25; i++) {
            Event e = new Event(makeDate(rand.nextInt(365)),
                                rand.nextInt(maxPrice),
                                "Company_X");
            if ((i%2) ==0) {
                e.addRep("Bob");
                e.addRep("Nikunj");
            } else {
                e.addRep("Yongmin");
            }
            eventByTime.put(e);
        }
        txn.commitWriteNoSync();

        /*
         * Windows of events - display the events between June 1 and Aug 31
         */
        System.out.println("\n-> Display the events between June 1 and Aug 31");
View Full Code Here

        if (cdbMode) {
            cursorConfig = new CursorConfig();
            DbCompat.setWriteCursor(cursorConfig, true);
        }
        Cursor cursor = null;
        Transaction txn = null;
        try {
            if (txnMode) {
                txn = db.getEnvironment().beginTransaction(null, null);
            }
            cursor = db.openCursor(txn, cursorConfig);

            /* Get the current class ID. */
            DatabaseEntry key = new DatabaseEntry(LAST_CLASS_ID_KEY);
            DatabaseEntry data = new DatabaseEntry();
            OperationStatus status = cursor.getSearchKey(key, data,
                                                         writeLockMode);
            if (status != OperationStatus.SUCCESS) {
                throw new IllegalStateException("Class ID not initialized");
            }
            byte[] idBytes = getBytes(data);

            /* Increment the ID by one and write the updated record.  */
            idBytes = incrementID(idBytes);
            data.setData(idBytes);
            cursor.put(key, data);

            /*
             * Write the new class format record whose key is the ID just
             * assigned.
             */
            byte[] keyBytes = new byte[1 + idBytes.length];
            keyBytes[0] = REC_CLASS_FORMAT;
            System.arraycopy(idBytes, 0, keyBytes, 1, idBytes.length);
            key.setData(keyBytes);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos;
            try {
                oos = new ObjectOutputStream(baos);
                oos.writeObject(classFormat);
            } catch (IOException e) {
                throw new RuntimeExceptionWrapper(e);
            }
            data.setData(baos.toByteArray());

            cursor.put(key, data);

            /*
             * Write the new class info record, using the key passed in; this
             * is done last so that a reader who gets the class info record
             * first will always find the corresponding class format record.
             */
            classInfo.setClassID(idBytes);
            classInfo.toDbt(data);

            cursor.put(classKey, data);

            /*
             * Update the maps before closing the cursor, so that the cursor
             * lock prevents other writers from duplicating this entry.
             */
            classInfo.setClassFormat(classFormat);
            classMap.put(className, classInfo);
            formatMap.put(new BigInteger(idBytes), classFormat);
            return classInfo;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (txn != null) {
                txn.commit();
            }
        }
    }
View Full Code Here

TOP

Related Classes of com.sleepycat.db.Transaction

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.