示例#1
0
        private void DumpSubFolder(ISqlDumper dmp, string subfolder)
        {
            string dir = GetPrivateSubFolder(subfolder);

            if (!Directory.Exists(dir))
            {
                return;
            }
            string[] files = Directory.GetFiles(dir);
            Array.Sort(files);
            foreach (string f in files)
            {
                if (!f.ToLower().EndsWith(".sql"))
                {
                    continue;
                }
                using (StreamReader sr = new StreamReader(f))
                {
                    foreach (string sql in QueryTools.GoSplit(sr))
                    {
                        dmp.WriteRaw(sql);
                        dmp.EndCommand();
                    }
                }
            }
        }
示例#2
0
        public void DecimalWithNegativeScaleTest()
        {
            const string query = "CREATE TABLE decimal_neg_scale(id uuid PRIMARY KEY, value decimal);";

            QueryTools.ExecuteSyncNonQuery(Session, query);

            const string insertQuery       = @"INSERT INTO decimal_neg_scale (id, value) VALUES (?, ?)";
            var          preparedStatement = Session.Prepare(insertQuery);

            const int scale      = -1;
            var       scaleBytes = BitConverter.GetBytes(scale);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(scaleBytes);
            }
            var bytes = new byte[scaleBytes.Length + 1];

            Array.Copy(scaleBytes, bytes, scaleBytes.Length);

            bytes[scaleBytes.Length] = 5;

            var firstRowValues = new object[] { Guid.NewGuid(), bytes };

            Session.Execute(preparedStatement.Bind(firstRowValues));

            var row      = Session.Execute("SELECT * FROM decimal_neg_scale").First();
            var decValue = row.GetValue <decimal>("value");

            Assert.AreEqual(50, decValue);

            const string dropQuery = "DROP TABLE decimal_neg_scale;";

            QueryTools.ExecuteSyncNonQuery(Session, dropQuery);
        }
示例#3
0
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="strCondition">查询条件 lucene的查询语法</param>
        /// <param name="page">分页相关</param>
        /// <param name="strFilter">[100,3000]</param>
        /// <returns></returns>
        public List <T> QueryByPage(string strCondition, Page page, string strFilter)
        {
            IndexSearcher searcher = null;

            try
            {
                List <T> ciList = new List <T>();
                searcher = CreateSearcher();
                Analyzer analyzer = new PanGuAnalyzer();
                //--------------------------------------这里配置搜索条件
                QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Title", analyzer);
                Query       query  = parser.Parse(strCondition);

                int startIndex = (page.PageIndex - 1) * page.PageSize;
                int endIndex   = page.PageIndex * page.PageSize;

                var property = Properties.Where(u => u.Name.Equals(page.Sort)).FirstOrDefault();

                Sort sort = null;
                if (!string.IsNullOrEmpty(page.Sort))
                {
                    //排序
                    sort = new Sort();
                    //找到该属性
                    SortField sortField = new SortField(page.Sort, SortField.DOUBLE, page.Order.Equals("asc", StringComparison.CurrentCultureIgnoreCase));
                    sort.SetSort(sortField);
                }
                Filter  filter = null;
                TopDocs docs   = null;
                if (sort != null && !string.IsNullOrEmpty(strFilter))
                {
                    Tuple <double, double> tuple = QueryTools.GetMinAndMax(strFilter);
                    if (tuple != null)
                    {
                        filter = QueryTools.GetNumberFilter(property, tuple.Item1, tuple.Item2);
                        docs   = searcher.Search(query, filter, 10000, sort);
                    }
                }
                else
                {
                    //filter = NumericRangeFilter.NewDoubleRange("Price", 100, 400, true, true);
                    docs = searcher.Search(query, filter, 1000);
                }

                //获取中标的数据
                page.Total = docs.TotalHits;

                //PrintScores(docs, startIndex, endIndex, searcher);
                for (int i = startIndex; i < endIndex && i < page.Total; i++)
                {
                    Document doc = searcher.Doc(docs.ScoreDocs[i].Doc);
                    ciList.Add(ParseDocToEntity(doc));
                }
                return(ciList);
            }
            finally
            {
                searcher?.Dispose();
            }
        }
示例#4
0
        public void TestCounters()
        {
            string tableName = TestUtils.GetUniqueTableName();

            try
            {
                var query = string.Format("CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, incdec counter);", tableName);
                QueryTools.ExecuteSyncNonQuery(Session, query);
            }
            catch (AlreadyExistsException)
            {
            }

            Guid tweet_id = Guid.NewGuid();

            Parallel.For(0, 100,
                         i =>
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format(@"UPDATE {0} SET incdec = incdec {2}  WHERE tweet_id = {1};", tableName,
                                                             tweet_id, (i % 2 == 0 ? "-" : "+") + i));
            });

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(),
                                        new List <object[]> {
                new object[2] {
                    tweet_id, (Int64)50
                }
            });
        }
示例#5
0
        private void DumpSubFolder(AlterPlan plan, string subfolder, int order)
        {
            string dir = GetPrivateSubFolder(subfolder);

            if (!Directory.Exists(dir))
            {
                return;
            }
            string[] files = Directory.GetFiles(dir);
            Array.Sort(files);
            foreach (string f in files)
            {
                if (!f.ToLower().EndsWith(".sql"))
                {
                    continue;
                }
                using (StreamReader sr = new StreamReader(f))
                {
                    foreach (string sql in QueryTools.GoSplit(sr))
                    {
                        plan.CustomAction(sql, order);
                    }
                }
            }
        }
示例#6
0
        private void ParameterizedStatement(Type type, bool testAsync = false)
        {
            var tableName             = "table" + Guid.NewGuid().ToString("N").ToLower();
            var cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(type);
            var expectedValues        = new List <object[]>(1);
            var val        = Randomm.RandomVal(type);
            var bindValues = new object[] { Guid.NewGuid(), val };

            expectedValues.Add(bindValues);

            CreateTable(tableName, cassandraDataTypeName);

            var statement = new SimpleStatement(String.Format("INSERT INTO {0} (id, val) VALUES (?, ?)", tableName), bindValues);

            if (testAsync)
            {
                Session.ExecuteAsync(statement).Wait(500);
            }
            else
            {
                Session.Execute(statement);
            }

            // Verify results
            RowSet rs = Session.Execute("SELECT * FROM " + tableName);

            VerifyData(rs, expectedValues);
        }
        public void Prepared_SelectOne()
        {
            var tableName = TestUtils.GetUniqueTableName();

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"
                    CREATE TABLE {0}(
                    tweet_id int PRIMARY KEY,
                    numb double,
                    label text);", tableName));
                TestUtils.WaitForSchemaAgreement(Session.Cluster);
            }
            catch (AlreadyExistsException)
            {
            }

            for (int i = 0; i < 10; i++)
            {
                Session.Execute(string.Format("INSERT INTO {0} (tweet_id, numb, label) VALUES({1}, 0.01,'{2}')", tableName, i, "row" + i));
            }

            var prepSelect = QueryTools.PrepareQuery(Session, string.Format("SELECT * FROM {0} WHERE tweet_id = ?;", tableName));

            var rowId  = 5;
            var result = QueryTools.ExecutePreparedSelectQuery(Session, prepSelect, new object[] { rowId });

            foreach (var row in result)
            {
                Assert.True((string)row.GetValue(typeof(int), "label") == "row" + rowId);
            }
            Assert.True(result.Columns != null);
            Assert.True(result.Columns.Length == 3);
        }
        public static Collection <Feature> GetFeaturesIntersecting(this QueryTools queryTools, BaseShape targetShape, IEnumerable <string> returningColumnNames, bool useSqlType)
        {
            Collection <Feature> returnFeatures = null;

            if (useSqlType)
            {
                returnFeatures = new Collection <Feature>();
                RectangleShape       boundingBox         = targetShape.GetBoundingBox();
                Collection <Feature> allPossibleFeatures = queryTools.GetFeaturesInsideBoundingBox(boundingBox, returningColumnNames);
                foreach (Feature feature in allPossibleFeatures)
                {
                    BaseShape sourceShape = feature.GetShape();
                    sourceShape = SqlTypesGeometryHelper.MakeValid(sourceShape);
                    targetShape = SqlTypesGeometryHelper.MakeValid(targetShape);
                    bool intersects = SqlTypesGeometryHelper.Intersects(sourceShape, targetShape);
                    if (intersects)
                    {
                        returnFeatures.Add(feature);
                    }
                }
            }
            else
            {
                returnFeatures = queryTools.GetFeaturesIntersecting(targetShape, returningColumnNames);
            }
            return(returnFeatures);
        }
示例#9
0
        public void ExceedingCassandraType(Type toExceed, Type toExceedWith, bool sameOutput = true)
        {
            string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(toExceed);
            string tableName             = TestUtils.GetUniqueTableName();
            var    query = String.Format("CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, label text, number {1});", tableName, cassandraDataTypeName);

            QueryTools.ExecuteSyncNonQuery(Session, query);

            object Minimum = toExceedWith.GetTypeInfo().GetField("MinValue").GetValue(this);
            object Maximum = toExceedWith.GetTypeInfo().GetField("MaxValue").GetValue(this);

            var row1 = new object[3] {
                Guid.NewGuid(), "Minimum", Minimum
            };
            var row2 = new object[3] {
                Guid.NewGuid(), "Maximum", Maximum
            };
            var toInsert_and_Check = new List <object[]>(2)
            {
                row1, row2
            };

            if (toExceedWith == typeof(Double) || toExceedWith == typeof(Single))
            {
                Minimum = Minimum.GetType().GetTypeInfo().GetMethod("ToString", new[] { typeof(string) }).Invoke(Minimum, new object[1] {
                    "r"
                });
                Maximum = Maximum.GetType().GetTypeInfo().GetMethod("ToString", new[] { typeof(string) }).Invoke(Maximum, new object[1] {
                    "r"
                });

                if (!sameOutput) //for ExceedingCassandra_FLOAT() test case
                {
                    toInsert_and_Check[0][2] = Single.NegativeInfinity;
                    toInsert_and_Check[1][2] = Single.PositiveInfinity;
                }
            }

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id, label, number) VALUES ({1}, '{2}', {3});", tableName,
                                                             toInsert_and_Check[0][0], toInsert_and_Check[0][1], Minimum), null);
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id, label, number) VALUES ({1}, '{2}', {3});", tableName,
                                                             toInsert_and_Check[1][0], toInsert_and_Check[1][1], Maximum), null);
            }
            catch (InvalidQueryException)
            {
                if (!sameOutput && toExceed == typeof(Int32)) //for ExceedingCassandra_INT() test case
                {
                    return;
                }
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.One, toInsert_and_Check);
        }
 private void CreateTable(ISession session, string tableName)
 {
     QueryTools.ExecuteSyncNonQuery(session, string.Format(@"CREATE TABLE {0}(
                                                         id int PRIMARY KEY,
                                                         label text,
                                                         number int
                                                         );", tableName));
     TestUtils.WaitForSchemaAgreement(session.Cluster);
 }
示例#11
0
        public void InsertingSingleValue(Type tp)
        {
            string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(tp);
            string tableName             = TestUtils.GetUniqueTableName();

            try
            {
                var query = string.Format(@"CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, value {1});", tableName, cassandraDataTypeName);
                QueryTools.ExecuteSyncNonQuery(Session, query);
            }
            catch (AlreadyExistsException)
            {
            }

            var    toInsert = new List <object[]>(1);
            object val      = Randomm.RandomVal(tp);

            if (tp == typeof(string))
            {
                val = "'" + val.ToString().Replace("'", "''") + "'";
            }
            var row1 = new object[2] {
                Guid.NewGuid(), val
            };

            toInsert.Add(row1);

            bool isFloatingPoint = false;

            if (row1[1].GetType() == typeof(string) || row1[1].GetType() == typeof(byte[]))
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id,value) VALUES ({1}, {2});", tableName, toInsert[0][0],
                                                             row1[1].GetType() == typeof(byte[])
                                                                 ? "0x" + CqlQueryTools.ToHex((byte[])toInsert[0][1])
                                                                 : "'" + toInsert[0][1] + "'"), null);
            }
            // rndm.GetType().GetMethod("Next" + tp.Name).Invoke(rndm, new object[] { })
            else
            {
                if (tp == typeof(Single) || tp == typeof(Double))
                {
                    isFloatingPoint = true;
                }
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id,value) VALUES ({1}, {2});", tableName, toInsert[0][0],
                                                             !isFloatingPoint
                                                                 ? toInsert[0][1]
                                                                 : toInsert[0][1].GetType()
                                                             .GetMethod("ToString", new[] { typeof(string) })
                                                             .Invoke(toInsert[0][1], new object[] { "r" })), null);
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), toInsert);
        }
示例#12
0
 private void CreateTable(string tableName, string type)
 {
     try
     {
         QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
                                                                 id uuid PRIMARY KEY,
                                                                 val {1}
                                                                 );", tableName, type));
     }
     catch (AlreadyExistsException)
     {
     }
 }
        private void CreateTwoTableTestEnv(string table1, string table2)
        {
            QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0} (
                                                                          id int PRIMARY KEY,
                                                                          label text,
                                                                          number int
                                                                          );", table1));

            QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0} (
                                                                        id int PRIMARY KEY,
                                                                        label text,
                                                                        number int
                                                                        );", table2));
            TestUtils.WaitForSchemaAgreement(Session.Cluster);
        }
示例#14
0
        ////////////////////////////////////
        /// Test Helpers
        ////////////////////////////////////

        /// <summary>
        /// Creates a table and inserts a number of records synchronously.
        /// </summary>
        /// <returns>The name of the table</returns>
        private string CreateSimpleTableAndInsert(int rowsInTable)
        {
            string tableName = TestUtils.GetUniqueTableName();

            QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"
                CREATE TABLE {0}(
                id uuid PRIMARY KEY,
                label text);", tableName));
            for (int i = 0; i < rowsInTable; i++)
            {
                Session.Execute(string.Format("INSERT INTO {2} (id, label) VALUES({0},'{1}')", Guid.NewGuid(), "LABEL" + i, tableName));
            }

            return(tableName);
        }
示例#15
0
        /// <summary>
        /// Creates a table with a composite index and inserts a number of records synchronously.
        /// </summary>
        /// <returns>The name of the table</returns>
        private Tuple <string, string> CreateTableWithCompositeIndexAndInsert(ISession session, int rowsInTable)
        {
            string tableName           = TestUtils.GetUniqueTableName();
            string staticClusterKeyStr = "staticClusterKeyStr";

            QueryTools.ExecuteSyncNonQuery(session, string.Format(@"
                CREATE TABLE {0} (
                id text,
                label text,
                PRIMARY KEY (label, id));",
                                                                  tableName));
            for (int i = 0; i < rowsInTable; i++)
            {
                session.Execute(string.Format("INSERT INTO {2} (label, id) VALUES('{0}','{1}')", staticClusterKeyStr, Guid.NewGuid().ToString(), tableName));
            }
            Tuple <string, string> infoTuple = new Tuple <string, string>(tableName, staticClusterKeyStr);

            return(infoTuple);
        }
示例#16
0
        public void TimestampTest()
        {
            string tableName   = TestUtils.GetUniqueTableName();
            var    createQuery = string.Format(@"CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, ts timestamp);", tableName);

            QueryTools.ExecuteSyncNonQuery(Session, createQuery);

            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
                                                         "2011-02-03 04:05+0000"), null);
            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
                                                         220898707200000), null);
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(), 0),
                                           null);

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
        public void InsertingSingleValuePrepared(Type tp, object value = null)
        {
            var cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(tp);
            var tableName             = "table" + Guid.NewGuid().ToString("N");

            QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
                tweet_id uuid PRIMARY KEY,
                value {1}
                );", tableName, cassandraDataTypeName));

            TestUtils.WaitForSchemaAgreement(Session.Cluster);

            var    toInsert = new List <object[]>(1);
            object val      = Randomm.RandomVal(tp);

            if (tp == typeof(string))
            {
                val = "'" + val.ToString().Replace("'", "''") + "'";
            }

            var row1 = new [] { Guid.NewGuid(), val };

            toInsert.Add(row1);

            var prep = QueryTools.PrepareQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id, value) VALUES ({1}, ?);", tableName,
                                                             toInsert[0][0]));

            if (value == null)
            {
                QueryTools.ExecutePreparedQuery(Session, prep, new [] { toInsert[0][1] });
            }
            else
            {
                QueryTools.ExecutePreparedQuery(Session, prep, new [] { value });
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.One, toInsert);
        }
        public override void Run(DashboardInfo_Widget1 widget, AppConfig appConfig)
        {
            if (widget.settings == null)
            {
                WriteWarning("Skipped: settings == null");
                return;
            }
            string        sourceProjectName = TfsStatic.GetTeamProjectName(true);
            string        sourceTeamName    = appConfig.SourceTeamName;
            string        targetProjectName = TfsStatic.GetTeamProjectName(false);
            string        targetTeamName    = appConfig.TargetTeamName;
            WorkItemQuery targetQuery;
            var           settings = JsonConvert.DeserializeObject <WitChartWidgetSettings>(widget.settings);

            targetQuery = QueryTools.CopyQuery(new CopyQueryParameters
            {
                QueryId           = settings.groupKey,
                QueryReplacements = appConfig.Queries,
            }, sourceProjectName, sourceTeamName, targetProjectName, targetTeamName);
            settings.groupKey = targetQuery.id;
            settings.transformOptions.filter = targetQuery.id;
            widget.settings = JsonConvert.SerializeObject(settings);
        }
 private static void CopyQueryFolder(WorkItemQuery queryFolder,
                                     string sourceProjectName, string sourceTeamName,
                                     string targetProjectName, string targetTeamName)
 {
     WriteLine($"{queryFolder.path}");
     if (!queryFolder.isFolder || queryFolder.children.Length == 0)
     {
         return;
     }
     foreach (var childQueryFolder in queryFolder.children.Where(o => o.isFolder))
     {
         var childQueryFolderObject = TfsStatic.GetWorkItemQuery(true, childQueryFolder.id, QueryExpand.minimal, 1);
         CopyQueryFolder(childQueryFolderObject, sourceProjectName, sourceTeamName, targetProjectName, targetTeamName);
     }
     foreach (var query in queryFolder.children.Where(o => !o.isFolder))
     {
         WriteLine($"\t- {query.name}");
         QueryTools.CopyQuery(new Tools.Parameters.CopyQueryParameters
         {
             QueryId           = query.id,
             QueryReplacements = _config.Queries,
         }, sourceProjectName, sourceTeamName, targetProjectName, targetTeamName);
     }
 }
示例#20
0
        public void insertingSingleCollectionPrepared(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null)
        {
            string cassandraDataTypeName    = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed);
            string cassandraKeyDataTypeName = "";
            string mapSyntax = "";

            object valueCollection = null;

            int Cnt = 10;

            if (CassandraCollectionType == "list" || CassandraCollectionType == "set")
            {
                Type openType = CassandraCollectionType == "list" ? typeof(List <>) : typeof(HashSet <>);
                Type listType = openType.MakeGenericType(TypeOfDataToBeInputed);
                valueCollection = Activator.CreateInstance(listType);
                MethodInfo addM = listType.GetMethod("Add");
                for (int i = 0; i < Cnt; i++)
                {
                    object randomValue = Randomm.RandomVal(TypeOfDataToBeInputed);
                    addM.Invoke(valueCollection, new[] { randomValue });
                }
            }
            else if (CassandraCollectionType == "map")
            {
                cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                Type openType = typeof(SortedDictionary <,>);
                Type dicType  = openType.MakeGenericType(TypeOfKeyForMap, TypeOfDataToBeInputed);
                valueCollection = Activator.CreateInstance(dicType);
                MethodInfo addM = dicType.GetMethod("Add");
                for (int i = 0; i < Cnt; i++)
                {
RETRY:
                    try
                    {
                        object randomKey   = Randomm.RandomVal(TypeOfKeyForMap);
                        object randomValue = Randomm.RandomVal(TypeOfDataToBeInputed);
                        addM.Invoke(valueCollection, new[] { randomKey, randomValue });
                    }
                    catch
                    {
                        goto RETRY;
                    }
                }
            }

            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
                 tweet_id uuid PRIMARY KEY,
                 some_collection {1}<{2}{3}>
                 );", tableName, CassandraCollectionType, mapSyntax, cassandraDataTypeName));
            }
            catch (AlreadyExistsException)
            {
            }

            Guid tweet_id = Guid.NewGuid();
            PreparedStatement prepInsert = QueryTools.PrepareQuery(Session,
                                                                   string.Format("INSERT INTO {0}(tweet_id,some_collection) VALUES (?, ?);", tableName));

            Session.Execute(prepInsert.Bind(tweet_id, valueCollection).SetConsistencyLevel(ConsistencyLevel.Quorum));
            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
示例#21
0
        public void InsertingSingleCollection(string cassandraCollectionType, Type typeOfDataToBeInputed, Type typeOfKeyForMap = null)
        {
            string cassandraDataTypeName    = QueryTools.convertTypeNameToCassandraEquivalent(typeOfDataToBeInputed);
            string cassandraKeyDataTypeName = "";

            string openBracket  = cassandraCollectionType == "list" ? "[" : "{";
            string closeBracket = cassandraCollectionType == "list" ? "]" : "}";
            string mapSyntax    = "";

            object randomValue = Randomm.RandomVal(typeOfDataToBeInputed);

            if (typeOfDataToBeInputed == typeof(string))
            {
                randomValue = "'" + randomValue.ToString().Replace("'", "''") + "'";
            }

            string randomKeyValue = string.Empty;

            if (typeOfKeyForMap != null)
            {
                cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(typeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                if (typeOfKeyForMap == typeof(DateTimeOffset))
                {
                    randomKeyValue = "'" +
                                     (Randomm.RandomVal(typeof(DateTimeOffset))
                                      .GetType()
                                      .GetMethod("ToString", new[] { typeof(string) })
                                      .Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] {
                        "yyyy-MM-dd H:mm:sszz00"
                    }) + "'");
                }
                else if (typeOfKeyForMap == typeof(string))
                {
                    randomKeyValue = "'" + Randomm.RandomVal(typeOfDataToBeInputed).ToString().Replace("'", "''") + "'";
                }
                else
                {
                    randomKeyValue = Randomm.RandomVal(typeOfDataToBeInputed).ToString();
                }
            }

            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         some_collection {1}<{2}{3}>
         );", tableName, cassandraCollectionType, mapSyntax, cassandraDataTypeName));
            }
            catch (AlreadyExistsException)
            {
            }

            Guid tweet_id = Guid.NewGuid();


            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,some_collection) VALUES ({1}, {2});", tableName, tweet_id,
                                                         openBracket + randomKeyValue + (string.IsNullOrEmpty(randomKeyValue) ? "" : " : ") +
                                                         randomValue + closeBracket));

            var longQ = new StringBuilder();

            longQ.AppendLine("BEGIN BATCH ");

            int    CollectionElementsNo = 100;
            object rval = Randomm.RandomVal(typeOfDataToBeInputed);

            for (int i = 0; i < CollectionElementsNo; i++)
            {
                object val = rval;
                if (typeOfDataToBeInputed == typeof(string))
                {
                    val = "'" + val.ToString().Replace("'", "''") + "'";
                }

                longQ.AppendFormat(@"UPDATE {0} SET some_collection = some_collection + {1} WHERE tweet_id = {2};"
                                   , tableName,
                                   openBracket + randomKeyValue + (string.IsNullOrEmpty(randomKeyValue) ? "" : " : ") + val + closeBracket, tweet_id);
            }
            longQ.AppendLine("APPLY BATCH;");
            QueryTools.ExecuteSyncNonQuery(Session, longQ.ToString(), "Inserting...");

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
示例#22
0
        public void CheckingOrderOfCollection(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null, string pendingMode = "")
        {
            string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed);
            string openBracket           = CassandraCollectionType == "list" ? "[" : "{";
            string closeBracket          = CassandraCollectionType == "list" ? "]" : "}";
            string mapSyntax             = "";

            string randomKeyValue = string.Empty;

            if (TypeOfKeyForMap != null)
            {
                string cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                if (TypeOfKeyForMap == typeof(DateTimeOffset))
                {
                    randomKeyValue =
                        Randomm.RandomVal(typeof(DateTimeOffset))
                        .GetType()
                        .GetMethod("ToString", new[] { typeof(string) })
                        .Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] {
                        "yyyy-MM-dd H:mm:sszz00"
                    }) + "' : '";
                }
                else
                {
                    randomKeyValue = Randomm.RandomVal(TypeOfDataToBeInputed) + "' : '";
                }
            }


            var tableName = "table" + Guid.NewGuid().ToString("N");

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
                    tweet_id uuid PRIMARY KEY,
                    some_collection {1}<{2}{3}>
                    );", tableName, CassandraCollectionType, mapSyntax, cassandraDataTypeName));
            }
            catch (AlreadyExistsException)
            {
            }
            Guid tweet_id = Guid.NewGuid();

            var longQ = new StringBuilder();

            longQ.AppendLine("BEGIN BATCH ");

            int collectionElementsNo = 100;
            var orderedAsInputed     = new List <Int32>(collectionElementsNo);

            string inputSide = "some_collection + {1}";

            if (CassandraCollectionType == "list" && pendingMode == "prepending")
            {
                inputSide = "{1} + some_collection";
            }

            for (int i = 0; i < collectionElementsNo; i++)
            {
                int data = i * (i % 2);
                longQ.AppendFormat(@"UPDATE {0} SET some_collection = " + inputSide + " WHERE tweet_id = {2};"
                                   , tableName, openBracket + randomKeyValue + data + closeBracket, tweet_id);
                orderedAsInputed.Add(data);
            }

            longQ.AppendLine("APPLY BATCH;");
            QueryTools.ExecuteSyncNonQuery(Session, longQ.ToString(), "Inserting...");

            if (CassandraCollectionType == "set")
            {
                orderedAsInputed.Sort();
                orderedAsInputed.RemoveRange(0, orderedAsInputed.LastIndexOf(0));
            }
            else if (CassandraCollectionType == "list" && pendingMode == "prepending")
            {
                orderedAsInputed.Reverse();
            }

            var rs = Session.Execute(string.Format("SELECT * FROM {0};", tableName),
                                     Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());

            {
                int ind = 0;
                foreach (Row row in rs.GetRows())
                {
                    foreach (object value in row[1] as IEnumerable)
                    {
                        Assert.True(orderedAsInputed[ind] == (int)value);
                        ind++;
                    }
                }
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
        private void CheckPureMetadata(Cluster cluster, ISession session, string tableName, string keyspaceName, TableOptions tableOptions = null)
        {
            // build create table cql
            tableName = TestUtils.GetUniqueTableName().ToLower();
            var columns = new Dictionary
                          <string, ColumnTypeCode>
            {
                { "q0uuid", ColumnTypeCode.Uuid },
                { "q1timestamp", ColumnTypeCode.Timestamp },
                { "q2double", ColumnTypeCode.Double },
                { "q3int32", ColumnTypeCode.Int },
                { "q4int64", ColumnTypeCode.Bigint },
                { "q5float", ColumnTypeCode.Float },
                { "q6inet", ColumnTypeCode.Inet },
                { "q7boolean", ColumnTypeCode.Boolean },
                { "q8inet", ColumnTypeCode.Inet },
                { "q9blob", ColumnTypeCode.Blob },
                { "q10varint", ColumnTypeCode.Varint },
                { "q11decimal", ColumnTypeCode.Decimal },
                { "q12list", ColumnTypeCode.List },
                { "q13set", ColumnTypeCode.Set },
                { "q14map", ColumnTypeCode.Map }
                //{"q12counter", Metadata.ColumnTypeCode.Counter}, A table that contains a counter can only contain counters
            };

            var stringBuilder = new StringBuilder(@"CREATE TABLE " + tableName + " (");

            foreach (KeyValuePair <string, ColumnTypeCode> col in columns)
            {
                stringBuilder.Append(col.Key + " " + col.Value +
                                     (((col.Value == ColumnTypeCode.List) ||
                                       (col.Value == ColumnTypeCode.Set) ||
                                       (col.Value == ColumnTypeCode.Map))
                              ? "<int" + (col.Value == ColumnTypeCode.Map ? ",varchar>" : ">")
                              : "") + ", ");
            }

            stringBuilder.Append("PRIMARY KEY(");
            int rowKeys = Randomm.Instance.Next(1, columns.Count - 3);

            for (int i = 0; i < rowKeys; i++)
            {
                stringBuilder.Append(columns.Keys.First(key => key.StartsWith("q" + i.ToString(CultureInfo.InvariantCulture))) + ((i == rowKeys - 1) ? "" : ", "));
            }
            string opt = tableOptions != null ? " WITH " + tableOptions : "";

            stringBuilder.Append("))" + opt + ";");

            QueryTools.ExecuteSyncNonQuery(session, stringBuilder.ToString());
            TestUtils.WaitForSchemaAgreement(session.Cluster);

            var table = cluster.Metadata.GetTable(keyspaceName, tableName);

            Assert.AreEqual(tableName, table.Name);
            foreach (var metaCol in table.TableColumns)
            {
                Assert.True(columns.Keys.Contains(metaCol.Name));
                Assert.True(metaCol.TypeCode == columns.First(tpc => tpc.Key == metaCol.Name).Value);
                Assert.True(metaCol.Table == tableName);
                Assert.True(metaCol.Keyspace == (keyspaceName));
            }

            if (tableOptions != null)
            {
                Assert.AreEqual(tableOptions.Comment, table.Options.Comment);
                Assert.AreEqual(tableOptions.ReadRepairChance, table.Options.ReadRepairChance);
                Assert.AreEqual(tableOptions.LocalReadRepairChance, table.Options.LocalReadRepairChance);
                Assert.AreEqual(tableOptions.ReplicateOnWrite, table.Options.replicateOnWrite);
                Assert.AreEqual(tableOptions.GcGraceSeconds, table.Options.GcGraceSeconds);
                Assert.AreEqual(tableOptions.bfFpChance, table.Options.bfFpChance);
                if (tableOptions.Caching == "ALL")
                {
                    //The string returned can be more complete than the provided
                    Assert.That(table.Options.Caching == "ALL" || table.Options.Caching.Contains("ALL"), "Caching returned does not match");
                }
                else
                {
                    Assert.AreEqual(tableOptions.Caching, table.Options.Caching);
                }
                Assert.AreEqual(tableOptions.CompactionOptions, table.Options.CompactionOptions);
                Assert.AreEqual(tableOptions.CompressionParams, table.Options.CompressionParams);
            }
        }