Exemple #1
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        public virtual void TestIndexUpdateMode()
        {
            View  view  = CreateView(database);
            Query query = view.CreateQuery();

            query.SetIndexUpdateMode(Query.IndexUpdateMode.Before);
            int numRowsBefore = query.Run().Count;

            NUnit.Framework.Assert.AreEqual(0, numRowsBefore);
            // do a query and force re-indexing, number of results should be +4
            PutNDocs(database, 1);
            query.SetIndexUpdateMode(Query.IndexUpdateMode.Before);
            NUnit.Framework.Assert.AreEqual(1, query.Run().Count);
            // do a query without re-indexing, number of results should be the same
            PutNDocs(database, 4);
            query.SetIndexUpdateMode(Query.IndexUpdateMode.Never);
            NUnit.Framework.Assert.AreEqual(1, query.Run().Count);
            // do a query and force re-indexing, number of results should be +4
            query.SetIndexUpdateMode(Query.IndexUpdateMode.Before);
            NUnit.Framework.Assert.AreEqual(5, query.Run().Count);
            // do a query which will kick off an async index
            PutNDocs(database, 1);
            query.SetIndexUpdateMode(Query.IndexUpdateMode.After);
            query.Run().Count;
            // wait until indexing is (hopefully) done
            try
            {
                Sharpen.Thread.Sleep(1 * 1000);
            }
            catch (Exception e)
            {
                Sharpen.Runtime.PrintStackTrace(e);
            }
            NUnit.Framework.Assert.AreEqual(6, query.Run().Count);
        }
Exemple #2
0
        public void TestQueryDefaultIndexUpdateMode()
        {
            View  view  = database.GetView("aview");
            Query query = view.CreateQuery();

            Assert.AreEqual(IndexUpdateMode.Before, query.IndexUpdateMode);
        }
        /// <summary>https://github.com/couchbase/couchbase-lite-android/issues/134</summary>
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void TestGetAttachmentBodyUsingPrefetch()
        {
            // add a doc with an attachment
            Document        doc = database.CreateDocument();
            UnsavedRevision rev = doc.CreateRevision();
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties["foo"] = "bar";
            rev.SetUserProperties(properties);
            byte[]     attachBodyBytes = Sharpen.Runtime.GetBytesForString("attach body");
            Attachment attachment      = new Attachment(new ByteArrayInputStream(attachBodyBytes),
                                                        "text/plain");
            string attachmentName = "test_attachment.txt";

            rev.AddAttachment(attachment, attachmentName);
            rev.Save();
            // do query that finds that doc with prefetch
            View view = database.GetView("aview");

            view.SetMapReduce((IDictionary <string, object> document, EmitDelegate emitter) =>
            {
                string id = (string)document["_id"];
                emitter.Emit(id, null);
            }, null, "1");
            // try to get the attachment
            Query query = view.CreateQuery();

            query.Prefetch = true;
            QueryEnumerator results = query.Run();

            while (results.MoveNext())
            {
                QueryRow row = results.Current;
                // This returns the revision just fine, but the sequence number
                // is set to 0.
                SavedRevision  revision    = row.Document.CurrentRevision;
                IList <string> attachments = revision.AttachmentNames;
                // This returns an Attachment object which looks ok, except again
                // its sequence number is 0. The metadata property knows about
                // the length and mime type of the attachment. It also says
                // "stub" -> "true".
                Attachment attachmentRetrieved = revision.GetAttachment(attachmentName);
                // This throws a CouchbaseLiteException with StatusCode.NOT_FOUND.
                InputStream @is = attachmentRetrieved.GetContent();
                NUnit.Framework.Assert.IsNotNull(@is);
                byte[] attachmentDataRetrieved       = TextUtils.Read(@is);
                string attachmentDataRetrievedString = Sharpen.Runtime.GetStringForBytes(attachmentDataRetrieved
                                                                                         );
                string attachBodyString = Sharpen.Runtime.GetStringForBytes(attachBodyBytes);
                NUnit.Framework.Assert.AreEqual(attachBodyString, attachmentDataRetrievedString);
            }
        }
Exemple #4
0
        private /*async*/ ObservableCollection <Dictionary <string, string> > LogQueryResultsAsync(Couchbase.Lite.View cbView)
        {
            var orderedQuery = cbView.CreateQuery();

            orderedQuery.Descending = true;
            var llista = new ObservableCollection <Dictionary <string, string> >();

            try {
                //var results = await orderedQuery.RunAsync ();
                var results = orderedQuery.Run();
                Console.WriteLine("Found rows: {0}",
                                  results.Count);
                results.ToList().ForEach(result => {
                    var doc = result.Document;
                    Dictionary <string, string> aux = new Dictionary <string, string> {
                        { "id", result.DocumentId },
                        { "nomCursa", doc.GetProperty <string>("nomCursa") },
                        { "dorsal", doc.GetProperty <string>("dorsal") },
                        { "posicio", doc.GetProperty <string>("posicio") },
                        { "distancia", doc.GetProperty <string>("distancia") },
                        { "posicioCategoria", doc.GetProperty <string>("posicioCategoria") },
                        { "categoria", doc.GetProperty <string>("categoria") },
                        { "club", doc.GetProperty <string>("club") },
                        { "iniciCursa", doc.GetProperty <string>("iniciCursa") },
                        { "tempsReal", doc.GetProperty <string>("tempsReal") },
                        { "tempsOficial", doc.GetProperty <string>("tempsOficial") },
                        { "iniciReal", doc.GetProperty <string>("iniciReal") },
                        { "horaMeta", doc.GetProperty <string>("horaMeta") },
                        { "ritme", doc.GetProperty <string>("ritme") },
                        { "km5", doc.GetProperty <string>("km5") },
                        { "horaKm5", doc.GetProperty <string>("horaKm5") },
                        { "km10", doc.GetProperty <string>("km10") },
                        { "horaKm10", doc.GetProperty <string>("horaKm10") },
                        { "tipus", doc.GetProperty <string>("tipus") },
                        { "esportista", doc.GetProperty <string>("esportista") }
                    };
                    Console.WriteLine("Found document with id: {0}",
                                      result.DocumentId);
                    var c = db.DocumentCount;
                    Console.WriteLine("num DESPUES DE QUERY: " + c);
                    llista.Add(aux);
                });
                cbView.DeleteIndex();
                Console.WriteLine("Num en la query: " + llista.Count);
            } catch (CouchbaseLiteException e) {
                Console.WriteLine("Error querying view", e.Message);
            }
            return(llista);
        }
Exemple #5
0
        public void TestPullerWithLiveQuery()
        {
            // Even though this test is passed, there is a runtime exception
            // thrown regarding the replication's number of changes count versus
            // number of completed changes count. Investigation is required.
            Log.D(Database.Tag, "testPullerWithLiveQuery");
            string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis());
            string doc1Id         = string.Format("doc1-{0}", docIdTimestamp);
            string doc2Id         = string.Format("doc2-{0}", docIdTimestamp);

            AddDocWithId(doc1Id, "attachment2.png");
            AddDocWithId(doc2Id, "attachment2.png");

            int  numDocsBeforePull = database.DocumentCount;
            View view = database.GetView("testPullerWithLiveQueryView");

            view.SetMapReduce((document, emitter) => {
                if (document.Get("_id") != null)
                {
                    emitter(document.Get("_id"), null);
                }
            }, null, "1");

            LiveQuery allDocsLiveQuery = view.CreateQuery().ToLiveQuery();

            allDocsLiveQuery.Changed += (sender, e) => {
                int numTimesCalled = 0;
                if (e.Error != null)
                {
                    throw new RuntimeException(e.Error);
                }
                if (numTimesCalled++ > 0)
                {
                    NUnit.Framework.Assert.IsTrue(e.Rows.Count > numDocsBeforePull);
                }
                Log.D(Database.Tag, "rows " + e.Rows);
            };

            // the first time this is called back, the rows will be empty.
            // but on subsequent times we should expect to get a non empty
            // row set.
            allDocsLiveQuery.Start();
            DoPullReplication();
            allDocsLiveQuery.Stop();
        }
        static ContactDatabase()
        {
            database = Manager.SharedInstance.GetDatabase ("contacts");
            emailLookup = new Dictionary<string, string> ();

            lookupView = database.GetView ("addresses");
            lookupView.SetMap ((document, emit) => {
                var val = document["contact.address.address"];
                emit(document["_id"], val);
            }, "1");

            Query lookupQuery = lookupView.CreateQuery ();

            BuildLookup(lookupQuery.Run ());

            lookupViewLiveQuery = lookupQuery.ToLiveQuery();
            lookupViewLiveQuery.Changed += (object sender, QueryChangeEventArgs e) => { BuildLookup(e.Rows); };
            lookupViewLiveQuery.Start ();
        }
        public void TestAsyncViewQuery()
        {
            var doneSignal = new CountDownLatch(1);
            var db         = StartDatabase();

            View view = db.GetView("vu");

            view.SetMap((document, emitter) => emitter(document ["sequence"], null), "1");

            const int kNDocs = 50;

            CreateDocuments(db, kNDocs);

            var query = view.CreateQuery();

            query.StartKey = 23;
            query.EndKey   = 33;

            var task = query.RunAsync().ContinueWith((resultTask) =>
            {
                Log.I(LiteTestCase.Tag, "Async query finished!");
                var rows = resultTask.Result;

                Assert.IsNotNull(rows);
                Assert.AreEqual(rows.Count, 11);

                var expectedKey = 23;
                for (IEnumerator <QueryRow> it = rows; it.MoveNext();)
                {
                    var row = it.Current;
                    Assert.AreEqual(row.Document.Database, db);
                    Assert.AreEqual(row.Key, expectedKey);
                    ++expectedKey;
                }
                doneSignal.CountDown();
            });

            Log.I(Tag, "Waiting for async query to finish...");

            var success = task.Wait(TimeSpan.FromSeconds(10));

            Assert.IsTrue(success, "Done signal timed out..StartKey=ry never ran");
        }
Exemple #8
0
        public void TestAsyncViewQuery()
        {
            var doneSignal = new CountdownEvent(1);
            var db         = database;

            View view = db.GetView("vu");

            view.SetMap((document, emitter) => emitter(document ["sequence"], null), "1");

            const int kNDocs = 50;

            CreateDocuments(db, kNDocs);

            var query = view.CreateQuery();

            query.StartKey = 23;
            query.EndKey   = 33;

            var task = query.RunAsync().ContinueWith((resultTask) =>
            {
                Log.I(TAG, "Async query finished!");
                var rows = resultTask.Result;

                Assert.IsNotNull(rows);
                Assert.AreEqual(11, rows.Count);

                var expectedKey = 23;
                foreach (var row in rows)
                {
                    Assert.AreEqual(row.Document.Database, db);
                    Assert.AreEqual(row.Key, expectedKey);
                    ++expectedKey;
                }

                doneSignal.Signal();
            }, manager.CapturedContext.Scheduler);

            Console.WriteLine("Waiting for async query to finish...");
            var success = task.Wait(TimeSpan.FromSeconds(130));

            Assert.IsTrue(success, "Done signal timed out. Query.RunAsync() has never run or returned the result.");
        }
        async void LogQueryResultsAsync(Couchbase.Lite.View cbView)
        {
            var orderedQuery = cbView.CreateQuery();

            orderedQuery.Descending = true;
            orderedQuery.Limit      = 20;
            try {
                var results = await orderedQuery.RunAsync();

                results.ToList().ForEach(result => {
                    var doc = result.Document;
                    Log.Info(TAG, String.Format("Found document with id: {0}, Date = {1}",
                                                result.DocumentId, doc.GetProperty <string>("date")));
                });
            } catch (CouchbaseLiteException e) {
                Log.Error(TAG, "Error querying view", e);
            }
            catch (Exception e) {
                Log.Error(TAG, e.Message, e);
            }
        }
Exemple #10
0
 /// <summary>
 /// Creates a query intended to return <see cref="EntityQueryRow{TEntity}"/> rows containing
 /// <see cref="EntityDocument{TEntity}"/> instances.
 /// </summary>
 /// <typeparam name="TEntity">The entity type.</typeparam>
 /// <param name="view">The <see cref="View"/>.</param>
 /// <returns>The created <see cref="EntityLiveQuery{TEntity}"/>.</returns>
 /// <remarks>
 /// <para>
 /// Entity queries are appropriate for situations where the application needs access to document
 /// properties that are not included in the view.  Loading the documents will incur a performance
 /// overhead.  You should use the base <see cref="View.CreateQuery()"/> method to see better performance
 /// for situations where the view covers the desired query results.
 /// </para>
 /// </remarks>
 public static EntityQuery <TEntity> CreateQuery <TEntity>(this View view)
     where TEntity : class, IDynamicEntity, new()
 {
     return(new EntityQuery <TEntity>(view.CreateQuery()));
 }