From 992ab3081563808fcf0b62af0737654777ba1122 Mon Sep 17 00:00:00 2001 From: tangyang9464 Date: Thu, 9 Sep 2021 16:17:55 +0800 Subject: [PATCH] fix: change AddPolicies to batch insert Signed-off-by: tangyang9464 --- adapter.go | 15 ++++++--------- adapter_test.go | 9 +++++++++ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/adapter.go b/adapter.go index d515ea2..4eb3970 100755 --- a/adapter.go +++ b/adapter.go @@ -562,15 +562,12 @@ func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { // AddPolicies adds multiple policy rules to the storage. func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error { - return a.db.Transaction(func(tx *gorm.DB) error { - for _, rule := range rules { - line := a.savePolicyLine(ptype, rule) - if err := tx.Create(&line).Error; err != nil { - return err - } - } - return nil - }) + var lines []CasbinRule + for _, rule := range rules { + line := a.savePolicyLine(ptype, rule) + lines = append(lines, line) + } + return a.db.Create(&lines).Error } // RemovePolicies removes multiple policy rules from the storage. diff --git a/adapter_test.go b/adapter_test.go index 481a494..8076e75 100755 --- a/adapter_test.go +++ b/adapter_test.go @@ -516,3 +516,12 @@ func TestAdapters(t *testing.T) { //testUpdatePolicy(t, a) //testUpdatePolicies(t, a) } + +func TestAddPolicies(t *testing.T) { + a := initAdapter(t, "mysql", "root:@tcp(127.0.0.1:3306)/", "casbin", "casbin_rule") + e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) + e.AddPolicies([][]string{{"jack", "data1", "read"}, {"jack2", "data1", "read"}}) + e.LoadPolicy() + + testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"jack", "data1", "read"}, {"jack2", "data1", "read"}}) +}