Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use transaction in SavePolicy() #208

Merged
merged 3 commits into from
Apr 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,17 @@ func (a *Adapter) savePolicyLine(ptype string, rule []string) CasbinRule {

// SavePolicy saves policy to database.
func (a *Adapter) SavePolicy(model model.Model) error {
err := a.truncateTable()
var err error
tx := a.db.Clauses(dbresolver.Write).Begin()

if a.db.Config.Name() == sqlite.DriverName {
err = tx.Exec(fmt.Sprintf("delete from %s", a.getFullTableName())).Error
} else {
err = tx.Exec(fmt.Sprintf("truncate table %s", a.getFullTableName())).Error
}

if err != nil {
tx.Rollback()
return err
}

Expand All @@ -590,7 +599,8 @@ func (a *Adapter) SavePolicy(model model.Model) error {
for _, rule := range ast.Policy {
lines = append(lines, a.savePolicyLine(ptype, rule))
if len(lines) > flushEvery {
if err := a.db.Create(&lines).Error; err != nil {
if err := tx.Create(&lines).Error; err != nil {
tx.Rollback()
return err
}
lines = nil
Expand All @@ -602,20 +612,23 @@ func (a *Adapter) SavePolicy(model model.Model) error {
for _, rule := range ast.Policy {
lines = append(lines, a.savePolicyLine(ptype, rule))
if len(lines) > flushEvery {
if err := a.db.Create(&lines).Error; err != nil {
if err := tx.Create(&lines).Error; err != nil {
tx.Rollback()
return err
}
lines = nil
}
}
}
if len(lines) > 0 {
if err := a.db.Create(&lines).Error; err != nil {
if err := tx.Create(&lines).Error; err != nil {
tx.Rollback()
return err
}
}

return nil
err = tx.Commit().Error
return err
}

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