public void HandleDidChangeRecord(string arg1, DatabaseEntry arg2, IDictionary arg3, string[] arg4)
 {
     Debug.Log ("record changed: " + arg2.location);
     if (arg2.location == "home") {
         cube.SetActive(true);
     }
 }
    //manages if a card is dealt to the player OR if the tabletop device recalls cards
    public void HandleDidChangeRecord(string arg1, DatabaseEntry arg2, IDictionary arg3, string[] arg4)
    {
        Debug.Log ("GameObject Record Change Detected");
        //if the card is dealt to us
        if (arg2.location == clientInit.playerName) {
            GameObject newCard = Instantiate (card1, new Vector3 (0f, 4.2f, -11.0f), card1.transform.rotation) as GameObject;
            newCard.name = "PlayingCard";
            newCard.transform.Rotate (new Vector3 (0, 0, 180));				//keep the card face down
            GameObject.Find("Hand").GetComponent<HandManager>().resetShowingCards();	//reset the hand so that cards are facing down by default
            playingCard1 = newCard.GetComponent<PlayingCard> ();			//set the PlayingCard component

            //sets the variables to a local copy of the card
            playingCard1.dbEntry.location = arg2.location;
            playingCard1.dbEntry.back = arg2.back;
            playingCard1.dbEntry.number = arg2.number;
            playingCard1.dbEntry.suit = arg2.suit;
            playingCard1.dbEntry._id = arg2._id;

            //keep track of this card and enable us to manipulate it
            playingCard1.AddToRecordGroup ();

            //pick the right face of a card to show
            string cardName = arg2.back + "" + arg2.number + "" + arg2.suit;
            foreach (Transform child in newCard.transform) {
                child.gameObject.GetComponent<MeshRenderer> ().enabled = false;
                child.gameObject.SetActive (false);
                if (child.gameObject.name == cardName) {
                    child.gameObject.GetComponent<MeshRenderer> ().enabled = true;
                    child.gameObject.SetActive (true);
                }
            }

            //move the card to the appropriate location
            if (cardInPosition1) {
                newCard.GetComponent<physicalCard> ().moveToTarget (GameObject.Find ("Hand/CardLocation1"));
                cardInPosition1 = false;
            } else {
                newCard.GetComponent<physicalCard> ().moveToTarget (GameObject.Find ("Hand/CardLocation2"));
                cardInPosition1 = true;
            }

            //set the parent to "Hand" so that "Hand can easily control the cards
            newCard.transform.parent = GameObject.Find ("Hand").gameObject.transform;

            //if the tabletop device is recalling the cards (to reshuffle)
        } else if (arg2.location == "deck") {
            //moves the cards to the discard pile on mobile screen
            //and re-syncs the database that the cards are at location 'deck'
            hand.GetComponent<HandManager>().Recall();
        }
        //the card is neither being passed to us nor being recalled by the tabletop
        else {
            Debug.LogError ("this card does not belong to us, it belongs to: " + arg2.location);
            if (!production) {
                debugList.Add(arg2.location + arg2.number + arg2.suit);
                //Debug.Log ("added to list: " + arg2.location + arg2.number + arg2.suit);
                //clientInit.createMsgLog(arg2.location + "\n" + arg2.number + "\n" + arg2.suit, 1f);
            }
        }
    }
  internal int get_key(DatabaseEntry key) {
    try {
		int ret;
		ret = libdb_csharpPINVOKE.DB_SEQUENCE_get_key(swigCPtr, DBT.getCPtr(DatabaseEntry.getDBT(key)));
		DatabaseException.ThrowException(ret);
		return ret;
} finally {
      GC.KeepAlive(key);
    }
  }
Exemple #4
0
 internal int send_request(IntPtr[] request, uint nrequest, DatabaseEntry response, uint timeout, uint flags)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_CHANNEL_send_request(swigCPtr, request, nrequest, DBT.getCPtr(DatabaseEntry.getDBT(response)).Handle, timeout, flags);
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(response);
     }
 }
Exemple #5
0
 internal int read(DatabaseEntry data, Int64 offset, uint size, uint flags)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_STREAM_read(swigCPtr, DBT.getCPtr(DatabaseEntry.getDBT(data)), offset, size, flags);
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(data);
     }
 }
    //manages if a card is dealt to the player OR if the tabletop device recalls cards
    public void HandleDidChangeRecord(string arg1, DatabaseEntry arg2, IDictionary arg3, string[] arg4)
    {
        Debug.Log ("GameObject Record Change Detected");
        //if the card is dealt to us
        if (arg2.location == "Player") {
            Debug.Log ("record change's location is 'Player'");
            something.SetActive(true);
            something.GetComponent<ExampleObject>().dbEntry._id = arg2._id;
            Debug.Log ("setting Id to " + arg2._id + "and it worked? " + something.GetComponent<ExampleObject>().dbEntry._id );

        } else {
            Debug.LogError ("this does not belong to us, it belongs to: " + arg2.location);
        }
    }
    public void HandleDidAddRecord(string arg1, DatabaseEntry arg2)
    {
        Debug.Log ("Record added: " + arg2.location + arg2.color + arg2._id + ".");
        if (arg2.location == "home") {
            something = Instantiate (newThing, new Vector3 (0f, 10f, 0f), newThing.transform.rotation) as GameObject;
            something.name = "thing";

            exampleObject = something.GetComponent<ExampleObject> ();

            //sets the variables to a local copy of the card
            exampleObject.dbEntry.location = arg2.location;
            exampleObject.dbEntry.color = arg2.color;
            exampleObject.dbEntry._id = arg2._id;
            Debug.Log ("Make sure ID is set: " + exampleObject.dbEntry._id);

            //keep track of this card and enable us to manipulate it
            exampleObject.AddToRecordGroup ();
            something.SetActive(false);

            //if the tabletop device is recalling the cards (to reshuffle)
        } else {
            Debug.LogError ("this: " + arg2.location);
        }
    }
 public IntelligentUpload(CloudManagerViewModel model)
 {
     this.ViewModel = model;
     this.dbEntry = new DatabaseEntry();
 }
Exemple #9
0
        public void TestCompact()
        {
            testName = "TestCompact";
            testHome = testFixtureHome + "/" + testName;
            string recnoDBFileName = testHome + "/" +
                                     testName + ".db";

            Configuration.ClearDir(testHome);

            RecnoDatabaseConfig recnoConfig =
                new RecnoDatabaseConfig();

            recnoConfig.Creation = CreatePolicy.ALWAYS;
            recnoConfig.Length   = 512;

            DatabaseEntry key, data;
            RecnoDatabase recnoDB;

            using (recnoDB = RecnoDatabase.Open(
                       recnoDBFileName, recnoConfig))
            {
                for (int i = 1; i <= 5000; i++)
                {
                    data = new DatabaseEntry(
                        BitConverter.GetBytes(i));
                    recnoDB.Append(data);
                }

                for (int i = 1; i <= 5000; i++)
                {
                    if (i > 500 && (i % 5 != 0))
                    {
                        key = new DatabaseEntry(
                            BitConverter.GetBytes(i));
                        recnoDB.Delete(key);
                    }
                }

                int           startInt = 1;
                int           stopInt = 2500;
                DatabaseEntry start, stop;

                start = new DatabaseEntry(
                    BitConverter.GetBytes(startInt));
                stop = new DatabaseEntry(
                    BitConverter.GetBytes(stopInt));
                Assert.IsTrue(recnoDB.Exists(start));
                Assert.IsTrue(recnoDB.Exists(stop));

                CompactConfig cCfg = new CompactConfig();
                cCfg.start          = start;
                cCfg.stop           = stop;
                cCfg.FillPercentage = 30;
                cCfg.Pages          = 1;
                cCfg.returnEnd      = true;
                cCfg.Timeout        = 5000;
                cCfg.TruncatePages  = true;
                CompactData compactData = recnoDB.Compact(cCfg);

                Assert.IsNotNull(compactData.End);
                Assert.AreNotEqual(0, compactData.PagesExamined);
            }
        }
 public void AppendRecord(DatabaseEntry data, uint recno)
 {
     data.Data = BitConverter.GetBytes(recno);
 }
Exemple #11
0
        static void Main(string[] args)
        {
            DatabaseEntry       data;
            DatabaseEnvironment env;
            List <Lock>         lockList;
            Lock     lk;
            LockMode mode;
            string   buff;
            string   home;
            string   progName;
            int      lockNo;
            uint     doUnLink;
            uint     locker;
            uint     maxLock;

            try {
                home     = args[0];
                maxLock  = uint.Parse(args[1]);
                doUnLink = uint.Parse(args[2]);
            } catch {
                Usage();
                return;
            }

            data     = new DatabaseEntry();
            lockList = new List <Lock>();
            progName = "ex_csharp_lock";

            /* Initialize the database environment. */
            if (DBInit(out env, home, progName, maxLock, doUnLink) == EXIT_FAILURE)
            {
                return;
            }

            /*
             * Accept lock requests.
             */
            try {
                locker = env.CreateLockerID();
            } catch (Exception e) {
                Console.WriteLine("{0}:{1}\n{2}",
                                  e.Source, e.Message, e.StackTrace);
                env.Close();
                return;
            }

            while (true)
            {
                /* Choose getting or releasing lock. */
                Console.WriteLine("Operation get/release/quit: ");
                buff = Console.ReadLine();
                if (buff == "get")
                {
                    /* Input the content to be locked. */
                    Console.WriteLine("Input text string to lock");
                    try {
                        buff = Console.ReadLine();
                        DbtFromString(data, buff);
                    } catch {
                        Console.WriteLine("Input fails");
                        continue;
                    }

                    /*
                     * Choose the locker's mode. More lock modes
                     * could be provided. Only support read/write
                     * mode here.
                     */
                    while (true)
                    {
                        Console.WriteLine("read or write");
                        buff = Console.ReadLine();
                        if (buff == "read" || buff == "write")
                        {
                            break;
                        }
                    }
                    if (buff == "write")
                    {
                        mode = LockMode.WRITE;
                    }
                    else
                    {
                        mode = LockMode.READ;
                    }

                    /* Get lock and add it to the list of locks. */
                    try {
                        lk = env.GetLock(locker, false, data, mode);
                    } catch (Exception e) {
                        Console.WriteLine("{0}:{1}\n{2}",
                                          e.Source, e.Message, e.StackTrace);
                        env.Close();
                        return;
                    }

                    Console.WriteLine("Lock #{0} granted",
                                      lockList.Count);
                    lockList.Add(lk);
                }
                else if (buff == "release")
                {
                    /*
                     * Release a lock.
                     */
                    while (true)
                    {
                        /* Input lock number to release. */
                        Console.WriteLine(
                            "Input lock number to release");
                        buff = Console.ReadLine();
                        try {
                            lockNo = int.Parse(buff);
                            if (lockNo > 0 && lockNo <
                                lockList.Count)
                            {
                                break;
                            }
                            else
                            {
                                Console.WriteLine(
                                    "Lock number is out of range");
                            }
                        } catch {
                            Console.WriteLine(
                                "Not a valid lock number");
                        }
                    }

                    /* Release a lock and remove it from the list of locks. */
                    try {
                        env.PutLock(lockList[lockNo]);
                    } catch (Exception e) {
                        Console.WriteLine("{0}:{1}\n{2}",
                                          e.Source, e.Message, e.StackTrace);
                        env.Close();
                        return;
                    }

                    lockList.Remove(lockList[lockNo]);
                }
                else if (buff == "quit")
                {
                    break;
                }
            }

            /*Free locker and close the environment. */
            env.FreeLockerID(locker);
            env.Close();
        }
Exemple #12
0
        public void Delete(DatabaseEntry graphKey, Transaction transaction)
        {
            //Get all reverse index values for the internal id.
            var allKeysInIndex =
                reverseIndex
                    .GetMultiple(graphKey, (int)reverseIndex.Pagesize, transaction);

            //In the forward index, get all keys for each reverse index value and delete the record if the value matches
            //the internal id of the graph we are deleting.
            foreach (var cursor in
                from indexKey in allKeysInIndex.Value
                let c = index.Cursor(new CursorConfig(), transaction)
                where c.Move(indexKey, true)
                select c)
            {
                do
                {
                    if (cursor.Current.Value.Data.SequenceEqual(graphKey.Data)) cursor.Delete();
                }
                while (cursor.MoveNextDuplicate());

                cursor.Close();
            }

            reverseIndex.Delete(graphKey, transaction);
        }
Exemple #13
0
        public void TestPrepare()
        {
            testName = "TestPrepare";
            SetUpTest(true);

            DatabaseEnvironment env;

            byte[] gid;

            /*
             * Open an environment and begin a transaction
             * called "transaction". Within the transacion, open a
             * database, write a record and close it. Then prepare
             * the transaction and panic the environment.
             */
            PanicPreparedTxn(testHome, testName, out env, out gid);

            /*
             * Recover the environment.     Log and db files are not
             * destoyed so run normal recovery. Recovery should
             * use DB_CREATE and DB_INIT_TXN flags when
             * opening the environment.
             */
            DatabaseEnvironmentConfig envConfig
                = new DatabaseEnvironmentConfig();

            envConfig.RunRecovery = true;
            envConfig.Create      = true;
            envConfig.UseTxns     = true;
            envConfig.UseMPool    = true;
            env = DatabaseEnvironment.Open(testHome, envConfig);

            // Reopen the database.
            BTreeDatabase db;

            OpenBtreeDBInEnv(testName + ".db", env, out db,
                             false, null);

            /*
             * Confirm that record("key", "data") exists in the
             * database.
             */
            DatabaseEntry key, data;

            key = new DatabaseEntry(
                ASCIIEncoding.ASCII.GetBytes("key"));
            data = new DatabaseEntry(
                ASCIIEncoding.ASCII.GetBytes("data"));
            try
            {
                db.GetBoth(key, data);
            }
            catch (DatabaseException)
            {
                throw new TestException();
            }
            finally
            {
                db.Close();
                env.Close();
            }
        }
Exemple #14
0
        public void TestDuplicateToDifferentPos()
        {
            BTreeDatabase             db;
            BTreeDatabaseConfig       dbConfig;
            BTreeCursor               cursor, dupCursor;
            DatabaseEnvironment       env;
            DatabaseEnvironmentConfig envConfig;
            DatabaseEntry             key, data;
            KeyValuePair <DatabaseEntry, DatabaseEntry> pair;
            Transaction txn;

            testName = "TestDuplicateToDifferentPos";
            SetUpTest(true);

            envConfig          = new DatabaseEnvironmentConfig();
            envConfig.Create   = true;
            envConfig.UseMPool = true;
            envConfig.UseTxns  = true;
            envConfig.NoMMap   = false;
            env = DatabaseEnvironment.Open(testHome, envConfig);

            txn               = env.BeginTransaction();
            dbConfig          = new BTreeDatabaseConfig();
            dbConfig.Creation = CreatePolicy.IF_NEEDED;
            dbConfig.Env      = env;
            db   = BTreeDatabase.Open(testName + ".db", dbConfig, txn);
            key  = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key"));
            data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"));
            pair = new KeyValuePair <DatabaseEntry, DatabaseEntry>(key, data);
            db.Put(key, data, txn);
            txn.Commit();

            txn    = env.BeginTransaction();
            cursor = db.Cursor(txn);
            cursor.Move(key, true);

            //Duplicate a new cursor to the same position.
            dupCursor = cursor.Duplicate(false);

            /*
             * The duplicate cursor points to nothing so overwriting the
             * record is not allowed.
             */
            try
            {
                dupCursor.Overwrite(new DatabaseEntry(
                                        ASCIIEncoding.ASCII.GetBytes("newdata")));
            }
            catch (DatabaseException)
            {
                throw new ExpectedTestException();
            }
            finally
            {
                dupCursor.Close();
                cursor.Close();
                txn.Commit();
                db.Close();
                env.Close();
            }
        }
Exemple #15
0
 internal int log_put(DB_LSN lsn, DatabaseEntry data, uint flags)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_ENV_log_put(swigCPtr, DB_LSN.getCPtr(lsn), DBT.getCPtr(DatabaseEntry.getDBT(data)), flags);
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(data);
     }
 }
Exemple #16
0
 public static byte[] Serialize(this DatabaseEntry entry) => MessagePackSerializer.Serialize(entry);
Exemple #17
0
        public void MoveWithRMW(string home, string name)
        {
            paramEnv = null;
            paramDB  = null;

            // Open the environment.
            DatabaseEnvironmentConfig envCfg =
                new DatabaseEnvironmentConfig();

            envCfg.Create       = true;
            envCfg.FreeThreaded = true;
            envCfg.UseLocking   = true;
            envCfg.UseLogging   = true;
            envCfg.UseMPool     = true;
            envCfg.UseTxns      = true;
            paramEnv            = DatabaseEnvironment.Open(home, envCfg);

            // Open database in transaction.
            Transaction         openTxn = paramEnv.BeginTransaction();
            BTreeDatabaseConfig cfg     = new BTreeDatabaseConfig();

            cfg.Creation     = CreatePolicy.ALWAYS;
            cfg.Env          = paramEnv;
            cfg.FreeThreaded = true;
            cfg.PageSize     = 4096;
            // Use record number.
            cfg.UseRecordNumbers = true;
            paramDB = BTreeDatabase.Open(name + ".db", cfg, openTxn);
            openTxn.Commit();

            /*
             * Put 10 different, 2 duplicate and another different
             * records into database.
             */
            Transaction txn = paramEnv.BeginTransaction();

            for (int i = 0; i < 13; i++)
            {
                DatabaseEntry key, data;
                if (i == 10 || i == 11)
                {
                    key  = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key"));
                    data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"));
                }
                else
                {
                    key  = new DatabaseEntry(BitConverter.GetBytes(i));
                    data = new DatabaseEntry(BitConverter.GetBytes(i));
                }
                paramDB.Put(key, data, txn);
            }

            txn.Commit();

            // Get a event wait handle.
            signal = new EventWaitHandle(false,
                                         EventResetMode.ManualReset);

            /*
             * Start RdMfWt() in two threads. RdMfWt() reads
             * and writes data into database.
             */
            Thread t1 = new Thread(new ThreadStart(RdMfWt));
            Thread t2 = new Thread(new ThreadStart(RdMfWt));

            t1.Start();
            t2.Start();

            // Give both threads time to read before signalling them to write.
            Thread.Sleep(1000);

            // Invoke the write operation in both threads.
            signal.Set();

            // Return the number of deadlocks.
            while (t1.IsAlive || t2.IsAlive)
            {
                /*
                 * Give both threads time to write before
                 * counting the number of deadlocks.
                 */
                Thread.Sleep(1000);
                uint deadlocks = paramEnv.DetectDeadlocks(DeadlockPolicy.DEFAULT);

                // Confirm that there won't be any deadlock.
                Assert.AreEqual(0, deadlocks);
            }

            t1.Join();
            t2.Join();
            paramDB.Close();
            paramEnv.Close();
        }
Exemple #18
0
 //public static IDatabaseEntry Get(this Guid entry) => Database.Get(entry);
 //public static T Get<T>(this Guid entry) where T : class, IDatabaseEntry => Database.Get(entry) as T;
 public static string ToJson(this DatabaseEntry entry) => MessagePackSerializer.SerializeToJson(entry);
Exemple #19
0
 internal int open(DB_TXN txn, DatabaseEntry key, uint flags)
 {
     try {
         int ret;
         ret = libdb_csharpPINVOKE.DB_SEQUENCE_open(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(key)), flags);
         if (ret != 0)
         {
             close(0);
         }
         DatabaseException.ThrowException(ret);
         return(ret);
     } finally {
         GC.KeepAlive(key);
     }
 }
Exemple #20
0
        static void Main(string[] args)
        {
            BTreeDatabase       btreeDB;
            BTreeDatabaseConfig btreeConfig;
            Cursor        dbc;
            DatabaseEntry key;
            DatabaseEntry data;
            string        buff, dbFileName, keyString;

            /*
             * excs_access is meant to be run from build_windows\AnyCPU, in either
             * the Debug or Release directory. The required core libraries,
             * however, are in either build_windows\Win32 or build_windows\x64,
             * depending upon the platform.  That location needs to be added
             * to the PATH environment variable for the P/Invoke calls to work.
             */
            try {
                String pwd = Environment.CurrentDirectory;
                pwd = Path.Combine(pwd, "..");
                pwd = Path.Combine(pwd, "..");
                if (IntPtr.Size == 4)
                {
                    pwd = Path.Combine(pwd, "Win32");
                }
                else
                {
                    pwd = Path.Combine(pwd, "x64");
                }
#if DEBUG
                pwd = Path.Combine(pwd, "Debug");
#else
                pwd = Path.Combine(pwd, "Release");
#endif
                pwd += ";" + Environment.GetEnvironmentVariable("PATH");
                Environment.SetEnvironmentVariable("PATH", pwd);
            } catch (Exception e) {
                Console.WriteLine(
                    "Unable to set the PATH environment variable.");
                Console.WriteLine(e.Message);
                return;
            }

            try {
                dbFileName = "access.db";
                if (args.Length > 0)
                {
                    dbFileName = args[0];
                }
            } catch {
                usage();
                return;
            }

            /* Optiionally remove the existing database file. */
            if (File.Exists(dbFileName))
            {
                while (true)
                {
                    Console.Write
                        ("{0} already exists.  Delete it? (y/n) ", dbFileName);
                    buff = Console.ReadLine().ToLower();
                    if (buff == "y" || buff == "n")
                    {
                        break;
                    }
                }

                if (buff == "y")
                {
                    try {
                        File.Delete(dbFileName);
                    } catch {
                        Console.WriteLine("Unable to delete {0}.", dbFileName);
                        return;
                    }
                }
            }

            /* Configure the database. */
            btreeConfig             = new BTreeDatabaseConfig();
            btreeConfig.Duplicates  = DuplicatesPolicy.SORTED;
            btreeConfig.ErrorPrefix = "excs_access";
            btreeConfig.Creation    = CreatePolicy.IF_NEEDED;
            btreeConfig.CacheSize   = new CacheInfo(0, 64 * 1024, 1);
            btreeConfig.PageSize    = 8 * 1024;

            /* Create and open a new database in the file. */
            try {
                btreeDB = BTreeDatabase.Open(dbFileName, btreeConfig);
            } catch (Exception e) {
                Console.WriteLine("Error opening {0}.", dbFileName);
                Console.WriteLine(e.Message);
                return;
            }

            /* Input key/data pairs and insert them into the database.*/
            key  = new DatabaseEntry();
            data = new DatabaseEntry();

            while (true)
            {
                Console.Write("key [blank line to quit] > ");
                keyString = Console.ReadLine();
                if (keyString == "")
                {
                    break;
                }

                dbtFromString(key, keyString);
                dbtFromString(data, reverse(keyString));

                try {
                    btreeDB.Put(key, data);
                } catch {
                    return;
                }
            }

            /* Acquire a cursor for the database. */
            using (dbc = btreeDB.Cursor()) {
                /* Walk through the database and print out key/data pairs. */
                Console.WriteLine("All key : data pairs:");
                foreach (KeyValuePair <DatabaseEntry, DatabaseEntry> p in dbc)
                {
                    Console.WriteLine("{0}::{1}",
                                      strFromDBT(p.Key), strFromDBT(p.Value));
                }
            }

            Console.Write("Press any key to exit >");
            Console.ReadKey(true);

            /* Close the cursor and database. */
            btreeDB.Close();
        }
Exemple #21
0
 internal int rep_process_message(DatabaseEntry control, DatabaseEntry rec, int envid, DB_LSN ret_lsnp)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_ENV_rep_process_message(swigCPtr, DBT.getCPtr(DatabaseEntry.getDBT(control)), DBT.getCPtr(DatabaseEntry.getDBT(rec)), envid, DB_LSN.getCPtr(ret_lsnp));
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(control);
       GC.KeepAlive(rec);
     }
 }
Exemple #22
0
        public void TestMoveMultipleKey()
        {
            testName = "TestMoveMultipleKey";
            SetUpTest(true);
            string btreeDBFileName = testHome + "/" +
                                     testName + ".db";
            BTreeDatabase            db;
            BTreeCursor              cursor;
            DatabaseEntry            key;
            MultipleKeyDatabaseEntry mulPair;;
            int cnt;

            BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig();

            dbConfig.Creation   = CreatePolicy.ALWAYS;
            dbConfig.Duplicates = DuplicatesPolicy.UNSORTED;
            dbConfig.PageSize   = 1024;
            GetMultipleDB(btreeDBFileName, dbConfig, null, out db, out cursor);

            /*
             * Bulk retrieve key/value pair from the pair whose key
             * is exact 99.
             */
            cnt = 0;
            key = new DatabaseEntry(BitConverter.GetBytes((int)99));
            cursor.MoveMultipleKey(key, true);
            mulPair = cursor.CurrentMultipleKey;
            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry>
                     pair in mulPair)
            {
                Assert.GreaterOrEqual(3,
                                      BitConverter.ToInt32(pair.Key.Data, 0) - 98);
                cnt++;
            }
            Assert.AreEqual(3, cnt);

            /*
             * Bulk retrieve key/value pair from the pair whose key
             * is the smallest one larger than 100.
             */
            cnt = 0;
            key = new DatabaseEntry(BitConverter.GetBytes((int)100));
            cursor.MoveMultipleKey(key, false);
            mulPair = cursor.CurrentMultipleKey;
            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry>
                     pair in mulPair)
            {
                Assert.AreEqual(101,
                                BitConverter.ToInt32(pair.Key.Data, 0));
                cnt++;
            }
            Assert.LessOrEqual(1, cnt);

            cnt = 0;
            key = new DatabaseEntry(BitConverter.GetBytes((int)100));
            cursor.MoveMultipleKey(key, false, 1024);
            mulPair = cursor.CurrentMultipleKey;
            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry>
                     pair in mulPair)
            {
                Assert.AreEqual(101,
                                BitConverter.ToInt32(pair.Key.Data, 0));
                Assert.AreEqual(101,
                                BitConverter.ToInt32(pair.Value.Data, 0));
                cnt++;
            }
            Assert.LessOrEqual(1, cnt);

            cursor.Close();
            db.Close();
        }
Exemple #23
0
 private DB_LOCK lock_get(uint locker, uint flags, DatabaseEntry arg2, db_lockmode_t mode, ref int err)
 {
     try {
       DB_LOCK ret = new DB_LOCK(libdb_csharpPINVOKE.DB_ENV_lock_get(swigCPtr, locker, flags, DBT.getCPtr(DatabaseEntry.getDBT(arg2)), (int)mode, ref err), true);
       return ret;
     } finally {
       GC.KeepAlive(arg2);
     }
 }
Exemple #24
0
        public void TestMoveMultiplePairs()
        {
            testName = "TestMoveMultiplePairs";
            SetUpTest(true);
            string btreeDBFileName = testHome + "/" +
                                     testName + ".db";
            BTreeDatabase db;
            BTreeCursor   cursor;
            DatabaseEntry key, data;
            KeyValuePair <DatabaseEntry, DatabaseEntry> pair;
            MultipleKeyDatabaseEntry multiKeyDBTs1, multiKeyDBTs2;
            int cnt;

            BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig();

            dbConfig.Creation   = CreatePolicy.ALWAYS;
            dbConfig.Duplicates = DuplicatesPolicy.SORTED;
            dbConfig.PageSize   = 1024;
            GetMultipleDB(btreeDBFileName, dbConfig, null, out db, out cursor);

            /*
             * Bulk retrieve pairs from the pair whose key/data
             * is exact 99/99.
             */
            cnt  = 0;
            key  = new DatabaseEntry(BitConverter.GetBytes((int)99));
            data = new DatabaseEntry(BitConverter.GetBytes((int)99));
            pair = new KeyValuePair <DatabaseEntry, DatabaseEntry>(key, data);
            cursor.MoveMultipleKey(pair, true);
            multiKeyDBTs1 = cursor.CurrentMultipleKey;
            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry>
                     p in multiKeyDBTs1)
            {
                cnt++;
            }
            Assert.AreEqual(3, cnt);

            // Bulk retrieve pairs from the pair whose key is exact 99.
            cnt  = 0;
            key  = new DatabaseEntry(BitConverter.GetBytes((int)99));
            data = new DatabaseEntry(BitConverter.GetBytes((int)98));
            cursor.MoveMultipleKey(pair, true);
            multiKeyDBTs2 = cursor.CurrentMultipleKey;
            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry>
                     dbts in multiKeyDBTs2)
            {
                cnt++;
            }
            Assert.AreEqual(3, cnt);

            /*
             * Bulk retrieve pairs from the pair whose key is
             * exact 99 in buffer size of 1024k.
             */
            cnt  = 0;
            key  = new DatabaseEntry(BitConverter.GetBytes((int)99));
            data = new DatabaseEntry(BitConverter.GetBytes((int)102));
            cursor.MoveMultipleKey(pair, true, 1024);
            multiKeyDBTs2 = cursor.CurrentMultipleKey;
            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry>
                     dbts in multiKeyDBTs2)
            {
                cnt++;
            }
            Assert.AreEqual(3, cnt);

            cursor.Close();
            db.Close();
        }
Exemple #25
0
Fichier : DB.cs Projet : mcandre/db
 internal int put(DB_TXN txn, DatabaseEntry key, DatabaseEntry data, uint flags)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_put(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(key)), DBT.getCPtr(DatabaseEntry.getDBT(data)), flags);
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(key);
       GC.KeepAlive(data);
     }
 }
Exemple #26
0
        public void TestMoveNextMultipleKey()
        {
            testName = "TestMoveNextMultipleKey";
            SetUpTest(true);

            BTreeDatabase       db;
            BTreeCursor         cursor;
            DatabaseEnvironment env;
            Transaction         txn;
            int cnt = 0;

            BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig();

            dbConfig.Creation   = CreatePolicy.ALWAYS;
            dbConfig.Duplicates = DuplicatesPolicy.UNSORTED;

            GetMultipleDB(testHome, testName + ".db", dbConfig,
                          out env, out txn, out db, out cursor);

            /*
             * Position the cursor to the first record, and bulk get
             * all other records.
             */
            Assert.True(cursor.MoveFirst());
            Assert.True(cursor.MoveNextMultipleKey());
            MultipleKeyDatabaseEntry pairs =
                cursor.CurrentMultipleKey;

            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry> p
                     in pairs)
            {
                cnt++;
            }
            Assert.AreEqual(cnt, 100);

            // Bulk read uncommitted records.
            cnt = 0;
            LockingInfo lockingInfo = new LockingInfo();

            Assert.True(cursor.MoveFirst(lockingInfo));
            lockingInfo.IsolationDegree = Isolation.DEGREE_ONE;
            Assert.True(cursor.MoveNextMultipleKey(lockingInfo));
            pairs = cursor.CurrentMultipleKey;
            foreach (KeyValuePair <DatabaseEntry, DatabaseEntry> p
                     in pairs)
            {
                cnt++;
            }
            Assert.AreEqual(cnt, 100);

            cursor.Dispose();
            txn.Commit();

            /*
             * Insert duplicate records of the key in the last
             * record.
             */
            txn    = env.BeginTransaction();
            cursor = db.Cursor(txn);
            Assert.IsTrue(cursor.MoveLast());
            DatabaseEntry key = cursor.Current.Key;

            for (int i = 200; i < 800; i++)
            {
                cursor.Insert(new DatabaseEntry(
                                  BitConverter.GetBytes(i)),
                              Cursor.InsertLocation.AFTER);
            }

            /*
             * Move to the first duplicate records, and bulk read
             * all duplicate ones.
             */
            cnt = 0;
            Assert.True(cursor.Move(key, true));
            while (cursor.MoveNextDuplicateMultipleKey(
                       (int)db.Pagesize))
            {
                pairs = cursor.CurrentMultipleKey;
                foreach (KeyValuePair <
                             DatabaseEntry, DatabaseEntry> p in pairs)
                {
                    Assert.AreEqual(key.Data, p.Key.Data);
                    cnt++;
                }
            }
            Assert.AreEqual(cnt, 600);

            cursor.Close();
            db.Close();
            txn.Commit();
            env.Close();
        }
Exemple #27
0
 internal int put(DB_TXN txn, DatabaseEntry key, DatabaseEntry data, uint flags)
 {
     try {
         int ret;
         ret = libdb_csharpPINVOKE.DB_put(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(key)), DBT.getCPtr(DatabaseEntry.getDBT(data)), flags);
         DatabaseException.ThrowException(ret);
         return(ret);
     } finally {
         GC.KeepAlive(key);
         GC.KeepAlive(data);
     }
 }
        public void TestCommitSuccess()
        {
            testName = "TestCommitSuccess";
            SetUpTest(true);
            string[] keys = { "key 1", "key 2", "key 3", "key 4",
                              "key 5", "key 6", "key 7", "key 8","key 9", "key 10" };

            DatabaseEnvironment master = SetUpEnv(testHome + "/master", 100, masterPort, true);
            DatabaseEnvironment client = SetUpEnv(testHome + "/client", 0, clientPort, false);

            master.RepMgrStartMaster(2);
            Thread.Sleep(2000);
            client.RepMgrStartClient(2);

            BTreeDatabase db1 = Open(master, true);
            BTreeDatabase db2 = null;

            for (; ;)
            {
                if (db2 == null)
                {
                    try {
                        db2 = Open(client, false);
                        break;
                    } catch (DatabaseException) {
                        if (db2 != null)
                        {
                            db2.Close(true);
                            db2 = null;
                        }
                        System.Threading.Thread.Sleep(1000);
                        continue;
                    }
                }
            }

            try {
                for (int i = 0; i < 3; i++)
                {
                    Transaction txn = master.BeginTransaction();

                    // Get the key.
                    DatabaseEntry key, data;
                    key = new DatabaseEntry(
                        ASCIIEncoding.ASCII.GetBytes(keys[i]));

                    data = new DatabaseEntry(
                        ASCIIEncoding.ASCII.GetBytes(keys[i]));

                    db1.Put(key, data, txn);
                    txn.Commit();

                    byte[] token = txn.CommitToken;
                    Assert.AreEqual(master.IsTransactionApplied(token, 5000), TransactionAppliedStatus.APPLIED);
                    Assert.AreEqual(client.IsTransactionApplied(token, 200000), TransactionAppliedStatus.APPLIED);
                }
            }
            finally {
                db1.Close();
                db2.Close();
                master.Close();
                client.Close();
            }
        }
 public IntelligentUpload(CloudManagerViewModel model)
 {
     this.ViewModel = model;
     this.dbEntry   = new DatabaseEntry();
 }
 void HandleDidAddRecord(string arg1, DatabaseEntry arg2)
 {
     Debug.LogError ("record added: " + arg2.back);
     //need to add record to prizm record group
 }
Exemple #31
0
        public int doloop()
        {
            BTreeDatabase db = null;

            for (;;)
            {
                if (db == null)
                {
                    BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig();
                    dbConfig.Env = dbenv.env;

                    if (dbenv.IsMaster)
                    {
                        /*
                         * Open database allowing create only if this is a master
                         * database.  A client database uses polling to attempt
                         * to open the database, without creating it, until the
                         * open succeeds.
                         *
                         * This polling logic for allowing create can be
                         * simplified under some circumstances.  For example, if
                         * the application can be sure a database is already
                         * there, it would never need to open it allowing create.
                         */
                        dbConfig.Creation = CreatePolicy.IF_NEEDED;
                    }

                    dbConfig.AutoCommit = true;

                    try
                    {
                        db = BTreeDatabase.Open(RepConfig.progname, dbConfig);
                    } catch (DatabaseException)
                    {
                        Console.WriteLine("no stock database available yet.");
                        if (db != null)
                        {
                            db.Close(true);
                            db = null;
                        }

                        Thread.Sleep(RepConfig.SLEEPTIME);
                        continue;
                    }
                }

                /* Listen for input, and add it to the database. */
                Console.Write("QUOTESERVER");
                if (dbenv.IsMaster == false)
                {
                    Console.Write("(read-only)");
                }
                Console.Write("> ");
                string nextLine = null;
                try
                {
                    nextLine = Console.ReadLine();
                } catch (System.IO.IOException)
                {
                    Console.WriteLine("Unable to get data");
                    break;
                }

                /* A blank line causes the DB to be dumped. */
                string[] words = nextLine.Split(' ');
                if (words.Length == 0 ||
                    words.Length == 1 && words[0].Length == 0)
                {
                    try
                    {
                        if (dbenv.InClientSync)
                        {
                            Console.WriteLine("Cannot read data during " +
                                              "client initialization - please try again.");
                        }
                        else
                        {
                            printStocks(db);
                        }
                    } catch (DeadlockException)
                    {
                        continue;
                    } catch (DatabaseException e)
                    {
                        /*
                         * This could be DB_REP_HANDLE_DEAD, which
                         * should close the database and continue.
                         */
                        Console.WriteLine("Got db exception reading replication"
                                          + "DB: " + e);
                        Console.WriteLine("Expected if it was due to a dead " +
                                          "replication handle, otherwise an unexpected error.");
                        db.Close(false);                        /* Close no sync. */
                        db = null;
                        continue;
                    }
                    continue;
                }

                if (words.Length == 1 &&
                    (words[0].ToLower().Equals("quit") ||
                     words[0].ToLower().Equals("exit")))
                {
                    dbenv.AppFinished = true;
                    break;
                }
                else if (words.Length != 2)
                {
                    Console.WriteLine("Format: TICKER VALUE");
                    continue;
                }

                if (!dbenv.IsMaster)
                {
                    Console.WriteLine("Can't update client");
                    continue;
                }

                DatabaseEntry key = new DatabaseEntry(
                    ASCIIEncoding.ASCII.GetBytes(words[0]));
                DatabaseEntry data = new DatabaseEntry(
                    ASCIIEncoding.ASCII.GetBytes(words[1]));

                db.Put(key, data);
            }

            if (db != null)
            {
                db.Close(true);
            }

            return(0);
        }
Exemple #32
0
        public void Delete(byte[] key, Transaction txn = null)
        {
            DatabaseEntry k = new DatabaseEntry(key);

            db.Delete(k, txn);
        }
        /*
         * Test the external file database with or without environment.
         * 1. Config and open the environment;
         * 2. Verify the environment external file configs;
         * 3. Config and open the database;
         * 4. Verify the database external file configs;
         * 5. Insert and verify some external file data by database methods;
         * 6. Insert some external file data by cursor, update it and verify
         * the update by database stream and cursor;
         * 7. Verify the stats;
         * 8. Close all handles.
         * If "blobdbt" is true, set the data DatabaseEntry.ExternalFile as
         * true, otherwise make the data DatabaseEntry reach the external file
         * threshold in size.
         */
        void TestBlobHashDatabase(uint env_threshold, string env_blobdir,
                                  uint db_threshold, string db_blobdir, bool blobdbt)
        {
            if (env_threshold == 0 && db_threshold == 0)
            {
                return;
            }

            string hashDBName =
                testHome + "/" + testName + ".db";

            Configuration.ClearDir(testHome);
            HashDatabaseConfig cfg = new HashDatabaseConfig();

            cfg.Creation = CreatePolicy.ALWAYS;
            string blrootdir = "__db_bl";

            // Open the environment and verify the external file config.
            if (env_threshold > 0)
            {
                DatabaseEnvironmentConfig envConfig =
                    new DatabaseEnvironmentConfig();
                envConfig.AutoCommit            = true;
                envConfig.Create                = true;
                envConfig.UseMPool              = true;
                envConfig.UseLogging            = true;
                envConfig.UseTxns               = true;
                envConfig.UseLocking            = true;
                envConfig.ExternalFileThreshold = env_threshold;
                if (env_blobdir != null)
                {
                    envConfig.ExternalFileDir = env_blobdir;
                    blrootdir = env_blobdir;
                }
                DatabaseEnvironment env = DatabaseEnvironment.Open(
                    testHome, envConfig);
                if (env_blobdir == null)
                {
                    Assert.IsNull(env.ExternalFileDir);
                }
                else
                {
                    Assert.AreEqual(0,
                                    env.ExternalFileDir.CompareTo(env_blobdir));
                }
                Assert.AreEqual(env_threshold,
                                env.ExternalFileThreshold);
                cfg.Env    = env;
                hashDBName = testName + ".db";
            }

            // Open the database and verify the external file config.
            if (db_threshold > 0)
            {
                cfg.ExternalFileThreshold = db_threshold;
            }
            if (db_blobdir != null)
            {
                cfg.ExternalFileDir = db_blobdir;

                /*
                 * The external file directory setting in the database
                 * is effective only when it is opened without
                 * an environment.
                 */
                if (cfg.Env == null)
                {
                    blrootdir = db_blobdir;
                }
            }

            HashDatabase db = HashDatabase.Open(hashDBName, cfg);

            Assert.AreEqual(
                db_threshold > 0 ? db_threshold : env_threshold,
                db.ExternalFileThreshold);
            if (db_blobdir == null && cfg.Env == null)
            {
                Assert.IsNull(db.ExternalFileDir);
            }
            else
            {
                Assert.AreEqual(0,
                                db.ExternalFileDir.CompareTo(blrootdir));
            }

            // Insert and verify some external file data by database
            // methods.
            string[]      records = { "a", "b", "c", "d", "e", "f", "g", "h",
                                      "i",      "j", "k", "l", "m", "n", "o", "p","q","r", "s",
                                      "t",      "u", "v", "w", "x", "y", "z" };
            DatabaseEntry kdbt = new DatabaseEntry();
            DatabaseEntry ddbt = new DatabaseEntry();

            byte[] kdata, ddata;
            string str;
            KeyValuePair <DatabaseEntry, DatabaseEntry> pair;

            ddbt.ExternalFile = blobdbt;
            Assert.AreEqual(blobdbt, ddbt.ExternalFile);
            for (int i = 0; i < records.Length; i++)
            {
                kdata = BitConverter.GetBytes(i);
                str   = records[i];
                if (!blobdbt)
                {
                    for (int j = 0; j < db_threshold; j++)
                    {
                        str = str + records[i];
                    }
                }
                ddata     = Encoding.ASCII.GetBytes(str);
                kdbt.Data = kdata;
                ddbt.Data = ddata;
                db.Put(kdbt, ddbt);
                try
                {
                    pair = db.Get(kdbt);
                }
                catch (DatabaseException)
                {
                    db.Close();
                    if (cfg.Env != null)
                    {
                        cfg.Env.Close();
                    }
                    throw new TestException();
                }
                Assert.AreEqual(ddata, pair.Value.Data);
            }

            /*
             * Insert some external file data by cursor, update it and
             * verify the update by database stream.
             */
            kdata             = BitConverter.GetBytes(records.Length);
            ddata             = Encoding.ASCII.GetBytes("abc");
            kdbt.Data         = kdata;
            ddbt.Data         = ddata;
            ddbt.ExternalFile = true;
            Assert.IsTrue(ddbt.ExternalFile);
            pair =
                new KeyValuePair <DatabaseEntry, DatabaseEntry>(kdbt, ddbt);
            CursorConfig dbcConfig = new CursorConfig();
            Transaction  txn       = null;

            if (cfg.Env != null)
            {
                txn = cfg.Env.BeginTransaction();
            }
            HashCursor cursor = db.Cursor(dbcConfig, txn);

            cursor.Add(pair);
            DatabaseStreamConfig dbsc = new DatabaseStreamConfig();

            dbsc.SyncPerWrite = true;
            DatabaseStream dbs = cursor.DbStream(dbsc);

            Assert.AreNotEqual(null, dbs);
            Assert.IsFalse(dbs.GetConfig.ReadOnly);
            Assert.IsTrue(dbs.GetConfig.SyncPerWrite);
            Assert.AreEqual(3, dbs.Size());
            DatabaseEntry sdbt = dbs.Read(0, 3);

            Assert.IsNotNull(sdbt);
            Assert.AreEqual(ddata, sdbt.Data);
            sdbt = new DatabaseEntry(Encoding.ASCII.GetBytes("defg"));
            Assert.IsTrue(dbs.Write(sdbt, 3));
            Assert.AreEqual(7, dbs.Size());
            sdbt = dbs.Read(0, 7);
            Assert.IsNotNull(sdbt);
            Assert.AreEqual(Encoding.ASCII.GetBytes("abcdefg"), sdbt.Data);
            dbs.Close();

            /*
             * Verify the database stream can not write when it is
             * configured to be read-only.
             */
            dbsc.ReadOnly = true;
            dbs           = cursor.DbStream(dbsc);
            Assert.IsTrue(dbs.GetConfig.ReadOnly);
            try
            {
                Assert.IsFalse(dbs.Write(sdbt, 7));
                throw new TestException();
            }
            catch (DatabaseException)
            {
            }
            dbs.Close();

            // Verify the update by cursor.
            Assert.IsTrue(cursor.Move(kdbt, true));
            pair = cursor.Current;
            Assert.AreEqual(Encoding.ASCII.GetBytes("abcdefg"),
                            pair.Value.Data);
            cursor.Close();
            if (cfg.Env != null)
            {
                txn.Commit();
            }

            /*
             * Verify the external files are created in the expected
             * location.
             * This part of test is disabled since BTreeDatabase.BlobSubDir
             * is not exposed to users.
             */
            //if (cfg.Env != null)
            //	blrootdir = testHome + "/" + blrootdir;
            //string blobdir = blrootdir + "/" + db.BlobSubDir;
            //Assert.AreEqual(records.Length + 1,
            //    Directory.GetFiles(blobdir, "__db.bl*").Length);
            //Assert.AreEqual(1,
            //    Directory.GetFiles(blobdir, "__db_blob_meta.db").Length);

            // Verify the stats.
            HashStats st = db.Stats();

            Assert.AreEqual(records.Length + 1, st.nExternalFiles);

            // Close all handles.
            db.Close();
            if (cfg.Env != null)
            {
                cfg.Env.Close();
            }

            /*
             * Remove the default external file directory
             * when it is not under the test home.
             */
            if (db_blobdir == null && cfg.Env == null)
            {
                Directory.Delete("__db_bl", true);
            }
        }
Exemple #34
0
        private void WriteData()
        {
            /*
             * Write a series of records to the database using transaction
             * protection. Deadlock handling is demonstrated here.
             */
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream    ms        = new MemoryStream();
            Random          generator = new Random();
            Transaction     txn       = null;

            string[] keys = { "key 1", "key 2", "key 3", "key 4",
                              "key 5", "key 6", "key 7", "key 8","key 9", "key 10" };

            // Perform 20 transactions.
            int iters       = 0;
            int retry_count = 0;
            int maxRetry    = 20;

            while (iters < 50)
            {
                try {
                    // Get a transaction.
                    txn = env.BeginTransaction();

                    // Write 10 records to the db for each transaction.
                    for (int j = 0; j < 10; j++)
                    {
                        // Get the key.
                        DatabaseEntry key;
                        key = new DatabaseEntry(
                            ASCIIEncoding.ASCII.GetBytes(keys[j]));

                        // Get the data.
                        PayloadData pd = new PayloadData(
                            iters + j,
                            Thread.CurrentThread.Name,
                            generator.NextDouble());

                        formatter.Serialize(ms, pd);
                        Byte[]        bytes = ms.GetBuffer();
                        DatabaseEntry data  = new DatabaseEntry(bytes);

                        // Put key/data pair within the transaction.
                        db.Put(key, data, txn);
                    }

                    // Commit the transaction.
                    Console.WriteLine("{0} committing txn: {1}",
                                      Thread.CurrentThread.Name, iters);

                    int recCount = CountRecords(inMem ? txn : null);
                    Console.WriteLine("{0} found {1} records in the database.",
                                      Thread.CurrentThread.Name, recCount);

                    try {
                        txn.Commit();
                        txn = null;
                    } catch (DatabaseException e) {
                        Console.WriteLine(
                            "Error on txn commit: " +
                            e.ToString());
                    }

                    iters++;
                    retry_count = 0;
                } catch (DeadlockException) {
                    Console.WriteLine(
                        "##### {0} deadlocked.", Thread.CurrentThread.Name);

                    // Retry if necessary.
                    if (retry_count < maxRetry)
                    {
                        Console.WriteLine("{0} retrying.",
                                          Thread.CurrentThread.Name);
                        retry_count++;
                    }
                    else
                    {
                        Console.WriteLine("{0} out of retries. Giving up.",
                                          Thread.CurrentThread.Name);
                        iters++;
                        retry_count = 0;
                    }
                } catch (DatabaseException e) {
                    // Abort and don't retry.
                    iters++;
                    retry_count = 0;
                    Console.WriteLine(Thread.CurrentThread.Name +
                                      " : caught exception: " + e.ToString());
                    Console.WriteLine(Thread.CurrentThread.Name +
                                      " : errno: " + e.ErrorCode);
                    Console.WriteLine(e.StackTrace);
                } finally {
                    if (txn != null)
                    {
                        try {
                            txn.Abort();
                        } catch (DatabaseException e) {
                            Console.WriteLine("Error aborting transaction: " +
                                              e.ToString());
                            Console.WriteLine(e.StackTrace);
                        }
                    }
                }
            }
        }
Exemple #35
0
        public void TestRefreshMultipleAndMultipleKey()
        {
            testName = "TestRefreshMultipleAndMultipleKey";
            SetUpTest(true);
            string btreeDBFileName = testHome + "/" +
                                     testName + ".db";
            BTreeDatabase db;
            BTreeCursor   cursor;
            DatabaseEntry key, data;
            KeyValuePair <DatabaseEntry, DatabaseEntry>         pair;
            KeyValuePair <DatabaseEntry, MultipleDatabaseEntry> pairs;
            MultipleKeyDatabaseEntry multiPair;
            int cnt;

            int[] size = new int[2];
            size[0] = 0;
            size[1] = 1024;

            BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig();

            dbConfig.Creation   = CreatePolicy.ALWAYS;
            dbConfig.Duplicates = DuplicatesPolicy.SORTED;
            dbConfig.PageSize   = 1024;
            GetMultipleDB(btreeDBFileName, dbConfig, null, out db, out cursor);

            key  = new DatabaseEntry(BitConverter.GetBytes(99));
            data = new DatabaseEntry(BitConverter.GetBytes(99));
            pair = new KeyValuePair <DatabaseEntry, DatabaseEntry>(key, data);

            for (int j = 0; j < 2; j++)
            {
                for (int i = 0; i < 2; i++)
                {
                    cnt = 0;
                    cursor.Move(pair, true);
                    if (j == 0)
                    {
                        if (size[i] == 0)
                        {
                            Assert.IsTrue(cursor.RefreshMultiple());
                        }
                        else
                        {
                            Assert.IsTrue(cursor.RefreshMultiple(size[i]));
                        }
                        pairs = cursor.CurrentMultiple;
                        foreach (DatabaseEntry dbt in pairs.Value)
                        {
                            cnt++;
                        }
                        Assert.AreEqual(2, cnt);
                    }
                    else
                    {
                        if (size[i] == 0)
                        {
                            Assert.IsTrue(cursor.RefreshMultipleKey());
                        }
                        else
                        {
                            Assert.IsTrue(cursor.RefreshMultipleKey(size[i]));
                        }
                        multiPair = cursor.CurrentMultipleKey;
                        foreach (KeyValuePair <DatabaseEntry, DatabaseEntry> p in multiPair)
                        {
                            cnt++;
                        }
                        Assert.AreEqual(3, cnt);
                    }
                }
            }

            cursor.Close();
            db.Close();
        }
        private void DeleteMultipleAndMultipleKey(string dbFileName,
                                                  string dbName, DatabaseType type, bool mulKey)
        {
            List <DatabaseEntry> kList = new List <DatabaseEntry>();
            List <uint>          rList = new List <uint>();
            List <KeyValuePair <DatabaseEntry, DatabaseEntry> > pList =
                new List <KeyValuePair <DatabaseEntry, DatabaseEntry> >();
            DatabaseEntry     key;
            Database          db;
            SecondaryDatabase secDb;

            Configuration.ClearDir(testHome);

            if (type == DatabaseType.BTREE)
            {
                BTreeDatabaseConfig dbConfig =
                    new BTreeDatabaseConfig();
                dbConfig.Creation = CreatePolicy.IF_NEEDED;
                db = BTreeDatabase.Open(
                    dbFileName, dbName, dbConfig);
                SecondaryBTreeDatabaseConfig secDbConfig =
                    new SecondaryBTreeDatabaseConfig(db, null);
                secDbConfig.Creation   = CreatePolicy.IF_NEEDED;
                secDbConfig.Duplicates = DuplicatesPolicy.SORTED;
                secDbConfig.KeyGen     =
                    new SecondaryKeyGenDelegate(SecondaryKeyGen);
                secDb = SecondaryBTreeDatabase.Open(
                    dbFileName, dbName + "_sec", secDbConfig);
            }
            else if (type == DatabaseType.HASH)
            {
                HashDatabaseConfig dbConfig =
                    new HashDatabaseConfig();
                dbConfig.Creation = CreatePolicy.IF_NEEDED;
                db = HashDatabase.Open(
                    dbFileName, dbName, dbConfig);
                SecondaryHashDatabaseConfig secDbConfig =
                    new SecondaryHashDatabaseConfig(db, null);
                secDbConfig.Creation   = CreatePolicy.IF_NEEDED;
                secDbConfig.Duplicates = DuplicatesPolicy.SORTED;
                secDbConfig.KeyGen     =
                    new SecondaryKeyGenDelegate(SecondaryKeyGen);
                secDb = SecondaryHashDatabase.Open(
                    dbFileName, dbName + "_sec", secDbConfig);
            }
            else if (type == DatabaseType.QUEUE)
            {
                QueueDatabaseConfig dbConfig =
                    new QueueDatabaseConfig();
                dbConfig.Creation = CreatePolicy.IF_NEEDED;
                dbConfig.Length   = 4;
                db = QueueDatabase.Open(dbFileName, dbConfig);
                SecondaryQueueDatabaseConfig secDbConfig =
                    new SecondaryQueueDatabaseConfig(db, null);
                secDbConfig.Creation = CreatePolicy.IF_NEEDED;
                secDbConfig.Length   = 4;
                secDbConfig.KeyGen   =
                    new SecondaryKeyGenDelegate(SecondaryKeyGen);
                secDb = SecondaryQueueDatabase.Open(
                    dbFileName + "_sec", secDbConfig);
            }
            else if (type == DatabaseType.RECNO)
            {
                RecnoDatabaseConfig dbConfig =
                    new RecnoDatabaseConfig();
                dbConfig.Creation = CreatePolicy.IF_NEEDED;
                db = RecnoDatabase.Open(
                    dbFileName, dbName, dbConfig);
                SecondaryRecnoDatabaseConfig secDbConfig =
                    new SecondaryRecnoDatabaseConfig(db, null);
                secDbConfig.Creation = CreatePolicy.IF_NEEDED;
                secDbConfig.KeyGen   =
                    new SecondaryKeyGenDelegate(SecondaryKeyGen);
                secDb = SecondaryRecnoDatabase.Open(
                    dbFileName, dbName + "_sec", secDbConfig);
            }
            else
            {
                throw new TestException();
            }

            for (uint i = 1; i <= 100; i++)
            {
                key = new DatabaseEntry(
                    BitConverter.GetBytes(i));
                if (i >= 50 && i < 60)
                {
                    kList.Add(key);
                }
                else if (i > 80)
                {
                    pList.Add(new KeyValuePair <
                                  DatabaseEntry, DatabaseEntry>(
                                  key, key));
                }
                else if (type == DatabaseType.QUEUE ||
                         type == DatabaseType.RECNO)
                {
                    rList.Add(i);
                }

                db.Put(key, key);
            }

            if (mulKey)
            {
                // Create bulk buffer for key/value pairs.
                MultipleKeyDatabaseEntry pBuff;
                if (type == DatabaseType.BTREE)
                {
                    pBuff = new MultipleKeyDatabaseEntry(
                        pList, false);
                }
                else if (type == DatabaseType.HASH)
                {
                    pBuff = new MultipleKeyDatabaseEntry(
                        pList, false);
                }
                else if (type == DatabaseType.QUEUE)
                {
                    pBuff = new MultipleKeyDatabaseEntry(
                        pList, true);
                }
                else
                {
                    pBuff = new MultipleKeyDatabaseEntry(
                        pList, true);
                }

                // Bulk delete with the key/value pair bulk buffer.
                secDb.Delete(pBuff);
                foreach (KeyValuePair <DatabaseEntry,
                                       DatabaseEntry> pair in pList)
                {
                    try {
                        db.GetBoth(pair.Key, pair.Value);
                        throw new TestException();
                    } catch (NotFoundException e1) {
                        if (type == DatabaseType.QUEUE)
                        {
                            throw e1;
                        }
                    } catch (KeyEmptyException e2) {
                        if (type == DatabaseType.BTREE ||
                            type == DatabaseType.HASH ||
                            type == DatabaseType.RECNO)
                        {
                            throw e2;
                        }
                    }
                }

                /*
                 * Dump the database to verify that 80 records
                 * remain after bulk delete.
                 */
                Assert.AreEqual(80, db.Truncate());
            }
            else
            {
                // Create bulk buffer for key.
                MultipleDatabaseEntry kBuff;
                if (type == DatabaseType.BTREE)
                {
                    kBuff = new MultipleDatabaseEntry(
                        kList, false);
                }
                else if (type == DatabaseType.HASH)
                {
                    kBuff = new MultipleDatabaseEntry(
                        kList, false);
                }
                else if (type == DatabaseType.QUEUE)
                {
                    kBuff = new MultipleDatabaseEntry(
                        kList, true);
                }
                else
                {
                    kBuff = new MultipleDatabaseEntry(
                        kList, true);
                }

                /*
                 * Bulk delete in secondary database with key
                 * buffer. Primary records that the deleted
                 * records in secondar database should be
                 * deleted as well.
                 */
                secDb.Delete(kBuff);
                foreach (DatabaseEntry dbt in kList)
                {
                    try {
                        db.Get(dbt);
                        throw new TestException();
                    } catch (NotFoundException e1) {
                        if (type == DatabaseType.QUEUE ||
                            type == DatabaseType.RECNO)
                        {
                            throw e1;
                        }
                    } catch (KeyEmptyException e2) {
                        if (type == DatabaseType.BTREE ||
                            type == DatabaseType.HASH)
                        {
                            throw e2;
                        }
                    }
                }

                /*
                 * Bulk delete in secondary database with recno
                 * based key buffer.
                 */
                if (type == DatabaseType.QUEUE ||
                    type == DatabaseType.RECNO)
                {
                    MultipleDatabaseEntry rBuff =
                        new MultipleDatabaseEntry(rList);
                    secDb.Delete(rBuff);
                    Assert.AreEqual(20, db.Truncate());
                }
            }

            secDb.Close();
            db.Close();
        }
Exemple #37
0
        private DatabaseEntry[] get_partition_keys(ref uint countp, ref uint sizep, ref int err)
        {
            IntPtr cPtr = libdb_csharpPINVOKE.DB_get_partition_keys(swigCPtr, ref countp, ref sizep, ref err);
            if (cPtr == IntPtr.Zero)
            return null;

            DatabaseEntry[] ret = new DatabaseEntry[countp - 1];
            IntPtr val;
            for (int i = 0; i < (countp - 1); i++) {
            val = new IntPtr((IntPtr.Size == 4 ? cPtr.ToInt32() : cPtr.ToInt64()) + i * sizep);
            ret[i] = DatabaseEntry.fromDBT(new DBT(val, false));
            }
            return ret;
        }
Exemple #38
0
        public void TestConsumeWithTxn()
        {
            testName = "TestConsumeWithTxn";
            SetUpTest(true);
            string queueDBFileName = testHome + "/" + testName + ".db";
            string queueDBName     = Path.GetFileName(queueDBFileName);

            DatabaseEnvironmentConfig envConfig =
                new DatabaseEnvironmentConfig();

            envConfig.Create   = true;
            envConfig.UseTxns  = true;
            envConfig.UseMPool = true;

            DatabaseEnvironment env = DatabaseEnvironment.Open(
                testHome, envConfig);
            Transaction txn = env.BeginTransaction();

            QueueDatabaseConfig queueConfig =
                new QueueDatabaseConfig();

            queueConfig.Creation = CreatePolicy.ALWAYS;
            queueConfig.Env      = env;
            queueConfig.Length   = 1000;
            QueueDatabase queueDB = QueueDatabase.Open(
                queueDBName, queueConfig, txn);

            int           i = 1;
            DatabaseEntry data;
            DatabaseEntry getData = new DatabaseEntry();

            while (i <= 10)
            {
                data = new DatabaseEntry(
                    ASCIIEncoding.ASCII.GetBytes(i.ToString()));
                queueDB.Append(data, txn);
                if (i == 5)
                {
                    getData = data;
                }
                i++;
            }

            KeyValuePair <uint, DatabaseEntry> pair = queueDB.Consume(false, txn);

            queueDB.Close();
            txn.Commit();
            env.Close();

            Database db = Database.Open(queueDBFileName,
                                        new QueueDatabaseConfig());

            try
            {
                DatabaseEntry key =
                    new DatabaseEntry(BitConverter.GetBytes(pair.Key));
                db.Get(key);
            }
            catch (NotFoundException)
            {
                throw new ExpectedTestException();
            }
            finally
            {
                db.Close();
            }
        }
Exemple #39
0
 internal int open(DB_TXN txn, DatabaseEntry key, uint flags)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_SEQUENCE_open(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(key)), flags);
     if (ret != 0)
     close(0);
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(key);
     }
 }
Exemple #40
0
        public void TestPutMultiple()
        {
            testName = "TestPutMultiple";
            SetUpTest(true);

            QueueDatabaseConfig dbConfig = new QueueDatabaseConfig();

            dbConfig.Creation   = CreatePolicy.IF_NEEDED;
            dbConfig.ExtentSize = 1024;
            dbConfig.Length     = 520;
            dbConfig.PadByte    = 0;
            QueueDatabase db = QueueDatabase.Open(testHome + "/" +
                                                  testName + ".db", dbConfig);

            List <uint>          kList = new List <uint>();
            List <DatabaseEntry> vList = new List <DatabaseEntry>();
            DatabaseEntry        key, data;

            for (uint i = 1; i <= 9; i++)
            {
                key  = new DatabaseEntry(BitConverter.GetBytes(i));
                data = new DatabaseEntry(
                    ASCIIEncoding.ASCII.GetBytes("data" + i +
                                                 Configuration.RandomString(512)));
                kList.Add(i);
                vList.Add(data);
            }

            // Create bulk buffer for recno based keys.
            MultipleDatabaseEntry kBuff =
                new MultipleDatabaseEntry(kList);

            Assert.IsTrue(kBuff.Recno);
            int val = 0;

            foreach (DatabaseEntry dbt in kBuff)
            {
                Assert.AreEqual(
                    BitConverter.GetBytes(kList[val]),
                    dbt.Data);
                val++;
            }
            Assert.AreEqual(9, val);

            // Create bulk buffer for data.
            MultipleDatabaseEntry vBuff =
                new MultipleDatabaseEntry(vList, false);

            /*
             * Create recno bulk buffer from another recno bulk
             * buffer.
             */
            MultipleDatabaseEntry kBuff1 =
                new MultipleDatabaseEntry(kBuff.Data, kBuff.Recno);

            val = 0;
            foreach (DatabaseEntry dbt in kBuff1)
            {
                Assert.AreEqual(
                    BitConverter.GetBytes(kList[val]),
                    dbt.Data);
                val++;
            }
            Assert.AreEqual(9, val);

            // Bulk insert to database with key and value buffers.
            db.Put(kBuff, vBuff);
            Cursor cursor = db.Cursor();
            KeyValuePair <DatabaseEntry, DatabaseEntry> pair;

            val = 0;
            while (cursor.MoveNext())
            {
                pair = cursor.Current;
                Assert.AreEqual(
                    BitConverter.GetBytes(kList[val]),
                    pair.Key.Data);
                for (int i = 0; i < 520; i++)
                {
                    if (i < vList[val].Data.Length)
                    {
                        Assert.AreEqual(vList[val].Data[i],
                                        pair.Value.Data[i]);
                    }
                    else
                    {
                        // The pad byte is 0.
                        Assert.AreEqual(0, pair.Value.Data[i]);
                    }
                }
                Assert.IsFalse(cursor.MoveNextDuplicate());
                val++;
            }
            Assert.AreEqual(9, val);

            cursor.Close();
            db.Close();
        }
 //call this function in any derived classes with base.Awake()
 protected virtual void Awake()
 {
     dbEntry = new DatabaseEntry ();
     //recordGroup = GameObject.Find ("GameManager").GetComponent<PrizmRecordGroup> ();
     recordGroup = GameObject.FindGameObjectWithTag ("GameManager").GetComponent<PrizmRecordGroup> ();
 }
Exemple #42
0
        /// <summary>
        /// Creates the temporaray databases for storing the input sets, and then reads the input
        /// sets in full and stores them in the databases.
        /// </summary>
        private void CreateTmpDbs()
        {
            //
            // the temporary databases are BerkeleyDB B+ tree databases. configuration for the
            // databases is hardcoded here.

            var config = new BTreeDatabaseConfig();

            config.Duplicates = DuplicatesPolicy.UNSORTED;
            config.CacheSize  = new CacheInfo(0, m_planOperator.MemorySize / 2, 4);
            config.PageSize   = 512;
            config.Creation   = CreatePolicy.ALWAYS;

            m_tmpDbLeftFile  = String.Format("~{0}.tmp", Generator.GetRandomFilename(12));
            m_tmpDbRightFile = String.Format("~{0}.tmp", Generator.GetRandomFilename(12));
#if DEBUG
            m_planOperator.StartIOWork();
#endif
            m_tmpDbLeft  = BTreeDatabase.Open(m_tmpDbLeftFile, config);
            m_tmpDbRight = BTreeDatabase.Open(m_tmpDbRightFile, config);
#if DEBUG
            m_planOperator.StopIOWork();
#endif

            //
            // peek-a-binding from the left and right input streams, to obtain the shared join
            // variables between them

            var peekLeft  = m_left.Peek();
            var peekRight = m_right.Peek();

            foreach (var b1 in peekLeft.Bindings)
            {
                var b2 = peekRight[b1.Variable];
                if (b2 != null)
                {
                    m_joinVariables.Add(b1.Variable);
                }
            }

            var barrier = new Barrier(2);

            //
            // do this multi-threaded. because why not?

            Action <Operator, BTreeDatabase> dbBuildAction = (op, db) => {
                while (op.HasNext)
                {
                    var next = op.Next();
#if DEBUG
                    lock (m_planOperator) {
                        m_planOperator.StartCPUWork();
                    }
#endif
                    var bKey = new List <Binding>();
                    foreach (var item in m_joinVariables)
                    {
                        bKey.Add(next[item]);
                    }
#if DEBUG
                    lock (m_planOperator) {
                        m_planOperator.StopCPUWork();
                        m_planOperator.StartIOWork();
                    }
#endif
                    var key  = new DatabaseEntry(Encoding.DbEncode(Hash(bKey.ToArray())));
                    var data = new DatabaseEntry(Encoding.DbEncode(next));
                    db.Put(key, data);
#if DEBUG
                    lock (m_planOperator) {
                        m_planOperator.StopIOWork();
                    }
#endif
                }

                barrier.SignalAndWait();
            };

            //
            // one goes in a seperate thread...

            var t = new Thread(() => dbBuildAction(m_left, m_tmpDbLeft));
            t.Start();

            //
            // ...the other one just in the main thread.

            dbBuildAction(m_right, m_tmpDbRight);

            //
            // create the cursors for moving through the databases

            m_cursorLeft          = m_tmpDbLeft.Cursor();
            m_cursorLeftMovePrev  = false;
            m_cursorRight         = m_tmpDbRight.Cursor();
            m_cursorRightMovePrev = false;

            m_tmpDbsCreated = true;
        }
Exemple #43
0
 public static extern void DBT_app_data_set(HandleRef jarg1, DatabaseEntry jarg2);
 /* Get dbt from string. */
 static void dbtFromString(DatabaseEntry dbt, string s)
 {
     dbt.Data = System.Text.Encoding.ASCII.GetBytes(s);
 }
Exemple #45
0
 internal int rep_start(DatabaseEntry cdata, uint flags)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_ENV_rep_start(swigCPtr, DBT.getCPtr(DatabaseEntry.getDBT(cdata)), flags);
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(cdata);
     }
 }
 /* Get string from dbt. */
 public static string strFromDBT(DatabaseEntry dbt)
 {
     System.Text.ASCIIEncoding decode =
         new ASCIIEncoding();
     return(decode.GetString(dbt.Data));
 }
Exemple #47
0
 internal DB_LOCK lock_get(uint locker, uint flags, DatabaseEntry arg2, db_lockmode_t mode)
 {
     int err = 0;
     DB_LOCK ret = lock_get(locker, flags, arg2, mode, ref err);
     DatabaseException.ThrowException(err);
     return ret;
 }
        public static int excs_btrec(string dbFileName,
                                     string dbName, string wordFile)
        {
            BTreeCursor         dbc;
            BTreeDatabase       btreeDB;
            BTreeDatabaseConfig btreeDBconfig;
            DatabaseEntry       key, data;
            KeyValuePair <DatabaseEntry, DatabaseEntry> pair;
            StreamReader wordList;
            string       buff;

            char[] rbuff;
            int    i, j;
            uint   cnt;

            string progName = "excs_btrec";

            /* Check if word list exists. */
            if (!File.Exists(wordFile))
            {
                Console.WriteLine("Cannot find {0}/{1}.",
                                  Environment.CurrentDirectory, wordFile);
                return(1);
            }

            /* Optionally remove the previous database. */
            if (File.Exists(dbFileName))
            {
                while (true)
                {
                    Console.Write
                        ("Database already exists, delete or not (y/n)?");
                    buff = Console.ReadLine();
                    if (buff == "y" || buff == "n")
                    {
                        break;
                    }
                }

                if (buff == "y")
                {
                    File.Delete(dbFileName);
                    Console.WriteLine("The existing {0} is deleted",
                                      dbName);
                }
            }

            /* Create and initialize database object, open the database. */
            btreeDBconfig                  = new BTreeDatabaseConfig();
            btreeDBconfig.Creation         = CreatePolicy.IF_NEEDED;
            btreeDBconfig.ErrorPrefix      = progName;
            btreeDBconfig.UseRecordNumbers = true;
            try {
                btreeDB = BTreeDatabase.Open(dbFileName, dbName,
                                             btreeDBconfig);
            } catch {
                Console.WriteLine("Database can not be opened");
                return(1);
            }

            /*
             * Insert records into the database, where the key is the word
             * preceded by its record number, and the data is the same,
             * but in reverse order.
             */
            key      = new DatabaseEntry();
            data     = new DatabaseEntry();
            wordList = new StreamReader(wordFile);
            for (cnt = 1; cnt <= 1000; cnt++)
            {
                /* Read one word from word list. */
                try {
                    buff = wordList.ReadLine();
                } catch {
                    Console.WriteLine("Error when reading word list");
                    btreeDB.Close();
                    wordList.Close();
                    return(1);
                }

                /*
                 * Prefix the word with record number and store
                 * them in key.
                 */
                try {
                    buff = cnt.ToString("0000") + buff;
                } catch {
                    Console.WriteLine(
                        "Wrong format for record number.");
                    btreeDB.Close();
                    wordList.Close();
                    return(1);
                }
                dbtFromString(key, buff);

                /* Reverse buff to rbuff and store them in data. */
                rbuff = new char[buff.Length];
                for (i = 0, j = buff.Length - 1; i < buff.Length; i++, j--)
                {
                    rbuff[i] = buff[j];
                }
                dbtFromString(data, new string(rbuff));

                /* Put the key/data pair into database. */
                try {
                    btreeDB.PutNoOverwrite(key, data);
                } catch {
                    Console.WriteLine("Put error with key::{0} and"
                                      + "data::{1}", buff, new string(rbuff));
                    btreeDB.Close();
                    wordList.Close();
                    return(1);
                }
            }

            /* Close the word list. */
            wordList.Close();

            /* Acquire a cursor for the database. */
            dbc = btreeDB.Cursor();

            /*
             * Input an available record number and get its
             * corresponding key/data pair in the database.
             */
            while (true)
            {
                Console.WriteLine("Please input record number"
                                  + ", input 0 to stop");

                while (true)
                {
                    Console.WriteLine("recno #:\t");
                    buff = Console.ReadLine();

                    try {
                        cnt = uint.Parse(buff);
                        break;
                    } catch {
                        Console.WriteLine("Invalid Record Number. "
                                          + "Try Again.");
                    }
                }

                if (cnt == 0)
                {
                    break;
                }

                /*
                 * Position the cursor at a key/data pair in the database
                 * where the record number points to.
                 */
                if (!dbc.Move(cnt))
                {
                    Console.WriteLine("No record is found");
                    break;
                }

                /* Get the current key/data pair and display them.*/
                pair = dbc.Current;
                Console.WriteLine("key::{0, 18:G}    data::{1, 18:G}",
                                  strFromDBT(pair.Key), strFromDBT(pair.Value));

                /* Check if it's the right record number. */
                if (dbc.Recno() != cnt)
                {
                    Console.WriteLine("The current record is not"
                                      + "the right one of the given record number.");
                    btreeDB.Close();
                    dbc.Close();
                    return(1);
                }

                /* Get the next record. */
                if (!dbc.MoveNext())
                {
                    Console.WriteLine(
                        "Next record is not found");
                    break;
                }

                /* Get the current key/data pair and display them.*/
                pair = dbc.Current;
                Console.WriteLine("key::{0, 18:G}    data::{1, 18:G}\n",
                                  strFromDBT(pair.Key), strFromDBT(pair.Value));
            }

            /* Close cursor and database. */
            dbc.Close();
            btreeDB.Close();

            return(0);
        }
Exemple #49
0
Fichier : DB.cs Projet : mcandre/db
 internal int key_range(DB_TXN txn, DatabaseEntry key, DB_KEY_RANGE range, uint flags)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_key_range(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(key)), DB_KEY_RANGE.getCPtr(range), flags);
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(key);
     }
 }
Exemple #50
0
 internal int compact(DB_TXN txn, DatabaseEntry start, DatabaseEntry stop, DB_COMPACT cdata, uint flags, DatabaseEntry end)
 {
     try {
         int ret;
         ret = libdb_csharpPINVOKE.DB_compact(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(start)), DBT.getCPtr(DatabaseEntry.getDBT(stop)), DB_COMPACT.getCPtr(cdata), flags, DBT.getCPtr(DatabaseEntry.getDBT(end)));
         DatabaseException.ThrowException(ret);
         return(ret);
     } finally {
         GC.KeepAlive(start);
         GC.KeepAlive(stop);
         GC.KeepAlive(end);
     }
 }
Exemple #51
0
Fichier : DB.cs Projet : mcandre/db
 internal int compact(DB_TXN txn, DatabaseEntry start, DatabaseEntry stop, DB_COMPACT cdata, uint flags, DatabaseEntry end)
 {
     try {
     int ret;
     ret = libdb_csharpPINVOKE.DB_compact(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(start)), DBT.getCPtr(DatabaseEntry.getDBT(stop)), DB_COMPACT.getCPtr(cdata), flags, DBT.getCPtr(DatabaseEntry.getDBT(end)));
     DatabaseException.ThrowException(ret);
     return ret;
     } finally {
       GC.KeepAlive(start);
       GC.KeepAlive(stop);
       GC.KeepAlive(end);
     }
 }
Exemple #52
0
 internal int key_range(DB_TXN txn, DatabaseEntry key, DB_KEY_RANGE range, uint flags)
 {
     try {
         int ret;
         ret = libdb_csharpPINVOKE.DB_key_range(swigCPtr, DB_TXN.getCPtr(txn), DBT.getCPtr(DatabaseEntry.getDBT(key)), DB_KEY_RANGE.getCPtr(range), flags);
         DatabaseException.ThrowException(ret);
         return(ret);
     } finally {
         GC.KeepAlive(key);
     }
 }