Skip to content

Commit

Permalink
Utilize correct db error when the duplicate database is created (#39)
Browse files Browse the repository at this point in the history
As per http://v2.gorm.io/docs/conventions.html#TableName TableName() suppose to generate static names only (it could not be dynamic). The same source suggests a workaround that I implemented as DynamicCasbinRuleTable along with a scoped DB object for NewAdapterByDBUsePrefix.

As a result of 2. we can remove tablePrefix from global state

Signed-off-by: l1ghtman2k <aibek.zhil@gmail.com>
  • Loading branch information
L1ghtman2k authored Jul 24, 2020
1 parent ac27d59 commit 81c2dc6
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
"errors"
"github.com/casbin/casbin/v2/model"
"github.com/casbin/casbin/v2/persist"
"github.com/lib/pq"
"github.com/jackc/pgconn"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
Expand All @@ -28,8 +28,6 @@ import (
"strings"
)

var tablePrefix string

type CasbinRule struct {
TablePrefix string `gorm:"-"`
PType string `gorm:"size:100"`
Expand All @@ -52,7 +50,13 @@ type Filter struct {
}

func (c *CasbinRule) TableName() string {
return c.TablePrefix + "casbin_rule" //as Gorm keeps table names are plural, and we love consistency
return "casbin_rule" //as Gorm keeps table names are plural, and we love consistency
}

func DynamicCasbinRuleTable(c *CasbinRule) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
return db.Table(c.TablePrefix + "casbin_rule") //as Gorm keeps table names are plural, and we love consistency
}
}

// Adapter represents the Gorm adapter for policy storage.
Expand Down Expand Up @@ -112,11 +116,9 @@ func NewAdapter(driverName string, dataSourceName string, dbSpecified ...bool) (
func NewAdapterByDBUsePrefix(db *gorm.DB, prefix string) (*Adapter, error) {
a := &Adapter{
tablePrefix: prefix,
db: db,
db: db.Scopes(DynamicCasbinRuleTable(&CasbinRule{TablePrefix: prefix})),
}

tablePrefix = prefix

err := a.createTable()
if err != nil {
return nil, err
Expand Down Expand Up @@ -167,7 +169,7 @@ func (a *Adapter) createDatabase() error {
if a.driverName == "postgres" {
if err = db.Exec("CREATE DATABASE casbin").Error; err != nil {
// 42P04 is duplicate_database
if err.(*pq.Error).Code == "42P04" {
if err.(*pgconn.PgError).Code == "42P04" {
return nil
}
}
Expand Down

0 comments on commit 81c2dc6

Please sign in to comment.