@@ -19,10 +19,30 @@ const (
1919 REASIGN_OBJECTS = `REASSIGN OWNED BY "%s" TO "%s"`
2020)
2121
22+ func isPQError (err error , codes ... pq.ErrorCode ) bool {
23+ if err == nil {
24+ return false
25+ }
26+
27+ pgError , ok := err .(* pq.Error )
28+ if ok {
29+ if len (codes ) == 0 {
30+ // just checking if its a pgerror
31+ return true
32+ }
33+ for _ , code := range codes {
34+ if pgError .Code == code {
35+ return true
36+ }
37+ }
38+ }
39+ return false
40+ }
41+
2242func (c * pg ) CreateGroupRole (role string ) error {
2343 // Error code 42710 is duplicate_object (role already exists)
2444 _ , err := c .db .Exec (fmt .Sprintf (CREATE_GROUP_ROLE , role ))
25- if err != nil && err .( * pq. Error ). Code != "42710" {
45+ if err != nil && isPQError ( err , "42710" ) {
2646 return err
2747 }
2848 return nil
@@ -64,7 +84,7 @@ func (c *pg) DropRole(role, newOwner, database string, logger logr.Logger) error
6484 // REASSIGN OWNED BY only works if the correct database is selected
6585 tmpDb , err := GetConnection (c .user , c .pass , c .host , c .port , database , c .args , logger )
6686 if err != nil {
67- if err .( * pq. Error ). Code == "3D000" {
87+ if isPQError ( err , "3D000" ) {
6888 return nil // Database is does not exist (anymore)
6989 } else {
7090 return err
@@ -73,20 +93,20 @@ func (c *pg) DropRole(role, newOwner, database string, logger logr.Logger) error
7393 _ , err = tmpDb .Exec (fmt .Sprintf (REASIGN_OBJECTS , role , newOwner ))
7494 defer tmpDb .Close ()
7595 // Check if error exists and if different from "ROLE NOT FOUND" => 42704
76- if err != nil && err .( * pq. Error ). Code != "42704" {
96+ if err != nil && isPQError ( err , "42704" ) {
7797 return err
7898 }
7999
80100 // We previously assigned all objects to the operator's role so DROP OWNED BY will drop privileges of role
81101 _ , err = tmpDb .Exec (fmt .Sprintf (DROP_OWNED_BY , role ))
82102 // Check if error exists and if different from "ROLE NOT FOUND" => 42704
83- if err != nil && err .( * pq. Error ). Code != "42704" {
103+ if err != nil && isPQError ( err , "42704" ) {
84104 return err
85105 }
86106
87107 _ , err = c .db .Exec (fmt .Sprintf (DROP_ROLE , role ))
88108 // Check if error exists and if different from "ROLE NOT FOUND" => 42704
89- if err != nil && err .( * pq. Error ). Code != "42704" {
109+ if err != nil && isPQError ( err , "42704" ) {
90110 return err
91111 }
92112 return nil
0 commit comments