casbin / gorm-adapter

GORM adapter for Casbin, see extended version of GORM Adapter Ex at: https://github.com/casbin/gorm-adapter-ex
https://github.com/casbin/casbin
Apache License 2.0
678 stars 206 forks source link

Adapter Transaction db table can not set #206

Closed weloe closed 1 year ago

weloe commented 1 year ago

https://github.com/casbin/casbin/issues/1205 I used the registration of this business to achieve what the issue said. https://github.com/casbin/casbin/issues/1205#issuecomment-1501221142 use db.Exec it works But when I used db.Model or db.Table to set table name,it does not work,it executes table is casbin_rule

// *request.Register has Username and Password
func Register(register *request.Register) {
    var err error

    // component.Enforcer type is *casbin.Enforcer
    e := component.Enforcer
    err = e.GetAdapter().(*gormadapter.Adapter).Transaction(e, func(copyEnforcer casbin.IEnforcer) error {
        // Insert to user table
        db := copyEnforcer.GetAdapter().(*gormadapter.Adapter).GetDb()
        //res := db.Exec("insert into user (username,password) values(?,?)", register.Username, register.Password)

               //User has Username and Password
        res := db.Table("user").Create(&User{
            Username: register.Username,
            Password: register.Password,
        })

        if err != nil || res.RowsAffected < 1 {
            return fmt.Errorf("insert error: %w", err)
        }
        // Add policy
        _, err = copyEnforcer.AddPolicy(register.Username, "resource", "write")
        if err != nil {
            return fmt.Errorf("add plocy error: %w", err)
        }
        if register.Username == "error" {
            return fmt.Errorf("register error: %w", err)
        }

        return nil
    })

    if err != nil {
        panic(fmt.Errorf("register error: %w", err))
    }

}

what it actually does is INSERT INTO casbin_rule (usernam,password) VALUES ('','') I think db.Statement.scopes effect the table name, but I don't know how to resolve it

casbin-bot commented 1 year ago

@tangyang9464 @JalinWang @imp2002

terry-xuan-gao commented 1 year ago

The following is my understanding, I hope it can help you.

The reason why db.Table() cannot execute the specified table name is this line of code: a.db = db.Scopes(a.casbinRuleTable()).Session(&gorm.Session{}) The default table for the current session is "casbin_rule", although you specify a different table name in the Table() , it does not work.

You want to operate the user table, why not use Exec() directly? res := db.Exec("insert into user (username,password) values(?,?)", register.Username, register.Password) As you said, it works.

Alternatively, you can try to create a new session, or try to modify the configuration of the current session.