microsoft / microsoft/sqlmanagementobjects

Login.EnumDatabaseMappings returns null unexpectedly

Open
#37 0 comments 1 reaction 1 assignee View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
143
Forks
28
PR merge metrics
No merged PRs in 30d

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
	

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.