Beispiel #1
0
        public void LinqInsert_MissingPartitionKey_Async_Test()
        {
            var   table = new Table <Movie>(Session, new MappingConfiguration());
            Movie objectMissingPartitionKey = new Movie()
            {
                MainActor = "doesntmatter"
            };

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"INSERT INTO \"{Movie.TableName}\" (\"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\") VALUES (?, ?, ?, ?, ?, ?)",
                    when => when.WithParams(objectMissingPartitionKey.GetParametersWithTypes()))
                .ThenServerError(ServerError.Invalid, "msg"));

            try
            {
                table.Insert(objectMissingPartitionKey).ExecuteAsync().Wait();
            }
            catch (Exception e) // Exception is gathered from the async task
            {
                int maxLayers     = 50;
                int layersChecked = 0;
                while (layersChecked < maxLayers && !e.GetType().Equals(typeof(InvalidQueryException)))
                {
                    layersChecked++;
                    e = e.InnerException;
                }
                Assert.IsInstanceOf <InvalidQueryException>(e);
            }
        }
Beispiel #2
0
        public void Append_ToArray_TableWithAllCollectionTypes()
        {
            var(table, expectedEntities) = EntityWithAllCollectionTypes.GetDefaultTable(Session, _tableName);

            var singleEntity = expectedEntities.First();
            var toAppend     = new string[] { "tag1", "tag2", "tag3" };

            table.Where(t => t.Id == singleEntity.Id)
            .Select(t => new EntityWithAllCollectionTypes {
                ArrayType = CqlOperator.Append(toAppend)
            })
            .Update().Execute();

            VerifyBoundStatement(
                $"UPDATE {_tableName} SET ArrayType = ArrayType + ? WHERE Id = ?",
                1,
                toAppend, singleEntity.Id);

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"SELECT ArrayType, DictionaryType, Id, ListType FROM {_tableName} WHERE Id = ?",
                    when => when.WithParam(singleEntity.Id))
                .ThenRowsSuccess(
                    new[] { "ArrayType", "DictionaryType", "Id", "ListType" },
                    r => r.WithRow(
                        singleEntity.ArrayType.Concat(toAppend),
                        singleEntity.DictionaryType,
                        singleEntity.Id,
                        singleEntity.ListType)));

            var entityList = table.Where(m => m.Id == singleEntity.Id).ExecuteAsync().Result.ToList();

            Assert.AreEqual(1, entityList.Count);
            CollectionAssert.AreEqual(singleEntity.ArrayType.Concat(toAppend), entityList.First().ArrayType);
        }
Beispiel #3
0
        public void LinqAttributes_Counter_AttemptInsert()
        {
            // Create config that uses linq based attributes
            var mappingConfig = new MappingConfiguration();

            mappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(CounterEntityWithLinqAttributes),
                                                                             () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(CounterEntityWithLinqAttributes)));
            var table = new Table <CounterEntityWithLinqAttributes>(Session, mappingConfig);

            CounterEntityWithLinqAttributes pocoAndLinqAttributesLinqPocos = new CounterEntityWithLinqAttributes()
            {
                KeyPart1 = Guid.NewGuid(),
                KeyPart2 = (decimal)123,
            };

            var expectedErrMsg = "INSERT statement(s)? are not allowed on counter tables, use UPDATE instead";

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "INSERT INTO \"CounterEntityWithLinqAttributes\" (\"Counter\", \"KeyPart1\", \"KeyPart2\") VALUES (?, ?, ?)",
                    when => pocoAndLinqAttributesLinqPocos.WithParams(when))
                .ThenServerError(
                    ServerError.Invalid, expectedErrMsg));

            var e = Assert.Throws <InvalidQueryException>(() => Session.Execute(table.Insert(pocoAndLinqAttributesLinqPocos)));

            Assert.AreEqual(expectedErrMsg, e.Message);
        }
Beispiel #4
0
        public void CreateTable_MakeAllPropertiesCaseSensitiveAtOnce()
        {
            var config = new MappingConfiguration().Define(new Map <ManyDataTypesPoco>()
                                                           .PartitionKey(u => u.StringType)
                                                           .TableName("tbl_case_sens_once")
                                                           .CaseSensitive());

            var table = new Table <ManyDataTypesPoco>(Session, config);

            table.Create();

            VerifyQuery(
                "CREATE TABLE \"tbl_case_sens_once\" " +
                $"({string.Join(", ", ManyDataTypesPoco.ColumnsToTypes.Select(k => $"\"{k.Key}\" {k.Value.Value}"))}, " +
                "PRIMARY KEY (\"StringType\"))",
                1);

            var mapper            = new Mapper(Session, config);
            var manyTypesInstance = ManyDataTypesPoco.GetRandomInstance();

            mapper.Insert(manyTypesInstance);

            var cqlSelect = $"SELECT * from \"{table.Name}\" where \"StringType\"='{manyTypesInstance.StringType}'";

            TestCluster.PrimeFluent(
                b => b.WhenQuery(cqlSelect)
                .ThenRowsSuccess(ManyDataTypesPoco.GetColumnsAndTypes(), r => r.WithRow(manyTypesInstance.GetParameters())));

            var objectsRetrieved = mapper.Fetch <ManyDataTypesPoco>(cqlSelect).ToList();

            Assert.AreEqual(1, objectsRetrieved.Count);
            objectsRetrieved[0].AssertEquals(manyTypesInstance);
        }
Beispiel #5
0
        public void Delete_DeleteOneEquals(bool async)
        {
            var table = new Table <AllDataTypesEntity>(Session, new MappingConfiguration());

            AllDataTypesEntity.PrimeCountQuery(TestCluster, _entityList.Count);
            var count = table.Count().Execute();

            Assert.AreEqual(_entityList.Count, count);

            AllDataTypesEntity entityToDelete = _entityList[0];

            var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType);
            var deleteQuery = selectQuery.Delete();

            if (async)
            {
                deleteQuery.ExecuteAsync().GetAwaiter().GetResult();
            }
            else
            {
                deleteQuery.Execute();
            }

            VerifyBoundStatement(
                $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?", 1, entityToDelete.StringType);

            TestCluster.PrimeDelete();
            AllDataTypesEntity.PrimeCountQuery(TestCluster, _entityList.Count - 1);

            count = table.Count().Execute();
            Assert.AreEqual(_entityList.Count - 1, count);
            TestCluster.PrimeFluent(b => entityToDelete.When(TestCluster, b).ThenVoidSuccess());
            Assert.AreEqual(0, selectQuery.Execute().ToList().Count);
        }
Beispiel #6
0
        public void Attributes_Ignore()
        {
            var table = GetTable <PocoWithIgnoredAttributes>();

            Assert.AreNotEqual(table.Name, table.Name.ToLower());
            table.Create();

            VerifyQuery(
                "CREATE TABLE PocoWithIgnoredAttributes " +
                "(SomeNonIgnoredDouble double, SomePartitionKey text, " +
                "PRIMARY KEY (SomePartitionKey))",
                1);

            var mapper       = GetMapper();
            var pocoToUpload = new PocoWithIgnoredAttributes
            {
                SomePartitionKey       = Guid.NewGuid().ToString(),
                IgnoredStringAttribute = Guid.NewGuid().ToString(),
            };

            mapper.Insert(pocoToUpload);

            VerifyBoundStatement(
                "INSERT INTO PocoWithIgnoredAttributes (SomeNonIgnoredDouble, SomePartitionKey) " +
                "VALUES (?, ?)",
                1,
                pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey);

            var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where \"{"somepartitionkey"}\"='{pocoToUpload.SomePartitionKey}'";

            TestCluster.PrimeFluent(
                b => b.WhenQuery(cqlSelect)
                .ThenRowsSuccess(
                    new[] { "somenonignoreddouble", "somepartitionkey" },
                    r => r.WithRow(pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey)));

            // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val
            var records = mapper.Fetch <PocoWithIgnoredAttributes>(cqlSelect).ToList();

            Assert.AreEqual(1, records.Count);
            Assert.AreEqual(pocoToUpload.SomePartitionKey, records[0].SomePartitionKey);
            var defaultPoco = new PocoWithIgnoredAttributes();

            Assert.AreNotEqual(defaultPoco.IgnoredStringAttribute, pocoToUpload.IgnoredStringAttribute);
            Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute);
            Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble);

            // Query for the column that the Linq table create created, verify no value was uploaded to it
            var rows = Session.Execute(cqlSelect).GetRows().ToList();

            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(pocoToUpload.SomePartitionKey, rows[0].GetValue <string>("somepartitionkey"));
            Assert.AreEqual(pocoToUpload.SomeNonIgnoredDouble, rows[0].GetValue <double>("somenonignoreddouble"));

            // Verify there was no column created for the ignored column
            var e = Assert.Throws <ArgumentException>(() => rows[0].GetValue <string>(IgnoredStringAttribute));
            var expectedErrMsg = "Column " + IgnoredStringAttribute + " not found";

            Assert.AreEqual(expectedErrMsg, e.Message);
        }
        public void LinqTable_GetTable_RegularStatement()
        {
            var table = Session.GetTable <AllDataTypesEntity>();
            var expectedDataTypesEntityRow = AllDataTypesEntity.GetRandomInstance();
            var uniqueKey = expectedDataTypesEntityRow.StringType;

            // insert record
            table.GetSession().Execute(table.Insert(expectedDataTypesEntityRow));

            VerifyStatement(QueryType.Query, GetTable.InsertCql, 1, expectedDataTypesEntityRow.GetColumnValues());

            TestCluster.PrimeDelete();
            TestCluster.PrimeFluent(
                b => b.WhenQuery(GetTable.SelectCql, p => p.WithParam(uniqueKey))
                .ThenRowsSuccess(expectedDataTypesEntityRow.CreateRowsResult()));

            // select record
            var listOfAllDataTypesObjects =
                (from x in table where x.StringType.Equals(uniqueKey) select x).Execute().ToList();

            Assert.NotNull(listOfAllDataTypesObjects);
            Assert.AreEqual(1, listOfAllDataTypesObjects.Count);
            var actualDataTypesEntityRow = listOfAllDataTypesObjects.First();

            expectedDataTypesEntityRow.AssertEquals(actualDataTypesEntityRow);
        }
Beispiel #8
0
        public void LinqUpdate_IfExists()
        {
            // Setup
            var table = new Table <Movie>(Session, new MappingConfiguration());

            var unexistingMovie = new Movie("Unexisting movie title", "Unexisting movie director", "Unexisting movie actor", "Unexisting movie maker", 1212);

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"UPDATE \"{Movie.TableName}\" " +
                    "SET \"yearMade\" = ?, \"mainGuy\" = ? " +
                    "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ? IF EXISTS",
                    when => when.WithParams(unexistingMovie.Year, unexistingMovie.MainActor, unexistingMovie.Title, unexistingMovie.MovieMaker,
                                            unexistingMovie.Director))
                .ThenRowsSuccess(Movie.CreateAppliedInfoRowsResultWithoutMovie(false)));

            var cql = table.Where(m => m.Title == unexistingMovie.Title && m.MovieMaker == unexistingMovie.MovieMaker && m.Director == unexistingMovie.Director)
                      .Select(m => new Movie {
                Year = unexistingMovie.Year, MainActor = unexistingMovie.MainActor
            })
                      .UpdateIfExists();
            var appliedInfo = cql.Execute();

            Assert.IsFalse(appliedInfo.Applied);

            VerifyBoundStatement(
                $"UPDATE \"{Movie.TableName}\" " +
                "SET \"yearMade\" = ?, \"mainGuy\" = ? " +
                "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ? IF EXISTS",
                1,
                unexistingMovie.Year, unexistingMovie.MainActor, unexistingMovie.Title, unexistingMovie.MovieMaker, unexistingMovie.Director);
        }
Beispiel #9
0
        public void TableCreateAsync_Create_KeyspaceOverride_NoSuchKeyspace()
        {
            var uniqueTableName = TestUtils.GetUniqueTableName();
            var uniqueKsName    = TestUtils.GetUniqueKeyspaceName();

            if (!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException())
            {
                TestCluster.PrimeFluent(
                    b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\""))
                    .ThenServerError(ServerError.ConfigError, "msg"));
            }
            else
            {
                TestCluster.PrimeFluent(
                    b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\""))
                    .ThenServerError(ServerError.Invalid, "msg"));
            }

            var table = new Table <AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName);

            if (!TestClusterManager.SchemaManipulatingQueriesThrowInvalidQueryException())
            {
                Assert.ThrowsAsync <InvalidConfigurationInQueryException>(() => table.CreateAsync());
            }
            else
            {
                Assert.ThrowsAsync <InvalidQueryException>(() => table.CreateAsync());
            }
        }
        public void LinqTable_GetTable_Batch()
        {
            // Test
            var table = Session.GetTable <AllDataTypesEntity>();

            var batch = table.GetSession().CreateBatch();
            var expectedDataTypesEntityRow = AllDataTypesEntity.GetRandomInstance();
            var uniqueKey = expectedDataTypesEntityRow.StringType;

            batch.Append(table.Insert(expectedDataTypesEntityRow));
            batch.Execute();

            VerifyBatchStatement(
                1,
                new[] { GetTable.InsertCql },
                new[] { expectedDataTypesEntityRow.GetColumnValues() });

            TestCluster.PrimeFluent(
                b => b.WhenQuery(GetTable.SelectCql, p => p.WithParam(uniqueKey))
                .ThenRowsSuccess(expectedDataTypesEntityRow.CreateRowsResult()));

            var listOfAllDataTypesObjects =
                (from x in table where x.StringType.Equals(uniqueKey) select x).Execute().ToList();

            Assert.NotNull(listOfAllDataTypesObjects);
            Assert.AreEqual(1, listOfAllDataTypesObjects.Count);
            var actualDataTypesEntityRow = listOfAllDataTypesObjects.First();

            expectedDataTypesEntityRow.AssertEquals(actualDataTypesEntityRow);
        }
Beispiel #11
0
        public void CqlClientConfiguration_UseIndividualMappingClassType_StaticMappingClass()
        {
            var config = new MappingConfiguration().Define(new ManyDataTypesPocoMappingCaseSensitive());
            var table  = new Table <ManyDataTypesPoco>(Session, config);

            table.CreateIfNotExists();

            VerifyQuery(CreateCqlCaseSensitive, 1);

            var mapper            = new Mapper(Session, config);
            var manyTypesInstance = ManyDataTypesPoco.GetRandomInstance();

            mapper.Insert(manyTypesInstance);

            VerifyBoundStatement(
                $"INSERT INTO \"{table.Name}\" ({ManyDataTypesPoco.GetCaseSensitiveColumnNamesStr()}) " +
                $"VALUES ({string.Join(", ", ManyDataTypesPoco.GetColumnNames().Select(_ => "?"))})",
                1,
                manyTypesInstance.GetParameters());

            var cqlSelect = $"SELECT * from \"{table.Name}\" where \"StringType\"='{manyTypesInstance.StringType}'";

            TestCluster.PrimeFluent(
                b => b.WhenQuery(cqlSelect)
                .ThenRowsSuccess(ManyDataTypesPoco.GetColumnsAndTypes(), r => r.WithRow(manyTypesInstance.GetParameters())));

            var instancesQueried = mapper.Fetch <ManyDataTypesPoco>(cqlSelect).ToList();

            ManyDataTypesPoco.AssertListEqualsList(new List <ManyDataTypesPoco> {
                manyTypesInstance
            }, instancesQueried);
        }
Beispiel #12
0
        public void TableCreate_CreateTable_SameNameDifferentTypeAlreadyExists_TableNameOverride()
        {
            // First table name creation works as expected
            const string staticTableName   = "staticTableName_2";
            var          mappingConfig     = new MappingConfiguration().Define(new Map <AllDataTypesEntity>().TableName(staticTableName).CaseSensitive().PartitionKey(c => c.StringType));
            var          allDataTypesTable = new Table <AllDataTypesEntity>(Session, mappingConfig);

            allDataTypesTable.Create();

            VerifyStatement(
                QueryType.Query,
                $"CREATE TABLE \"{staticTableName}\" ({CreateTable.CreateCqlDefaultColumnsCaseSensitive}, PRIMARY KEY (\"StringType\"))",
                1);

            // Second creation attempt with same table name should fail
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"CREATE TABLE \"{staticTableName}\" (" +
                    "\"director\" text, \"list\" list<text>, \"mainGuy\" text, " +
                    "\"movie_maker\" text, \"unique_movie_title\" text, " +
                    "\"yearMade\" int, " +
                    "PRIMARY KEY ((\"unique_movie_title\", \"movie_maker\"), \"director\"))")
                .ThenAlreadyExists(_uniqueKsName, staticTableName));
            var movieTable = new Table <Movie>(Session, new MappingConfiguration(), staticTableName);

            Assert.Throws <AlreadyExistsException>(() => movieTable.Create());
        }
Beispiel #13
0
        public void CqlClientConfiguration_UseIndividualMappingGeneric_StaticMappingClass()
        {
            var config = new MappingConfiguration().Define(new ManyDataTypesPocoMappingCaseSensitive());
            var table  = new Table <ManyDataTypesPoco>(Session, config);

            Assert.AreNotEqual(table.Name, table.Name.ToLower()); // make sure the case sensitivity rule is being used
            table.CreateIfNotExists();

            VerifyQuery(CreateCqlCaseSensitive, 1);

            var mapper            = new Mapper(Session, config);
            var manyTypesInstance = ManyDataTypesPoco.GetRandomInstance();

            mapper.Insert(manyTypesInstance);

            VerifyBoundStatement(
                $"INSERT INTO \"{table.Name}\" ({ManyDataTypesPoco.GetCaseSensitiveColumnNamesStr()}) " +
                $"VALUES ({string.Join(", ", ManyDataTypesPoco.GetColumnNames().Select(_ => "?"))})",
                1,
                manyTypesInstance.GetParameters());

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"SELECT {ManyDataTypesPoco.GetCaseSensitiveColumnNamesStr()} FROM \"{table.Name}\"")
                .ThenRowsSuccess(ManyDataTypesPoco.GetColumnsAndTypes(), r => r.WithRow(manyTypesInstance.GetParameters())));

            var instancesQueried = mapper.Fetch <ManyDataTypesPoco>().ToList();

            Assert.AreEqual(instancesQueried.Count, 1);
            manyTypesInstance.AssertEquals(instancesQueried[0]);
        }
Beispiel #14
0
        public void LinqOrderBy()
        {
            List <Movie> moreMovies     = new List <Movie>();
            string       sameTitle      = "sameTitle";
            string       sameMovieMaker = "sameMovieMaker";

            for (int i = 0; i < 10; i++)
            {
                Movie movie = Movie.GetRandomMovie();
                movie.Title      = sameTitle;
                movie.MovieMaker = sameMovieMaker;
                moreMovies.Add(movie);
            }
            List <Movie> expectedOrderedMovieList = moreMovies.OrderBy(m => m.Director).ToList();

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " +
                    $"FROM \"{Movie.TableName}\" WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? ALLOW FILTERING",
                    rows => rows.WithParams(sameTitle, sameMovieMaker))
                .ThenRowsSuccess(Movie.CreateRowsResult(expectedOrderedMovieList)));

            var movieQuery = _movieTable.Where(m => m.Title == sameTitle && m.MovieMaker == sameMovieMaker);

            List <Movie> actualOrderedMovieList = movieQuery.Execute().ToList();

            Assert.AreEqual(expectedOrderedMovieList.Count, actualOrderedMovieList.Count);
            for (int i = 0; i < expectedOrderedMovieList.Count; i++)
            {
                Assert.AreEqual(expectedOrderedMovieList[i].Director, actualOrderedMovieList[i].Director);
                Assert.AreEqual(expectedOrderedMovieList[i].MainActor, actualOrderedMovieList[i].MainActor);
                Assert.AreEqual(expectedOrderedMovieList[i].MovieMaker, actualOrderedMovieList[i].MovieMaker);
            }
        }
Beispiel #15
0
        public void LinqWhere_TupleWithCompositeKeys_Scopes()
        {
            var tableName = TestUtils.GetUniqueTableName();
            var map       = new Map <TestTable>()
                            .ExplicitColumns()
                            .Column(t => t.UserId, cm => cm.WithName("id"))
                            .Column(t => t.Date, cm => cm.WithName("date"))
                            .Column(t => t.TimeColumn, cm => cm.WithName("time"))
                            .PartitionKey(t => t.UserId)
                            .ClusteringKey(t => t.Date)
                            .ClusteringKey(t => t.TimeColumn)
                            .TableName(tableName);

            var table   = new Table <TestTable>(Session, new MappingConfiguration().Define(map));
            var anomObj = new
            {
                list = new List <Tuple <int, long> > {
                    Tuple.Create(0, 0L), Tuple.Create(1, 1L), Tuple.Create(0, 2L)
                }
            };

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"SELECT date, id, time FROM {tableName} " +
                    "WHERE id = ? AND (date, time) IN ?",
                    rows => rows.WithParams(1, anomObj.list))
                .ThenRowsSuccess(new[] { "date", "id", "time" }, rows => rows.WithRow(1, 1, 1L)));

            var listInsideObjResults = table.Where(t => t.UserId == 1 && anomObj.list.Contains(Tuple.Create(t.Date, t.TimeColumn))).Execute();

            Assert.NotNull(listInsideObjResults);
            Assert.AreEqual(1, listInsideObjResults.Count());

            TestCluster.PrimeDelete();
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"SELECT date, id, time FROM {tableName} " +
                    "WHERE id = ? AND (date, time) IN ?",
                    rows => rows.WithParams(1, _tupleList))
                .ThenRowsSuccess(new[] { "date", "id", "time" }, rows => rows.WithRow(1, 1, 1L)));

            var listOuterScopeResults = table.Where(t => t.UserId == 1 && _tupleList.Contains(Tuple.Create(t.Date, t.TimeColumn))).Execute();

            Assert.NotNull(listOuterScopeResults);
            Assert.AreEqual(1, listOuterScopeResults.Count());

            TestCluster.PrimeDelete();
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    $"SELECT date, id, time FROM {tableName} " +
                    "WHERE id = ? AND (date, time) IN ?",
                    rows => rows.WithParams(1, TupleList))
                .ThenRowsSuccess(new[] { "date", "id", "time" }, rows => rows.WithRow(1, 1, 1L)));

            var listOuterStaticScopeResults = table.Where(t => t.UserId == 1 && TupleList.Contains(Tuple.Create(t.Date, t.TimeColumn))).Execute();

            Assert.NotNull(listOuterStaticScopeResults);
            Assert.AreEqual(1, listOuterStaticScopeResults.Count());
        }
Beispiel #16
0
 public void Delete_MissingWhereClause_Sync()
 {
     TestCluster.PrimeFluent(
         b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\"",
                          when => when.WithParam(true))
         .ThenSyntaxError("invalid"));
     Assert.Throws <SyntaxError>(() => _table.Select(m => m).Delete().Execute());
 }
Beispiel #17
0
        public void LinqWhere_Boolean()
        {
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"BooleanType\", \"DateTimeOffsetType\", \"DateTimeType\", \"DecimalType\", " +
                    "\"DictionaryStringLongType\", \"DictionaryStringStringType\", \"DoubleType\", \"FloatType\", " +
                    "\"GuidType\", \"Int64Type\", \"IntType\", \"ListOfGuidsType\", \"ListOfStringsType\", " +
                    "\"NullableIntType\", \"StringType\" " +
                    $"FROM \"{ManyDataTypesEntity.TableName}\" " +
                    $"WHERE \"BooleanType\" = ? " +
                    "ALLOW FILTERING",
                    p => p.WithParams(true))
                .ThenRowsSuccess(ManyDataTypesEntity.GetColumnsWithTypes()));

            //there are no records with BooleanType == true
            var rs = _manyDataTypesEntitiesTable.Where(m => m.BooleanType).Execute();

            Assert.NotNull(rs);
            var rows = rs.ToArray();

            Assert.AreEqual(0, rows.Length);
            var guid = Guid.NewGuid();
            var data = new ManyDataTypesEntity
            {
                BooleanType        = true,
                DateTimeOffsetType = DateTimeOffset.Now,
                DateTimeType       = DateTime.Now,
                DecimalType        = 10,
                DoubleType         = 10.0,
                FloatType          = 10.0f,
                GuidType           = guid,
                IntType            = 10,
                StringType         = "Boolean True"
            };

            TestCluster.PrimeDelete();
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"BooleanType\", \"DateTimeOffsetType\", \"DateTimeType\", \"DecimalType\", " +
                    "\"DictionaryStringLongType\", \"DictionaryStringStringType\", \"DoubleType\", \"FloatType\", " +
                    "\"GuidType\", \"Int64Type\", \"IntType\", \"ListOfGuidsType\", \"ListOfStringsType\", " +
                    "\"NullableIntType\", \"StringType\" " +
                    $"FROM \"{ManyDataTypesEntity.TableName}\" " +
                    $"WHERE \"BooleanType\" = ? " +
                    "ALLOW FILTERING",
                    p => p.WithParams(true))
                .ThenRowsSuccess(
                    ManyDataTypesEntity.GetColumnsWithTypes(),
                    r => r.WithRow(data.GetColumnValues())));

            rs = _manyDataTypesEntitiesTable.Where(m => m.BooleanType).Execute();
            Assert.NotNull(rs);
            rows = rs.ToArray();
            Assert.AreEqual(1, rows.Length);
            Assert.AreEqual(guid, rows[0].GuidType);
            Assert.AreEqual("Boolean True", rows[0].StringType);
            Assert.IsTrue(rows[0].BooleanType);
        }
Beispiel #18
0
 private void PrimeLinqCounterQuery(CounterEntityWithLinqAttributes counter)
 {
     TestCluster.PrimeDelete();
     TestCluster.PrimeFluent(
         b => b.WhenQuery(
             "SELECT \"Counter\", \"KeyPart1\", \"KeyPart2\" " +
             "FROM \"CounterEntityWithLinqAttributes\" " +
             "WHERE \"KeyPart1\" = ? AND \"KeyPart2\" = ?",
             when => counter.WithParams(when, "KeyPart1", "KeyPart2"))
         .ThenRowsSuccess(counter.CreateRowsResult()));
 }
        public void LinqTable(bool async)
        {
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " +
                    $"FROM \"{Movie.TableName}\" ALLOW FILTERING")
                .ThenRowsSuccess(Movie.CreateRowsResult(_movieList)));
            var table  = Session.GetTable <Movie>();
            var movies = async ? table.ExecuteAsync().GetAwaiter().GetResult().ToArray() : table.Execute().ToArray();

            Assert.AreEqual(_movieList.Count, movies.Length);
        }
Beispiel #20
0
        public void InsertingSingleValue(Type tp)
        {
            var tableName = TestUtils.GetUniqueTableName();

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

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

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

            toInsert.Add(row1);

            var isFloatingPoint = false;

            if (row1[1].GetType() == typeof(string) || row1[1].GetType() == typeof(byte[]))
            {
                var query =
                    $"INSERT INTO {tableName}(tweet_id,value) VALUES (" +
                    $"{toInsert[0][0]}, " +
                    $"{(row1[1].GetType() == typeof(byte[]) ? "0x" + CqlQueryTools.ToHex((byte[]) toInsert[0][1]) : "'" + toInsert[0][1] + "'")}" +
                    ");";
                QueryTools.ExecuteSyncNonQuery(Session, query, null);
                VerifyStatement(QueryType.Query, query, 1);
            }
            else
            {
                if (tp == typeof(Single) || tp == typeof(Double))
                {
                    isFloatingPoint = true;
                }

                var query =
                    $"INSERT INTO {tableName}(tweet_id,value) VALUES (" +
                    $"{toInsert[0][0]}, " +
                    $"{(!isFloatingPoint ? toInsert[0][1] : toInsert[0][1].GetType().GetMethod("ToString", new[] { typeof(string) }).Invoke(toInsert[0][1], new object[] { "r" }))}" +
                    ");";
                QueryTools.ExecuteSyncNonQuery(Session, query, null);
                VerifyStatement(QueryType.Query, query, 1);
            }

            TestCluster.PrimeFluent(
                b => b.WhenQuery($"SELECT * FROM {tableName};", when => when.WithConsistency(ConsistencyLevel.LocalOne))
                .ThenRowsSuccess(new[] { "tweet_id", "value" }, r => r.WithRow(toInsert[0][0], toInsert[0][1])));

            QueryTools.ExecuteSyncQuery(
                Session, $"SELECT * FROM {tableName};", Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), toInsert);
        }
Beispiel #21
0
        private void PrimeLinqCounterRangeQuery(
            IEnumerable <CounterEntityWithLinqAttributes> counters,
            string tableName   = "CounterEntityWithLinqAttributes",
            bool caseSensitive = true)
        {
            var cql = caseSensitive
                ? $"SELECT \"Counter\", \"KeyPart1\", \"KeyPart2\" FROM \"{tableName}\""
                : $"SELECT Counter, KeyPart1, KeyPart2 FROM {tableName}";

            TestCluster.PrimeDelete();
            TestCluster.PrimeFluent(b => b.WhenQuery(cql).ThenRowsSuccess(AddRows(counters)));
        }
Beispiel #22
0
        public void LinqOrderBy_Unrestricted_Async()
        {
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " +
                    $"FROM \"{Movie.TableName}\" ORDER BY \"mainGuy\" ALLOW FILTERING")
                .ThenServerError(ServerError.Invalid, "ORDER BY is only supported when the partition key is restricted by an EQ or an IN."));
            var ex = Assert.ThrowsAsync <InvalidQueryException>(
                async() => await _movieTable.OrderBy(m => m.MainActor).ExecuteAsync().ConfigureAwait(false));
            const string expectedException = "ORDER BY is only supported when the partition key is restricted by an EQ or an IN.";

            Assert.AreEqual(expectedException, ex.Message);
        }
Beispiel #23
0
        public void TableCreate_CreateIfNotExists_KeyspaceOverride_NoSuchKeyspace()
        {
            var uniqueTableName = TestUtils.GetUniqueTableName();
            var uniqueKsName    = TestUtils.GetUniqueKeyspaceName();

            TestCluster.PrimeFluent(
                b => b.WhenQuery(string.Format(CreateTable.CreateCqlFormatStr, $"\"{uniqueKsName}\".\"{uniqueTableName}\""))
                .ThenServerError(ServerError.ConfigError, "msg"));

            var table = new Table <AllDataTypesEntity>(Session, new MappingConfiguration(), uniqueTableName, uniqueKsName);

            Assert.Throws <InvalidConfigurationInQueryException>(() => table.CreateIfNotExists());
        }
Beispiel #24
0
        public void LinqWhere_With_LocalSerial_ConsistencyLevel_Does_Not_Throw()
        {
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " +
                    $"FROM \"{Movie.TableName}\" WHERE \"movie_maker\" = ? AND \"unique_movie_title\" = ? ALLOW FILTERING",
                    rows => rows.WithParams("dum", "doesnt_matter").WithConsistency(ConsistencyLevel.LocalSerial))
                .ThenRowsSuccess(Movie.GetColumns()));

            Assert.DoesNotThrow(() =>
                                _movieTable.Where(m => m.MovieMaker == "dum" && m.Title == "doesnt_matter")
                                .SetConsistencyLevel(ConsistencyLevel.LocalSerial).Execute());
        }
Beispiel #25
0
        public void Delete_MissingKey_Sync()
        {
            var table = new Table <AllDataTypesEntity>(Session, new MappingConfiguration());

            TestCluster.PrimeFluent(
                b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"boolean_type\" = ?",
                                 when => when.WithParam(true))
                .ThenServerError(ServerError.Invalid, "invalid"));

            var selectQuery = table.Select(m => m).Where(m => m.BooleanType == true);
            var deleteQuery = selectQuery.Delete();

            Assert.Throws <InvalidQueryException>(() => deleteQuery.Execute());
        }
Beispiel #26
0
        public void First_With_Serial_ConsistencyLevel()
        {
            var expectedMovie = _movieList.First();

            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " +
                    $"FROM \"{Movie.TableName}\" LIMIT ? ALLOW FILTERING",
                    rows => rows.WithParams(1))
                .ThenRowsSuccess(expectedMovie.CreateRowsResult()));
            var actualMovie = _movieTable.First().SetConsistencyLevel(ConsistencyLevel.Serial).Execute();

            Movie.AssertEquals(expectedMovie, actualMovie);
        }
Beispiel #27
0
        public void Delete_IfExists_ClusteringKeyOmitted()
        {
            var table = new Table <AllDataTypesEntity>(Session, new MappingConfiguration());
            AllDataTypesEntity entityToDelete = _entityList[0];

            TestCluster.PrimeFluent(
                b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? IF EXISTS",
                                 when => when.WithParam(entityToDelete.StringType))
                .ThenServerError(ServerError.Invalid, "invalid"));

            var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType);
            var deleteQuery = selectQuery.Delete().IfExists();

            Assert.Throws <InvalidQueryException>(() => deleteQuery.Execute());
        }
Beispiel #28
0
        public void Batch_UsingTwoTables_OneInvalidTable()
        {
            var batch = new BatchStatement();

            TestCluster.PrimeFluent(
                b => b.WhenBatch(when => when.WithQueries(
                                     $@"INSERT INTO {_tableName} (id, label, number) VALUES ({400}, '{"label1"}', {1})",
                                     $@"INSERT INTO table_randomnonexistent (id, label, number) VALUES ({2}, '{"label2"}', {2})"))
                .ThenServerError(ServerError.Invalid, "msg"));

            batch.Add(new SimpleStatement($@"INSERT INTO {_tableName} (id, label, number) VALUES ({400}, '{"label1"}', {1})"));
            batch.Add(new SimpleStatement($@"INSERT INTO table_randomnonexistent (id, label, number) VALUES ({2}, '{"label2"}', {2})"));

            Assert.Throws <InvalidQueryException>(() => Session.Execute(batch));
        }
        public void SessionExecuteAsyncPreparedToSync()
        {
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT key FROM system.local WHERE key = ?",
                    when => when.WithParam("local"))
                .ThenRowsSuccess(new[] { "key" }, r => r.WithRow("local")));

            var statement = Session.Prepare("SELECT key FROM system.local WHERE key = ?");
            var task      = Session.ExecuteAsync(statement.Bind("local"));
            //forcing it to execute sync for testing purposes
            var rowset = task.Result;

            Assert.True(rowset.Any(), "Returned result should contain rows.");
        }
Beispiel #30
0
        public void LinqTable_Take_Zero_Sync(bool async)
        {
            TestCluster.PrimeFluent(
                b => b.WhenQuery(
                    "SELECT \"director\", \"list\", \"mainGuy\", \"movie_maker\", \"unique_movie_title\", \"yearMade\" " +
                    $"FROM \"{Movie.TableName}\" ALLOW FILTERING")
                .ThenRowsSuccess(Movie.CreateRowsResult(_movieList)));

            // Without where clause
            List <Movie> actualMovieList = async
                ? _movieTable.Take(0).ExecuteAsync().GetAwaiter().GetResult().ToList()
                : _movieTable.Take(0).Execute().ToList();

            Assert.AreEqual(5, actualMovieList.Count());
        }