Skip to content

Commit

Permalink
create table and index in the transaction (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Mar 30, 2024
1 parent bc9f8b5 commit 714c35c
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,28 +114,33 @@ func connectDB(driverName, dataSourceName string) (*bun.DB, error) {
}

func (a *bunAdapter) createTalbe() error {
if _, err := a.db.NewCreateTable().
Model((*CasbinPolicy)(nil)).
ModelTableExpr(a.tableName).
IfNotExists().
Exec(context.Background()); err != nil {
if err := a.db.RunInTx(context.Background(), &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
if _, err := tx.NewCreateTable().
Model((*CasbinPolicy)(nil)).
ModelTableExpr(a.tableName).
IfNotExists().
Exec(ctx); err != nil {
return err
}
// it might be better to create a unique index using hooks
// but the table name(a.tableName) cannot be accessed from the hook
// so we create the index here
if _, err := tx.NewCreateIndex().
Model((*CasbinPolicy)(nil)).
ModelTableExpr(a.tableName).
Unique().
Index("idx_ptype_v0_v1_v2_v3_v4_v5").
Column("ptype", "v0", "v1", "v2", "v3", "v4", "v5").
Exec(ctx); err != nil {
return err
}
return nil
}); err != nil {
return err
}
return nil
}

var _ bun.AfterCreateTableHook = (*CasbinPolicy)(nil)

func (*CasbinPolicy) AfterCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
_, err := query.DB().NewCreateIndex().
Model((*CasbinPolicy)(nil)).
Unique().
Index("idx_ptype_v0_v1_v2_v3_v4_v5").
Column("ptype", "v0", "v1", "v2", "v3", "v4", "v5").
Exec(ctx)
return err
}

// LoadPolicy loads all policy rules from the storage.
func (a *bunAdapter) LoadPolicy(model model.Model) error {
var policies []CasbinPolicy
Expand Down

0 comments on commit 714c35c

Please sign in to comment.