public void ExecuteNonQueryInsertAndSelectTest() { _connection.Open(); var cmd = _connection.CreateCommand(); string keyspaceName = "keyspace_ado_1"; cmd.CommandText = string.Format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspaceName, 3); cmd.ExecuteNonQuery(); _connection.ChangeDatabase(keyspaceName); string tableName = "table_ado_1"; cmd.CommandText = string.Format(@" CREATE TABLE {0}( tweet_id uuid, author text, body text, isok boolean, PRIMARY KEY(tweet_id))", tableName); cmd.ExecuteNonQuery(); var longQ = new StringBuilder(); longQ.AppendLine("BEGIN BATCH "); int RowsNo = 300; for (int i = 0; i < RowsNo; i++) { longQ.AppendFormat(@" INSERT INTO {0} (tweet_id, author, isok, body) VALUES ({1},'test{2}',{3},'body{2}');", tableName, Guid.NewGuid(), i, i % 2 == 0 ? "false" : "true"); } longQ.AppendLine("APPLY BATCH;"); cmd.CommandText = longQ.ToString(); cmd.ExecuteNonQuery(); cmd.CommandText = string.Format(@"SELECT * from {0} LIMIT 10000;", tableName); var reader = cmd.ExecuteReader(); var counter = 0; while (reader.Read()) { Assert.AreEqual(4, reader.FieldCount); counter++; } Assert.AreEqual(RowsNo, counter); cmd.CommandText = string.Format(@"DROP TABLE {0};", tableName); cmd.ExecuteNonQuery(); cmd.CommandText = string.Format(@"DROP KEYSPACE {0};", keyspaceName); cmd.ExecuteNonQuery(); }
public void ConnectToUnknownDb() { try { //Act using( var connection = new CqlConnection( "Servers=localhost;Database=DoesNotExist;username=cassandra;password=cassandra;loggerfactory=debug;loglevel=verbose") ) { connection.Open(); //invoke random command, as it will try to change database on the connection var command = new CqlCommand(connection, "select * from randomTable;"); var reader = command.ExecuteReader(); reader.Dispose(); } } catch(Exception ex) { Assert.IsInstanceOfType(ex, typeof(InvalidException)); return; } Assert.Fail("Exception should have been thrown;"); }
public static void Init(TestContext context) { const string createKsCql = @"CREATE KEYSPACE Test WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1} and durable_writes = 'false';"; const string createTableCql = @"create table Test.BasicFlow (id int primary key, value text, ignored text);"; using(var connection = new CqlConnection(ConnectionString)) { connection.SetConnectionTimeout(0); connection.Open(); try { var createKs = new CqlCommand(connection, createKsCql); createKs.ExecuteNonQuery(); } catch(AlreadyExistsException) { //ignore } try { var createTable = new CqlCommand(connection, createTableCql); createTable.ExecuteNonQuery(); } catch(AlreadyExistsException) { } } }
public static void ClassInit(TestContext context) { using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); try { var createKs = new CqlCommand(connection, CreateKsCql); createKs.ExecuteNonQuery(); } catch(AlreadyExistsException) { //ignore } try { var createTable = new CqlCommand(connection, CreateTableCql); createTable.ExecuteNonQuery(); } catch(AlreadyExistsException) { //ignore } } }
/// <summary> /// Insert retrived data into destination table /// </summary> /// <param name="server">ip or name of the destination database</param> /// <param name="keyspace">name of the keyspace to use for the insert</param> /// <param name="columnFamily">name of the column family for the insert</param> /// <param name="sourceData">data retrieved from the source</param> private static void InsertIntoDest(string server, string keyspace, string columnFamily, List <dynamic> sourceData, TransferResultsInfo info) { try { CqlConnection destConn = new CqlConnection("Contact Points=" + server, server); CqlCommand destCmd = new CqlCommand(); destConn.Open(); destConn.ChangeDatabase(keyspace); destCmd.Connection = destConn; destCmd.CommandText = "SELECT COUNT(*) FROM " + columnFamily; info.OriginalDestCount = Convert.ToInt32(destCmd.ExecuteScalar()); destCmd.InsertDynamicList(sourceData, columnFamily); destCmd.CommandText = "SELECT COUNT(*) FROM " + columnFamily; info.AfterDestCount = Convert.ToInt32(destCmd.ExecuteScalar()); //cleanup destCmd.Connection.Close(); destCmd.Connection.Dispose(); destCmd.Dispose(); } catch (Exception ex) { info.Message = "Error writting to destination: \r\n" + ex.Message; } }
/// <summary> /// Run the provided query against the source database to get the data to be moved. /// </summary> /// <param name="server">ip or name of the source database</param> /// <param name="keyspace">name of the keyspace to use for the source query</param> /// <param name="query">query to get source data</param> /// <param name="gotSourceData">Data retrieved</param> /// <param name="sourceData">indicator of if an error was thrown</param> private static void GetSourceData(string server, string keyspace, string query, TransferResultsInfo info, out bool gotSourceData, out List <dynamic> sourceData) { sourceData = new List <dynamic>(); gotSourceData = true; try { CqlConnection srcConn = new CqlConnection("Contact Points=" + server, server); CqlCommand srcCmd = new CqlCommand(); srcConn.Open(); srcConn.ChangeDatabase(keyspace); srcCmd.Connection = srcConn; srcCmd.CommandType = CommandType.Text; srcCmd.CommandText = query; sourceData = srcCmd.ExecuteDynamics(); info.SourceCount = sourceData.Count; //cleanup srcCmd.Connection.Close(); srcCmd.Connection.Dispose(); srcCmd.Dispose(); } catch (Exception ex) { info.Message = "Error getting source data: \r\n" + ex.Message; gotSourceData = false; } }
public static void ClassInit(TestContext context) { using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); try { var createKs = new CqlCommand(connection, CreateKsCql); createKs.ExecuteNonQuery(); } catch (AlreadyExistsException) { //ignore } try { var createTable = new CqlCommand(connection, CreateTableCql); createTable.ExecuteNonQuery(); } catch (AlreadyExistsException) { //ignore } } }
public void Init() { const string createKsCql = @"CREATE KEYSPACE Test WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1} and durable_writes = 'false';"; const string createTableCql = @"create table Test.BasicFlow (id int primary key, value text);"; const string truncateTableCql = @"truncate Test.BasicFlow;"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); try { var createKs = new CqlCommand(connection, createKsCql); createKs.ExecuteNonQuery(); } catch (AlreadyExistsException) { //ignore } try { var createTable = new CqlCommand(connection, createTableCql); createTable.ExecuteNonQuery(); } catch (AlreadyExistsException) { var truncTable = new CqlCommand(connection, truncateTableCql); truncTable.ExecuteNonQuery(); } } }
public void Init() { using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); var truncTable = new CqlCommand(connection, TruncateTableCql); truncTable.ExecuteNonQuery(); } }
public static void Init(TestContext context) { const string createConnection = "Server=localhost;username=cassandra;password=cassandra"; const string createKsCql = @"CREATE KEYSPACE LinqTest WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1} and durable_writes = 'false';"; const string createTableCql = @"create table linqtest.myvalue (id int primary key, value text, ignored text);"; using (var connection = new CqlConnection(createConnection)) { connection.SetConnectionTimeout(0); connection.Open(); try { var createKs = new CqlCommand(connection, createKsCql); createKs.ExecuteNonQuery(); var createTable = new CqlCommand(connection, createTableCql); createTable.ExecuteNonQuery(); using (var transaction = connection.BeginTransaction()) { transaction.BatchType = CqlBatchType.Unlogged; var insert = new CqlCommand(connection, "insert into linqtest.myvalue (id,value) values(?,?)"); insert.Transaction = transaction; insert.Prepare(); for (int i = 0; i < 10000; i++) { insert.Parameters[0].Value = i; insert.Parameters[1].Value = "Hallo " + i; insert.ExecuteNonQuery(); } transaction.Commit(); } } catch (AlreadyExistsException) { //ignore } } CqlConnection.Shutdown(createConnection); }
public static void Init(TestContext context) { const string createKsCql = @"CREATE KEYSPACE TestUDT WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1} and durable_writes = 'false';"; const string createAddressType = @"create type TestUDT.TAddress (street text, number int);"; const string createUserType = @"CREATE type TestUDT.TUser (name text, password blob, address frozen<TAddress>, phones list<text>);"; const string createTableCql = @"create table TestUDT.Members (id int primary key, user frozen<TUser>, comment frozen<tuple<text,text>>);"; const string createTable2Cql = @"create table TestUDT.Groups (id int primary key, members set<frozen<tuple<int, frozen<TUser>>>>);"; using(var connection = new CqlConnection(ConnectionString)) { connection.SetConnectionTimeout(0); connection.Open(); Cassandra210OrUp = string.CompareOrdinal(connection.ServerVersion, "2.1.0") >= 0; if(!Cassandra210OrUp) return; try { var createKs = new CqlCommand(connection, createKsCql); createKs.ExecuteNonQuery(); var createAddress = new CqlCommand(connection, createAddressType); createAddress.ExecuteNonQuery(); var createUser = new CqlCommand(connection, createUserType); createUser.ExecuteNonQuery(); var createTable = new CqlCommand(connection, createTableCql); createTable.ExecuteNonQuery(); var createTable2 = new CqlCommand(connection, createTable2Cql); createTable2.ExecuteNonQuery(); } catch(AlreadyExistsException) { } } }
static void SetupDatabase() { const string createKsCql = @"CREATE KEYSPACE linqperftest WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1} and durable_writes = 'false';"; const string createTableCql = @"create table linqperftest.myvalue (id int primary key, value text, ignored text);"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); try { var createKs = new CqlCommand(connection, createKsCql); createKs.ExecuteNonQuery(); var createTable = new CqlCommand(connection, createTableCql); createTable.ExecuteNonQuery(); using (var transaction = connection.BeginTransaction()) { transaction.BatchType = CqlBatchType.Unlogged; var insert = new CqlCommand(connection, "insert into linqperftest.myvalue (id,value) values(?,?)"); insert.Transaction = transaction; insert.Prepare(); for (int i = 0; i < 10000; i++) { insert.Parameters[0].Value = i; insert.Parameters[1].Value = "Hallo " + i; insert.ExecuteNonQuery(); } transaction.Commit(); } } catch (AlreadyExistsException) { } } }
public static void Cleanup() { const string dropCql = @"drop keyspace Test;"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); try { var drop = new CqlCommand(connection, dropCql); drop.ExecuteNonQuery(); } catch (InvalidException) { //ignore } } }
public void DefaultDeserializeTest() { const string insertCql = @"insert into Test.Types(aInt) values (1);"; const string selectCql = "select * from Test.Types limit 1;"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); Types result = null; using (var reader = selectCmd.ExecuteReader <Types>()) { if (reader.Read()) { result = reader.Current; } } Assert.IsNotNull(result); Assert.AreEqual(result.aASCIIString, default(string)); Assert.AreEqual(result.aVarcharString, default(string)); Assert.AreEqual(result.aVarint, default(BigInteger)); Assert.AreEqual(result.aTextString, default(string)); Assert.AreEqual(result.aBool, default(bool)); Assert.AreEqual(result.aDouble, default(double)); Assert.AreEqual(result.aFloat, default(float)); Assert.AreEqual(result.aInet, default(IPAddress)); Assert.AreEqual(result.aLong, default(long)); Assert.AreEqual(result.aTimeUUID, default(Guid)); Assert.AreEqual(result.aUUID, default(Guid)); Assert.AreEqual(result.aBlob, default(byte[])); Assert.AreEqual(result.aList, default(List <string>)); Assert.AreEqual(result.aSet, default(HashSet <int>)); Assert.AreEqual(result.aMap, default(Dictionary <long, string>)); } }
public void NullableDeserializeTest() { const string insertCql = @"insert into Test.Types(aInt) values (4);"; const string selectCql = "select * from Test.Types limit 1;"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); NullableTypes result = null; using (var reader = selectCmd.ExecuteReader <NullableTypes>()) { if (reader.Read()) { result = reader.Current; } } Assert.IsNotNull(result); Assert.IsNull(result.aASCIIString); Assert.IsNull(result.aVarcharString); Assert.IsNull(result.aVarint); Assert.IsNull(result.aTextString); Assert.IsNull(result.aBool); Assert.IsNull(result.aDouble); Assert.IsNull(result.aFloat); Assert.IsNull(result.aInet); Assert.IsNull(result.aLong); Assert.IsNull(result.aTimeUUID); Assert.IsNull(result.aUUID); Assert.IsNull(result.aBlob); Assert.IsNull(result.aList); Assert.IsNull(result.aSet); Assert.IsNull(result.aMap); } }
public static void Cleanup() { const string dropCql = @"drop keyspace Test;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); try { var drop = new CqlCommand(connection, dropCql); drop.ExecuteNonQuery(); } catch(InvalidException) { //ignore } } CqlConnection.ShutdownAll(); }
public void AuthenticateError() { try { using( var connection = new CqlConnection( "Servers=localhost;username=doesNotExist;password=too;loggerfactory=debug;loglevel=verbose") ) { connection.Open(); } } catch(AuthenticationException uex) { Debug.WriteLine("Expected Unauthenticated exception: {0}", uex); } catch(Exception ex) { Assert.Fail("Wrong exception thrown: {0}", ex.GetType().Name); } }
public void TransactionAddAfterDisposeThrowsException() { const string insertCql = @"insert into Test.BasicFlow (id,value) values (6000, 'Transaction 6000');"; const string insertCql2 = @"insert into Test.BasicFlow (id,value) values (6001, 'Transaction 6001');"; //Act using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); //skip if server version too low if(string.CompareOrdinal(connection.ServerVersion, "2.0.0") < 0) throw new ObjectDisposedException("dummy"); //as expected for this test //create transaction var transaction = connection.BeginTransaction(); //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.Transaction = transaction; cmd.ExecuteNonQuery(); //commit transaction.Commit(); //dispose transaction.Dispose(); //add again var cmd2 = new CqlCommand(connection, insertCql2, CqlConsistency.One); cmd2.Transaction = transaction; cmd2.ExecuteNonQuery(); } }
public void SerializeNullableObjectOutDefaultsTest() { const string insertCql = @"insert into LinqTest.Types(aInt) values (1);"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); } using (var context = new SerializationContext()) { var result = context.NullableTypes.FirstOrDefault(); Assert.IsNotNull(result); Assert.IsNull(result.aASCIIString); Assert.IsNull(result.aVarcharString); Assert.IsNull(result.aVarint); Assert.IsNull(result.aTextString); Assert.IsNull(result.aBool); Assert.IsNull(result.aDecimal); Assert.IsNull(result.aDouble); Assert.IsNull(result.aFloat); Assert.IsNull(result.aInet); Assert.IsNull(result.aLong); Assert.IsNull(result.aTimeUUID); Assert.IsNull(result.aUUID); Assert.IsNull(result.aBlob); Assert.IsNull(result.aList); Assert.IsNull(result.aSet); Assert.IsNull(result.aMap); } }
public void complexTest() { connection.Open(); var cmd = connection.CreateCommand(); string keyspaceName = "keyspace" + Guid.NewGuid().ToString("N").ToLower(); cmd.CommandText = string.Format(@"CREATE KEYSPACE {0} WITH replication = {{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }};" , keyspaceName); cmd.ExecuteNonQuery(); connection.ChangeDatabase(keyspaceName); string tableName = "table" + Guid.NewGuid().ToString("N").ToLower(); cmd.CommandText = string.Format(@"CREATE TABLE {0}( tweet_id uuid, author text, body text, isok boolean, PRIMARY KEY(tweet_id))", tableName); cmd.ExecuteNonQuery(); StringBuilder longQ = new StringBuilder(); longQ.AppendLine("BEGIN BATCH "); int RowsNo = 2000; for (int i = 0; i < RowsNo; i++) { longQ.AppendFormat(@"INSERT INTO {0} ( tweet_id, author, isok, body) VALUES ({1},'test{2}',{3},'body{2}');", tableName, Guid.NewGuid().ToString(), i, i % 2 == 0 ? "false" : "true"); } longQ.AppendLine("APPLY BATCH;"); cmd.CommandText = longQ.ToString(); cmd.ExecuteNonQuery(); cmd.CommandText = string.Format(@"SELECT * from {0} LIMIT 10000;", tableName); var reader = cmd.ExecuteReader(); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { Console.Write(reader.GetValue(i).ToString() + "|"); } Console.WriteLine(); } cmd.CommandText = string.Format(@"DROP TABLE {0};", tableName); cmd.ExecuteNonQuery(); cmd.CommandText = string.Format(@"DROP KEYSPACE {0};", keyspaceName); cmd.ExecuteNonQuery(); }
public void Init() { using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var truncTable = new CqlCommand(connection, TruncateTableCql); truncTable.ExecuteNonQuery(); } }
public void SerializeObjectInOutNullTest() { const string insertCql = @"insert into SerializationTest.Types( aInt, aLong , aVarint , aTextString , aVarcharString , aASCIIString , aBlob , aBool , aDecimal , aDouble , aFloat , aTimestamp , aTimeUUID , aUUID , aInet , aList, aSet, aMap) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var values = new NullableTypes { aInt = 3, aASCIIString = null, aBlob = null, aBool = null, aDecimal = null, aDouble = null, aFloat = null, aInet = null, aLong = null, aTextString = null, aVarcharString = null, aTimeUUID = null, aUUID = null, aTimestamp = null, aVarint = null, aList = null, aSet = null, aMap = null }; var insertCmd = new CqlCommand(connection, insertCql); insertCmd.Prepare(); insertCmd.Parameters.Set(values); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); NullableTypes result = null; using(var reader = selectCmd.ExecuteReader<NullableTypes>()) { if(reader.Read()) result = reader.Current; } Assert.IsNotNull(result); Assert.IsNull(result.aASCIIString); Assert.IsNull(result.aVarcharString); Assert.IsNull(result.aVarint); Assert.IsNull(result.aTextString); Assert.IsNull(result.aBool); Assert.IsNull(result.aDecimal); Assert.IsNull(result.aDouble); Assert.IsNull(result.aFloat); Assert.IsNull(result.aInet); Assert.IsNull(result.aLong); Assert.IsNull(result.aTimeUUID); Assert.IsNull(result.aUUID); Assert.IsNull(result.aBlob); Assert.IsNull(result.aList); Assert.IsNull(result.aSet); Assert.IsNull(result.aMap); } }
public void SerializeObjectInOutDefaultsTest() { const string insertCql = @"insert into SerializationTest.Types( aInt, aLong , aVarint , aTextString , aVarcharString , aASCIIString , aBlob , aBool , aDecimal , aDouble , aFloat , aTimestamp , aTimeUUID , aUUID , aInet , aList, aSet, aMap) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var values = new Types { aInt = 2, aASCIIString = default(string), aBlob = default(byte[]), aBool = default(bool), aDecimal = default(decimal), aDouble = default(double), aFloat = default(float), aInet = default(IPAddress), aLong = default(long), aTextString = default(string), aVarcharString = default(string), aTimeUUID = TimeGuid.Default, aUUID = default(Guid), aTimestamp = default(DateTime), aVarint = default(BigInteger), aList = default(List<string>), aSet = default(HashSet<int>), aMap = default(Dictionary<long, string>) }; var insertCmd = new CqlCommand(connection, insertCql); insertCmd.Prepare(); insertCmd.Parameters.Set(values); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); Types result = null; using(var reader = selectCmd.ExecuteReader<Types>()) { if(reader.Read()) result = reader.Current; } Assert.IsNotNull(result); Assert.AreEqual(result.aASCIIString, default(string)); Assert.AreEqual(result.aVarcharString, default(string)); Assert.AreEqual(result.aVarint, default(BigInteger)); Assert.AreEqual(result.aTextString, default(string)); Assert.AreEqual(result.aBool, default(bool)); Assert.AreEqual(result.aDecimal, default(decimal)); Assert.AreEqual(result.aDouble, default(double)); Assert.AreEqual(result.aFloat, default(float)); Assert.AreEqual(result.aInet, default(IPAddress)); Assert.AreEqual(result.aLong, default(long)); Assert.AreEqual(result.aTimeUUID, TimeGuid.Default); Assert.AreEqual(result.aUUID, default(Guid)); Assert.AreEqual(result.aBlob, default(byte[])); Assert.AreEqual(result.aList, default(List<string>)); Assert.AreEqual(result.aSet, default(HashSet<int>)); Assert.AreEqual(result.aMap, default(Dictionary<long, string>)); } }
public void SerializeOutNullTest() { const string insertCql = @"insert into SerializationTest.Types(aInt) values (1);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { string aAsciiString; string aVarcharString; BigInteger? aVarint; string aTextString; bool? aBool; decimal? aDecimal; double? aDouble; float? aFloat; IPAddress aInet; long? aLong; Guid? aTimeUUID; Guid? aUUID; byte[] aBlob; List<string> aList; HashSet<int> aSet; Dictionary<long, string> aMap; connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); using(var reader = selectCmd.ExecuteReader()) { if(reader.Read()) { aAsciiString = reader["aasciistring"] as string; aVarcharString = reader["avarcharstring"] as string; aVarint = reader["avarint"] as BigInteger?; aTextString = reader["atextstring"] as string; aBool = reader["abool"] as bool?; aDecimal = reader["adecimal"] as decimal?; aDouble = reader["adouble"] as double?; aFloat = reader["afloat"] as float?; aInet = reader["ainet"] as IPAddress; aLong = reader["along"] as long?; aTimeUUID = reader["atimeuuid"] as Guid?; aUUID = reader["auuid"] as Guid?; aBlob = reader["ablob"] as byte[]; aList = reader["alist"] as List<string>; aSet = reader["aset"] as HashSet<int>; aMap = reader["amap"] as Dictionary<long, string>; } else throw new Exception("No row returned!"); } Assert.AreEqual(aAsciiString, default(string)); Assert.AreEqual(aVarcharString, default(string)); Assert.AreEqual(aVarint, default(BigInteger?)); Assert.AreEqual(aTextString, default(string)); Assert.AreEqual(aBool, default(bool?)); Assert.AreEqual(aDecimal, default(decimal?)); Assert.AreEqual(aDouble, default(double?)); Assert.AreEqual(aFloat, default(float?)); Assert.AreEqual(aInet, default(IPAddress)); Assert.AreEqual(aLong, default(long?)); Assert.AreEqual(aTimeUUID, default(Guid?)); Assert.AreEqual(aUUID, default(Guid?)); Assert.AreEqual(aBlob, default(byte[])); Assert.AreEqual(aList, default(List<string>)); Assert.AreEqual(aSet, default(HashSet<int>)); Assert.AreEqual(aMap, default(Dictionary<long, string>)); } }
public void NullableSerializeTest() { const string insertCql = @"insert into Test.Types( aInt, aLong , aVarint , aTextString , aVarcharString , aASCIIString , aBlob , aBool , aDouble , aFloat , aTimestamp , aTimeUUID , aUUID , aInet , aList, aSet, aMap) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; const string selectCql = "select * from Test.Types limit 1;"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); var values = new NullableTypes { aInt = 3, aASCIIString = null, aBlob = null, aBool = null, aDouble = null, aFloat = null, aInet = null, aLong = null, aTextString = null, aVarcharString = null, aTimeUUID = null, aUUID = null, aTimestamp = null, aVarint = null, aList = null, aSet = null, aMap = null }; var insertCmd = new CqlCommand(connection, insertCql); insertCmd.Prepare(); insertCmd.Parameters.Set(values); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); NullableTypes result = null; using (var reader = selectCmd.ExecuteReader <NullableTypes>()) { if (reader.Read()) { result = reader.Current; } } Assert.IsNotNull(result); Assert.IsNull(result.aASCIIString); Assert.IsNull(result.aVarcharString); Assert.IsNull(result.aVarint); Assert.IsNull(result.aTextString); Assert.IsNull(result.aBool); Assert.IsNull(result.aDouble); Assert.IsNull(result.aFloat); Assert.IsNull(result.aInet); Assert.IsNull(result.aLong); Assert.IsNull(result.aTimeUUID); Assert.IsNull(result.aUUID); Assert.IsNull(result.aBlob); Assert.IsNull(result.aList); Assert.IsNull(result.aSet); Assert.IsNull(result.aMap); } }
public void BasicInsertSelectSynchronous() { //Assume const string insertCql = @"insert into Test.BasicFlow (id,value) values (12367,'Hallo 12367');"; const string retrieveCql = @"select * from Test.BasicFlow;"; //Act using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.ExecuteNonQuery(); //select data var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One); selectCmd.CommandTimeout = Timeout.Infinite; selectCmd.Prepare(); CqlDataReader reader = selectCmd.ExecuteReader(); Assert.AreEqual(1, reader.Count); if (reader.Read()) { Assert.AreEqual(12367, reader["id"]); Assert.AreEqual("Hallo 12367", reader["value"]); Assert.AreEqual(DBNull.Value, reader["ignored"]); } else { Assert.Fail("Read should have succeeded"); } } }
// ReSharper disable InconsistentNaming public void Issue19_PrepareAndSelectCountStar() // ReSharper restore InconsistentNaming { //Assume const string insertCql = @"select count(*) from system.schema_keyspaces;"; long count; //Act using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); //known issue in Cassandra 2.0.0 and 2.0.1. Prepare returns wrong results for count(*) queries Assert.IsNotNull(connection.ServerVersion); if(connection.ServerVersion.Equals("2.0.0") || connection.ServerVersion.Equals("2.0.1")) return; //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.Quorum); cmd.Prepare(); count = (long)(cmd.ExecuteScalar()); } Assert.IsTrue(count > 0, "Count should be larger than zero"); }
public void TransactionResetAfterDispose() { const string insertCql = @"insert into Test.BasicFlow (id,value) values (7000, 'Transaction 7000');"; const string insertCql2 = @"insert into Test.BasicFlow (id,value) values (7001, 'Transaction 7001');"; //Act using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); //skip if server version too low if(string.CompareOrdinal(connection.ServerVersion, "2.0.0") < 0) return; //create transaction var transaction = connection.BeginTransaction(); //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.Transaction = transaction; cmd.ExecuteNonQuery(); //commit transaction.Commit(); //dispose transaction.Dispose(); //reset transaction to empty state, such that it can be reused transaction.Reset(); //add again var cmd2 = new CqlCommand(connection, insertCql2, CqlConsistency.One); cmd2.Transaction = transaction; cmd2.ExecuteNonQuery(); transaction.Commit(); transaction.Dispose(); } }
public void TransactionCommitAfterRollbackThrowsException() { const string insertCql = @"insert into Test.BasicFlow (id,value) values (8000, 'Transaction 8000');"; //Act using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); //create transaction using(var transaction = connection.BeginTransaction()) { //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.Transaction = transaction; cmd.ExecuteNonQuery(); //rollback transaction.Rollback(); //commit -> throws error transaction.Commit(); } } }
public void TransactionRollbackAfterCommitThrowsException() { const string insertCql = @"insert into Test.BasicFlow (id,value) values (8000, 'Transaction 8000');"; //Act using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); //skip if server version too low if(string.CompareOrdinal(connection.ServerVersion, "2.0.0") < 0) throw new InvalidOperationException("as expected by test"); //create transaction using(var transaction = connection.BeginTransaction()) { //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.Transaction = transaction; cmd.ExecuteNonQuery(); //commit transaction.Commit(); //rollback -> throws error transaction.Rollback(); } } }
public void SerializeInOutTest() { const string insertCql = @"insert into SerializationTest.Types( aInt, aLong , aVarint , aTextString , aVarcharString , aASCIIString , aBlob , aBool , aDecimal , aDouble , aFloat , aTimestamp , aTimeUUID , aUUID , aInet , aList, aSet, aMap) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.Prepare(); insertCmd.Parameters["aasciistring"].Value = "hello world!"; insertCmd.Parameters["ablob"].Value = new byte[] {1, 2, 3, 4}; insertCmd.Parameters["abool"].Value = true; insertCmd.Parameters["adecimal"].Value = -1234567890.0987654321m; insertCmd.Parameters["adouble"].Value = 1.234; insertCmd.Parameters["afloat"].Value = 5.789f; insertCmd.Parameters["ainet"].Value = new IPAddress(new byte[] {127, 0, 0, 1}); insertCmd.Parameters["aint"].Value = 10; insertCmd.Parameters["along"].Value = 56789012456; insertCmd.Parameters["atextstring"].Value = "some other text with \u005C unicode"; insertCmd.Parameters["avarcharstring"].Value = "some other varchar with \u005C unicode"; insertCmd.Parameters["atimeuuid"].Value = DateTime.Now.GenerateTimeBasedGuid(); insertCmd.Parameters["auuid"].Value = Guid.NewGuid(); insertCmd.Parameters["atimestamp"].Value = DateTime.Now; insertCmd.Parameters["avarint"].Value = new BigInteger(12345678901234); insertCmd.Parameters["alist"].Value = new List<string> {"string 1", "string 2"}; insertCmd.Parameters["aset"].Value = new HashSet<int> {1, 3, 3}; insertCmd.Parameters["amap"].Value = new Dictionary<long, string> {{1, "value 1"}, {2, "value 2"}, {3, "value 3"}}; insertCmd.ExecuteNonQuery(); string aAsciiString; string aVarcharString; BigInteger aVarint; string aTextString; bool aBool; decimal aDecimal; double aDouble; float aFloat; IPAddress aInet; long aLong; Guid aTimeUUID; Guid aUUID; byte[] aBlob; List<string> aList; HashSet<int> aSet; Dictionary<long, string> aMap; var selectCmd = new CqlCommand(connection, selectCql); using(var reader = selectCmd.ExecuteReader()) { if(reader.Read()) { aAsciiString = reader.GetString(reader.GetOrdinal("aasciistring")); aVarcharString = reader.GetString(reader.GetOrdinal("avarcharstring")); aVarint = reader.GetBigInteger(reader.GetOrdinal("avarint")); aTextString = reader.GetString(reader.GetOrdinal("atextstring")); aBool = reader.GetBoolean(reader.GetOrdinal("abool")); aDecimal = reader.GetDecimal(reader.GetOrdinal("adecimal")); aDouble = reader.GetDouble(reader.GetOrdinal("adouble")); aFloat = reader.GetFloat(reader.GetOrdinal("afloat")); aInet = reader.GetIPAddress(reader.GetOrdinal("ainet")); aLong = reader.GetInt64(reader.GetOrdinal("along")); aTimeUUID = reader.GetGuid(reader.GetOrdinal("atimeuuid")); aUUID = reader.GetGuid(reader.GetOrdinal("auuid")); aBlob = reader.GetBytes(reader.GetOrdinal("ablob")); aList = reader.GetList<string>(reader.GetOrdinal("alist")); aSet = reader.GetSet<int>(reader.GetOrdinal("aset")); aMap = reader.GetDictionary<long, string>(reader.GetOrdinal("amap")); } else throw new Exception("No row returned!"); } Assert.AreEqual(insertCmd.Parameters["aasciistring"].Value, aAsciiString); Assert.AreEqual(insertCmd.Parameters["avarcharstring"].Value, aVarcharString); Assert.AreEqual(insertCmd.Parameters["avarint"].Value, aVarint); Assert.AreEqual(insertCmd.Parameters["atextstring"].Value, aTextString); Assert.AreEqual(insertCmd.Parameters["abool"].Value, aBool); Assert.AreEqual(insertCmd.Parameters["adecimal"].Value, aDecimal); Assert.AreEqual(insertCmd.Parameters["adouble"].Value, aDouble); Assert.AreEqual(insertCmd.Parameters["afloat"].Value, aFloat); Assert.AreEqual(insertCmd.Parameters["ainet"].Value, aInet); Assert.AreEqual(insertCmd.Parameters["along"].Value, aLong); Assert.AreEqual(insertCmd.Parameters["atimeuuid"].Value, aTimeUUID); Assert.AreEqual(insertCmd.Parameters["auuid"].Value, aUUID); Assert.IsTrue(((byte[])insertCmd.Parameters["ablob"].Value).SequenceEqual(aBlob)); Assert.IsTrue(((List<string>)insertCmd.Parameters["alist"].Value).SequenceEqual(aList)); Assert.IsTrue(((HashSet<int>)insertCmd.Parameters["aset"].Value).SequenceEqual(aSet)); foreach(var entry in ((Dictionary<long, string>)insertCmd.Parameters["amap"].Value)) { var val = aMap[entry.Key]; Assert.AreEqual(entry.Value, val); } } }
public void SerializeObjectOutDefaultsTest() { const string insertCql = @"insert into SerializationTest.Types(aInt) values (1);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); Types result = null; using(var reader = selectCmd.ExecuteReader<Types>()) { if(reader.Read()) result = reader.Current; } Assert.IsNotNull(result); Assert.AreEqual(result.aASCIIString, default(string)); Assert.AreEqual(result.aVarcharString, default(string)); Assert.AreEqual(result.aVarint, default(BigInteger)); Assert.AreEqual(result.aTextString, default(string)); Assert.AreEqual(result.aBool, default(bool)); Assert.AreEqual(result.aDecimal, default(decimal)); Assert.AreEqual(result.aDouble, default(double)); Assert.AreEqual(result.aFloat, default(float)); Assert.AreEqual(result.aInet, default(IPAddress)); Assert.AreEqual(result.aLong, default(long)); Assert.AreEqual(result.aTimeUUID, default(Guid)); Assert.AreEqual(result.aUUID, default(Guid)); Assert.AreEqual(result.aBlob, default(byte[])); Assert.AreEqual(result.aList, default(List<string>)); Assert.AreEqual(result.aSet, default(HashSet<int>)); Assert.AreEqual(result.aMap, default(Dictionary<long, string>)); } }
public void SelectWithPaging() { //Assume const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);"; const string retrieveCql = @"select * from Test.BasicFlow;"; //Act using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.Prepare(); for(int i = 0; i < 100; i++) { cmd.Parameters[0].Value = i; cmd.Parameters[1].Value = "Hello " + i; cmd.ExecuteNonQuery(); } //select data var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One); selectCmd.PageSize = 10; using(var reader = selectCmd.ExecuteReader()) { //no paging when version < 2.0.0 is used... var expectedCount = String.Compare(connection.ServerVersion, "2.0.0", StringComparison.Ordinal) < 0 ? 100 : 10; Assert.AreEqual(expectedCount, reader.Count); var results = new bool[100]; for(int i = 0; i < 100; i++) { if(reader.Read()) { results[(int)reader["id"]] = true; Assert.AreEqual("Hello " + reader["id"], reader["value"]); } else Assert.Fail("Read should have succeeded"); } Assert.IsFalse(reader.Read()); Assert.IsTrue(results.All(p => p)); } } }
public void SerializeOutDefaultTest() { const string insertCql = @"insert into SerializationTest.Types(aInt) values (1);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); string aAsciiString; string aVarcharString; BigInteger aVarint; string aTextString; bool aBool; decimal aDecimal; double aDouble; float aFloat; IPAddress aInet; long aLong; Guid aTimeUUID; Guid aUUID; byte[] aBlob; List<string> aList; HashSet<int> aSet; Dictionary<long, string> aMap; var selectCmd = new CqlCommand(connection, selectCql); using(var reader = selectCmd.ExecuteReader()) { if(reader.Read()) { aAsciiString = reader.GetString(reader.GetOrdinal("aasciistring")); aVarcharString = reader.GetString(reader.GetOrdinal("avarcharstring")); aVarint = reader.GetBigInteger(reader.GetOrdinal("avarint")); aTextString = reader.GetString(reader.GetOrdinal("atextstring")); aBool = reader.GetBoolean(reader.GetOrdinal("abool")); aDecimal = reader.GetDecimal(reader.GetOrdinal("adecimal")); aDouble = reader.GetDouble(reader.GetOrdinal("adouble")); aFloat = reader.GetFloat(reader.GetOrdinal("afloat")); aInet = reader.GetIPAddress(reader.GetOrdinal("ainet")); aLong = reader.GetInt64(reader.GetOrdinal("along")); aTimeUUID = reader.GetGuid(reader.GetOrdinal("atimeuuid")); aUUID = reader.GetGuid(reader.GetOrdinal("auuid")); aBlob = reader.GetBytes(reader.GetOrdinal("ablob")); aList = reader.GetList<string>(reader.GetOrdinal("alist")); aSet = reader.GetSet<int>(reader.GetOrdinal("aset")); aMap = reader.GetDictionary<long, string>(reader.GetOrdinal("amap")); } else throw new Exception("No row returned!"); } Assert.AreEqual(aAsciiString, default(string)); Assert.AreEqual(aVarcharString, default(string)); Assert.AreEqual(aVarint, default(BigInteger)); Assert.AreEqual(aTextString, default(string)); Assert.AreEqual(aBool, default(bool)); Assert.AreEqual(aDecimal, default(decimal)); Assert.AreEqual(aDouble, default(double)); Assert.AreEqual(aFloat, default(float)); Assert.AreEqual(aInet, default(IPAddress)); Assert.AreEqual(aLong, default(long)); Assert.AreEqual(aTimeUUID, default(Guid)); Assert.AreEqual(aUUID, default(Guid)); Assert.AreEqual(aBlob, default(byte[])); Assert.AreEqual(aList, default(List<string>)); Assert.AreEqual(aSet, default(HashSet<int>)); Assert.AreEqual(aMap, default(Dictionary<long, string>)); } }
public void SelectTypedMultiple() { //Assume const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);"; const string retrieveCql = @"select * from Test.BasicFlow;"; //Act using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.Prepare(); for (int i = 0; i < 100; i++) { cmd.Parameters[0].Value = i; cmd.Parameters[1].Value = "Hello " + i; cmd.ExecuteNonQuery(); } //select data var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One); using (var reader = selectCmd.ExecuteReader<BasicFlowData>()) { Assert.AreEqual(100, reader.Count); var results = new bool[100]; for (int i = 0; i < 100; i++) { if (reader.Read()) { var current = reader.Current; results[current.Id] = true; Assert.AreEqual("Hello " + current.Id, current.Data); } else Assert.Fail("Read should have succeeded"); } Assert.IsFalse(reader.Read()); Assert.IsTrue(results.All(p => p), "Not all expected entries are returned"); } } }
public void TrySetKeepAlive() { var builder = new CqlConnectionStringBuilder( "node=localhost;Logger=Debug;LogLevel=Verbose;Username=cassandra;password=cassandra"); builder.SocketKeepAlive = 10*60*1000; //10 mins using(var connection = new CqlConnection(builder)) { connection.Open(); } }
public void Run_all_Cassandra_integration_tests_work() { // Open a connection to Cassandra var cnn = new CqlConnection($"Contact Points=127.0.0.1;Port={_cassandraFixture.Cassandra.HostPort};Cluster Name={_cassandraFixture.Cassandra.ClusterName}"); cnn.Open(); Assert.True(cnn.State == ConnectionState.Open, "Cannot open a connection to Cassandra."); // Initiate a connection to the database var wcnn = new WrappedConnection(cnn); // Validate DBMS.Cassandra Assert.Equal(DBMS.Cassandra, wcnn.GetDatabaseServerType()); // Init the DatabaseHelper var db = DatabaseHelperFactory.GetDatabaseHelper(DBMS.Cassandra, wcnn); // Create schema string metadataKeyspaceName = "my_keyspace"; Schema metadataSchema = new CassandraKeyspace(metadataKeyspaceName, CassandraKeyspace.CreateSimpleStrategy(1), wcnn); Assert.False(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should not already exist."); Assert.True(metadataSchema.Create(), $"Creation of the schema [{metadataKeyspaceName}] failed."); Assert.True(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should be created."); Assert.True(metadataSchema.IsEmpty(), $"The schema [{metadataKeyspaceName}] should be empty."); var s = db.GetSchema("my_keyspace"); // Get MetadataTable string metadataTableName = "evolve_change_log"; var metadata = db.GetMetadataTable(metadataKeyspaceName, metadataTableName); // Create MetadataTable Assert.False(metadata.IsExists(), "MetadataTable sould not already exist."); Assert.True(metadata.CreateIfNotExists(), "MetadataTable creation failed."); Assert.True(metadata.IsExists(), "MetadataTable sould exist."); Assert.False(metadata.CreateIfNotExists(), "MetadataTable already exists. Creation should return false."); Assert.True(metadata.GetAllMigrationMetadata().Count() == 0, "No migration metadata should be found."); //Lock & Unlock //..Applicaiton level: return true if the cluster lock keyspace/table is not present Assert.True(db.TryAcquireApplicationLock()); wcnn.ExecuteNonQuery("create keyspace cluster_lock with replication = { 'class' : 'SimpleStrategy','replication_factor' : '1' }; "); Assert.True(db.TryAcquireApplicationLock()); //Still true, table is missing wcnn.ExecuteNonQuery("create table cluster_lock.lock (locked int, primary key(locked))"); Assert.True(db.TryAcquireApplicationLock()); //Still true, lock is not present wcnn.ExecuteNonQuery("insert into cluster_lock.lock (locked) values (1) using TTL 3600"); Assert.False(db.TryAcquireApplicationLock()); wcnn.ExecuteNonQuery("drop keyspace cluster_lock"); Assert.True(db.TryAcquireApplicationLock()); Assert.True(db.ReleaseApplicationLock()); Assert.True(db.ReleaseApplicationLock()); //..Table level: lock implemented with LWT on evolve metadata table Assert.True(metadata.TryLock()); Assert.False(metadata.TryLock()); Assert.True(metadata.ReleaseLock()); Assert.False(metadata.ReleaseLock()); // Save NewSchema metadata metadata.Save(MetadataType.NewSchema, "0", "New schema created.", metadataKeyspaceName); Assert.True(metadata.CanDropSchema(metadataKeyspaceName), $"[{metadataKeyspaceName}] should be droppable."); Assert.False(metadata.CanEraseSchema(metadataKeyspaceName), $"[{metadataKeyspaceName}] should not be erasable."); // Add metadata migration var migrationScript = new FileMigrationScript(TestContext.EmptyMigrationScriptPath, "1_3_2", "Migration_description"); metadata.SaveMigration(migrationScript, true); var migrationMetadata = metadata.GetAllMigrationMetadata().FirstOrDefault(); Assert.True(migrationMetadata != null, "One migration metadata should be found."); Assert.True(migrationMetadata.Version == migrationScript.Version, "Metadata version is not the same."); Assert.True(migrationMetadata.Checksum == migrationScript.CalculateChecksum(), "Metadata checksum is not the same."); Assert.True(migrationMetadata.Description == migrationScript.Description, "Metadata descritpion is not the same."); Assert.True(migrationMetadata.Name == migrationScript.Name, "Metadata name is not the same."); Assert.True(migrationMetadata.Success == true, "Metadata success is not true."); Assert.True(migrationMetadata.Id != 0, "Metadata id is not set."); Assert.True(migrationMetadata.InstalledOn.Date == DateTime.UtcNow.Date, $"Installed date is {migrationMetadata.InstalledOn.Date} whereas UtcNow is {DateTime.UtcNow.Date}."); // Update checksum metadata.UpdateChecksum(migrationMetadata.Id, "Hi !"); Assert.Equal("Hi !", metadata.GetAllMigrationMetadata().First().Checksum); // Assert metadata schema is not empty Assert.False(metadataSchema.IsEmpty(), $"[{metadataKeyspaceName}] should not be empty."); // Erase schema metadataSchema.Erase(); Assert.True(metadataSchema.IsEmpty(), $"The schema [{metadataKeyspaceName}] should be empty."); Assert.True(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should exist."); // Drop schema metadataSchema.Drop(); Assert.False(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should not exist."); }
public void SerializeObjectOutNullTest() { const string insertCql = @"insert into SerializationTest.Types(aInt) values (4);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); NullableTypes result = null; using(var reader = selectCmd.ExecuteReader<NullableTypes>()) { if(reader.Read()) result = reader.Current; } Assert.IsNotNull(result); Assert.IsNull(result.aASCIIString); Assert.IsNull(result.aVarcharString); Assert.IsNull(result.aVarint); Assert.IsNull(result.aTextString); Assert.IsNull(result.aBool); Assert.IsNull(result.aDecimal); Assert.IsNull(result.aDouble); Assert.IsNull(result.aFloat); Assert.IsNull(result.aInet); Assert.IsNull(result.aLong); Assert.IsNull(result.aTimeUUID); Assert.IsNull(result.aUUID); Assert.IsNull(result.aBlob); Assert.IsNull(result.aList); Assert.IsNull(result.aSet); Assert.IsNull(result.aMap); } }
public void DefaultSerializeTest() { const string insertCql = @"insert into Test.Types( aInt, aLong , aVarint , aTextString , aVarcharString , aASCIIString , aBlob , aBool , aDouble , aFloat , aTimestamp , aTimeUUID , aUUID , aInet , aList, aSet, aMap) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; const string selectCql = "select * from Test.Types limit 1;"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); var values = new Types { aInt = 2, aASCIIString = default(string), aBlob = default(byte[]), aBool = default(bool), aDouble = default(double), aFloat = default(float), aInet = default(IPAddress), aLong = default(long), aTextString = default(string), aVarcharString = default(string), aTimeUUID = default(Guid), aUUID = default(Guid), aTimestamp = default(DateTime), aVarint = default(BigInteger), aList = default(List <string>), aSet = default(HashSet <int>), aMap = default(Dictionary <long, string>) }; var insertCmd = new CqlCommand(connection, insertCql); insertCmd.Prepare(); insertCmd.Parameters.Set(values); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); Types result = null; using (var reader = selectCmd.ExecuteReader <Types>()) { if (reader.Read()) { result = reader.Current; } } Assert.IsNotNull(result); Assert.AreEqual(result.aASCIIString, default(string)); Assert.AreEqual(result.aVarcharString, default(string)); Assert.AreEqual(result.aVarint, default(BigInteger)); Assert.AreEqual(result.aTextString, default(string)); Assert.AreEqual(result.aBool, default(bool)); Assert.AreEqual(result.aDouble, default(double)); Assert.AreEqual(result.aFloat, default(float)); Assert.AreEqual(result.aInet, default(IPAddress)); Assert.AreEqual(result.aLong, default(long)); Assert.AreEqual(result.aTimeUUID, default(Guid)); Assert.AreEqual(result.aUUID, default(Guid)); Assert.AreEqual(result.aBlob, default(byte[])); Assert.AreEqual(result.aList, default(List <string>)); Assert.AreEqual(result.aSet, default(HashSet <int>)); Assert.AreEqual(result.aMap, default(Dictionary <long, string>)); } }
public void ExecuteNonQueryInsertAndSelectTest() { _connection.Open(); var cmd = _connection.CreateCommand(); string keyspaceName = "keyspace_ado_1"; cmd.CommandText = string.Format(TestUtils.CreateKeyspaceSimpleFormat, keyspaceName, 3); cmd.ExecuteNonQuery(); VerifyStatement( QueryType.Query, $"CREATE KEYSPACE \"{keyspaceName}\" WITH replication = {{ 'class' : 'SimpleStrategy', 'replication_factor' : {3} }}", 1); _connection.ChangeDatabase(keyspaceName); VerifyStatement(QueryType.Query, $"USE \"{keyspaceName}\"", 1); string tableName = "table_ado_1"; cmd.CommandText = string.Format("CREATE TABLE {0} (tweet_id uuid,author text,body text,isok boolean,PRIMARY KEY(tweet_id))", tableName); cmd.ExecuteNonQuery(); VerifyStatement( QueryType.Query, $"CREATE TABLE {tableName} (tweet_id uuid,author text,body text,isok boolean,PRIMARY KEY(tweet_id))", 1); var longQ = new StringBuilder(); longQ.AppendLine("BEGIN BATCH "); var guids = Enumerable.Range(0, 300).Select(i => Guid.NewGuid()).ToArray(); int RowsNo = 300; for (int i = 0; i < RowsNo; i++) { longQ.AppendFormat("INSERT INTO {0} (tweet_id, author, isok, body) VALUES ({1},'test{2}',{3},'body{2}');", tableName, guids[i], i, i % 2 == 0 ? "false" : "true"); } longQ.AppendLine("APPLY BATCH;"); cmd.CommandText = longQ.ToString(); cmd.ExecuteNonQuery(); VerifyStatement( QueryType.Query, longQ.ToString(), 1); TestCluster.PrimeFluent( b => b.WhenQuery($"SELECT * from {tableName} LIMIT 10000;") .ThenRowsSuccess( new[] { "tweet_id", "author", "body", "isok" }, r => r.WithRows(guids.Select((guid, idx) => new object[] { guid, $"test{idx}", $"body{idx}", idx % 2 != 0 }).ToArray()))); cmd.CommandText = string.Format(@"SELECT * from {0} LIMIT 10000;", tableName); var reader = cmd.ExecuteReader(); var counter = 0; while (reader.Read()) { Assert.AreEqual(4, reader.FieldCount); counter++; } Assert.AreEqual(RowsNo, counter); }
public void PrepareTest() { const string truncateTableCql = @"truncate Test.BasicFlow;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var truncTable = new CqlCommand(connection, truncateTableCql); truncTable.ExecuteNonQuery(); } }
public void Run_all_Cassandra_integration_tests_work() { // Open a connection to Cassandra var cnn = new CqlConnection($"Contact Points=127.0.0.1;Port={_cassandraFixture.Cassandra.HostPort};Cluster Name={_cassandraFixture.Cassandra.ClusterName}"); cnn.Open(); Assert.True(cnn.State == ConnectionState.Open, "Cannot open a connection to Cassandra."); // Initiate a connection to the database var wcnn = new WrappedConnection(cnn); // Validate DBMS.Cassandra Assert.Equal(DBMS.Cassandra, wcnn.GetDatabaseServerType()); // Init the DatabaseHelper var db = DatabaseHelperFactory.GetDatabaseHelper(DBMS.Cassandra, wcnn); // Create schema string metadataKeyspaceName = "my_metadata_keyspace"; Schema metadataSchema = new CassandraKeyspace(metadataKeyspaceName, CassandraKeyspace.CreateSimpleStrategy(1), wcnn); Assert.False(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should not already exist."); Assert.True(metadataSchema.Create(), $"Creation of the schema [{metadataKeyspaceName}] failed."); Assert.True(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should be created."); Assert.True(metadataSchema.IsEmpty(), $"The schema [{metadataKeyspaceName}] should be empty."); var s = db.GetSchema("my_metadata_keyspace"); // Get MetadataTable string metadataTableName = "change_log"; var metadata = db.GetMetadataTable(metadataKeyspaceName, metadataTableName); // Create MetadataTable Assert.False(metadata.IsExists(), "MetadataTable sould not already exist."); Assert.True(metadata.CreateIfNotExists(), "MetadataTable creation failed."); Assert.True(metadata.IsExists(), "MetadataTable sould exist."); Assert.False(metadata.CreateIfNotExists(), "MetadataTable already exists. Creation should return false."); Assert.True(metadata.GetAllMigrationMetadata().Count() == 0, "No migration metadata should be found."); // Lock MetadataTable metadata.Lock(); // Save NewSchema metadata metadata.Save(MetadataType.NewSchema, "0", "New schema created.", metadataKeyspaceName); Assert.True(metadata.CanDropSchema(metadataKeyspaceName), $"[{metadataKeyspaceName}] should be droppable."); Assert.False(metadata.CanEraseSchema(metadataKeyspaceName), $"[{metadataKeyspaceName}] should not be erasable."); // Add metadata migration var migrationScript = new FileMigrationScript(TestContext.EmptyMigrationScriptPath, "1_3_2", "Migration_description"); metadata.SaveMigration(migrationScript, true); var migrationMetadata = metadata.GetAllMigrationMetadata().FirstOrDefault(); Assert.True(migrationMetadata != null, "One migration metadata should be found."); Assert.True(migrationMetadata.Version == migrationScript.Version, "Metadata version is not the same."); Assert.True(migrationMetadata.Checksum == migrationScript.CalculateChecksum(), "Metadata checksum is not the same."); Assert.True(migrationMetadata.Description == migrationScript.Description, "Metadata descritpion is not the same."); Assert.True(migrationMetadata.Name == migrationScript.Name, "Metadata name is not the same."); Assert.True(migrationMetadata.Success == true, "Metadata success is not true."); Assert.True(migrationMetadata.Id != 0, "Metadata id is not set."); Assert.True(migrationMetadata.InstalledOn.Date == DateTime.UtcNow.Date, $"Installed date is {migrationMetadata.InstalledOn.Date} whereas UtcNow is {DateTime.UtcNow.Date}."); // Update checksum metadata.UpdateChecksum(migrationMetadata.Id, "Hi !"); Assert.Equal("Hi !", metadata.GetAllMigrationMetadata().First().Checksum); // Assert metadata schema is not empty Assert.False(metadataSchema.IsEmpty(), $"[{metadataKeyspaceName}] should not be empty."); // Erase schema metadataSchema.Erase(); Assert.True(metadataSchema.IsEmpty(), $"The schema [{metadataKeyspaceName}] should be empty."); Assert.True(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should exist."); // Drop schema metadataSchema.Drop(); Assert.False(metadataSchema.IsExists(), $"The schema [{metadataKeyspaceName}] should not exist."); }
public void SerializeObjectInOutTest() { const string insertCql = @"insert into SerializationTest.Types( aInt, aLong , aVarint , aTextString , aVarcharString , aASCIIString , aBlob , aBool , aDecimal , aDouble , aFloat , aTimestamp , aTimeUUID , aUUID , aInet , aList, aSet, aMap) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; const string selectCql = "select * from SerializationTest.Types limit 1;"; using(var connection = new CqlConnection(ConnectionString)) { connection.Open(); var values = new Types { aASCIIString = "hello world!", aBlob = new byte[] {1, 2, 3, 4}, aBool = true, aDecimal = decimal.MaxValue/2, aDouble = 1.234, aFloat = 5.789f, aInet = new IPAddress(new byte[] {127, 0, 0, 1}), aInt = 10, aLong = 56789012456, aTextString = "some other text with \u005C unicode", aVarcharString = "some other varchar with \u005C unicode", aTimeUUID = DateTime.Now.GenerateTimeBasedGuid(), aUUID = Guid.NewGuid(), aTimestamp = DateTime.Now, aVarint = new BigInteger(12345678901234), aList = new List<string> {"string 1", "string 2"}, aSet = new HashSet<int> {1, 3, 3}, aMap = new Dictionary<long, string> {{1, "value 1"}, {2, "value 2"}, {3, "value 3"}}, }; var insertCmd = new CqlCommand(connection, insertCql); insertCmd.Prepare(); insertCmd.Parameters.Set(values); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); Types result = null; using(var reader = selectCmd.ExecuteReader<Types>()) { if(reader.Read()) result = reader.Current; } Assert.IsNotNull(result); Assert.AreEqual(values.aASCIIString, result.aASCIIString); Assert.AreEqual(values.aVarcharString, result.aVarcharString); Assert.AreEqual(values.aVarint, result.aVarint); Assert.AreEqual(values.aTextString, result.aTextString); Assert.AreEqual(values.aBool, result.aBool); Assert.AreEqual(values.aDecimal, result.aDecimal); Assert.AreEqual(values.aDouble, result.aDouble); Assert.AreEqual(values.aFloat, result.aFloat); Assert.AreEqual(values.aInet, result.aInet); Assert.AreEqual(values.aInt, result.aInt); Assert.AreEqual(values.aLong, result.aLong); Assert.AreEqual(values.aTimeUUID, result.aTimeUUID); Assert.AreEqual(values.aUUID, result.aUUID); Assert.IsTrue(result.aBlob.SequenceEqual(values.aBlob)); Assert.IsTrue(result.aList.SequenceEqual(values.aList)); Assert.IsTrue(result.aSet.SequenceEqual(values.aSet)); } }
public void BasicFlowAdo() { //Assume const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);"; const string retrieveCql = @"select id,value,ignored from Test.BasicFlow;"; //Act using(IDbConnection connection = new CqlConnection(ConnectionString)) { connection.Open(); IDbCommand cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.Parameters.Add(new CqlParameter("id", CqlType.Int)); cmd.Parameters.Add(new CqlParameter("value", CqlType.Text)); cmd.Prepare(); ((IDbDataParameter)cmd.Parameters["id"]).Value = 456; ((IDbDataParameter)cmd.Parameters["value"]).Value = "Hallo 456"; cmd.ExecuteNonQuery(); IDbCommand selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One) { EnableTracing = true }; IDataReader reader = selectCmd.ExecuteReader(); DataTable schema = reader.GetSchemaTable(); Assert.AreEqual(3, schema.Rows.Count); Assert.IsTrue( schema.Rows.Cast<DataRow>().Any(row => row[CqlSchemaTableColumnNames.ColumnName].Equals("ignored"))); if(reader.Read()) { int id = reader.GetInt32(0); string value = reader.GetString(1); Assert.AreEqual(456, id); Assert.IsTrue(reader.IsDBNull(2)); Assert.AreEqual("Hallo 456", value); } else Assert.Fail("Read should have succeeded"); } }
public void SerializeTest() { const string insertCql = @"insert into Test.Types( aInt, aLong , aVarint , aTextString , aVarcharString , aASCIIString , aBlob , aBool , aDouble , aFloat , aTimestamp , aTimeUUID , aUUID , aInet , aList, aSet, aMap) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; const string selectCql = "select * from Test.Types limit 1;"; using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); var values = new Types { aASCIIString = "hello world!", aBlob = new byte[] { 1, 2, 3, 4 }, aBool = true, aDouble = 1.234, aFloat = 5.789f, aInet = new IPAddress(new byte[] { 127, 0, 0, 1 }), aInt = 10, aLong = 56789012456, aTextString = "some other text with \u005C unicode", aVarcharString = "some other varchar with \u005C unicode", aTimeUUID = DateTime.Now.GenerateTimeBasedGuid(), aUUID = Guid.NewGuid(), aTimestamp = DateTime.Now, aVarint = new BigInteger(12345678901234), aList = new List <string> { "string 1", "string 2" }, aSet = new HashSet <int> { 1, 3, 3 }, aMap = new Dictionary <long, string> { { 1, "value 1" }, { 2, "value 2" }, { 3, "value 3" } }, }; var insertCmd = new CqlCommand(connection, insertCql); insertCmd.Prepare(); insertCmd.Parameters.Set(values); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); Types result = null; using (var reader = selectCmd.ExecuteReader <Types>()) { if (reader.Read()) { result = reader.Current; } } Assert.IsNotNull(result); Assert.AreEqual(result.aASCIIString, values.aASCIIString); Assert.AreEqual(result.aVarcharString, values.aVarcharString); Assert.AreEqual(result.aVarint, values.aVarint); Assert.AreEqual(result.aTextString, values.aTextString); Assert.AreEqual(result.aBool, values.aBool); Assert.AreEqual(result.aDouble, values.aDouble); Assert.AreEqual(result.aFloat, values.aFloat); Assert.AreEqual(result.aInet, values.aInet); Assert.AreEqual(result.aInt, values.aInt); Assert.AreEqual(result.aLong, values.aLong); Assert.AreEqual(result.aTimeUUID, values.aTimeUUID); Assert.AreEqual(result.aUUID, values.aUUID); Assert.IsTrue(result.aBlob.SequenceEqual(values.aBlob)); Assert.IsTrue(result.aList.SequenceEqual(values.aList)); Assert.IsTrue(result.aSet.SequenceEqual(values.aSet)); } }
public void BasicInsertSelectSynchronousTimeout() { //Assume const string insertCql = @"insert into Test.BasicFlow (id,value) values (13244,'Hallo 54235');"; const string retrieveCql = @"select * from Test.BasicFlow;"; //Act using (var connection = new CqlConnection(ConnectionString)) { connection.Open(); //insert data var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One); cmd.ExecuteNonQuery(); //select data var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One); selectCmd.CommandTimeout = Timeout.Infinite; selectCmd.Prepare(); //get connection, and cancel the select as soon as it registers EventHandler<Network.LoadChangeEvent> delayHandler = (src, ev) => Thread.Sleep(1200); Connection networkConnection = connection.GetConnection(); networkConnection.OnLoadChange += delayHandler; try { //set command timeout as low as possible (1 second) selectCmd.CommandTimeout = 1; CqlDataReader reader = selectCmd.ExecuteReader(); } finally { networkConnection.OnLoadChange -= delayHandler; } } }
public void NullDeserializeParameterTest() { const string insertCql = @"insert into Test.Types(aInt) values (1);"; const string selectCql = "select * from Test.Types limit 1;"; using (var connection = new CqlConnection(ConnectionString)) { string aASCIIString; string aVarcharString; BigInteger? aVarint; string aTextString; bool? aBool; double? aDouble; float? aFloat; IPAddress aInet; long? aLong; Guid? aTimeUUID; Guid? aUUID; byte[] aBlob; List <string> aList; HashSet <int> aSet; Dictionary <long, string> aMap; connection.Open(); var insertCmd = new CqlCommand(connection, insertCql); insertCmd.ExecuteNonQuery(); var selectCmd = new CqlCommand(connection, selectCql); using (var reader = selectCmd.ExecuteReader()) { if (reader.Read()) { aASCIIString = (string)reader["aasciistring"]; aVarcharString = (string)reader["avarcharstring"]; aVarint = (BigInteger?)reader["avarint"]; aTextString = (string)reader["atextstring"]; aBool = (bool?)reader["abool"]; aDouble = (double?)reader["adouble"]; aFloat = (float?)reader["afloat"]; aInet = (IPAddress)reader["ainet"]; aLong = (long?)reader["along"]; aTimeUUID = (Guid?)reader["atimeuuid"]; aUUID = (Guid?)reader["auuid"]; aBlob = (byte[])reader["ablob"]; aList = (List <string>)reader["alist"]; aSet = (HashSet <int>)reader["aset"]; aMap = (Dictionary <long, string>)reader["amap"]; } else { throw new Exception("No row returned!"); } } Assert.AreEqual(aASCIIString, default(string)); Assert.AreEqual(aVarcharString, default(string)); Assert.AreEqual(aVarint, default(BigInteger?)); Assert.AreEqual(aTextString, default(string)); Assert.AreEqual(aBool, default(bool?)); Assert.AreEqual(aDouble, default(double?)); Assert.AreEqual(aFloat, default(float?)); Assert.AreEqual(aInet, default(IPAddress)); Assert.AreEqual(aLong, default(long?)); Assert.AreEqual(aTimeUUID, default(Guid?)); Assert.AreEqual(aUUID, default(Guid?)); Assert.AreEqual(aBlob, default(byte[])); Assert.AreEqual(aList, default(List <string>)); Assert.AreEqual(aSet, default(HashSet <int>)); Assert.AreEqual(aMap, default(Dictionary <long, string>)); } }