Skip to content

Commit

Permalink
create index in hooks (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Mar 30, 2024
1 parent f72285c commit 685d414
Showing 1 changed file with 22 additions and 29 deletions.
51 changes: 22 additions & 29 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func NewAdapter(driverName, dataSourceName string, opts ...adapterOption) (*bunA
b.db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
}

if err := b.createTalbe(); err != nil {
if err := b.createTable(); err != nil {
return nil, err
}

Expand Down Expand Up @@ -113,33 +113,26 @@ func connectDB(driverName, dataSourceName string) (*bun.DB, error) {
}
}

func (a *bunAdapter) createTalbe() error {
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).
IfNotExists().
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
func (a *bunAdapter) createTable() error {
_, err := a.db.NewCreateTable().
Model((*CasbinPolicy)(nil)).
ModelTableExpr(a.tableName).
IfNotExists().
Exec(context.Background())
return err
}

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

func (*CasbinPolicy) AfterCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
_, err := query.DB().NewCreateIndex().
Model((*CasbinPolicy)(nil)).
ModelTableExpr(query.GetTableName()).
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.
Expand Down Expand Up @@ -225,7 +218,7 @@ func (a *bunAdapter) refreshTable() error {
Exec(context.Background()); err != nil {
return err
}
return a.createTalbe()
return a.createTable()
}

// AddPolicy adds a policy rule to the storage.
Expand Down

0 comments on commit 685d414

Please sign in to comment.