private void Init() { if (_initialized) { return; } _initialized = true; Cluster cluster = Cluster.Builder().AddContactPoint(_clusterAddress).Build(); CassandraSession = cluster.Connect(_keyspace); CassandraMetadata = cluster.Metadata; try { RowSet result = CassandraSession.Execute(string.Format("select * from system.schema_columnfamilies where keyspace_name='{0}';", _keyspace)); foreach (var table in result) { _tables.Add(new CassandraTable(table["columnfamily_name"].ToString(), this)); } } catch (Exception ex) { Logger.Error(LogCategory.DataProvider, "Error while querying system.schema_columnfamilies: {0}.", ex); throw; } }
public async Task UpsertLoginsAsync(ProviderLoginHandle login, CancellationToken cancellationToken = default(CancellationToken)) { if (login == null) { throw new ArgumentNullException("login"); } cancellationToken.ThrowIfCancellationRequested(); var batch = new BatchStatement(); var prepared = await _createLoginByUserId; var bound = prepared.Bind(login.UserId, login.LoginProvider, login.ProviderKey); batch.Add(bound); cancellationToken.ThrowIfCancellationRequested(); prepared = await _createLoginByLoginProvider; bound = prepared.Bind(login.UserId, login.LoginProvider, login.ProviderKey); batch.Add(bound); cancellationToken.ThrowIfCancellationRequested(); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
public async Task DeleteUserFromRolesAsync(Guid userId, CancellationToken cancellationToken = default(CancellationToken)) { //TODO: User the pager here to loop through in a more orderly fashion. // you can't send too many batch statements // Currently this method is crazy inneficient. if (userId == Guid.Empty) { throw new ArgumentNullException("userId"); } cancellationToken.ThrowIfCancellationRequested(); var roleNames = await FindRoleNamesByUserIdAsync(userId, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); PreparedStatement[] prepared = await _deleteRolesFromUserIdAsync; var batch = new BatchStatement(); foreach (var roleName in roleNames) { // TODO: Don't do this, especially for large data sets. await RemoveFromRoleAsync(userId, roleName); // DELETE FROM user_roles_by_role ... //batch.Add(prepared[1].Bind(userId,roleName)); } // DELETE FROM user_roles ... batch.Add(prepared[0].Bind(userId)); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
public void PrepareRolesStatements() { _addToRoleAsync = new AsyncLazy <PreparedStatement[]>(() => Task.WhenAll(new[] { CassandraSession.PrepareAsync( string.Format("INSERT INTO user_roles (userid, rolename, assigned) VALUES (?, ?, ?)")), CassandraSession.PrepareAsync( string.Format("INSERT INTO user_roles_by_role (userid, rolename, assigned) VALUES (?, ?, ?)")) })); _removeFromRoleAsync = new AsyncLazy <PreparedStatement[]>(() => Task.WhenAll(new[] { CassandraSession.PrepareAsync(string.Format("DELETE FROM user_roles " + "WHERE userId = ? and rolename = ?")), CassandraSession.PrepareAsync(string.Format("DELETE FROM user_roles_by_role " + "WHERE userId = ? and rolename = ?")) })); _deleteRolesFromUserIdAsync = new AsyncLazy <PreparedStatement[]>(() => Task.WhenAll(new[] { CassandraSession.PrepareAsync(string.Format("DELETE FROM user_roles WHERE userId = ?")), CassandraSession.PrepareAsync( string.Format("DELETE FROM user_roles_by_role WHERE userId = ? AND rolename = ?")) })); }
public async Task RenameRoleNameInUsersAsync(string oldRoleName, string newRoleName, CancellationToken cancellationToken = default(CancellationToken)) { var session = CassandraSession; IMapper mapper = new Mapper(session); var createdDate = DateTimeOffset.UtcNow; cancellationToken.ThrowIfCancellationRequested(); var records = (await FindUserRolesByNameAsync(oldRoleName, cancellationToken)).ToList(); cancellationToken.ThrowIfCancellationRequested(); foreach (var record in records) { var batch = new BatchStatement(); var statements = await BuildAddToRole(record.UserId, newRoleName, createdDate); batch.AddRange(statements); statements = await BuildRemoveFromRole(record.UserId, oldRoleName); batch.AddRange(statements); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); } }
public void PrepareProviderLoginsStatements() { string columns = "tenantid, " + "userid, " + "login_provider, " + "provider_key"; // Create some reusable prepared statements so we pay the cost of preparing once, then bind multiple times _createLoginByUserId = new AsyncLazy <PreparedStatement>(() => CassandraSession.PrepareAsync( "INSERT INTO logins (" + columns + ") " + string.Format("VALUES ({0}, ?, ?, ?)", TenantId))); _createLoginByLoginProvider = new AsyncLazy <PreparedStatement>(() => CassandraSession.PrepareAsync( "INSERT INTO logins_by_provider (" + columns + ") " + string.Format("VALUES ({0}, ?, ?, ?)", TenantId))); _deleteLoginByUserId = new AsyncLazy <PreparedStatement>( () => CassandraSession.PrepareAsync( "DELETE FROM logins WHERE userId = ? and login_provider = ? and provider_key = ?")); _deleteLoginByLoginProvider = new AsyncLazy <PreparedStatement>( () => CassandraSession.PrepareAsync( string.Format( "DELETE FROM logins_by_provider WHERE login_provider = ? AND provider_key = ? AND tenantid = {0}", TenantId))); }
private static void SetupKeyspace() { if (!CassandraSession.KeyspaceExists(server, keyspaceName)) { CassandraSession.AddKeyspace(server, new KsDef { Name = keyspaceName, Replication_factor = 1, Strategy_class = "org.apache.cassandra.locator.SimpleStrategy", Cf_defs = new List <CfDef>() }); } var keyspace = new CassandraKeyspace(keyspaceName); if (!keyspace.ColumnFamilyExists(server, "Posts")) { keyspace.AddColumnFamily(server, new CfDef { Name = "Posts", Keyspace = keyspaceName, Column_type = "Super", Comparator_type = "UTF8Type", Subcomparator_type = "UTF8Type", Comment = "Used for blog posts." }); } }
public async Task UpdateRoleAsync(CassandraRole role, CancellationToken cancellationToken = default(CancellationToken)) { if (role == null) { throw new ArgumentNullException("role"); } if (string.IsNullOrEmpty(role.Name)) { throw new ArgumentNullException("role", "role.Name cannot be null or empty"); } var modifiedDate = DateTimeOffset.UtcNow; role.Modified = modifiedDate; var batch = new BatchStatement(); string oldName; var changed = role.HasNameChanged(out oldName); if (changed) { // This a Create/Delete move // can only change the name if that target name does not exist. var findResult = await FindRoleByNameAsync(role.Name); if (findResult.Any()) { // sorry, no go, this is record must either be deleted first or use another name. throw new Exception( string.Format( "Cannot change role name:[{0}] to an existing role, pick another name, or delete this one first", role.Name)); } var boundStatements = await BuildCreateStatements(role); batch.AddRange(boundStatements); var oldRole = new CassandraRole(role.TenantId, oldName); boundStatements = await BuildDeleteStatements(oldRole); batch.AddRange(boundStatements); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); await RenameRoleNameInUsersAsync(oldName, role.Name, cancellationToken); } else { PreparedStatement[] prepared = await _updateRole; // UPDATE roles ... batch.Add(prepared[0].Bind(role.Name, role.DisplayName, role.IsSystemRole, modifiedDate, role.Id)); // UPDATE roles_by_name ... (since username hasn't changed) batch.Add(prepared[1].Bind(role.DisplayName, role.IsSystemRole, modifiedDate, role.TenantId, role.Name)); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); } }
protected virtual void Setup() { if (!CassandraSession.KeyspaceExists(Server, KeyspaceName)) { CassandraSession.AddKeyspace(Server, new KsDef { Name = KeyspaceName, Replication_factor = 1, Strategy_class = "org.apache.cassandra.locator.SimpleStrategy", Cf_defs = new List <CfDef>() }); } }
public async Task DeleteRoleAsync(CassandraRole role) { PreparedStatement[] prepared = await _deleteRole; var batch = new BatchStatement(); // DELETE FROM roles ... batch.Add(prepared[0].Bind(role.Id)); // DELETE FROM roles_by_rolename ... batch.Add(prepared[1].Bind(role.Name, role.TenantId)); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
private static void SetupKeyspace() { if (CassandraSession.KeyspaceExists(server, keyspaceName)) { CassandraSession.DropKeyspace(server, keyspaceName); } var keyspace = new CassandraKeyspace(keyspaceName); keyspace.TryCreateSelf(server); keyspace.TryCreateColumnFamily <UTF8Type>(server, "Posts"); keyspace.TryCreateColumnFamily <LongType>(server, "Tags"); keyspace.TryCreateColumnFamily <TimeUUIDType, UTF8Type>(server, "Comments"); }
public void PrepareUserStatements() { string columns = "tenantid, " + "username, " + "userid, " + "password_hash, " + "security_stamp, " + "two_factor_enabled, " + "access_failed_count," + "lockout_enabled, " + "lockout_end_date, " + "phone_number, " + "phone_number_confirmed, " + "email, " + "email_confirmed, " + "created, " + "modified, " + "enabled, " + "source, " + "source_id"; // Create some reusable prepared statements so we pay the cost of preparing once, then bind multiple times _createUserByUserName = new AsyncLazy <PreparedStatement>(() => CassandraSession.PrepareAsync( "INSERT INTO users_by_username (" + columns + ") " + string.Format("VALUES ({0}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", TenantId))); _createUserByEmail = new AsyncLazy <PreparedStatement>(() => CassandraSession.PrepareAsync( "INSERT INTO users_by_email (" + columns + ") " + string.Format("VALUES ({0}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", TenantId))); _createUserById = new AsyncLazy <PreparedStatement>(() => CassandraSession.PrepareAsync( "INSERT INTO users (" + columns + ") " + string.Format("VALUES ({0}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", TenantId))); _deleteUserByUserName = new AsyncLazy <PreparedStatement>( () => CassandraSession.PrepareAsync( string.Format( "DELETE FROM users_by_username WHERE tenantid = {0} AND username = ?", TenantId))); _deleteUserByEmail = new AsyncLazy <PreparedStatement>( () => CassandraSession.PrepareAsync( string.Format("DELETE FROM users_by_email WHERE tenantid = {0} AND email = ?", TenantId))); _deleteUserById = new AsyncLazy <PreparedStatement>( () => CassandraSession.PrepareAsync( string.Format("DELETE FROM users WHERE userid = ?", TenantId))); }
/// <summary> /// Initializes the database and establishes the connections. /// </summary> private void Initialize() { // Establish the database connections. Note that rather than using a fragile // warmup delay, we'll just retry establishing the connections for up to 15 seconds. // // Note that we're going to delete the Cassandra keyspace and Postgres database // before recreating them so they'll start out empty for each unit test. var retry = new LinearRetryPolicy(e => true, int.MaxValue, retryInterval: TimeSpan.FromSeconds(1), timeout: new TimeSpan(15)); // Establish the Cassandra session, recreating the keyspace. var cluster = Cluster.Builder() .AddContactPoint("localhost") .WithPort(ycqlPort) .Build(); retry.Invoke( () => { CassandraSession = cluster.Connect(); }); CassandraSession.Execute($"DROP KEYSPACE IF EXISTS \"{cassandraKeyspace}\""); CassandraSession.Execute($"CREATE KEYSPACE \"{cassandraKeyspace}\""); CassandraSession = cluster.Connect(cassandraKeyspace); // Establish the Postgres connection, recreating the database. PostgresConnection = new NpgsqlConnection($"host=localhost;port={ysqlPort};user id=yugabyte;password="******"DROP DATABASE IF EXISTS \"{postgresDatabase}\"", PostgresConnection); command.ExecuteNonQuery(); command = new NpgsqlCommand($"CREATE DATABASE \"{postgresDatabase}\"", PostgresConnection); command.ExecuteNonQuery(); PostgresConnection = new NpgsqlConnection($"host=localhost;database={postgresDatabase};port={ysqlPort};user id=yugabyte;password="); PostgresConnection.Open(); }
public override IEnumerable <IFluentSuperColumn <CompareWith, CompareSubcolumnWith> > Execute(BaseCassandraColumnFamily columnFamily) { CassandraSession _localSession = null; if (CassandraSession.Current == null) { _localSession = new CassandraSession(); } try { var parent = new ColumnParent { Column_family = columnFamily.FamilyName }; if (SuperColumnName != null) { parent.Super_column = SuperColumnName; } var output = CassandraSession.Current.GetClient().multiget_slice( Keys.ToByteArrayList(), parent, SlicePredicate.CreateSlicePredicate(), CassandraSession.Current.ReadConsistency ); foreach (var result in output) { var r = new FluentSuperColumn <CompareWith, CompareSubcolumnWith>(result.Value.Select(col => { return(Helper.ConvertColumnToFluentColumn <CompareSubcolumnWith>(col.Column)); })); columnFamily.Context.Attach(r); r.MutationTracker.Clear(); yield return(r); } } finally { if (_localSession != null) { _localSession.Dispose(); } } }
public async Task CreateRoleAsync(CassandraRole role, CancellationToken cancellationToken = default(CancellationToken)) { if (role == null) { throw new ArgumentNullException("role"); } var boundStatements = await BuildCreateStatements(role); cancellationToken.ThrowIfCancellationRequested(); var batch = new BatchStatement(); batch.AddRange(boundStatements); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
public override IEnumerable <IFluentSuperColumnFamily <CompareWith, CompareSubcolumnWith> > Execute(BaseCassandraColumnFamily columnFamily) { CassandraSession _localSession = null; if (CassandraSession.Current == null) { _localSession = new CassandraSession(); } try { var parent = new ColumnParent { Column_family = columnFamily.FamilyName }; var output = CassandraSession.Current.GetClient().get_indexed_slices( parent, IndexClause.CreateIndexClause(), SlicePredicate.CreateSlicePredicate(), CassandraSession.Current.ReadConsistency ); foreach (var result in output) { var r = new FluentSuperColumnFamily <CompareWith, CompareSubcolumnWith>(result.Key, columnFamily.FamilyName, result.Columns.Select(col => { var superCol = Helper.ConvertSuperColumnToFluentSuperColumn <CompareWith, CompareSubcolumnWith>(col.Super_column); columnFamily.Context.Attach(superCol); superCol.MutationTracker.Clear(); return(superCol); })); columnFamily.Context.Attach(r); r.MutationTracker.Clear(); yield return(r); } } finally { if (_localSession != null) { _localSession.Dispose(); } } }
public async Task DeleteUserAsync(CassandraUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException("user"); } if (string.IsNullOrEmpty(user.UserName)) { throw new ArgumentNullException("user", "user.UserName cannot be null or empty"); } var foundUserResult = await FindUserByUserNameAsync(user.UserName, cancellationToken); var foundUserlist = foundUserResult.ToList(); if (!foundUserlist.Any()) { return; } user = foundUserlist[0]; var batch = new BatchStatement(); PreparedStatement prepared = await _deleteUserById; BoundStatement bound = prepared.Bind(user.Id); batch.Add(bound); prepared = await _deleteUserByEmail; bound = prepared.Bind(user.Email); batch.Add(bound); prepared = await _deleteUserByUserName; bound = prepared.Bind(user.UserName); batch.Add(bound); await RemoveLoginsFromUserAsync(user.Id, cancellationToken); await DeleteUserFromRolesAsync(user.Id, cancellationToken); await DeleteClaimHandleByUserIdAsync(user.Id, cancellationToken); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
static void Main(string[] args) { Program p = new Program(); //Create database context and connect to Keyspace FluentCassandra.Connections.Server svr = new FluentCassandra.Connections.Server(Properties.Settings.Default.CassandraIP); FluentCassandra.CassandraSession session = new CassandraSession(Properties.Settings.Default.KeySpace, svr); var db = new CassandraContext(session); Console.WriteLine("Time Started: " + DateTime.Now.ToString()); //INSERT DATA!!! p.insertHighwayStations(db); p.InsertStationLoops(db); Console.WriteLine("Time Finished: " + DateTime.Now.ToString()); Console.Read(); }
public override IDictionary <BytesType, int> Execute(BaseCassandraColumnFamily columnFamily) { CassandraSession _localSession = null; if (CassandraSession.Current == null) { _localSession = new CassandraSession(); } try { var parent = new ColumnParent { Column_family = columnFamily.FamilyName }; if (SuperColumnName != null) { parent.Super_column = SuperColumnName; } var output = CassandraSession.Current.GetClient().multiget_count( Keys.ToByteArrayList(), parent, SlicePredicate.CreateSlicePredicate(), CassandraSession.Current.ReadConsistency ); var results = new Dictionary <BytesType, int>(); foreach (var result in output) { results.Add(result.Key, result.Value); } return(results); } finally { if (_localSession != null) { _localSession.Dispose(); } } }
public async Task RemoveFromRoleAsync(Guid userId, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { if (userId == Guid.Empty) { throw new ArgumentNullException("userId"); } if (roleName == null) { throw new ArgumentNullException("roleName"); } cancellationToken.ThrowIfCancellationRequested(); PreparedStatement[] preparedStatements = await _removeFromRoleAsync; var batch = new BatchStatement(); var statements = await BuildRemoveFromRole(userId, roleName); batch.AddRange(statements); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
private IEnumerable <IFluentColumn <CompareSubcolumnWith> > GetColumns(BaseCassandraColumnFamily columnFamily) { CassandraSession _localSession = null; if (CassandraSession.Current == null) { _localSession = new CassandraSession(); } try { var parent = new ColumnParent { Column_family = columnFamily.FamilyName }; if (SuperColumnName != null) { parent.Super_column = SuperColumnName; } var output = CassandraSession.Current.GetClient().get_slice( Key, parent, SlicePredicate.CreateSlicePredicate(), CassandraSession.Current.ReadConsistency ); foreach (var result in output) { var r = Helper.ConvertColumnToFluentColumn <CompareSubcolumnWith>(result.Column); yield return(r); } } finally { if (_localSession != null) { _localSession.Dispose(); } } }
private IEnumerable <IFluentColumnFamily <CompareWith> > GetFamilies(BaseCassandraColumnFamily columnFamily) { CassandraSession _localSession = null; if (CassandraSession.Current == null) { _localSession = new CassandraSession(); } try { var parent = new ColumnParent { Column_family = columnFamily.FamilyName }; var output = CassandraSession.Current.GetClient().get_range_slices( parent, SlicePredicate.CreateSlicePredicate(), KeyRange.CreateKeyRange(), CassandraSession.Current.ReadConsistency ); foreach (var result in output) { var r = new FluentColumnFamily <CompareWith>(result.Key, columnFamily.FamilyName, result.Columns.Select(col => { return(Helper.ConvertColumnToFluentColumn <CompareWith>(col.Column)); })); columnFamily.Context.Attach(r); r.MutationTracker.Clear(); yield return(r); } } finally { if (_localSession != null) { _localSession.Dispose(); } } }
public async Task AddToRoleAsync(Guid userId, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { if (userId == Guid.Empty) { throw new ArgumentNullException("userId"); } if (roleName == null) { throw new ArgumentNullException("roleName"); } var createdDate = DateTimeOffset.UtcNow; cancellationToken.ThrowIfCancellationRequested(); var statements = await BuildAddToRole(userId, roleName, createdDate); var batch = new BatchStatement(); batch.AddRange(statements); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
public void PrepareUserRolesStatements() { _createRole = new AsyncLazy <PreparedStatement[]>(() => Task.WhenAll(new[] { CassandraSession.PrepareAsync( "INSERT INTO roles (roleid, name, displayname, is_systemrole, is_global, tenantid, created, modified) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"), _createRoleByName.Value })); _createRoleByName = new AsyncLazy <PreparedStatement>(() => CassandraSession.PrepareAsync( "INSERT INTO roles_by_name (roleid, name, displayname, is_systemrole, is_global, tenantid, created, modified) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)")); // All the statements needed by the UpdateAsync method _updateRole = new AsyncLazy <PreparedStatement[]>(() => Task.WhenAll(new[] { CassandraSession.PrepareAsync( "UPDATE roles " + "SET name = ?, displayname = ?, is_systemrole = ?, modified = ? " + "WHERE roleid = ?"), CassandraSession.PrepareAsync("UPDATE roles_by_name SET displayname = ?, is_systemrole = ?, modified = ? " + "WHERE tenantid = ? AND name = ?"), _deleteRoleByName.Value, _createRoleByName.Value, })); _deleteRole = new AsyncLazy <PreparedStatement[]>(() => Task.WhenAll(new[] { CassandraSession.PrepareAsync( "DELETE FROM roles WHERE roleid = ?"), _deleteRoleByName.Value })); _deleteRoleByName = new AsyncLazy <PreparedStatement>(() => CassandraSession.PrepareAsync( "DELETE FROM roles_by_name WHERE name = ? AND tenantid = ?")); }
public _CassandraSetup() { var keyspaceName = "Testing"; var server = new Server("localhost"); if (!CassandraSession.KeyspaceExists(server, keyspaceName)) { CassandraSession.AddKeyspace(server, new KsDef { Name = "Testing", Replication_factor = 1, Strategy_class = "org.apache.cassandra.locator.SimpleStrategy", Cf_defs = new List <CfDef>() }); } var keyspace = new CassandraKeyspace(keyspaceName); if (!keyspace.ColumnFamilyExists(server, "Standard")) { keyspace.AddColumnFamily(server, new CfDef { Name = "Standard", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "AsciiType", Comment = "Used for testing Standard family." }); } if (!keyspace.ColumnFamilyExists(server, "StandardAsciiType")) { keyspace.AddColumnFamily(server, new CfDef { Name = "StandardAsciiType", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "AsciiType", Comment = "Used for testing Standard family." }); } if (!keyspace.ColumnFamilyExists(server, "StandardBytesType")) { keyspace.AddColumnFamily(server, new CfDef { Name = "StandardBytesType", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "BytesType", Comment = "Used for testing BytesType family." }); } if (!keyspace.ColumnFamilyExists(server, "StandardIntegerType")) { keyspace.AddColumnFamily(server, new CfDef { Name = "StandardIntegerType", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "IntegerType", Comment = "Used for testing IntegerType family." }); } if (!keyspace.ColumnFamilyExists(server, "StandardLexicalUUIDType")) { keyspace.AddColumnFamily(server, new CfDef { Name = "StandardLexicalUUIDType", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "LexicalUUIDType", Comment = "Used for testing LexicalUUIDType family." }); } if (!keyspace.ColumnFamilyExists(server, "StandardLongType")) { keyspace.AddColumnFamily(server, new CfDef { Name = "StandardLongType", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "LongType", Comment = "Used for testing LongType family." }); } if (!keyspace.ColumnFamilyExists(server, "StandardTimeUUIDType")) { keyspace.AddColumnFamily(server, new CfDef { Name = "StandardTimeUUIDType", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "TimeUUIDType", Comment = "Used for testing TimeUUIDType family." }); } if (!keyspace.ColumnFamilyExists(server, "StandardUTF8Type")) { keyspace.AddColumnFamily(server, new CfDef { Name = "StandardUTF8Type", Keyspace = "Testing", Column_type = "Standard", Comparator_type = "UTF8Type", Comment = "Used for testing UTF8Type family." }); } if (!keyspace.ColumnFamilyExists(server, "Super")) { keyspace.AddColumnFamily(server, new CfDef { Name = "Super", Keyspace = "Testing", Column_type = "Super", Comparator_type = "AsciiType", Subcomparator_type = "AsciiType", Comment = "Used for testing Super family." }); } DB = new CassandraContext(keyspaceName, server); DB.ThrowErrors = true; Family = DB.GetColumnFamily <AsciiType>("Standard"); SuperFamily = DB.GetColumnFamily <AsciiType, AsciiType>("Super"); Family.RemoveAllRows(); SuperFamily.RemoveAllRows(); Family.InsertColumn(TestKey1, "Test1", Math.PI); Family.InsertColumn(TestKey1, "Test2", Math.PI); Family.InsertColumn(TestKey1, "Test3", Math.PI); SuperFamily.InsertColumn(TestKey1, TestSuperName, "Test1", Math.PI); SuperFamily.InsertColumn(TestKey1, TestSuperName, "Test2", Math.PI); SuperFamily.InsertColumn(TestKey1, TestSuperName, "Test3", Math.PI); Family.InsertColumn(TestKey2, "Test1", Math.PI); Family.InsertColumn(TestKey2, "Test2", Math.PI); Family.InsertColumn(TestKey2, "Test3", Math.PI); SuperFamily.InsertColumn(TestKey2, TestSuperName, "Test1", Math.PI); SuperFamily.InsertColumn(TestKey2, TestSuperName, "Test2", Math.PI); SuperFamily.InsertColumn(TestKey2, TestSuperName, "Test3", Math.PI); }
public async Task UpsertUserAsync(CassandraUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException("user"); } if (string.IsNullOrEmpty(user.UserName)) { throw new ArgumentNullException("user", "user.UserName cannot be null or empty"); } var now = DateTimeOffset.UtcNow; var foundUserResult = await FindUserByEmailAsync(user.Email, cancellationToken); var foundUserList = foundUserResult.ToList(); if (foundUserList.Any()) { // we have an update, and not a create. // we don't let you update the username/email. That is done by ChangeUserNameAsync var foundUser = foundUserList[0]; user.Email = foundUser.Email; user.UserName = foundUser.UserName; } else { // We have a brand new user, // we want to make the Id and user record immutable. // This allows us to change out the email address, which is the only thing we will allow for what looks like a username. user.Id = Guid.NewGuid(); user.Created = now; } user.Modified = now; var batch = new BatchStatement(); var prepared = await _createUserByUserName; var bound = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp, user.TwoFactorEnabled, user.AccessFailedCount, user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed, user.Email, user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId); batch.Add(bound); prepared = await _createUserByEmail; bound = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp, user.TwoFactorEnabled, user.AccessFailedCount, user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed, user.Email, user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId); batch.Add(bound); prepared = await _createUserById; bound = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp, user.TwoFactorEnabled, user.AccessFailedCount, user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed, user.Email, user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId); batch.Add(bound); cancellationToken.ThrowIfCancellationRequested(); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); }
public void ResetDatabase() { using (var session = new CassandraSession(ConnectionBuilder)) using (var db = new CassandraContext(session)) { db.ThrowErrors = true; db.TryDropKeyspace(Keyspace); var keyspace = new CassandraKeyspace(new CassandraKeyspaceSchema { Name = Keyspace }, db); db.Keyspace = keyspace; keyspace.TryCreateSelf(); keyspace.TryCreateColumnFamily<AsciiType>("Standard"); keyspace.TryCreateColumnFamily<AsciiType, AsciiType>("Super"); keyspace.TryCreateColumnFamily<AsciiType>("StandardAsciiType"); keyspace.TryCreateColumnFamily<BytesType>("StandardBytesType"); keyspace.TryCreateColumnFamily<IntegerType>("StandardIntegerType"); keyspace.TryCreateColumnFamily<LexicalUUIDType>("StandardLexicalUUIDType"); keyspace.TryCreateColumnFamily<LongType>("StandardLongType"); keyspace.TryCreateColumnFamily<TimeUUIDType>("StandardTimeUUIDType"); keyspace.TryCreateColumnFamily<UTF8Type>("StandardUTF8Type"); keyspace.TryCreateColumnFamily<UUIDType>("StandardUUIDType"); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema() { FamilyName = "Counters", ColumnNameType = CassandraType.AsciiType, DefaultColumnValueType = CassandraType.CounterColumnType }); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema { FamilyName = "StandardDecimalType", ColumnNameType = CassandraType.DecimalType }); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema { FamilyName = "StandardCompositeType", ColumnNameType = CassandraType.CompositeType(new[] { CassandraType.AsciiType, CassandraType.DoubleType }) }); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema { FamilyName = "StandardDynamicCompositeType", ColumnNameType = CassandraType.DynamicCompositeType(new Dictionary<char, CassandraType> { { 'a', CassandraType.AsciiType }, { 'd', CassandraType.DoubleType } }) }); db.ExecuteNonQuery(@" CREATE COLUMNFAMILY Users ( Id int PRIMARY KEY, Name ascii, Email ascii, Age int );", CqlVersion.Cql); db.ExecuteNonQuery(@"CREATE INDEX User_Age ON Users (Age);", CqlVersion.Cql); db.Keyspace.ClearCachedKeyspaceSchema(); var family = db.GetColumnFamily<AsciiType>("Standard"); var superFamily = db.GetColumnFamily<AsciiType, AsciiType>("Super"); var userFamily = db.GetColumnFamily("Users"); var counterFamily = db.GetColumnFamily("Counters"); ResetFamily(family); ResetSuperFamily(superFamily); ResetUsersFamily(userFamily); ResetCounterColumnFamily(counterFamily); } }
public async Task ChangeUserNameAsync(string oldUserName, string newUserName, CancellationToken cancellationToken = default(CancellationToken)) { if (oldUserName == null) { throw new ArgumentNullException("oldUserName"); } if (newUserName == null) { throw new ArgumentNullException("newUserName"); } var foundUserResult = await FindUserByUserNameAsync(oldUserName, cancellationToken); var foundUserList = foundUserResult.ToList(); if (foundUserList.Any()) { var user = foundUserList[0]; var foundNewResult = await FindUserByUserNameAsync(newUserName, cancellationToken); if (foundNewResult.Any()) { throw new Exception(String.Format("User: {0} exists, so you can't rename to this. Pick another name", newUserName)); } var batch = new BatchStatement(); PreparedStatement prepared = await _deleteUserByEmail; BoundStatement bound = prepared.Bind(oldUserName); batch.Add(bound); prepared = await _deleteUserByUserName; bound = prepared.Bind(oldUserName); batch.Add(bound); user.UserName = newUserName; user.Email = newUserName; prepared = await _createUserByUserName; bound = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp, user.TwoFactorEnabled, user.AccessFailedCount, user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed, user.Email, user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId); batch.Add(bound); prepared = await _createUserByEmail; bound = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp, user.TwoFactorEnabled, user.AccessFailedCount, user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed, user.Email, user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId); batch.Add(bound); prepared = await _createUserById; bound = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp, user.TwoFactorEnabled, user.AccessFailedCount, user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed, user.Email, user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId); batch.Add(bound); cancellationToken.ThrowIfCancellationRequested(); await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false); } else { throw new Exception(string.Format("user:{0} does not exist", oldUserName)); } }
public void ResetDatabase() { using (var session = new CassandraSession(ConnectionBuilder)) using (var db = new CassandraContext(session)) { db.ThrowErrors = true; db.TryDropKeyspace(Keyspace); var keyspace = new CassandraKeyspace(new CassandraKeyspaceSchema { Name = Keyspace }, db); db.Keyspace = keyspace; keyspace.TryCreateSelf(); keyspace.TryCreateColumnFamily <AsciiType>("Standard"); keyspace.TryCreateColumnFamily <AsciiType, AsciiType>("Super"); keyspace.TryCreateColumnFamily <AsciiType>("StandardAsciiType"); keyspace.TryCreateColumnFamily <BytesType>("StandardBytesType"); keyspace.TryCreateColumnFamily <IntegerType>("StandardIntegerType"); keyspace.TryCreateColumnFamily <LexicalUUIDType>("StandardLexicalUUIDType"); keyspace.TryCreateColumnFamily <LongType>("StandardLongType"); keyspace.TryCreateColumnFamily <TimeUUIDType>("StandardTimeUUIDType"); keyspace.TryCreateColumnFamily <UTF8Type>("StandardUTF8Type"); keyspace.TryCreateColumnFamily <UUIDType>("StandardUUIDType"); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema() { FamilyName = "Counters", ColumnNameType = CassandraType.AsciiType, DefaultColumnValueType = CassandraType.CounterColumnType }); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema(type: ColumnType.Super) { FamilyName = "SuperCounters", SuperColumnNameType = CassandraType.AsciiType, ColumnNameType = CassandraType.AsciiType, DefaultColumnValueType = CassandraType.CounterColumnType }); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema { FamilyName = "StandardDecimalType", ColumnNameType = CassandraType.DecimalType }); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema { FamilyName = "StandardCompositeType", ColumnNameType = CassandraType.CompositeType(new[] { CassandraType.AsciiType, CassandraType.DoubleType }) }); keyspace.TryCreateColumnFamily(new CassandraColumnFamilySchema { FamilyName = "StandardDynamicCompositeType", ColumnNameType = CassandraType.DynamicCompositeType(new Dictionary <char, CassandraType> { { 'a', CassandraType.AsciiType }, { 'd', CassandraType.DoubleType } }) }); db.ExecuteNonQuery(@" CREATE COLUMNFAMILY ""Users"" ( Id int PRIMARY KEY, Name ascii, Email ascii, Age int );"); db.ExecuteNonQuery(@"CREATE INDEX User_Age ON ""Users"" (Age);"); db.ExecuteNonQuery(@" CREATE COLUMNFAMILY Cql3List ( Id int PRIMARY KEY, TagList list<text> --list of strings );"); db.ExecuteNonQuery(@" CREATE COLUMNFAMILY Cql3Set ( Id int PRIMARY KEY, TagSet set<uuid> --set of Guids );"); db.ExecuteNonQuery(@" CREATE COLUMNFAMILY Cql3Map ( Id int PRIMARY KEY, TagMap map<bigint,uuid> --map of long integers and Guids );"); db.Keyspace.ClearCachedKeyspaceSchema(); var family = db.GetColumnFamily <AsciiType>("Standard"); var superFamily = db.GetColumnFamily <AsciiType, AsciiType>("Super"); var userFamily = db.GetColumnFamily("Users"); var counterFamily = db.GetColumnFamily("Counters"); ResetFamily(family); ResetSuperFamily(superFamily); ResetUsersFamily(userFamily); ResetCounterColumnFamily(counterFamily); } }
private void InitSession() { Session = new CassandraSession(); }
public void PrepareFlattenedDocumentStatements(string seedTableName) { #region PREPARED STATEMENTS for FlattenedDocument string tableById = TableByIdName(seedTableName); string tableByTypeAndVersion = TableByTypeAndVersionName(seedTableName); /* ************************************************ * Id uuid, * DocumentType text, * DocumentVersion text, * Document text, ************************************************ */ FindFlattenedDocumentQuery = string.Format("SELECT * FROM {0}", tableById); FindFlattenedDocumentByIdQuery = string.Format("SELECT * FROM {0} WHERE id = ?", tableById); FindFlattenedDocumentByType = string.Format("SELECT * FROM {0} WHERE DocumentType = ?", tableByTypeAndVersion); FindFlattenedDocumentByTypeAndVersion = string.Format("SELECT * FROM {0} WHERE DocumentType = ? AND DocumentVersion = ?", tableByTypeAndVersion); var queryUpsertFlattenedDocumentById = string.Format(@"INSERT INTO " + @"{0}(Id,DocumentType,DocumentVersion,DocumentJson) " + @"VALUES(?,?,?,?)", tableById); _UpsertFlattenedDocumentById = new AsyncLazy <PreparedStatement>( () => { var result = CassandraSession.PrepareAsync(queryUpsertFlattenedDocumentById); return(result); }); var queryUpsertFlattenedDocumentByTypeAndVersion = string.Format(@"INSERT INTO " + @"{0}(Id,DocumentType,DocumentVersion,DocumentJson) " + @"VALUES(?,?,?,?)", tableByTypeAndVersion); _UpsertFlattenedDocumentByTypeAndVersion = new AsyncLazy <PreparedStatement>( () => { var result = CassandraSession.PrepareAsync(queryUpsertFlattenedDocumentByTypeAndVersion); return(result); }); var queryDeleteFlattenedDocumentById = string.Format(@"Delete FROM {0} " + @"WHERE id = ?", tableById); _DeleteFlattenedDocumentById = new AsyncLazy <PreparedStatement>( () => { var result = CassandraSession.PrepareAsync(queryDeleteFlattenedDocumentById); return(result); }); var queryDeleteFlattenedDocumentByType = string.Format(@"Delete FROM {0} " + @"WHERE DocumentType = ?", tableByTypeAndVersion); _DeleteFlattenedDocumentByType = new AsyncLazy <PreparedStatement>( () => { var result = CassandraSession.PrepareAsync(queryDeleteFlattenedDocumentByType); return(result); }); var queryDeleteFlattenedDocumentByTypeAndVersion = string.Format(@"Delete FROM {0} " + @"WHERE DocumentType = ? " + @"AND DocumentVersion = ?", tableByTypeAndVersion); _DeleteFlattenedDocumentByTypeAndVersion = new AsyncLazy <PreparedStatement>( () => { var result = CassandraSession.PrepareAsync(queryDeleteFlattenedDocumentByTypeAndVersion); return(result); }); #endregion }