Skip to content

Commit

Permalink
Merge pull request #3 from Dasio/master
Browse files Browse the repository at this point in the history
Create table if not exists already
  • Loading branch information
hsluoyz authored Feb 17, 2020
2 parents 4b984d2 + 5058cc5 commit 13bf718
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ import (
"github.com/mmcloughlin/meow"
)

const (
tableExistsErrorCode = "ERROR #42P07"
)

// CasbinRule represents a rule in Casbin.
type CasbinRule struct {
ID string
Expand Down Expand Up @@ -49,7 +45,7 @@ func NewAdapter(arg interface{}) (*Adapter, error) {

a := &Adapter{db: db}

if err := a.createTable(); err != nil {
if err := a.createTableifNotExists(); err != nil {
return nil, fmt.Errorf("pgadapter.NewAdapter: %v", err)
}

Expand All @@ -60,7 +56,7 @@ func NewAdapter(arg interface{}) (*Adapter, error) {
// creates table from CasbinRule struct if it doesn't exist
func NewAdapterByDB(db *pg.DB) (*Adapter, error) {
a := &Adapter{db: db}
if err := a.createTable(); err != nil {
if err := a.createTableifNotExists(); err != nil {
return nil, fmt.Errorf("pgadapter.NewAdapter: %v", err)
}
return a, nil
Expand Down Expand Up @@ -101,15 +97,13 @@ func (a *Adapter) Close() error {
return nil
}

func (a *Adapter) createTable() error {
func (a *Adapter) createTableifNotExists() error {
err := a.db.CreateTable(&CasbinRule{}, &orm.CreateTableOptions{
Temp: false,
Temp: false,
IfNotExists: true,
})
if err != nil {
errorCode := err.Error()[0:12]
if errorCode != tableExistsErrorCode {
return err
}
return err
}
return nil
}
Expand Down

0 comments on commit 13bf718

Please sign in to comment.