Skip to content

Login.EnumDatabaseMappings returns null unexpectedly #37

Description

Create a login on the server using SQL Authentication
Create a user in a database for that login
call Login.EnumDatabaseMappings.
It should return a collection with 1 entry at least, but sometimes it returns null.

var login = new Login(db.Parent, GenerateUniqueSmoObjectName("login"))
                {
                    LoginType = LoginType.SqlLogin,
                    
                };
                var pwd = Guid.NewGuid().ToString();
                login.Create(pwd);
                var credential = new Credential(db.Parent, GenerateUniqueSmoObjectName("login")) { Identity = "someidentity" };
                var dbUser = db.CreateUser("loginUser", login.Name);
// this assert can fail
                Assert.That(login.EnumDatabaseMappings()?.Select(m => m.DBName), Has.Member(db.Name), "login.EnumDatabaseMappings");

This is the query:

create table #loginmappings( LoginName sysname NULL, DBName sysname NULL, UserName sysname NULL, AliasName sysname NULL )
declare @db_name nvarchar(512)
declare crs cursor local fast_forward
	

 
	for ( select name from sys.databases where 1 = has_dbaccess(name)) 
			


open crs 
fetch crs into @db_name
while @@fetch_status >= 0 
begin 
	set @db_name = quotename(@db_name)
		

 
	exec('use ' + @db_name + ' INSERT #loginmappings select suser_sname(u.sid), db_name(), u.name, null from sys.database_principals AS u where suser_sname(u.sid) is not null')
			

 
	fetch crs into @db_name
end 
close crs
deallocate crs
		


SELECT
logmap.LoginName AS [LoginName],
logmap.DBName AS [DBName],
logmap.UserName AS [UserName]
FROM
sys.server_principals AS log
INNER JOIN #loginmappings AS logmap ON logmap.LoginName=log.name
WHERE
(log.type in ('U', 'G', 'S', 'C', 'K', 'E', 'X') AND log.principal_id not between 101 and 255 AND log.name <> N'##MS_AgentSigningCertificate##')and(log.name='login_Login_apis_work_correctly824ead3d-8f57-4c48-9f19-59c8dd560808')

drop table #loginmappings
	

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions