예제 #1
0
        public IDictionary <string, object> AsStubDictionary()
        {
            var retVal = new NonNullDictionary <string, object> {
                { "stub", true },
                { "digest", Digest },
                { "content_type", ContentType },
                { "revpos", RevPos },
                { "length", Length }
            };

            if (EncodedLength > 0)
            {
                retVal["encoded_length"] = EncodedLength;
            }

            switch (Encoding)
            {
            case AttachmentEncoding.GZIP:
                retVal["encoding"] = "gzip";
                break;

            case AttachmentEncoding.None:
                break;
            }

            return(retVal);
        }
예제 #2
0
        private IDictionary <string, object> GetAllDocsEntry(string docId)
        {
            var value       = default(IDictionary <string, object>);
            var existingDoc = default(C4Document *);

            try {
                existingDoc = (C4Document *)ForestDBBridge.Check(err => Native.c4doc_get(Forest, docId, true, err));
                if (existingDoc != null)
                {
                    value = new NonNullDictionary <string, object> {
                        { "rev", (string)existingDoc->revID },
                        { "deleted", true }
                    };
                }
            } catch (CBForestException e) {
                if (e.Domain != C4ErrorDomain.ForestDB || e.Code != (int)ForestDBStatus.KeyNotFound)
                {
                    throw;
                }
            } finally {
                Native.c4doc_free(existingDoc);
            }

            return(value);
        }
예제 #3
0
        public void NonNullDictionary_Unit_Add1_KeyIsNull()
        {
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>();
            String key = null;
            String value = "MyValue";

            target.Add(key, value);
        }
예제 #4
0
        public void NonNullDictionary_Unit_Add1_KeyExists()
        {
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>();
            String key = "MyKey";
            String value = "MyValue";

            target.Add(key, value);
            target.Add(key, value);
        }
예제 #5
0
        public void NonNullDictionary_Unit_Add1_Optimal()
        {
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>();
            String key = "MyKey";
            String value = "MyValue";

            target.Add(key, value);
            Assert.IsTrue(target[key] == value);
        }
        protected IDictionary <string, object> CreateAttachmentsDict(IEnumerable <byte> data, string name, string type, bool gzipped)
        {
            if (gzipped)
            {
                using (var ms = new MemoryStream())
                    using (var gs = new GZipStream(ms, CompressionMode.Compress)) {
                        gs.Write(data.ToArray(), 0, data.Count());
                        data = ms.ToArray();
                    }
            }

            var att = new NonNullDictionary <string, object> {
                { "content_type", type },
                { "data", data },
                { "encoding", gzipped ? "gzip" : null }
            };

            return(new Dictionary <string, object> {
                { name, att }
            });
        }
예제 #7
0
        public void NonNullDictionary_Unit_TryGetValue_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);
            String key = dictionary.Keys.First();
            String value;

            Boolean actual = target.TryGetValue(key, out value);
            Assert.AreEqual(true, actual);
            Assert.AreEqual(dictionary[key], value);
        }
예제 #8
0
        public void NonNullDictionary_Unit_CopyTo_ArrayIsTooSmall()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ICollection<KeyValuePair<String, String>> target = new NonNullDictionary<String, String>(dictionary);
            KeyValuePair<String, String>[] array = new KeyValuePair<String, String>[dictionary.Count - 2];
            Int32 arrayIndex = 1;

            target.CopyTo(array, arrayIndex);
        }
예제 #9
0
        /// <summary>Updates or deletes an attachment, creating a new document revision in the process.
        ///     </summary>
        /// <remarks>
        /// Updates or deletes an attachment, creating a new document revision in the process.
        /// Used by the PUT / DELETE methods called on attachment URLs.
        /// </remarks>
        /// <exclude></exclude>
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        internal RevisionInternal UpdateAttachment(string filename, BlobStoreWriter body, string contentType, AttachmentEncoding encoding, string docID, string oldRevID)
        {
            if(StringEx.IsNullOrWhiteSpace(filename) || (body != null && contentType == null) || 
                (oldRevID != null && docID == null) || (body != null && docID == null)) {
                throw new CouchbaseLiteException(StatusCode.BadAttachment);
            }

            var oldRev = new RevisionInternal(docID, oldRevID, false);
            if (oldRevID != null) {
                // Load existing revision if this is a replacement:
                try {
                    oldRev = LoadRevisionBody(oldRev);
                } catch (CouchbaseLiteException e) {
                    if (e.Code == StatusCode.NotFound && GetDocument(docID, null, false) != null) {
                        throw new CouchbaseLiteException(StatusCode.Conflict);
                    }

                    throw;
                }
            } else {
                // If this creates a new doc, it needs a body:
                oldRev.SetBody(new Body(new Dictionary<string, object>()));
            }

            // Update the _attachments dictionary:
            var attachments = oldRev.GetProperties().Get("_attachments").AsDictionary<string, object>();
            if (attachments == null) {
                attachments = new Dictionary<string, object>();
            }

            if (body != null) {
                var key = body.GetBlobKey();
                string digest = key.Base64Digest();
                RememberAttachmentWriter(body);
                string encodingName = (encoding == AttachmentEncoding.GZIP) ? "gzip" : null;
                attachments[filename] = new NonNullDictionary<string, object> {
                    { "digest", digest },
                    { "length", body.GetLength() },
                    { "follows", true },
                    { "content_type", contentType },
                    { "encoding", encodingName }
                };
            } else {
                if (oldRevID != null && attachments.Get(filename) == null) {
                    throw new CouchbaseLiteException(StatusCode.AttachmentNotFound);
                }

                attachments.Remove(filename);
            }

            var properties = oldRev.GetProperties();
            properties["_attachments"] = attachments;
            oldRev.SetProperties(properties);

            Status status = new Status();
            var newRev = PutRevision(oldRev, oldRevID, false, status);
            if (status.IsError) {
                throw new CouchbaseLiteException(status.Code);
            }

            return newRev;
        }
예제 #10
0
        public void NonNullDictionary_Unit_Indexer_KeyDoesNotExist()
        {
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>();
            String key = "MyKey";

            String actual = target[key];
        }
예제 #11
0
        protected IDictionary<string, object> CreateAttachmentsDict(IEnumerable<byte> data, string name, string type, bool gzipped)
        {
            if (gzipped) {
                using (var ms = new MemoryStream())
                using (var gs = new GZipStream(ms, CompressionMode.Compress)) {
                    gs.Write(data.ToArray(), 0, data.Count());
                    data = ms.ToArray();
                }
            }

            var att = new NonNullDictionary<string, object> {
                { "content_type", type },
                { "data", data },
                { "encoding", gzipped ? "gzip" : null }
            };

            return new Dictionary<string, object> {
                { name, att }
            };
        }
예제 #12
0
        public void NonNullDictionary_Unit_Remove1_KeyIsNull()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);
            String key = null;

            target.Remove(key);
        }
            private Status AddAttachmentsToSequence(long sequence, List<byte> json)
            {
                // CREATE TABLE attachments (
                //  sequence INTEGER NOT NULL REFERENCES revs(sequence) ON DELETE CASCADE,
                //  filename TEXT NOT NULL,
                //  key BLOB NOT NULL,
                //  type TEXT,
                //  length INTEGER NOT NULL,
                //  revpos INTEGER DEFAULT 0,
                //  encoding INTEGER DEFAULT 0,
                //  encoded_length INTEGER );
                sqlite3_stmt attQuery = null;
                Status status = PrepareSQL(ref attQuery, "SELECT filename, key, type, length,"
                                + " revpos, encoding, encoded_length FROM attachments WHERE sequence=?");
                if (status.IsError) {
                    return status;
                }

                raw.sqlite3_bind_int64(attQuery, 1, sequence);

                var attachments = new Dictionary<string, object>();

                int err;
                while (raw.SQLITE_ROW == (err = raw.sqlite3_step(attQuery))) {
                    string name = raw.sqlite3_column_text(attQuery, 0);
                    var key = raw.sqlite3_column_blob(attQuery, 1);
                    string mimeType = raw.sqlite3_column_text(attQuery, 2);
                    long length = raw.sqlite3_column_int64(attQuery, 3);
                    int revpos = raw.sqlite3_column_int(attQuery, 4);
                    int encoding = raw.sqlite3_column_int(attQuery, 5);
                    long encodedLength = raw.sqlite3_column_int64(attQuery, 6);

                    if (key.Length != SHA1.Create().HashSize / 8) {
                        raw.sqlite3_finalize(attQuery);
                        return new Status(StatusCode.CorruptError);
                    }

                    var blobKey = new BlobKey(key);
                    var att = new NonNullDictionary<string, object> {
                        { "type", mimeType },
                        { "digest", blobKey.Base64Digest() },
                        { "length", length },
                        { "revpos", revpos },
                        { "follows", true },
                        { "encoding", encoding != 0 ? "gzip" : null },
                        { "encoded_length", encoding != 0 ? (object)encodedLength : null }
                    };

                    attachments[name] = att;
                }

                raw.sqlite3_finalize(attQuery);
                if (err != raw.SQLITE_DONE) {
                    return SqliteErrToStatus(err);
                }

                if (attachments.Count > 0) {
                    // Splice attachment JSON into the document JSON:
                    var attJson = Manager.GetObjectMapper().WriteValueAsBytes(new Dictionary<string, object> { { "_attachments", attachments } });

                    if (json.Count > 2) {
                        json.Insert(json.Count - 1, (byte)',');
                    }

                    json.InsertRange(json.Count - 1, attJson.Skip(1).Take(attJson.Count() - 2));
                }

                return new Status(StatusCode.Ok);
            }
예제 #14
0
        public void NonNullDictionary_Unit_IsReadOnly_Optimal()
        {
            ICollection<KeyValuePair<String, String>> target = new NonNullDictionary<String, String>();

            Boolean actual = target.IsReadOnly;
            Assert.IsFalse(actual);
        }
예제 #15
0
        public void NonNullDictionary_Unit_Remove1_KeyDoesNotExist()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);
            String key = "MyKey";

            Boolean actual = target.Remove(key);
            Assert.AreEqual(false, actual);
        }
예제 #16
0
        public void NonNullDictionary_Unit_Indexer_ValueIsNull()
        {
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>();
            String key = "MyKey";
            String value = null;

            target[key] = value;
        }
예제 #17
0
        public void NonNullDictionary_Unit_Count_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);

            Int32 actual = target.Count;
            Assert.AreEqual(dictionary.Count, actual);
        }
예제 #18
0
        public void NonNullDictionary_Unit_Indexer_Optimal()
        {
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>();
            String key = "MyKey";
            String value = "MyValue";

            target[key] = value;
            String actual = target[key];
            Assert.AreEqual(value, actual);
        }
예제 #19
0
        public void NonNullDictionary_Unit_Values2_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            IDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);

            String[] actual = target.Values.ToArray();
            CollectionAssert.AreEquivalent(dictionary.Values.ToArray(), actual);
        }
예제 #20
0
        public void NonNullDictionary_Unit_Remove1_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);
            String key = dictionary.Keys.First();

            Boolean actual = target.Remove(key);
            Assert.AreEqual(true, actual);
            Assert.IsFalse(target.ContainsKey(key));
        }
        public IEnumerable<QueryRow> GetAllDocs(QueryOptions options)
        {
            var remainingIDs = default(List<string>);
            var enumerator = GetDocEnumerator(options, out remainingIDs);
            var current = 0;
            foreach(var next in enumerator) {
                if(current++ >= options.Limit) {
                    yield break;
                }

                var sequenceNumber = 0L;
                var docID = next.CurrentDocID;
                remainingIDs.Remove(docID);
                var value = default(IDictionary<string, object>);
                if(next.Exists) {
                    sequenceNumber = (long)next.SelectedRev.sequence;
                    var conflicts = default(IList<string>);
                    if(options.AllDocsMode >= AllDocsMode.ShowConflicts && next.IsConflicted) {
                        SelectCurrentRevision(next);
                        LoadRevisionBody(next);
                        using(var innerEnumerator = GetHistoryFromSequence(next.Sequence)) {
                            conflicts = innerEnumerator.Select(x => (string)x.SelectedRev.revID).ToList();
                        }

                        if(conflicts.Count == 1) {
                            conflicts = null;
                        }
                    }

                    bool valid = conflicts != null || options.AllDocsMode != AllDocsMode.OnlyConflicts;
                    if(!valid) {
                        continue;
                    }

                    value = new NonNullDictionary<string, object> {
                        { "rev", next.CurrentRevID },
                        { "deleted", next.IsDeleted ? (object)true : null },
                        { "_conflicts", conflicts }
                    };
                    Log.To.Query.V(TAG, "AllDocs: Found row with key=\"{0}\", value={1}",
                        new SecureLogString(docID, LogMessageSensitivity.PotentiallyInsecure),
                        new SecureLogJsonString(value, LogMessageSensitivity.PotentiallyInsecure));
                } else {
                    Log.To.Query.V(TAG, "AllDocs: No such row with key=\"{0}\"", new SecureLogString(docID, LogMessageSensitivity.PotentiallyInsecure));
                }

                var row = new QueryRow(value == null ? null : docID, sequenceNumber, docID, value,
                    value == null ? null : new ForestRevisionInternal(next, options.IncludeDocs), null);
                if(options.Filter == null || options.Filter(row)) {
                    yield return row;
                } else {
                    Log.To.Query.V(TAG, "   ... on 2nd thought, filter predicate skipped that row");
                }
            }

            foreach(var docId in remainingIDs) {
                var value = GetAllDocsEntry(docId);


                var row = new QueryRow(value != null ? docId as string : null, 0, docId, value, null, null);
                if(options.Filter == null || options.Filter(row)) {
                    yield return row;
                }
            }

        }
예제 #22
0
        public IEnumerable <QueryRow> GetAllDocs(QueryOptions options)
        {
            var remainingIDs = default(List <string>);
            var enumerator   = GetDocEnumerator(options, out remainingIDs);
            var current      = 0;

            foreach (var next in enumerator)
            {
                if (current++ >= options.Limit)
                {
                    yield break;
                }

                var sequenceNumber = 0L;
                var docID          = next.CurrentDocID;
                remainingIDs.Remove(docID);
                var value = default(IDictionary <string, object>);
                if (next.Exists)
                {
                    sequenceNumber = (long)next.SelectedRev.sequence;
                    var conflicts = default(IList <string>);
                    if (options.AllDocsMode >= AllDocsMode.ShowConflicts && next.IsConflicted)
                    {
                        SelectCurrentRevision(next);
                        LoadRevisionBody(next);
                        using (var innerEnumerator = new CBForestHistoryEnumerator(next, true, false)) {
                            conflicts = innerEnumerator.Select(x => (string)x.SelectedRev.revID).ToList();
                        }

                        if (conflicts.Count == 1)
                        {
                            conflicts = null;
                        }
                    }

                    bool valid = conflicts != null || options.AllDocsMode != AllDocsMode.OnlyConflicts;
                    if (!valid)
                    {
                        continue;
                    }

                    value = new NonNullDictionary <string, object> {
                        { "rev", next.CurrentRevID },
                        { "deleted", next.IsDeleted ? (object)true : null },
                        { "_conflicts", conflicts }
                    };
                }

                var row = new QueryRow(value == null ? null : docID, sequenceNumber, docID, value,
                                       value == null ? null : new RevisionInternal(next, options.IncludeDocs), null);
                if (options.Filter == null || options.Filter(row))
                {
                    yield return(row);
                }
            }

            foreach (var docId in remainingIDs)
            {
                var value = GetAllDocsEntry(docId);


                var row = new QueryRow(value != null ? docId as string : null, 0, docId, value, null, null);
                if (options.Filter == null || options.Filter(row))
                {
                    yield return(row);
                }
            }
        }
            private void AddAttachmentsToSequence(long sequence, List<byte> json)
            {
                // CREATE TABLE attachments (
                //  sequence INTEGER NOT NULL REFERENCES revs(sequence) ON DELETE CASCADE,
                //  filename TEXT NOT NULL,
                //  key BLOB NOT NULL,
                //  type TEXT,
                //  length INTEGER NOT NULL,
                //  revpos INTEGER DEFAULT 0,
                //  encoding INTEGER DEFAULT 0,
                //  encoded_length INTEGER );
                sqlite3_stmt attQuery = null;
                try {
                    PrepareSQL(ref attQuery, "SELECT filename, key, type, length,"
                                + " revpos, encoding, encoded_length FROM attachments WHERE sequence=?");
                } catch(CouchbaseLiteException) {
                    Log.W(TAG, "Failed to create SQLite query for attachments table in source database '{0}'", _path);
                    throw;
                } catch(Exception e) {
                    throw new CouchbaseLiteException(String.Format(
                        "Error creating SQLite query for attachments table in source database '{0}'", _path),
                        e) { Code = StatusCode.DbError };
                }

                raw.sqlite3_bind_int64(attQuery, 1, sequence);

                var attachments = new Dictionary<string, object>();

                int err;
                while (raw.SQLITE_ROW == (err = raw.sqlite3_step(attQuery))) {
                    string name = raw.sqlite3_column_text(attQuery, 0);
                    var key = raw.sqlite3_column_blob(attQuery, 1);
                    string mimeType = raw.sqlite3_column_text(attQuery, 2);
                    long length = raw.sqlite3_column_int64(attQuery, 3);
                    int revpos = raw.sqlite3_column_int(attQuery, 4);
                    int encoding = raw.sqlite3_column_int(attQuery, 5);
                    long encodedLength = raw.sqlite3_column_int64(attQuery, 6);

                    if (key.Length != SHA1.Create().HashSize / 8) {
                        raw.sqlite3_finalize(attQuery);
                        throw new CouchbaseLiteException(String.Format(
                            "Digest key length incorrect ({0})", Convert.ToBase64String(key)), StatusCode.CorruptError);
                    }

                    var blobKey = new BlobKey(key);
                    var att = new NonNullDictionary<string, object> {
                        { "type", mimeType },
                        { "digest", blobKey.Base64Digest() },
                        { "length", length },
                        { "revpos", revpos },
                        { "follows", true },
                        { "encoding", encoding != 0 ? "gzip" : null },
                        { "encoded_length", encoding != 0 ? (object)encodedLength : null }
                    };

                    attachments[name] = att;
                }

                raw.sqlite3_finalize(attQuery);
                if (err != raw.SQLITE_DONE) {
                    throw new CouchbaseLiteException(String.Format(
                        "Failed to finalize attachment query ({0}: {1})", err, raw.sqlite3_errmsg(_sqlite)),
                        SqliteErrToStatus(err).Code);
                }

                if (attachments.Count > 0) {
                    // Splice attachment JSON into the document JSON:
                    var attJson = Manager.GetObjectMapper().WriteValueAsBytes(new Dictionary<string, object> { { "_attachments", attachments } });

                    if (json.Count > 2) {
                        json.Insert(json.Count - 1, (byte)',');
                    }

                    json.InsertRange(json.Count - 1, attJson.Skip(1).Take(attJson.Count() - 2));
                }
            }
        public IEnumerable<QueryRow> GetAllDocs(QueryOptions options)
        {
            var remainingIDs = default(List<string>);
            var enumerator = GetDocEnumerator(options, out remainingIDs);
            var current = 0;
            foreach(var next in enumerator) {
                if (current++ >= options.Limit) {
                    yield break;
                }

                var sequenceNumber = 0L;
                var docID = next.CurrentDocID;
                remainingIDs.Remove(docID);
                var value = default(IDictionary<string, object>);
                if (next.Exists) {
                    sequenceNumber = (long)next.SelectedRev.sequence;
                    var conflicts = default(IList<string>);
                    if (options.AllDocsMode >= AllDocsMode.ShowConflicts && next.IsConflicted) {
                        SelectCurrentRevision(next);
                        using (var innerEnumerator = new CBForestHistoryEnumerator(next, true, false)) {
                            conflicts = innerEnumerator.Select(x => (string)x.SelectedRev.revID).ToList();
                        }

                        if (conflicts.Count == 1) {
                            conflicts = null;
                        }
                    }

                    bool valid = conflicts != null || options.AllDocsMode != AllDocsMode.OnlyConflicts;
                    if (!valid) {
                        continue;
                    }

                    value = new NonNullDictionary<string, object> {
                        { "rev", next.CurrentRevID },
                        { "deleted", next.IsDeleted ? (object)true : null },
                        { "_conflicts", conflicts }
                    };
                }

                var row = new QueryRow(value == null ? null : docID, sequenceNumber, docID, value, 
                    value == null ? null : new RevisionInternal(next, options.IncludeDocs), null);
                if (options.Filter == null || options.Filter(row)) {
                    yield return row;
                }
            }

            foreach (var docId in remainingIDs) {
                var value = GetAllDocsEntry(docId);
                
                    
                var row = new QueryRow(value != null ? docId as string : null, 0, docId, value, null, null);
                if (options.Filter == null || options.Filter(row)) {
                    yield return row;
                }
            }
                
        }
예제 #25
0
        public void NonNullDictionary_Unit_CopyTo_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ICollection<KeyValuePair<String, String>> target = new NonNullDictionary<String, String>(dictionary);
            KeyValuePair<String, String>[] array = new KeyValuePair<String, String>[dictionary.Count];
            Int32 arrayIndex = 0;

            target.CopyTo(array, arrayIndex);
            Assert.AreEqual(dictionary.Count, array.Length);
            foreach (KeyValuePair<String, String> pair in array) {
                Assert.IsTrue(dictionary.Contains(pair));
            }
        }
            private Status AddAttachmentsToSequence(long sequence, List <byte> json)
            {
                // CREATE TABLE attachments (
                //  sequence INTEGER NOT NULL REFERENCES revs(sequence) ON DELETE CASCADE,
                //  filename TEXT NOT NULL,
                //  key BLOB NOT NULL,
                //  type TEXT,
                //  length INTEGER NOT NULL,
                //  revpos INTEGER DEFAULT 0,
                //  encoding INTEGER DEFAULT 0,
                //  encoded_length INTEGER );
                sqlite3_stmt attQuery = null;
                Status       status   = PrepareSQL(ref attQuery, "SELECT filename, key, type, length,"
                                                   + " revpos, encoding, encoded_length FROM attachments WHERE sequence=?");

                if (status.IsError)
                {
                    return(status);
                }

                raw.sqlite3_bind_int64(attQuery, 1, sequence);

                var attachments = new Dictionary <string, object>();

                int err;

                while (raw.SQLITE_ROW == (err = raw.sqlite3_step(attQuery)))
                {
                    string name          = raw.sqlite3_column_text(attQuery, 0);
                    var    key           = raw.sqlite3_column_blob(attQuery, 1);
                    string mimeType      = raw.sqlite3_column_text(attQuery, 2);
                    long   length        = raw.sqlite3_column_int64(attQuery, 3);
                    int    revpos        = raw.sqlite3_column_int(attQuery, 4);
                    int    encoding      = raw.sqlite3_column_int(attQuery, 5);
                    long   encodedLength = raw.sqlite3_column_int64(attQuery, 6);

                    if (key.Length != SHA1.Create().HashSize / 8)
                    {
                        raw.sqlite3_finalize(attQuery);
                        return(new Status(StatusCode.CorruptError));
                    }

                    var blobKey = new BlobKey(key);
                    var att     = new NonNullDictionary <string, object> {
                        { "type", mimeType },
                        { "digest", blobKey.Base64Digest() },
                        { "length", length },
                        { "revpos", revpos },
                        { "follows", true },
                        { "encoding", encoding != 0 ? "gzip" : null },
                        { "encoded_length", encoding != 0 ? (object)encodedLength : null }
                    };

                    attachments[name] = att;
                }

                raw.sqlite3_finalize(attQuery);
                if (err != raw.SQLITE_DONE)
                {
                    return(SqliteErrToStatus(err));
                }

                if (attachments.Count > 0)
                {
                    // Splice attachment JSON into the document JSON:
                    var attJson = Manager.GetObjectMapper().WriteValueAsBytes(new Dictionary <string, object> {
                        { "_attachments", attachments }
                    });

                    if (json.Count > 2)
                    {
                        json.Insert(json.Count - 1, (byte)',');
                    }

                    json.InsertRange(json.Count - 1, attJson.Skip(1).Take(attJson.Count() - 2));
                }

                return(new Status(StatusCode.Ok));
            }
예제 #27
0
        public void NonNullDictionary_Unit_Remove2_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ICollection<KeyValuePair<String, String>> target = new NonNullDictionary<String, String>(dictionary);
            String key = dictionary.Keys.First();
            String value = dictionary[dictionary.Keys.First()];
            KeyValuePair<String, String> item = new KeyValuePair<String, String>(key, value);

            Boolean actual = target.Remove(item);
            Assert.AreEqual(true, actual);
            Assert.IsFalse(target.Contains(item));
        }
예제 #28
0
        public void NonNullDictionary_Unit_GetEnumerator3_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            IEnumerable target = new NonNullDictionary<String, String>(dictionary);

            IEnumerator actual = target.GetEnumerator();
            Int32 count = 0;
            while (actual.MoveNext()) {
                count++;
                Assert.IsTrue(dictionary.Contains((KeyValuePair<String, String>)actual.Current));
            }
            Assert.AreEqual(dictionary.Count, count);
        }
        private IDictionary<string, object> GetAllDocsEntry(string docId)
        {
            var value = default(IDictionary<string, object>);
            var existingDoc = default(C4Document*);
            try {
                existingDoc = (C4Document*)ForestDBBridge.Check(err => Native.c4doc_get(Forest, docId, true, err));
                if(existingDoc != null) {
                    value = new NonNullDictionary<string, object> {
                            { "rev", (string)existingDoc->revID },
                            { "deleted", true }
                        };
                }
            } catch(CBForestException e) {
                if(e.Domain != C4ErrorDomain.ForestDB || e.Code != (int)ForestDBStatus.KeyNotFound) {
                    throw;
                }
            } finally {
                Native.c4doc_free(existingDoc);
            }

            return value;
        }
예제 #30
0
        public void NonNullDictionary_Unit_Remove2_ValueDoesNotExist()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ICollection<KeyValuePair<String, String>> target = new NonNullDictionary<String, String>(dictionary);
            String key = dictionary.Keys.First();
            String value = "MyValue";
            KeyValuePair<String, String> item = new KeyValuePair<String, String>(key, value);

            Boolean actual = target.Remove(item);
            Assert.AreEqual(false, actual);
        }
        public IDictionary<string, object> AsStubDictionary()
        {
            var retVal = new NonNullDictionary<string, object> {
                { "stub", true },
                { "digest", Digest },
                { "content_type", ContentType },
                { "revpos", RevPos },
                { "length", Length }
            };

            if (EncodedLength > 0) {
                retVal["encoded_length"] = EncodedLength;
            }

            switch (Encoding) {
                case AttachmentEncoding.GZIP:
                    retVal["encoding"] = "gzip";
                    break;
                case AttachmentEncoding.None:
                    break;
            }

            return retVal;
        }
예제 #32
0
        public void NonNullDictionary_Unit_TryGetValue_KeyDoesNotExist()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);
            String key = "MyKey";
            String value;

            Boolean actual = target.TryGetValue(key, out value);
            Assert.AreEqual(false, actual);
            Assert.IsNull(value);
        }
예제 #33
0
            private void AddAttachmentsToSequence(long sequence, List <byte> json)
            {
                // CREATE TABLE attachments (
                //  sequence INTEGER NOT NULL REFERENCES revs(sequence) ON DELETE CASCADE,
                //  filename TEXT NOT NULL,
                //  key BLOB NOT NULL,
                //  type TEXT,
                //  length INTEGER NOT NULL,
                //  revpos INTEGER DEFAULT 0,
                //  encoding INTEGER DEFAULT 0,
                //  encoded_length INTEGER );
                sqlite3_stmt attQuery = null;

                try {
                    PrepareSQL(ref attQuery, "SELECT filename, key, type, length,"
                               + " revpos, encoding, encoded_length FROM attachments WHERE sequence=?");
                } catch (CouchbaseLiteException) {
                    Log.To.Upgrade.E(TAG, "Failed to create SQLite query for attachments table in " +
                                     "source database '{0}', rethrowing...", _path);
                    throw;
                } catch (Exception e) {
                    throw Misc.CreateExceptionAndLog(Log.To.Upgrade, e, TAG,
                                                     "Error creating SQLite query for attachments table in source database '{0}'", _path);
                }

                raw.sqlite3_bind_int64(attQuery, 1, sequence);

                var attachments = new Dictionary <string, object>();

                int err;

                while (raw.SQLITE_ROW == (err = raw.sqlite3_step(attQuery)))
                {
                    string name          = raw.sqlite3_column_text(attQuery, 0);
                    var    key           = raw.sqlite3_column_blob(attQuery, 1);
                    string mimeType      = raw.sqlite3_column_text(attQuery, 2);
                    long   length        = raw.sqlite3_column_int64(attQuery, 3);
                    int    revpos        = raw.sqlite3_column_int(attQuery, 4);
                    int    encoding      = raw.sqlite3_column_int(attQuery, 5);
                    long   encodedLength = raw.sqlite3_column_int64(attQuery, 6);

                    if (key.Length != SHA1.Create().HashSize / 8)
                    {
                        raw.sqlite3_finalize(attQuery);
                        throw Misc.CreateExceptionAndLog(Log.To.Upgrade, StatusCode.CorruptError, TAG,
                                                         "Digest key length incorrect ({0})", Convert.ToBase64String(key));
                    }

                    var blobKey = new BlobKey(key);
                    var att     = new NonNullDictionary <string, object> {
                        { "type", mimeType },
                        { "digest", blobKey.Base64Digest() },
                        { "length", length },
                        { "revpos", revpos },
                        { "follows", true },
                        { "encoding", encoding != 0 ? "gzip" : null },
                        { "encoded_length", encoding != 0 ? (object)encodedLength : null }
                    };

                    attachments[name] = att;
                }

                raw.sqlite3_finalize(attQuery);
                if (err != raw.SQLITE_DONE)
                {
                    throw Misc.CreateExceptionAndLog(Log.To.Upgrade, SqliteErrToStatus(err).Code, TAG,
                                                     "Failed to finalize attachment query ({0}: {1})", err, raw.sqlite3_errmsg(_sqlite));
                }

                if (attachments.Count > 0)
                {
                    // Splice attachment JSON into the document JSON:
                    var attJson = Manager.GetObjectMapper().WriteValueAsBytes(new Dictionary <string, object> {
                        { "_attachments", attachments }
                    });

                    if (json.Count > 2)
                    {
                        json.Insert(json.Count - 1, (byte)',');
                    }

                    json.InsertRange(json.Count - 1, attJson.Skip(1).Take(attJson.Count() - 2));
                }
            }
예제 #34
0
        public void NonNullDictionary_Unit_TryGetValue_KeyIsNull()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            NonNullDictionary<String, String> target = new NonNullDictionary<String, String>(dictionary);
            String key = null;
            String value;

            target.TryGetValue(key, out value);
        }
예제 #35
0
        internal IEnumerable<QueryRow> GetAllDocs(QueryOptions options)
        {
            // For regular all-docs, let storage do it all:
            if (options == null || options.AllDocsMode != AllDocsMode.BySequence) {
                return Storage.GetAllDocs(options);
            }

            if (options.Descending) {
                throw new CouchbaseLiteException("Descending all docs not implemented", StatusCode.NotImplemented);
            }

            ChangesOptions changesOpts = new ChangesOptions();
            changesOpts.SetLimit(options.Limit);
            changesOpts.SetIncludeDocs(options.IncludeDocs);
            changesOpts.SetIncludeConflicts(true);
            changesOpts.SetSortBySequence(true);

            long startSeq = KeyToSequence(options.StartKey, 1);
            long endSeq = KeyToSequence(options.EndKey, long.MaxValue);
            if (!options.InclusiveStart) {
                ++startSeq;
            }

            if (!options.InclusiveEnd) {
                --endSeq;
            }

            long minSeq = startSeq, maxSeq = endSeq;
            if (minSeq > maxSeq) {
                return null; // empty result
            }

            RevisionList revs = Storage.ChangesSince(minSeq - 1, changesOpts, null);
            if (revs == null) {
                return null;
            }

            var result = new List<QueryRow>();
            var revEnum = options.Descending ? revs.Reverse<RevisionInternal>() : revs;
            foreach (var rev in revEnum) {
                long seq = rev.GetSequence();
                if (seq < minSeq || seq > maxSeq) {
                    break;
                }

                var value = new NonNullDictionary<string, object> {
                    { "rev", rev.GetRevId() },
                    { "deleted", rev.IsDeleted() ? (object)true : null }
                };
                result.Add(new QueryRow(rev.GetDocId(), seq, rev.GetDocId(), value, rev, null));
            }

            return result;
        }
예제 #36
0
        public void NonNullDictionary_Unit_Contains_ValueIsNull()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ICollection<KeyValuePair<String, String>> target = new NonNullDictionary<String, String>(dictionary);
            KeyValuePair<String, String> item = new KeyValuePair<String, String>(dictionary.Keys.First(), null);

            Boolean actual = target.Contains(item);
            Assert.AreEqual(false, actual);
        }