Skip to content

Commit

Permalink
feat: fix Postgres primary keys growing (#224)
Browse files Browse the repository at this point in the history
* fix: fix postgres truncate not restart identify

* fix: fix testing error
fix the test error Error 1065: Query was empty

* fix: fix sqlite unique key conflict

---------

Co-authored-by: wuzhican <3245076860@qq.com>
  • Loading branch information
wuzhican and wuzhican authored Sep 27, 2023
1 parent 6f78166 commit b48be9f
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,10 +435,22 @@ func (a *Adapter) dropTable() error {
}

func (a *Adapter) truncateTable() error {
if a.db.Config.Name() == sqlite.DriverName {
return a.db.Exec(fmt.Sprintf("delete from %s", a.getFullTableName())).Error
var sql string
switch a.db.Config.Name() {
case sqlite.DriverName:
sql = fmt.Sprintf("delete from %s", a.getFullTableName())
case "sqlite3":
sql = fmt.Sprintf("delete from %s", a.getFullTableName())
case "postgres":
sql = fmt.Sprintf("truncate table %s RESTART IDENTITY", a.getFullTableName())
case "sqlserver":
sql = fmt.Sprintf("truncate table %s", a.getFullTableName())
case "mysql":
sql = fmt.Sprintf("truncate table %s", a.getFullTableName())
default:
sql = fmt.Sprintf("truncate table %s", a.getFullTableName())
}
return a.db.Exec(fmt.Sprintf("truncate table %s", a.getFullTableName())).Error
return a.db.Exec(sql).Error
}

func loadPolicyLine(line CasbinRule, model model.Model) error {
Expand Down Expand Up @@ -582,11 +594,7 @@ func (a *Adapter) SavePolicy(model model.Model) error {
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
}
err = a.truncateTable()

if err != nil {
tx.Rollback()
Expand Down

0 comments on commit b48be9f

Please sign in to comment.