Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/AgDatabase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ namespace AgDatabaseMove
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Exceptions;
using Microsoft.SqlServer.Management.Smo;
using Polly;
using SmoFacade;
using AvailabilityGroup = SmoFacade.AvailabilityGroup;
using Server = SmoFacade.Server;


public interface IAgDatabase
Expand Down Expand Up @@ -158,7 +162,29 @@ public void DropAllLogins()

public void AddLogin(LoginProperties login)
{
_listener.ForEachAgInstance(server => server.AddLogin(login));
if (login.LoginType == LoginType.SqlLogin && login.Sid == null) {
AddNewSqlLogin(login);
} else
{
_listener.ForEachAgInstance(server => server.AddLogin(login));
}
}

/// <summary>
/// Creates a new Sql login across all members of the availability group.
/// Assumes associated database has been created and the login being
/// created does not previously exist. In the case of
/// Sql logins on availability groups, the login must first be created on
/// a singular instance in the availability group, in this case the primary,
/// so Sql Server will generate a new SID. This SID will be saved and used to
/// create the same login on each ag replica.
/// </summary>
/// <param name="login"></param> A new login to create across all members of an availability group.
private void AddNewSqlLogin(LoginProperties login)
{
var createdLogin = _listener.Primary.AddLogin(login);
login.Sid = createdLogin.Sid;
Parallel.ForEach(_listener.Secondaries, server => server.AddLogin(login));
}

public IEnumerable<RoleProperties> AssociatedRoles()
Expand Down
1 change: 1 addition & 0 deletions src/SmoFacade/Login.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ private static Microsoft.SqlServer.Management.Smo.Login ConstructLogin(LoginProp
else {
login.Create();
}
login.Refresh();

return login;
}
Expand Down
4 changes: 2 additions & 2 deletions src/SmoFacade/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,11 +278,11 @@ private void Backup(Backup backup, string backupDirectoryPathQuery, string datab
backup.SqlBackup(_server);
}

public void AddLogin(LoginProperties login)
public Login AddLogin(LoginProperties login)
{
var matchingLogin =
Logins.SingleOrDefault(l => l.Name.Equals(login.Name, StringComparison.InvariantCultureIgnoreCase));
if(matchingLogin == null) matchingLogin = new Login(login, this);
return matchingLogin ?? new Login(login, this);
}

public void AddRole(LoginProperties login, RoleProperties role)
Expand Down