Ejemplo n.º 1
0
        /// <summary>
        /// Drop a table from the database schema
        /// </summary>
        /// <param name="table">Name of table to drop</param>
        public async Task DropAsync(string table)
        {
            var totalTimer = ScopeTiming.StartTiming();

            try
            {
                NameValues.ClearCaches();

                int tableId = await Tables.GetIdAsync(Ctxt, table, noCreate : true, noException : true).ConfigureAwait(false);

                if (tableId < 0)
                {
                    return;
                }

                await Ctxt.Db.ExecuteSqlAsync($"DELETE FROM itemnamevalues WHERE nameid IN (SELECT id FROM names WHERE tableid = {tableId})").ConfigureAwait(false);

                await Ctxt.Db.ExecuteSqlAsync($"DELETE FROM names WHERE tableid = {tableId}").ConfigureAwait(false);

                await Ctxt.Db.ExecuteSqlAsync($"DELETE FROM items WHERE tableid = {tableId}").ConfigureAwait(false);

                await Ctxt.Db.ExecuteSqlAsync($"DELETE FROM tables WHERE id = {tableId}").ConfigureAwait(false);

                NameValues.ClearCaches();
            }
            finally
            {
                ScopeTiming.RecordScope("Cmd.Drop", totalTimer);
            }
        }
Ejemplo n.º 2
0
        public void TestNames()
        {
            using (var ctxt = TestUtils.GetCtxt())
            {
                int tableId = Tables.GetIdAsync(ctxt, "sometable").Result;

                int firstId  = Names.GetIdAsync(ctxt, tableId, "foobar").Result;
                int secondId = Names.GetIdAsync(ctxt, tableId, "foobar").Result;
                Assert.AreEqual(firstId, secondId);

                NameObj name = Names.GetNameAsync(ctxt, secondId).Result;
                Assert.AreEqual("foobar", name.name);
                Assert.IsTrue(!name.isNumeric);
                Assert.AreEqual("foobar", Names.GetNameAsync(ctxt, secondId).Result.name);
                Assert.AreEqual(name.isNumeric, Names.GetNameIsNumericAsync(ctxt, firstId).Result);

                int thirdId  = Names.GetIdAsync(ctxt, tableId, "bletmonkey", isNumeric: true).Result;
                int fourthId = Names.GetIdAsync(ctxt, tableId, "bletmonkey").Result;
                Assert.AreEqual(thirdId, fourthId);
                Assert.AreNotEqual(firstId, thirdId);

                NameObj name2 = Names.GetNameAsync(ctxt, fourthId).Result;
                Assert.AreEqual("bletmonkey", name2.name);
                Assert.IsTrue(name2.isNumeric);
                Assert.AreEqual("bletmonkey", Names.GetNameAsync(ctxt, fourthId).Result.name);
                Assert.AreEqual(name2.isNumeric, Names.GetNameIsNumericAsync(ctxt, fourthId).Result);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Process a delete request.
        /// </summary>
        /// <param name="toDelete">Delete reqeuest</param>
        public async Task DeleteAsync(Delete toDelete)
        {
            var totalTimer = ScopeTiming.StartTiming();

            try
            {
                int tableId = await Tables.GetIdAsync(Ctxt, toDelete.table, noCreate : true, noException : true).ConfigureAwait(false);

                if (tableId < 0)
                {
                    return;
                }

                foreach (var val in toDelete.values)
                {
                    long valueId = await Values.GetIdAsync(Ctxt, val).ConfigureAwait(false);

                    string sql = $"DELETE FROM items WHERE valueid = {valueId} AND tableid = {tableId}";
                    Ctxt.AddPostOp(sql);
                }

                await Ctxt.ProcessPostOpsAsync().ConfigureAwait(false);
            }
            finally
            {
                ScopeTiming.RecordScope("Cmd.Delete", totalTimer);
            }
        }
Ejemplo n.º 4
0
        public void TestEnsureItem()
        {
            using (var ctxt = TestUtils.GetCtxt())
            {
                int  tableId = Tables.GetIdAsync(ctxt, "foo").Result;
                long valueId = Values.GetIdAsync(ctxt, "bar").Result;

                long id0 = Items.GetIdAsync(ctxt, tableId, valueId).Result;
                long id1 = Items.GetIdAsync(ctxt, tableId, valueId).Result;

                Assert.AreEqual(id0, id1);
            }
        }
Ejemplo n.º 5
0
        public void TestItemNameValues()
        {
            using (var ctxt = TestUtils.GetCtxt())
            {
                int  tableId       = Tables.GetIdAsync(ctxt, "ape").Result;
                int  bletNameId    = Names.GetIdAsync(ctxt, tableId, "blet").Result;
                long monkeyValueId = Values.GetIdAsync(ctxt, "monkey").Result;

                long itemId0 = Items.GetIdAsync(ctxt, tableId, monkeyValueId).Result;
                long itemId1 = Items.GetIdAsync(ctxt, tableId, monkeyValueId).Result;
                Assert.AreEqual(itemId0, itemId1);

                Items.DeleteAsync(ctxt, itemId1).ConfigureAwait(false);
                long itemId2 = Items.GetIdAsync(ctxt, tableId, monkeyValueId).Result;
                Assert.AreNotEqual(itemId0, itemId2);

                var  metaDict     = new Dictionary <int, long>();
                int  fredNameId   = Names.GetIdAsync(ctxt, tableId, "fred").Result;
                long earnyValueId = Values.GetIdAsync(ctxt, "earny").Result;
                metaDict[fredNameId] = earnyValueId;
                Items.SetItemData(ctxt, itemId2, metaDict);
                ctxt.ProcessPostOpsAsync().Wait();

                var outMetaDict = Items.GetItemDataAsync(ctxt, itemId2).Result;
                Assert.AreEqual(1, outMetaDict.Count);
                Assert.IsTrue(outMetaDict.ContainsKey(fredNameId));
                Assert.AreEqual(earnyValueId, outMetaDict[fredNameId]);

                Define define = new Define("apelike", "foo");
                define.Set("blet", "monkey").Set("something", "else");
                ctxt.Cmd.DefineAsync(define).Wait();

                GetRequest get = new GetRequest()
                {
                    table = "apelike"
                };
                get.values = new List <object> {
                    "foo"
                };
                var gotten = ctxt.Cmd.GetAsync(get).Result;

                Assert.AreEqual(1, gotten.metadata.Count);

                var result = gotten.metadata[0];
                Assert.AreEqual("monkey", result["blet"]);
                Assert.AreEqual("else", result["something"]);
            }
        }
Ejemplo n.º 6
0
        public void TestTables()
        {
            using (var ctxt = TestUtils.GetCtxt())
            {
                for (int t = 1; t <= 3; ++t)
                {
                    int firstId  = Tables.GetIdAsync(ctxt, "foobar", isNumeric: true).Result;
                    int secondId = Tables.GetIdAsync(ctxt, "foobar").Result;
                    Assert.AreEqual(firstId, secondId);

                    int thirdId  = Tables.GetIdAsync(ctxt, "bletmonkey", isNumeric: true).Result;
                    int fourthId = Tables.GetIdAsync(ctxt, "bletmonkey").Result;
                    Assert.AreEqual(thirdId, fourthId);
                    Assert.AreNotEqual(firstId, thirdId);

                    using (var reader = ctxt.Db.ExecuteReaderAsync("SELECT * FROM tables").Result)
                    {
                        while (reader.Read())
                        {
                            object id   = reader["id"];
                            object name = reader["name"];
                            Console.WriteLine("tables {0} - {1}", id, name);
                        }
                    }

                    TableObj table = Tables.GetTableAsync(ctxt, secondId).Result;
                    Assert.AreEqual("foobar", table.name);
                    Assert.IsTrue(table.isNumeric);

                    TableObj tables2 = Tables.GetTableAsync(ctxt, secondId).Result;
                    Assert.AreEqual("foobar", tables2.name);
                    Assert.IsTrue(tables2.isNumeric);

                    TableObj tables3 = Tables.GetTableAsync(ctxt, thirdId).Result;
                    Assert.AreEqual("bletmonkey", tables3.name);
                    Assert.IsTrue(tables3.isNumeric);

                    TableObj tables4 = Tables.GetTableAsync(ctxt, fourthId).Result;
                    Assert.AreEqual("bletmonkey", tables4.name);
                    Assert.IsTrue(tables4.isNumeric);
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Get the metadata for a set of items
        /// </summary>
        /// <param name="request">List of values to get metadata for</param>
        /// <returns>Metadata for the items</returns>
        public async Task <GetResponse> GetAsync(GetRequest request)
        {
            var totalTimer = ScopeTiming.StartTiming();

            try
            {
                var responses = new List <Dictionary <string, object> >(request.values.Count);

                int tableId = await Tables.GetIdAsync(Ctxt, request.table, noCreate : true).ConfigureAwait(false);

                foreach (var value in request.values)
                {
                    long valueId = await Values.GetIdAsync(Ctxt, value).ConfigureAwait(false);

                    long itemId = await Items.GetIdAsync(Ctxt, tableId, valueId, noCreate : true).ConfigureAwait(false);

                    if (itemId < 0)
                    {
                        responses.Add(null);
                        continue;
                    }

                    var metaIds = await Items.GetItemDataAsync(Ctxt, itemId).ConfigureAwait(false);

                    var metaStrings = await NameValues.GetMetadataValuesAsync(Ctxt, metaIds).ConfigureAwait(false);

                    responses.Add(metaStrings);
                }

                GetResponse response = new GetResponse()
                {
                    metadata = responses
                };
                return(response);
            }
            finally
            {
                ScopeTiming.RecordScope("Cmd.Get", totalTimer);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// This is where the magic metastrings SQL => MySQL SQL conversion takes place
        /// </summary>
        /// <param name="ctxt">Database connection</param>
        /// <param name="query">metastrings query</param>
        /// <returns>MySQL SQL</returns>
        public static async Task <string> GenerateSqlAsync(Context ctxt, Select query)
        {
            //
            // "COMPILE"
            //
            if (string.IsNullOrWhiteSpace(query.from))
            {
                throw new MetaStringsException("Invalid query, FROM is missing");
            }

            if (query.select == null || query.select.Count == 0)
            {
                throw new MetaStringsException("Invalid query, SELECT is empty");
            }

            if (query.orderBy != null)
            {
                foreach (var order in query.orderBy)
                {
                    string orderField = order.field.Trim();
                    if (!query.select.Contains(orderField))
                    {
                        throw
                            new MetaStringsException
                            (
                                "Invalid query, ORDER BY columns must be present in SELECT column list: " +
                                $"{order.field.Trim()}"
                            );
                    }
                }
            }

            if (query.where != null)
            {
                foreach (var criteriaSet in query.where)
                {
                    foreach (var criteria in criteriaSet.criteria)
                    {
                        Utils.ValidateColumnName(criteria.name, "WHERE");
                        Utils.ValidateOperator(criteria.op, "WHERE");
                        Utils.ValidateParameterName(criteria.paramName, "WHERE");
                    }
                }
            }


            //
            // SETUP
            //
            int tableId = await Tables.GetIdAsync(ctxt, query.from, noCreate : true, noException : true).ConfigureAwait(false);

            TableObj tableObj = await Tables.GetTableAsync(ctxt, tableId).ConfigureAwait(false);

            // Gather columns
            var names = new List <string>();

            names.AddRange(query.select);

            if (query.orderBy != null)
            {
                names.AddRange(query.orderBy.Select(o => o.field));
            }

            if (query.where != null)
            {
                foreach (var criteriaSet in query.where)
                {
                    names.AddRange(criteriaSet.criteria.Select(w => w.name));
                }
            }

            // Cut them down
            names = names.Select(n => n.Trim()).Where(n => !string.IsNullOrEmpty(n)).Distinct().ToList();

            // Get name objects
            var nameObjs = new Dictionary <string, NameObj>(names.Count);

            foreach (var name in names)
            {
                if (Utils.IsNameReserved(name))
                {
                    nameObjs.Add(name, null);
                }
                else
                {
                    NameObj nameObj;
                    {
                        int nameId = await Names.GetIdAsync(ctxt, tableId, name, noCreate : true, noException : true).ConfigureAwait(false);

                        if (nameId < 0)
                        {
                            nameObj = null;
                        }
                        else
                        {
                            nameObj = await Names.GetNameAsync(ctxt, nameId);
                        }
                    }
                    nameObjs.Add(name, nameObj);
                }
            }


            //
            // SELECT
            //
            string selectPart = "";

            foreach (var name in query.select.Select(n => n.Trim()).Where(n => !string.IsNullOrWhiteSpace(n)))
            {
                var cleanName = Utils.CleanName(name);

                if (selectPart.Length > 0)
                {
                    selectPart += ",\r\n";
                }

                if (name == "value")
                {
                    if (tableObj == null)
                    {
                        selectPart += "NULL";
                    }
                    else if (tableObj.isNumeric)
                    {
                        selectPart += "bv.numberValue";
                    }
                    else
                    {
                        selectPart += "bv.stringValue";
                    }
                }
                else if (name == "id")
                {
                    selectPart += "i.id";
                }
                else if (name == "created")
                {
                    selectPart += "i.created";
                }
                else if (name == "lastmodified")
                {
                    selectPart += "i.lastmodified";
                }
                else if (name == "count")
                {
                    selectPart += "COUNT(*)";
                }
                else if (nameObjs[name] == null)
                {
                    selectPart += "NULL";
                }
                else if (nameObjs[name].isNumeric)
                {
                    selectPart += $"iv{cleanName}.numberValue";
                }
                else
                {
                    selectPart += $"iv{cleanName}.stringValue";
                }
                selectPart += $" AS {cleanName}";
            }
            selectPart = "SELECT\r\n" + selectPart;


            //
            // FROM
            //
            string fromPart = "FROM\r\nitems AS i";

            if (nameObjs.ContainsKey("value"))
            {
                fromPart += "\r\nJOIN bvalues bv ON bv.id = i.valueid";
            }

            foreach (var name in names.Select(n => n.Trim()).Where(n => !string.IsNullOrWhiteSpace(n)))
            {
                if (!Utils.IsNameReserved(name) && nameObjs.ContainsKey(name) && nameObjs[name] != null)
                {
                    var cleanName = Utils.CleanName(name);
                    fromPart +=
                        $"\r\nLEFT OUTER JOIN itemvalues AS iv{cleanName} ON iv{cleanName}.itemid = i.id" +
                        $" AND iv{cleanName}.nameid = {nameObjs[name].id}";
                }
            }


            //
            // WHERE
            //
            string wherePart = $"i.tableid = {tableId}";

            if (query.where != null)
            {
                foreach (var criteriaSet in query.where)
                {
                    if (criteriaSet.criteria.Count == 0)
                    {
                        continue;
                    }

                    wherePart += "\r\nAND\r\n";

                    wherePart += "(";
                    bool addedOneYet = false;
                    foreach (var where in criteriaSet.criteria)
                    {
                        string name = where.name.Trim();
                        if (string.IsNullOrWhiteSpace(name))
                        {
                            continue;
                        }

                        if (!addedOneYet)
                        {
                            addedOneYet = true;
                        }
                        else
                        {
                            wherePart += $" {Enum.GetName(criteriaSet.combine.GetType(), criteriaSet.combine)} ";
                        }

                        var nameObj   = nameObjs[name];
                        var cleanName = Utils.CleanName(name);

                        if (where.op.Equals("matches", StringComparison.OrdinalIgnoreCase))
                        {
                            if (nameObj == null)
                            {
                                wherePart += "1 = 0"; // name doesn't exist, no match!
                            }
                            else
                            {
                                wherePart += cleanName == "value" ? "i.valueid" : $"iv{cleanName}.valueid";
                                wherePart += $" IN (SELECT bvt.valueid FROM bvaluetext AS bvt WHERE bvt.stringSearchValue MATCH {where.paramName})";
                            }
                        }
                        else if (cleanName == "id")
                        {
                            wherePart += $"i.id {where.op} {where.paramName}";
                        }
                        else if (cleanName == "value")
                        {
                            if (tableObj == null)
                            {
                                wherePart += "1 = 0"; // no table, no match
                            }
                            else if (tableObj.isNumeric)
                            {
                                wherePart += $"bv.numberValue {where.op} {where.paramName}";
                            }
                            else
                            {
                                wherePart += $"bv.stringValue {where.op} {where.paramName}";
                            }
                        }
                        else if (cleanName == "created" || cleanName == "lastmodified")
                        {
                            wherePart += $"{cleanName} {where.op} {where.paramName}";
                        }
                        else if (nameObj == null)
                        {
                            wherePart += "1 = 0"; // name doesn't exist, no match!
                        }
                        else if (nameObj.isNumeric)
                        {
                            wherePart += $"iv{cleanName}.numberValue {where.op} {where.paramName}";
                        }
                        else
                        {
                            wherePart += $"iv{cleanName}.stringValue {where.op} {where.paramName}";
                        }
                    }
                    wherePart += ")";
                }
            }
            wherePart = "WHERE " + wherePart;


            //
            // ORDER BY
            //
            string orderBy = "";

            if (query.orderBy != null)
            {
                foreach (var order in query.orderBy)
                {
                    if (string.IsNullOrWhiteSpace(order.field))
                    {
                        continue;
                    }

                    if (orderBy.Length > 0)
                    {
                        orderBy += ",\r\n";
                    }

                    string orderColumn = order.field;
                    if (!Utils.IsNameReserved(order.field))
                    {
                        Utils.CleanName(order.field);
                    }

                    orderBy += orderColumn + (order.descending ? " DESC" : " ASC");
                }

                if (orderBy.Length > 0)
                {
                    orderBy = "ORDER BY\r\n" + orderBy;
                }
            }


            //
            // LIMIT
            //
            string limitPart = "";

            if (query.limit > 0)
            {
                limitPart = $"LIMIT\r\n{query.limit}";
            }


            //
            // SQL
            //
            StringBuilder sb = new StringBuilder();

            sb.Append($"{selectPart.Trim()}");

            sb.Append($"\r\n\r\n{fromPart}");

            if (!string.IsNullOrWhiteSpace(wherePart))
            {
                sb.Append($"\r\n\r\n{wherePart}");
            }

            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                sb.Append($"\r\n\r\n{orderBy}");
            }

            if (!string.IsNullOrWhiteSpace(limitPart))
            {
                sb.Append($"\r\n\r\n{limitPart}");
            }

            string sql = sb.ToString();

            return(sql);
        }
Ejemplo n.º 9
0
        public void TestDefine()
        {
            using (var ctxt = TestUtils.GetCtxt())
            {
                {
                    var define = new Define("fun", "some");
                    define.Set("num", 42).Set("str", "foobar").Set("multi", "blet\nmonkey");
                    ctxt.Cmd.DefineAsync(define).Wait();
                }

                {
                    var define = new Define("fun", "another");
                    define.Set("num", 69).Set("str", "boofar").Set("multi", "ape\nagony");
                    ctxt.Cmd.DefineAsync(define).Wait();
                }

                {
                    var define = new Define("fun", "yetsome");
                    define.Set("num", 19).Set("str", "playful").Set("multi", "balloni\nbeats");
                    ctxt.Cmd.DefineAsync(define).Wait();
                }

                long itemId   = Items.GetIdAsync(ctxt, Tables.GetIdAsync(ctxt, "fun").Result, Values.GetIdAsync(ctxt, "some").Result).Result;
                var  itemData = NameValues.GetMetadataValuesAsync(ctxt, Items.GetItemDataAsync(ctxt, itemId).Result).Result;

                Assert.AreEqual(42.0, itemData["num"]);
                Assert.AreEqual("foobar", itemData["str"]);
                Assert.AreEqual("blet\nmonkey", itemData["multi"]);

                {
                    Select select =
                        Sql.Parse
                        (
                            "SELECT value, multi\n" +
                            $"FROM fun\n" +
                            "WHERE multi MATCHES @search"
                        );
                    select.AddParam("@search", "monkey");
                    using (var reader = ctxt.ExecSelectAsync(select).Result)
                    {
                        if (!reader.ReadAsync().Result)
                        {
                            Assert.Fail();
                        }

                        var val = reader.GetString(0);
                        var str = reader.GetString(1);

                        Assert.AreEqual("some", val);
                        Assert.AreEqual("blet\nmonkey", str);

                        if (reader.ReadAsync().Result)
                        {
                            Assert.Fail();
                        }
                    }
                }

                {
                    Define define = new Define("fun", "some");
                    define.Set("num", 43.0);
                    define.Set("str", null); // remove the metadata

                    ctxt.Cmd.DefineAsync(define).Wait();
                }

                itemData = NameValues.GetMetadataValuesAsync(ctxt, Items.GetItemDataAsync(ctxt, itemId).Result).Result;
                Assert.IsTrue(!itemData.ContainsKey("str"));
                Assert.AreEqual(43.0, itemData["num"]);
                Assert.IsTrue(!itemData.ContainsKey("str"));

                ctxt.Cmd.DeleteAsync("fun", new[] { "some", "another", "yetsome" }).Wait();

                {
                    Select select = new Select()
                    {
                        from   = "fun",
                        select = new List <string> {
                            "value"
                        }
                    };
                    using (var reader = ctxt.ExecSelectAsync(select).Result)
                    {
                        if (reader.ReadAsync().Result) // should be gone
                        {
                            Assert.Fail();
                        }
                    }
                }

                {
                    Define numsFirst = new Define("numsFirst", 1);
                    numsFirst.Set("foo", 12);
                    numsFirst.Set("blet", "79");
                    ctxt.Cmd.DefineAsync(numsFirst).Wait();

                    Define numsNext = new Define("numsFirst", 2);
                    numsNext.Set("foo", 15).Set("blet", "63");
                    ctxt.Cmd.DefineAsync(numsNext).Wait();

                    Select select = Sql.Parse("SELECT value, foo, blet\nFROM numsFirst");
                    using (var reader = ctxt.ExecSelectAsync(select).Result)
                    {
                        while (reader.Read())
                        {
                            if (reader.GetInt64(0) == 1)
                            {
                                Assert.AreEqual(12, reader.GetDouble(1));
                                Assert.AreEqual("79", reader.GetString(2));
                            }
                            else if (reader.GetInt64(0) == 2)
                            {
                                Assert.AreEqual(15, reader.GetDouble(1));
                                Assert.AreEqual("63", reader.GetString(2));
                            }
                            else
                            {
                                Assert.Fail();
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Explicitly create a table in the schema.
 /// This is usually unnecessary as tables are created as referred to by Define.
 /// </summary>
 /// <param name="name">Table name to create request</param>
 public async Task CreateTableAsync(string name, bool isNumeric)
 {
     await Tables.GetIdAsync(Ctxt, name, isNumeric).ConfigureAwait(false);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// This is the main UPSERT method to populate the database.
        /// </summary>
        /// <param name="define">Info about metadata to apply to the key</param>
        public async Task DefineAsync(Define define)
        {
            var totalTimer = ScopeTiming.StartTiming();

            try
            {
                var localTimer = ScopeTiming.StartTiming();

                bool isKeyNumeric = !(define.key is string);
                int  tableId      = await Tables.GetIdAsync(Ctxt, define.table, isKeyNumeric).ConfigureAwait(false);

                long valueId = await Values.GetIdAsync(Ctxt, define.key).ConfigureAwait(false);

                long itemId = await Items.GetIdAsync(Ctxt, tableId, valueId).ConfigureAwait(false);

                ScopeTiming.RecordScope("Define.Setup", localTimer);

                if (define.metadata != null)
                {
                    // name => nameid
                    var nameValueIds = new Dictionary <int, long>();
                    foreach (var kvp in define.metadata)
                    {
                        bool isMetadataNumeric = !(kvp.Value is string);
                        int  nameId            = await Names.GetIdAsync(Ctxt, tableId, kvp.Key, isMetadataNumeric).ConfigureAwait(false);

                        if (kvp.Value == null) // erase value
                        {
                            nameValueIds[nameId] = -1;
                            continue;
                        }
                        bool isNameNumeric = await Names.GetNameIsNumericAsync(Ctxt, nameId).ConfigureAwait(false);

                        bool isValueNumeric = !(kvp.Value is string);
                        if (isValueNumeric != isNameNumeric)
                        {
                            throw
                                new MetaStringsException
                                (
                                    $"Data numeric does not match name: {kvp.Key}" +
                                    $"\n - value is numeric: {isValueNumeric} - {kvp.Value}" +
                                    $"\n - name is numeric: {isNameNumeric}"
                                );
                        }
                        nameValueIds[nameId] =
                            await Values.GetIdAsync(Ctxt, kvp.Value).ConfigureAwait(false);
                    }
                    ScopeTiming.RecordScope("Define.NameIds", localTimer);

                    Items.SetItemData(Ctxt, itemId, nameValueIds);
                    ScopeTiming.RecordScope("Define.ItemsCommit", localTimer);
                }

                await Ctxt.ProcessPostOpsAsync().ConfigureAwait(false);

                ScopeTiming.RecordScope("Define.PostOps", localTimer);
            }
#if !DEBUG
            catch
            {
                Ctxt.ClearPostOps();
                throw;
            }
#endif
            finally
            {
                ScopeTiming.RecordScope("Define", totalTimer);
            }
        }
Ejemplo n.º 12
0
        public void TestItemData()
        {
            using (var ctxt = TestUtils.GetCtxt())
            {
                int  tableId = Tables.GetIdAsync(ctxt, "blet").Result;
                long itemId  = Items.GetIdAsync(ctxt, tableId, Values.GetIdAsync(ctxt, "monkey").Result).Result;

                {
                    var itemData = new Dictionary <int, long>();
                    itemData[Names.GetIdAsync(ctxt, tableId, "foo").Result]       = Values.GetIdAsync(ctxt, "bar").Result;
                    itemData[Names.GetIdAsync(ctxt, tableId, "something").Result] = Values.GetIdAsync(ctxt, "else").Result;
                    Items.SetItemData(ctxt, itemId, itemData);
                    ctxt.ProcessPostOpsAsync().Wait();

                    var metadata = Items.GetItemDataAsync(ctxt, itemId).Result;
                    Console.WriteLine($"metadata1 Dict contents ({metadata.Count}):");
                    Console.WriteLine(string.Join("\n", metadata.Select(kvp => $"{kvp.Key}: {kvp.Value}")));

                    foreach (var kvp in metadata)
                    {
                        string nameVal  = Names.GetNameAsync(ctxt, kvp.Key).Result.name;
                        string valueVal = Values.GetValueAsync(ctxt, kvp.Value).Result.ToString();
                        if (nameVal == "foo")
                        {
                            Assert.AreEqual("bar", valueVal);
                        }
                        else if (nameVal == "something")
                        {
                            Assert.AreEqual("else", valueVal);
                        }
                        else
                        {
                            Assert.Fail("Name not recognized: " + nameVal);
                        }
                    }
                }

                {
                    var itemData = new Dictionary <int, long>();
                    itemData[Names.GetIdAsync(ctxt, tableId, "foo").Result]       = Values.GetIdAsync(ctxt, "blet").Result;
                    itemData[Names.GetIdAsync(ctxt, tableId, "something").Result] = Values.GetIdAsync(ctxt, "monkey").Result;
                    Items.SetItemData(ctxt, itemId, itemData);
                    ctxt.ProcessPostOpsAsync().Wait();

                    var metadata = Items.GetItemDataAsync(ctxt, itemId).Result;
                    Console.WriteLine($"metadata2 Dict contents ({metadata.Count}):");
                    Console.WriteLine(string.Join("\n", metadata.Select(kvp => $"{kvp.Key}: {kvp.Value}")));

                    foreach (var kvp in metadata)
                    {
                        string nameVal  = Names.GetNameAsync(ctxt, kvp.Key).Result.name;
                        string valueVal = Values.GetValueAsync(ctxt, kvp.Value).Result.ToString();
                        if (nameVal == "foo")
                        {
                            Assert.AreEqual("blet", valueVal);
                        }
                        else if (nameVal == "something")
                        {
                            Assert.AreEqual("monkey", valueVal);
                        }
                        else
                        {
                            Assert.Fail("Name not recognized: " + nameVal);
                        }
                    }
                }
            }
        }