github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/sql/sem/tree/role_spec.go (about) 1 // Copyright 2021 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package tree 12 13 import ( 14 "fmt" 15 16 "github.com/cockroachdb/cockroachdb-parser/pkg/sql/lexbase" 17 ) 18 19 // RoleSpecType represents whether the RoleSpec is represented by 20 // string name or if the spec is CURRENT_USER or SESSION_USER. 21 type RoleSpecType int 22 23 const ( 24 // RoleName represents if a RoleSpec is defined using an IDENT or 25 // unreserved_keyword in the grammar. 26 RoleName RoleSpecType = iota 27 // CurrentUser represents if a RoleSpec is defined using CURRENT_USER. 28 CurrentUser 29 // SessionUser represents if a RoleSpec is defined using SESSION_USER. 30 SessionUser 31 ) 32 33 func (r RoleSpecType) String() string { 34 switch r { 35 case RoleName: 36 return "ROLE_NAME" 37 case CurrentUser: 38 return "CURRENT_USER" 39 case SessionUser: 40 return "SESSION_USER" 41 default: 42 panic(fmt.Sprintf("unknown role spec type: %d", r)) 43 } 44 } 45 46 // RoleSpecList is a list of RoleSpec. 47 type RoleSpecList []RoleSpec 48 49 // RoleSpec represents a role. 50 // Name should only be populated if RoleSpecType is RoleName. 51 type RoleSpec struct { 52 RoleSpecType RoleSpecType 53 Name string 54 } 55 56 // MakeRoleSpecWithRoleName creates a RoleSpec using a RoleName. 57 func MakeRoleSpecWithRoleName(name string) RoleSpec { 58 return RoleSpec{RoleSpecType: RoleName, Name: name} 59 } 60 61 // Undefined returns if RoleSpec is undefined. 62 func (r RoleSpec) Undefined() bool { 63 return r.RoleSpecType == RoleName && len(r.Name) == 0 64 } 65 66 // Format implements the NodeFormatter interface. 67 func (r *RoleSpec) Format(ctx *FmtCtx) { 68 f := ctx.flags 69 if f.HasFlags(FmtAnonymize) && !isArityIndicatorString(r.Name) { 70 ctx.WriteByte('_') 71 } else { 72 switch r.RoleSpecType { 73 case RoleName: 74 lexbase.EncodeRestrictedSQLIdent(&ctx.Buffer, r.Name, f.EncodeFlags()) 75 return 76 case CurrentUser, SessionUser: 77 ctx.WriteString(r.RoleSpecType.String()) 78 } 79 } 80 } 81 82 // Format implements the NodeFormatter interface. 83 func (l *RoleSpecList) Format(ctx *FmtCtx) { 84 for i := range *l { 85 if i > 0 { 86 ctx.WriteString(", ") 87 } 88 ctx.FormatNode(&(*l)[i]) 89 } 90 }