Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sql: simplify user id querying for GRANT ROLE #96205

Merged
merged 1 commit into from
Jan 31, 2023
Merged
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
47 changes: 8 additions & 39 deletions pkg/sql/grant_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ func (n *GrantRoleNode) startExec(params runParams) error {
// If admin option is false, we do not remove it from existing memberships.
memberStmt := `INSERT INTO system.role_members ("role", "member", "isAdmin") VALUES ($1, $2, $3) ON CONFLICT ("role", "member")`
if roleMembersHasIDs {
memberStmt = `INSERT INTO system.role_members ("role", "member", "isAdmin", "role_id", "member_id") VALUES ($1, $2, $3, $4, $5) ON CONFLICT ("role", "member")`
memberStmt = `
INSERT INTO system.role_members ("role", "member", "isAdmin", role_id, member_id)
VALUES ($1, $2, $3, (SELECT user_id FROM system.users WHERE username = $1), (SELECT user_id FROM system.users WHERE username = $2))
ON CONFLICT ("role", "member")`
}
if n.adminOption {
// admin option: true, set "isAdmin" even if the membership exists.
Expand All @@ -184,49 +187,15 @@ func (n *GrantRoleNode) startExec(params runParams) error {
memberStmt += ` DO NOTHING`
}

// Get user IDs for both role and member if ID columns have been added.
var qargs []interface{}
if roleMembersHasIDs {
qargs = make([]interface{}, 5)
} else {
qargs = make([]interface{}, 3)
}

qargs[2] = n.adminOption
for _, r := range n.roles {
qargs[0] = r.Normalized()

if roleMembersHasIDs {
idRow, err := params.p.InternalSQLTxn().QueryRowEx(
params.ctx, "get-user-id", params.p.Txn(),
sessiondata.NodeUserSessionDataOverride,
`SELECT user_id FROM system.users WHERE username = $1`, r.Normalized(),
)
if err != nil {
return err
}
qargs[3] = tree.MustBeDOid(idRow[0])
}

for _, m := range n.members {
qargs[1] = m.Normalized()

if roleMembersHasIDs {
idRow, err := params.p.InternalSQLTxn().QueryRowEx(
params.ctx, "get-user-id", params.p.Txn(),
sessiondata.NodeUserSessionDataOverride,
`SELECT user_id FROM system.users WHERE username = $1`, m.Normalized(),
)
if err != nil {
return err
}
qargs[4] = tree.MustBeDOid(idRow[0])
}

memberStmtRowsAffected, err := params.p.InternalSQLTxn().ExecEx(
params.ctx, "grant-role", params.p.Txn(),
sessiondata.RootUserSessionDataOverride,
memberStmt, qargs...,
memberStmt,
r.Normalized(),
m.Normalized(),
n.adminOption,
)
if err != nil {
return err
Expand Down