示例#1
0
        public void InsertingArray()
        {
            var docs = new[]
            {
                new { id = 1, title = "Book 1" },
                new { id = 2, title = "Book 2" },
            };
            DbDoc d2 = new DbDoc();

            d2.SetValue("_id", 1);
            d2.SetValue("books", docs);
            d2.SetValue("pages", 20);

            Collection coll = CreateCollection("test");

            coll.Add(d2).Execute();
            var result = coll.Find().Execute().FetchAll();

            Assert.Equal(1, result.Count);
            Assert.Equal(d2.ToString(), result[0].ToString());
        }
示例#2
0
        public void RemoveOne()
        {
            Collection collection = CreateCollection("test");
            var        docs       = new[]
            {
                new { _id = 1, title = "Book 1", pages = 20 },
                new { _id = 2, title = "Book 2", pages = 30 },
                new { _id = 3, title = "Book 3", pages = 40 },
                new { _id = 4, title = "Book 4", pages = 50 },
            };
            Result result = collection.Add(docs).Execute();

            Assert.Equal <ulong>(4, result.RecordsAffected);

            collection.Add(new { title = "Book 5", pages = 60 }).Execute();
            Assert.Equal(5, collection.Find().Execute().FetchAll().Count);

            // Expected exceptions.
            Assert.Throws <ArgumentNullException>(() => collection.RemoveOne(null));
            Assert.Throws <ArgumentNullException>(() => collection.RemoveOne(""));
            Assert.Throws <ArgumentNullException>(() => collection.RemoveOne(string.Empty));

            // Remove sending numeric parameter.
            Assert.Equal <ulong>(1, collection.RemoveOne(1).RecordsAffected);
            Assert.Equal(4, collection.Find().Execute().FetchAll().Count);

            // Remove sending string parameter.
            Assert.Equal <ulong>(1, collection.RemoveOne("3").RecordsAffected);
            Assert.Equal(3, collection.Find().Execute().FetchAll().Count);

            // Remove an auto-generated id.
            DbDoc document = collection.Find("pages = 60").Execute().FetchOne();

            Assert.Equal <ulong>(1, collection.RemoveOne(document.Id).RecordsAffected);
            Assert.Equal(2, collection.Find().Execute().FetchAll().Count);

            // Remove a non-existing document.
            Assert.Equal <ulong>(0, collection.RemoveOne(5).RecordsAffected);
            Assert.Equal(2, collection.Find().Execute().FetchAll().Count);
        }
示例#3
0
        public void ParseWithArray()
        {
            string json = @"{
  ""id"": 1, 
  ""pages"": 20, 
  ""books"": [
    {
      ""_id"": 1, 
      ""title"": ""Book 1""
    }, 
    {
      ""_id"": 2, 
      ""title"": ""Book 2""
    }
  ]
}";

            string[] lines = json.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < lines.Length; i++)
            {
                lines[i] = lines[i].Trim();
            }

            string noFormat = string.Join(" ", lines);

            DbDoc d = new DbDoc(noFormat);

            var docs = new[]
            {
                new { _id = 1, title = "Book 1" },
                new { _id = 2, title = "Book 2" },
            };
            DbDoc d2 = new DbDoc();

            d2.SetValue("id", 1);
            d2.SetValue("pages", 20);
            d2.SetValue("books", docs);
            Assert.Equal(d.ToString(), d2.ToString());
            Assert.Equal(json.Replace("\r\n", Environment.NewLine), d2.ToString());
        }
示例#4
0
        public void ReplaceOne()
        {
            Collection collection = CreateCollection("test");
            var        docs       = new[]
            {
                new { _id = 1, title = "Book 1", pages = 20 },
                new { _id = 2, title = "Book 2", pages = 30 },
                new { _id = 3, title = "Book 3", pages = 40 },
                new { _id = 4, title = "Book 4", pages = 50 },
            };
            Result result = ExecuteAddStatement(collection.Add(docs));

            Assert.AreEqual(4, result.AffectedItemsCount);

            // Expected exceptions.
            Assert.Throws <ArgumentNullException>(() => collection.ReplaceOne(null, docs[1]));
            Assert.Throws <ArgumentNullException>(() => collection.ReplaceOne("", docs[1]));
            Assert.Throws <ArgumentNullException>(() => collection.ReplaceOne(string.Empty, docs[1]));
            Assert.Throws <ArgumentNullException>(() => collection.ReplaceOne("1", null));

            // Replace using a numeric identifier.
            Assert.AreEqual(1, collection.ReplaceOne(1, docs[1]).AffectedItemsCount);
            DbDoc document = collection.GetOne(1);

            Assert.AreEqual(1, Convert.ToInt32(document.Id));
            Assert.AreEqual("Book 2", document["title"]);
            Assert.AreEqual(30, Convert.ToInt32(document["pages"]));

            // Replace using a string identifier.
            Assert.AreEqual(1, collection.ReplaceOne("2", new DbDoc("{ \"name\": \"John\", \"lastName\": \"Smith\" }")).AffectedItemsCount);
            document = collection.GetOne(2);
            Assert.AreEqual(2, Convert.ToInt32(document.Id));
            Assert.AreEqual("John", document["name"]);
            Assert.AreEqual("Smith", document["lastName"]);

            // Replace a non-existing document.
            Assert.AreEqual(0, collection.ReplaceOne(5, docs[1]).AffectedItemsCount);
            Assert.True(collection.GetOne(5) == null);
        }
示例#5
0
        public void AddNestedNullFields()
        {
            if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3))
            {
                return;
            }

            Collection collection = CreateCollection("test");
            Result     r          = ExecuteAddStatement(collection.Add(documentsAsJsonStrings));

            Assert.AreEqual(1, r.AffectedItemsCount);

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"additionalinfo\": { \"nullfield\": NULL } }"));
            Assert.False(((Dictionary <string, object>)ExecuteFindStatement(collection.Find()).FetchOne().values["additionalinfo"]).ContainsKey("nullfield"));

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"additionalinfo\": { \"nullfield\": [NULL, NULL] } }"));
            DbDoc document        = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            var   nestedNullArray = (object[])((Dictionary <string, object>)document.values["additionalinfo"])["nullfield"];

            Assert.Null(nestedNullArray[0]);
            Assert.Null(nestedNullArray[1]);

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"additionalinfo\": { \"nullfield\": { \"nested\": NULL } } }"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.False(((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["nullfield"]).ContainsKey("nullfield"));

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"additionalinfo\": { \"nullfield\": { \"nested\": [NULL, NULL] } } }"));
            document        = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            nestedNullArray = (object[])((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["nullfield"])["nested"];
            Assert.Null(nestedNullArray[0]);
            Assert.Null(nestedNullArray[1]);

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"additionalinfo\": { \"nullfield\": { \"nested\": JSON_OBJECT('field', null) } } }"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            var nestedObject = (Dictionary <string, object>)((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["nullfield"])["nested"];

            CollectionAssert.IsEmpty(nestedObject);
        }
示例#6
0
        public void AddRemoveFieldInDifferentNestingLevels()
        {
            if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3))
            {
                return;
            }

            Collection collection = CreateCollection("test");
            Result     r          = ExecuteAddStatement(collection.Add(documentsAsDbDocs));

            Assert.AreEqual(1, r.AffectedItemsCount);

            DbDoc document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");

            Assert.False(document.values.ContainsKey("translations"));
            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"translations\": [\"Spanish\"] }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.True(document.values.ContainsKey("translations"));
            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"translations\": null }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.False(document.values.ContainsKey("translations"));

            Assert.False(((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["director"]).ContainsKey("country"));
            ExecuteModifyStatement(collection.Modify("additionalinfo.director.name = :director").Patch("{ \"additionalinfo\": { \"director\": { \"country\": \"France\" } } }").Bind("director", "Sharice Legaspi"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.True(((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["director"]).ContainsKey("country"));
            ExecuteModifyStatement(collection.Modify("additionalinfo.director.name = :director").Patch("{ \"additionalinfo\": { \"director\": { \"country\": null } } }").Bind("director", "Sharice Legaspi"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.False(((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["director"]).ContainsKey("country"));

            Assert.False(((Dictionary <string, object>)document.values["additionalinfo"]).ContainsKey("musicby"));
            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"additionalinfo\": { \"musicby\": \"The Sakila\" } }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.True(((Dictionary <string, object>)document.values["additionalinfo"]).ContainsKey("musicby"));
            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"additionalinfo\": { \"musicby\": null } }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.False(((Dictionary <string, object>)document.values["additionalinfo"]).ContainsKey("musicby"));
        }
示例#7
0
        public void ArrayAppend()
        {
            Collection collection = CreateCollection("test");

            ExecuteAddStatement(collection.Add("{ \"x\":[1,2] }"));

            // Append values of different types, null and spaces.
            ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", 43));
            ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", "string"));
            ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", true));
            ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", null));
            ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", " "));
            DocResult result   = ExecuteFindStatement(collection.Find());
            DbDoc     document = result.FetchOne();
            var       x        = (object[])document.values["x"];

            Assert.AreEqual(7, x.Length);
            Assert.AreEqual(1, (int)x[0]);
            Assert.AreEqual(2, (int)x[1]);
            Assert.AreEqual(43, (int)x[2]);
            Assert.AreEqual("string", x[3]);
            Assert.AreEqual(true, x[4]);
            Assert.Null(x[5]);
            Assert.AreEqual(" ", x[6]);

            // No value is appended if the array doesn't exist.
            ExecuteModifyStatement(collection.Modify("true").ArrayAppend("y", 45));

            result   = ExecuteFindStatement(collection.Find());
            document = result.FetchOne();
            Assert.False(document.values.ContainsKey("y"));

            var ex = Assert.Throws <ArgumentException>(() => ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", "")));

            StringAssert.Contains("String can't be empty.", ex.Message);
            ex = Assert.Throws <ArgumentException>(() => ExecuteModifyStatement(collection.Modify("true").ArrayAppend("x", string.Empty)));
            StringAssert.Contains("String can't be empty.", ex.Message);
        }
示例#8
0
        public void AddNewFieldUsingExpressions()
        {
            if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3))
            {
                return;
            }

            Collection collection = CreateCollection("test");
            Result     r          = ExecuteAddStatement(collection.Add(documentsAsDbDocs));

            Assert.AreEqual(1, r.AffectedItemsCount);

            DbDoc document = ExecuteFindStatement(collection.Find()).FetchOne();

            Assert.False(((Dictionary <string, object>)((object[])document.values["actors"])[0]).ContainsKey("age"));
            Assert.Throws <Exception>(() => ExecuteModifyStatement(collection.Modify("true").Patch("{ \"actors\": { \"age\": Year(CURDATE()) - CAST(SUBSTRING_INDEX(actors.birthdate, ' ', - 1) AS DECIMAL)) } }")));

            document = ExecuteFindStatement(collection.Find()).FetchOne();
            Assert.False(document.values.ContainsKey("audio"));
            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"audio\": CONCAT($.language, ', no subtitles') }"));
            document = ExecuteFindStatement(collection.Find()).FetchOne();
            Assert.AreEqual("English, no subtitles", document.values["audio"]);
        }
        public void ParseBooleanValue()
        {
            Collection collection = CreateCollection("test");

            DbDoc  document = new DbDoc(@"{ ""_id"": 1, ""isDocument"": true }");
            Result result   = ExecuteAddStatement(collection.Add(document));

            Assert.Equal <ulong>(1, result.AffectedItemsCount);

            document = collection.GetOne(1);
            Assert.True(document.values.ContainsKey("isDocument"));
            Assert.True((bool)document.values["isDocument"]);

            document = new DbDoc(new { _id = 2, isDocument = false });
            result   = ExecuteAddStatement(collection.Add(document));
            Assert.Equal <ulong>(1, result.AffectedItemsCount);

            document = collection.GetOne(2);
            Assert.True(document.values.ContainsKey("isDocument"));
            Assert.False((bool)document.values["isDocument"]);

            Assert.True(ExecuteFindStatement(collection.Find("isDocument = false")).FetchAll().Count > 0);
        }
示例#10
0
        public void ParseBooleanValue()
        {
            // TODO: Boolean values are currently stored as strings.
            // Fix is required in JsonParser.ReadValue().
            Collection collection = CreateCollection("test");

            DbDoc  document = new DbDoc(@"{ ""isDocument"": true }");
            Result result   = collection.Add(document).Execute();

            Assert.Equal <ulong>(1, result.RecordsAffected);

            document = collection.Find().Execute().FetchOne();
            Assert.True(document.values.ContainsKey("isDocument"));
            Assert.True((bool)document.values["isDocument"]);

            document = new DbDoc(new { isDocument = true });
            result   = collection.Add(document).Execute();
            Assert.Equal <ulong>(1, result.RecordsAffected);

            document = collection.Find().Execute().FetchOne();
            Assert.True(document.values.ContainsKey("isDocument"));
            Assert.True((bool)document.values["isDocument"]);
        }
示例#11
0
        public void ReplaceUpdateInDifferentNestingLevels()
        {
            if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3))
            {
                return;
            }

            Collection collection = CreateCollection("test");
            Result     r          = ExecuteAddStatement(collection.Add(documentsAsDbDocs));

            Assert.AreEqual(1, r.AffectedItemsCount);

            DbDoc document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");

            Assert.AreEqual("AFRICAN EGG", document["title"]);
            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"title\": \"The African Egg\" }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.AreEqual("The African Egg", document["title"]);

            Assert.AreEqual(57, ((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["director"])["age"]);
            ExecuteModifyStatement(collection.Modify("additionalinfo.director.name = :director").Patch("{ \"additionalinfo\": { \"director\": { \"age\": 67 } } }").Bind("director", "Sharice Legaspi"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.AreEqual(67, ((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["director"])["age"]);

            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"additionalinfo\": { \"director\": { \"age\": 77 } } }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.AreEqual(77, ((Dictionary <string, object>)((Dictionary <string, object>)document.values["additionalinfo"])["director"])["age"]);

            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"title\": { \"movie\": \"The African Egg\"} }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.AreEqual("The African Egg", ((Dictionary <string, object>)document.values["title"])["movie"]);

            ExecuteModifyStatement(collection.Modify("_id = :id").Patch("{ \"additionalinfo\": \"No data available\" }").Bind("id", "a6f4b93e1a264a108393524f29546a8c"));
            document = collection.GetOne("a6f4b93e1a264a108393524f29546a8c");
            Assert.AreEqual("No data available", document.values["additionalinfo"]);
        }
示例#12
0
        public void GetOne()
        {
            Collection coll = CreateCollection("test");
            var        docs = new[]
            {
                new { _id = 1, title = "Book 1", pages = 20 },
                new { _id = 2, title = "Book 2", pages = 30 },
                new { _id = 3, title = "Book 3", pages = 40 },
                new { _id = 4, title = "Book 4", pages = 50 },
            };
            Result r = coll.Add(docs).Execute();

            Assert.Equal <ulong>(4, r.RecordsAffected);

            // Expected exceptions.
            Assert.Throws <ArgumentNullException>(() => coll.GetOne(null));
            Assert.Throws <ArgumentNullException>(() => coll.GetOne(""));
            Assert.Throws <ArgumentNullException>(() => coll.GetOne(string.Empty));

            // Get document using numeric parameter.
            DbDoc document = coll.GetOne(1);

            Assert.Equal(1, document.Id);
            Assert.Equal("Book 1", document["title"]);
            Assert.Equal(20, Convert.ToInt32(document["pages"]));

            // Get document using string parameter.
            document = coll.GetOne("3");
            Assert.Equal(3, document.Id);
            Assert.Equal("Book 3", document["title"]);
            Assert.Equal(40, Convert.ToInt32(document["pages"]));

            // Get a non-existing document.
            document = coll.GetOne(5);
            Assert.Equal(null, document);
        }
示例#13
0
        public void AddNullFields()
        {
            if (!session.InternalSession.GetServerVersion().isAtLeast(8, 0, 3))
            {
                return;
            }

            Collection collection = CreateCollection("test");
            Result     r          = ExecuteAddStatement(collection.Add(documentsAsJsonStrings));

            Assert.AreEqual(1, r.AffectedItemsCount);

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"nullfield\": NULL }"));
            Assert.False(ExecuteFindStatement(collection.Find()).FetchOne().values.ContainsKey("nullfield"));

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"nullfield\": [NULL, NULL] }"));
            DbDoc document = ExecuteFindStatement(collection.Find()).FetchOne();

            Assert.True(document.values.ContainsKey("nullfield"));
            var nullArray = (object[])document.values["nullfield"];

            Assert.Null(nullArray[0]);
            Assert.Null(nullArray[1]);

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"nullfield\": { \"nested\": NULL } }"));
            document = ExecuteFindStatement(collection.Find()).FetchOne();
            Assert.True(ExecuteFindStatement(collection.Find()).FetchOne().values.ContainsKey("nullfield"));
            Assert.True(((Dictionary <string, object>)document.values["nullfield"]).Count == 0);

            ExecuteModifyStatement(collection.Modify("true").Patch("{ \"nullfield\": { \"nested\": [NULL, NULL] } }"));
            document = ExecuteFindStatement(collection.Find()).FetchOne();
            var nestedNullArray = (object[])((Dictionary <string, object>)document.values["nullfield"])["nested"];

            Assert.Null(nestedNullArray[0]);
            Assert.Null(nestedNullArray[1]);
        }
示例#14
0
        public void InsertNullValuesAsJson()
        {
            var docs = new[]
            {
                @"{ ""_id"": 1, ""foo"": null}",
                @"{ ""_id"": 2, ""foo"": null }",
                @"{ ""_id"": 3, ""foo"": ""null"" }",
                @"{ ""_id"": 4, ""foo"": ""NULL"" }",
            };

            Collection collection = CreateCollection("test");

            ExecuteAddStatement(collection.Add(docs));
            var result = ExecuteFindStatement(collection.Find()).FetchAll();

            Assert.AreEqual(docs.Length, result.Count);
            for (int i = 0; i < docs.Length; i++)
            {
                var currentDoc   = new DbDoc(docs[i]);
                var resultingDoc = new DbDoc(result[i]);
                Assert.AreEqual(currentDoc.Id, resultingDoc.Id);
                Assert.AreEqual(currentDoc["foo"], resultingDoc["foo"]);
            }
        }
示例#15
0
        public void InsertNullValuesAsDbDoc()
        {
            Collection collection = CreateCollection("test");

            var nullValues = new String[] { null, "null", "NULL" };
            var docs       = new DbDoc[3];

            for (int i = 0; i < docs.Length; i++)
            {
                docs[i] = new DbDoc();
                docs[i].SetValue("a", nullValues[i]);
                docs[i].SetValue("_id", (i + 1));
            }

            ExecuteAddStatement(collection.Add(docs));
            var result = ExecuteFindStatement(collection.Find()).FetchAll();

            Assert.AreEqual(docs.Length, result.Count);

            for (int i = 0; i < docs.Length; i++)
            {
                Assert.AreEqual(docs[i].ToString(), result[i].ToString());
            }
        }
        public void DbDocToString()
        {
            var document = new DbDoc("{ \"_id\": 1, \"title\": \"Book 1\", \"pagess\":10, \"author\":\"Ana\" }");

            document.ToString();
        }
 public void DbDocCreateWithAnonymousObject()
 {
     var document = new DbDoc(new { _id = 2, title = "Book 2", pages = 20, author = "John" });
 }
 public void DbDocCreateWithJSONString()
 {
     var document = new DbDoc("{ \"_id\": 1, \"title\": \"Book 1\", \"pagess\":10, \"author\":\"Ana\" }");
 }
 public void DbDocCreateEmpty()
 {
     var document = new DbDoc();
 }
示例#20
0
 public static DateTime GetApproxLastChangeDate(this DbDoc dbDoc) => DateTimeOffset.FromUnixTimeSeconds(dbDoc._ts).UtcDateTime;
示例#21
0
        /// <summary>
        /// Saves the session configuration.
        /// </summary>
        /// <param name="name">The session configuration name.</param>
        /// <param name="data">The session configuration data as a dictionary.</param>
        /// <returns>A <see cref="SessionConfig"/> object set with the saved configuration data.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
        /// <exception cref="ArgumentException">Both 'uri' and 'host' were found in <paramref name="data"/> dictionary.</exception>
        /// <exception cref="ArgumentNullException">'host' wasn't found in the <paramref name="data"/> dictionary.</exception>
        public static SessionConfig Save(string name, Dictionary <string, string> data)
        {
            ValidateName(name);
            if (data == null)
            {
                throw new ArgumentNullException("Data");
            }

            DbDoc json = new DbDoc();
            Dictionary <string, object> appdata = new Dictionary <string, object>();
            bool hasUri = false, hasHost = false;

            foreach (string key in data.Keys)
            {
                switch (key)
                {
                case "uri":
                    if (hasHost)
                    {
                        throw new ArgumentException(ResourcesX.JsonUriOrHost);
                    }
                    if (string.IsNullOrEmpty(data["uri"]))
                    {
                        throw new ArgumentNullException("uri");
                    }
                    json.SetValue("uri", data["uri"]);
                    hasUri = true;
                    break;

                case "host":
                case "user":
                case "password":
                case "port":
                case "schema":
                    if (hasUri)
                    {
                        throw new ArgumentException(ResourcesX.JsonUriOrHost);
                    }
                    hasHost = true;
                    break;

                default:
                    appdata.Add(key, data[key]);
                    break;
                }
            }
            if (hasHost)
            {
                if (!data.ContainsKey("host") || string.IsNullOrEmpty(data["host"]))
                {
                    throw new ArgumentNullException(ResourcesX.NoHost);
                }
                StringBuilder sb = new StringBuilder("mysqlx://");
                if (data.ContainsKey("user") && !string.IsNullOrWhiteSpace(data["user"]))
                {
                    sb.Append(data["user"]).Append("@");
                }
                sb.Append(data["host"]);
                if (data.ContainsKey("port") && !string.IsNullOrWhiteSpace(data["port"]))
                {
                    sb.Append(":").Append(data["port"]);
                }
                if (data.ContainsKey("schema") && !string.IsNullOrWhiteSpace(data["schema"]))
                {
                    sb.Append("/").Append(data["schema"]);
                }

                json.SetValue("uri", sb.ToString());
            }
            if (appdata.Count > 0)
            {
                json.SetValue("appdata", appdata);
            }

            return(Save(name, json));
        }
        internal CreateCollectionIndexStatement(Collection collection, string indexName, DbDoc indexDefinition) : base(collection)
        {
            // Fields allowed at the root level.
            var allowedFields = new string[] { "fields", "type" };

            // Fields allowed for embedded documents.
            var allowedInternalFields = new string[] { "field", "type", "required", "options", "srid", "array" };

            // Validate the index follows the allowed format.
            if (!indexDefinition.values.ContainsKey(allowedFields[0]))
            {
                throw new FormatException(string.Format(ResourcesX.MandatoryFieldNotFound, allowedFields[0]));
            }

            // Validate that fields on the root level are allowed.
            foreach (var field in indexDefinition.values)
            {
                if (!allowedFields.Contains(field.Key))
                {
                    throw new FormatException(string.Format(ResourcesX.UnexpectedField, field.Key));
                }
            }

            // Validate embedded documents.
            foreach (var item in indexDefinition.values[allowedFields[0]] as Object[])
            {
                var field = item as Dictionary <string, object>;

                // Validate embedded documents have the field field.
                if (!field.ContainsKey(allowedInternalFields[0]))
                {
                    throw new FormatException(string.Format(ResourcesX.MandatoryFieldNotFound, allowedInternalFields[0]));
                }

                // Validate embedded documents have the type field.
                if (!field.ContainsKey(allowedInternalFields[1]))
                {
                    throw new FormatException(string.Format(ResourcesX.MandatoryFieldNotFound, allowedInternalFields[1]));
                }

                foreach (var internalField in field)
                {
                    if (!allowedInternalFields.Contains(internalField.Key))
                    {
                        throw new FormatException(string.Format(ResourcesX.UnexpectedField, internalField.Key));
                    }
                }
            }

            createIndexParams = new CreateIndexParams(indexName, indexDefinition);
        }
示例#23
0
 public void RemovingDocWithNoIdThrowsException()
 {
     Collection coll = CreateCollection("test");
     DbDoc      doc  = new DbDoc();
     Exception  ex   = Assert.Throws <KeyNotFoundException>(() => ExecuteRemoveStatement(coll.Remove("_id = :id").Bind("id", doc.Id)));
 }
示例#24
0
 /// <summary>
 /// Binds the parameter values in filter expression.
 /// </summary>
 /// <param name="dbDocParams">The parameters as a DbDoc object.</param>
 /// <returns>A generic object representing the implementing statement type.</returns>
 public T Bind(DbDoc dbDocParams)
 {
     return(Bind(dbDocParams.ToString()));
 }
示例#25
0
 public void RemovingDocWithNoIdThrowsException()
 {
     Collection coll = CreateCollection("test");
     DbDoc      doc  = new DbDoc();
     Exception  ex   = Assert.Throws <InvalidOperationException>(() => coll.Remove(doc));
 }
 public override Task?GetHandlerTask(DbDoc change, CancellationToken cancellationToken = default) => throw new NotImplementedException();
示例#27
0
 public abstract Task?GetHandlerTask(DbDoc change, CancellationToken cancellationToken = default);