diff --git a/README.md b/README.md index ee3321a..30ae38c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -# Go-pg Adapter +# Go pgx Adapter [![Go](https://github.com/casbin/casbin-pg-adapter/actions/workflows/ci.yml/badge.svg)](https://github.com/casbin/casbin-pg-adapter/actions/workflows/ci.yml) [![Coverage Status](https://coveralls.io/repos/github/casbin/casbin-pg-adapter/badge.svg?branch=master)](https://coveralls.io/github/casbin/casbin-pg-adapter?branch=master) -Go-pg Adapter is the [Go-pg](https://github.com/go-pg/pg) adapter for [Casbin](https://github.com/casbin/casbin). With this library, Casbin can load policy from PostgreSQL or save policy to it. +Go-pgx Adapter is the [pgx](https://github.com/jackc/pgx) adapter for [Casbin](https://github.com/casbin/casbin). With this library, Casbin can load policy from PostgreSQL or save policy to it. ## Installation @@ -20,23 +20,11 @@ import ( ) func main() { - // Initialize a Go-pg adapter and use it in a Casbin enforcer: + // Initialize a pgx adapter and use it in a Casbin enforcer: // The adapter will use the Postgres database named "casbin". // If it doesn't exist, the adapter will create it automatically. a, _ := pgadapter.NewAdapter("postgresql://username:password@postgres:5432/database?sslmode=disable") // Your driver and data source. - // Alternatively, you can construct an adapter instance with *pg.Options: - // a, _ := pgadapter.NewAdapter(&pg.Options{ - // Database: "...", - // User: "...", - // Password: "...", - // }) - - // The adapter will use the table named "casbin_rule". - // If it doesn't exist, the adapter will create it automatically. - // Or you can use an existing DB by adding a second string parameter with your database name to the NewAdapter(), like this: - // a, _ := pgadapter.NewAdapter("postgresql://username:password@postgres:5432/database?sslmode=disable", "your_database_name") - e := casbin.NewEnforcer("examples/rbac_model.conf", a) // Load the policy from DB. @@ -88,13 +76,11 @@ package main import ( "github.com/casbin/casbin/v2" pgadapter "github.com/casbin/casbin-pg-adapter" - "github.com/go-pg/pg/v9" + "github.com/jackc/pgx/v5/pgxpool" ) func main() { - opts, _ := pg.ParseURL("postgresql://pguser:pgpassword@localhost:5432/pgdb?sslmode=disable") - - db := pg.Connect(opts) + db, _ := pgxpool.New(context.Background(), "postgresql://pguser:pgpassword@localhost:5432/pgdb?sslmode=disable") defer db.Close() a, _ := pgadapter.NewAdapterByDB(db, pgadapter.WithTableName("custom_table")) diff --git a/adapter.go b/adapter.go index 402c412..85eef08 100644 --- a/adapter.go +++ b/adapter.go @@ -7,8 +7,7 @@ import ( "github.com/casbin/casbin/v2/model" "github.com/casbin/casbin/v2/persist" - "github.com/go-pg/pg/v10" - "github.com/go-pg/pg/v10/orm" + "github.com/jackc/pgx/v5/pgxpool" "github.com/mmcloughlin/meow" ) @@ -20,12 +19,12 @@ type CasbinRule struct { tableName struct{} `pg:"_"` ID string Ptype string - V0 string `pg:",use_zero"` - V1 string `pg:",use_zero"` - V2 string `pg:",use_zero"` - V3 string `pg:",use_zero"` - V4 string `pg:",use_zero"` - V5 string `pg:",use_zero"` + V0 *string + V1 *string + V2 *string + V3 *string + V4 *string + V5 *string } type Filter struct { @@ -33,9 +32,9 @@ type Filter struct { G []string } -// Adapter represents the github.com/go-pg/pg adapter for policy storage. +// Adapter represents the pgx adapter for policy storage. type Adapter struct { - db *pg.DB + db *pgxpool.Pool tableName string skipTableCreate bool filtered bool @@ -44,43 +43,88 @@ type Adapter struct { type Option func(a *Adapter) // NewAdapter is the constructor for Adapter. -// param:arg should be a PostgreS URL string or of type *pg.Options -// param:dbname is the name of the database to use and can is optional. -// If no dbname is provided, the default database name is "casbin" which will be created automatically. -// If arg is *pg.Options, the arg.Database field is omitted and will be modified according to dbname -func NewAdapter(arg interface{}, dbname ...string) (*Adapter, error) { - var db *pg.DB - var err error +func NewAdapter(connString string, dbname ...string) (*Adapter, error) { + config, err := pgxpool.ParseConfig(connString) + if err != nil { + return nil, fmt.Errorf("pgadapter.NewAdapter: %v", err) + } if len(dbname) > 0 { - db, err = createCasbinDatabase(arg, dbname[0]) + config.ConnConfig.Database = dbname[0] + createCasbinDatabase(connString, dbname[0]) + } else { - db, err = createCasbinDatabase(arg, DefaultDatabaseName) + config.ConnConfig.Database = DefaultDatabaseName + createCasbinDatabase(connString, DefaultDatabaseName) } + db, err := pgxpool.NewWithConfig(context.Background(), config) if err != nil { return nil, fmt.Errorf("pgadapter.NewAdapter: %v", err) } a := &Adapter{db: db, tableName: DefaultTableName} - if err := a.createTableifNotExists(); err != nil { + if err := a.createTableIfNotExists(); err != nil { return nil, fmt.Errorf("pgadapter.NewAdapter: %v", err) } return a, nil } +func createCasbinDatabase(arg interface{}, dbname string) error { + var connString string + var ok bool + + if connString, ok = arg.(string); !ok { + return fmt.Errorf("must pass in a PostgreSQL connection string, received %T instead", arg) + } + + // Connect to the default database + config, err := pgxpool.ParseConfig(connString) + if err != nil { + return fmt.Errorf("failed to parse connection string: %v", err) + } + + // Temporarily connect to the default database + tempConfig := *config + tempConfig.ConnConfig.Database = "postgres" + tempPool, err := pgxpool.NewWithConfig(context.Background(), &tempConfig) + if err != nil { + return fmt.Errorf("failed to connect to default database: %v", err) + } + defer tempPool.Close() + + // Check if the database already exists + var exists bool + err = tempPool.QueryRow(context.Background(), "SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", dbname).Scan(&exists) + if err != nil { + return fmt.Errorf("failed to check if database exists: %v", err) + } + + if exists { + return nil // Database already exists, no need to create + } + + // Create the new database + _, err = tempPool.Exec(context.Background(), fmt.Sprintf("CREATE DATABASE %s", dbname)) + if err != nil && !strings.Contains(err.Error(), "already exists") { + return fmt.Errorf("failed to create database: %v", err) + } + + return nil +} + // NewAdapterByDB creates new Adapter by using existing DB connection // creates table from CasbinRule struct if it doesn't exist -func NewAdapterByDB(db *pg.DB, opts ...Option) (*Adapter, error) { +func NewAdapterByDB(db *pgxpool.Pool, opts ...Option) (*Adapter, error) { a := &Adapter{db: db, tableName: DefaultTableName} for _, opt := range opts { opt(a) } if !a.skipTableCreate { - if err := a.createTableifNotExists(); err != nil { + if err := a.createTableIfNotExists(); err != nil { return nil, fmt.Errorf("pgadapter.NewAdapter: %v", err) } } @@ -102,58 +146,48 @@ func SkipTableCreate() Option { } } -func createCasbinDatabase(arg interface{}, dbname string) (*pg.DB, error) { - var opts *pg.Options - var err error - if connURL, ok := arg.(string); ok { - opts, err = pg.ParseURL(connURL) - if err != nil { - return nil, err - } - } else { - opts, ok = arg.(*pg.Options) - if !ok { - return nil, fmt.Errorf("must pass in a PostgreS URL string or an instance of *pg.Options, received %T instead", arg) - } - } - - db := pg.Connect(opts) - defer db.Close() - - _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", dbname)) - if err != nil && !strings.Contains(err.Error(), "42P04") { - return nil, err - } - db.Close() - - opts.Database = dbname - db = pg.Connect(opts) - - return db, nil -} - -// Close close database connection +// Close closes the database connection. func (a *Adapter) Close() error { if a != nil && a.db != nil { - return a.db.Close() + a.db.Close() } return nil } -func (a *Adapter) createTableifNotExists() error { - err := a.db.Model((*CasbinRule)(nil)).Table(a.tableName).CreateTable(&orm.CreateTableOptions{ - Temp: false, - IfNotExists: true, - }) - if err != nil { - return err +func (a *Adapter) createTableIfNotExists() error { + _, err := a.db.Exec(context.Background(), fmt.Sprintf(` + CREATE TABLE IF NOT EXISTS %s ( + id TEXT PRIMARY KEY, + ptype TEXT, + v0 TEXT, + v1 TEXT, + v2 TEXT, + v3 TEXT, + v4 TEXT, + v5 TEXT + )`, a.tableName)) + return err +} + +// getStringLength safely returns the length of a string pointer. +func getStringLength(s *string) int { + if s == nil { + return 0 } - return nil + return len(*s) } // getValues returns the V0-V5 values as a slice func (r *CasbinRule) getValues() []string { - return []string{r.V0, r.V1, r.V2, r.V3, r.V4, r.V5} + values := []string{} + for _, v := range []*string{r.V0, r.V1, r.V2, r.V3, r.V4, r.V5} { + if v != nil { + values = append(values, *v) + } else { + values = append(values, "") + } + } + return values } // getLastNonEmptyIndex returns the index of the last non-empty value in the given slice @@ -173,15 +207,15 @@ func (r *CasbinRule) String() string { sb.Grow( len(r.Ptype) + - len(r.V0) + len(r.V1) + len(r.V2) + - len(r.V3) + len(r.V4) + len(r.V5), + getStringLength(r.V0) + getStringLength(r.V1) + getStringLength(r.V2) + + getStringLength(r.V3) + getStringLength(r.V4) + getStringLength(r.V5), ) sb.WriteString(r.Ptype) - + values := r.getValues() lastIndex := getLastNonEmptyIndex(values) - + // Include all values up to and including the last non-empty one // This preserves empty strings in the middle while trimming trailing empty strings for i := 0; i <= lastIndex; i++ { @@ -192,23 +226,25 @@ func (r *CasbinRule) String() string { return sb.String() } -// LoadPolicy loads policy from database. +// LoadPolicy loads policy from the database. func (a *Adapter) LoadPolicy(model model.Model) error { - var lines []*CasbinRule - - if err := a.db.Model(&lines).Table(a.tableName).Select(); err != nil { + rows, err := a.db.Query(context.Background(), fmt.Sprintf("SELECT id, ptype, v0, v1, v2, v3, v4, v5 FROM %s", a.tableName)) + if err != nil { return err } + defer rows.Close() - for _, line := range lines { - err := persist.LoadPolicyLine(line.String(), model) - if err != nil { + for rows.Next() { + var line CasbinRule + if err := rows.Scan(&line.ID, &line.Ptype, &line.V0, &line.V1, &line.V2, &line.V3, &line.V4, &line.V5); err != nil { + return err + } + if err := persist.LoadPolicyLine(line.String(), model); err != nil { return err } } a.filtered = false - return nil } @@ -223,22 +259,22 @@ func savePolicyLine(ptype string, rule []string) *CasbinRule { l := len(rule) if l > 0 { - line.V0 = rule[0] + line.V0 = &rule[0] } if l > 1 { - line.V1 = rule[1] + line.V1 = &rule[1] } if l > 2 { - line.V2 = rule[2] + line.V2 = &rule[2] } if l > 3 { - line.V3 = rule[3] + line.V3 = &rule[3] } if l > 4 { - line.V4 = rule[4] + line.V4 = &rule[4] } if l > 5 { - line.V5 = rule[5] + line.V5 = &rule[5] } line.ID = policyID(ptype, rule) @@ -248,13 +284,13 @@ func savePolicyLine(ptype string, rule []string) *CasbinRule { // SavePolicy saves policy to database. func (a *Adapter) SavePolicy(model model.Model) error { - tx, err := a.db.Begin() + tx, err := a.db.Begin(context.Background()) if err != nil { return fmt.Errorf("start DB transaction: %v", err) } - defer tx.Close() + defer tx.Rollback(context.Background()) - _, err = tx.Model((*CasbinRule)(nil)).Table(a.tableName).Where("id IS NOT NULL").Delete() + _, err = tx.Exec(context.Background(), fmt.Sprintf("DELETE FROM %s WHERE id IS NOT NULL", a.tableName)) if err != nil { return err } @@ -276,15 +312,17 @@ func (a *Adapter) SavePolicy(model model.Model) error { } for _, line := range lines { - _, err = tx.Model(line).Table(a.tableName). - OnConflict("DO NOTHING"). - Insert() + _, err = tx.Exec(context.Background(), fmt.Sprintf(` + INSERT INTO %s (id, ptype, v0, v1, v2, v3, v4, v5) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT DO NOTHING`, a.tableName), + line.ID, line.Ptype, line.V0, line.V1, line.V2, line.V3, line.V4, line.V5) if err != nil { return err } } - err = tx.Commit() + err = tx.Commit(context.Background()) if err != nil { return fmt.Errorf("commit DB transaction: %v", err) } @@ -295,94 +333,86 @@ func (a *Adapter) SavePolicy(model model.Model) error { // AddPolicy adds a policy rule to the storage. func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error { line := savePolicyLine(ptype, rule) - err := a.db.RunInTransaction(context.Background(), func(tx *pg.Tx) error { - _, err := a.db.Model(line). - Table(a.tableName). - OnConflict("DO NOTHING"). - Insert() - - return err - }) - + _, err := a.db.Exec(context.Background(), fmt.Sprintf(` + INSERT INTO %s (id, ptype, v0, v1, v2, v3, v4, v5) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT DO NOTHING`, a.tableName), + line.ID, line.Ptype, line.V0, line.V1, line.V2, line.V3, line.V4, line.V5) return err } // AddPolicies adds policy rules to the storage. func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error { - var lines []*CasbinRule + tx, err := a.db.Begin(context.Background()) + if err != nil { + return err + } + defer tx.Rollback(context.Background()) + for _, rule := range rules { line := savePolicyLine(ptype, rule) - lines = append(lines, line) + _, err := tx.Exec(context.Background(), fmt.Sprintf(` + INSERT INTO %s (id, ptype, v0, v1, v2, v3, v4, v5) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT DO NOTHING`, a.tableName), + line.ID, line.Ptype, line.V0, line.V1, line.V2, line.V3, line.V4, line.V5) + if err != nil { + return err + } } - err := a.db.RunInTransaction(context.Background(), func(tx *pg.Tx) error { - _, err := tx.Model(&lines). - Table(a.tableName). - OnConflict("DO NOTHING"). - Insert() + err = tx.Commit(context.Background()) + if err != nil { return err - }) + } - return err + return nil } // RemovePolicy removes a policy rule from the storage. func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { line := savePolicyLine(ptype, rule) - err := a.db.RunInTransaction(context.Background(), func(tx *pg.Tx) error { - _, err := a.db.Model(line).Table(a.tableName).WherePK().Delete() - return err - }) - + _, err := a.db.Exec(context.Background(), fmt.Sprintf("DELETE FROM %s WHERE id = $1", a.tableName), line.ID) return err } // RemovePolicies removes policy rules from the storage. func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) error { - var lines []*CasbinRule + tx, err := a.db.Begin(context.Background()) + if err != nil { + return err + } + defer tx.Rollback(context.Background()) + for _, rule := range rules { line := savePolicyLine(ptype, rule) - lines = append(lines, line) + _, err := tx.Exec(context.Background(), fmt.Sprintf("DELETE FROM %s WHERE id = $1", a.tableName), line.ID) + if err != nil { + return err + } } - err := a.db.RunInTransaction(context.Background(), func(tx *pg.Tx) error { - _, err := tx.Model(&lines).Table(a.tableName). - Delete() + err = tx.Commit(context.Background()) + if err != nil { return err - }) + } - return err + return nil } // RemoveFilteredPolicy removes policy rules that match the filter from the storage. func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { - query := a.db.Model((*CasbinRule)(nil)).Table(a.tableName).Where("ptype = ?", ptype) + query := fmt.Sprintf("DELETE FROM %s WHERE ptype = $1", a.tableName) + args := []interface{}{ptype} - idx := fieldIndex + len(fieldValues) - if fieldIndex <= 0 && idx > 0 && fieldValues[0-fieldIndex] != "" { - query = query.Where("v0 = ?", fieldValues[0-fieldIndex]) - } - if fieldIndex <= 1 && idx > 1 && fieldValues[1-fieldIndex] != "" { - query = query.Where("v1 = ?", fieldValues[1-fieldIndex]) - } - if fieldIndex <= 2 && idx > 2 && fieldValues[2-fieldIndex] != "" { - query = query.Where("v2 = ?", fieldValues[2-fieldIndex]) - } - if fieldIndex <= 3 && idx > 3 && fieldValues[3-fieldIndex] != "" { - query = query.Where("v3 = ?", fieldValues[3-fieldIndex]) - } - if fieldIndex <= 4 && idx > 4 && fieldValues[4-fieldIndex] != "" { - query = query.Where("v4 = ?", fieldValues[4-fieldIndex]) - } - if fieldIndex <= 5 && idx > 5 && fieldValues[5-fieldIndex] != "" { - query = query.Where("v5 = ?", fieldValues[5-fieldIndex]) + for i, v := range fieldValues { + if v != "" { + query += fmt.Sprintf(" AND v%d = $%d", fieldIndex+i, len(args)+1) + args = append(args, v) + } } - err := a.db.RunInTransaction(context.Background(), func(tx *pg.Tx) error { - _, err := query.Delete() - return err - }) - + _, err := a.db.Exec(context.Background(), query, args...) return err } @@ -403,64 +433,54 @@ func (a *Adapter) LoadFilteredPolicy(model model.Model, filter interface{}) erro return nil } -func buildQuery(query *orm.Query, values []string) (*orm.Query, error) { - for ind, v := range values { - if v == "" { - continue - } - switch ind { - case 0: - query = query.Where("v0 = ?", v) - case 1: - query = query.Where("v1 = ?", v) - case 2: - query = query.Where("v2 = ?", v) - case 3: - query = query.Where("v3 = ?", v) - case 4: - query = query.Where("v4 = ?", v) - case 5: - query = query.Where("v5 = ?", v) - default: - return nil, fmt.Errorf("filter has more values than expected, should not exceed 6 values") +func buildQuery(query string, values []string) (string, []interface{}) { + args := []interface{}{} + for i, v := range values { + if v != "" { + query += fmt.Sprintf(" AND v%d = $%d", i, len(args)+1) + args = append(args, v) } } - return query, nil + return query, args } func (a *Adapter) loadFilteredPolicy(model model.Model, filter *Filter, handler func(string, model.Model) error) error { if filter.P != nil { - lines := []*CasbinRule{} - - query := a.db.Model(&lines).Table(a.tableName).Where("ptype = 'p'") - query, err := buildQuery(query, filter.P) - if err != nil { - return err - } - err = query.Select() + query := fmt.Sprintf("SELECT id, ptype, v0, v1, v2, v3, v4, v5 FROM %s WHERE ptype = 'p'", a.tableName) + query, args := buildQuery(query, filter.P) + rows, err := a.db.Query(context.Background(), query, args...) if err != nil { return err } + defer rows.Close() - for _, line := range lines { - handler(line.String(), model) + for rows.Next() { + var line CasbinRule + if err := rows.Scan(&line.ID, &line.Ptype, &line.V0, &line.V1, &line.V2, &line.V3, &line.V4, &line.V5); err != nil { + return err + } + if err := handler(line.String(), model); err != nil { + return err + } } } if filter.G != nil { - lines := []*CasbinRule{} - - query := a.db.Model(&lines).Table(a.tableName).Where("ptype = 'g'") - query, err := buildQuery(query, filter.G) - if err != nil { - return err - } - err = query.Select() + query := fmt.Sprintf("SELECT id, ptype, v0, v1, v2, v3, v4, v5 FROM %s WHERE ptype = 'g'", a.tableName) + query, args := buildQuery(query, filter.G) + rows, err := a.db.Query(context.Background(), query, args...) if err != nil { return err } + defer rows.Close() - for _, line := range lines { - handler(line.String(), model) + for rows.Next() { + var line CasbinRule + if err := rows.Scan(&line.ID, &line.Ptype, &line.V0, &line.V1, &line.V2, &line.V3, &line.V4, &line.V5); err != nil { + return err + } + if err := handler(line.String(), model); err != nil { + return err + } } } return nil @@ -478,16 +498,28 @@ func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []st // UpdatePolicies updates some policy rules to storage, like db, redis. func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error { - oldLines := make([]*CasbinRule, 0, len(oldRules)) - newLines := make([]*CasbinRule, 0, len(newRules)) - for _, rule := range oldRules { - oldLines = append(oldLines, savePolicyLine(ptype, rule)) + tx, err := a.db.Begin(context.Background()) + if err != nil { + return err } - for _, rule := range newRules { - newLines = append(newLines, savePolicyLine(ptype, rule)) + defer tx.Rollback(context.Background()) + + for i, oldRule := range oldRules { + oldLine := savePolicyLine(ptype, oldRule) + newLine := savePolicyLine(ptype, newRules[i]) + _, err := tx.Exec(context.Background(), fmt.Sprintf("UPDATE %s SET ptype = $1, v0 = $2, v1 = $3, v2 = $4, v3 = $5, v4 = $6, v5 = $7 WHERE id = $8", a.tableName), + newLine.Ptype, newLine.V0, newLine.V1, newLine.V2, newLine.V3, newLine.V4, newLine.V5, oldLine.ID) + if err != nil { + return err + } + } + + err = tx.Commit(context.Background()) + if err != nil { + return err } - return a.updatePolicies(oldLines, newLines) + return nil } func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) { @@ -495,22 +527,22 @@ func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [ line.Ptype = ptype if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) { - line.V0 = fieldValues[0-fieldIndex] + line.V0 = &fieldValues[0-fieldIndex] } if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) { - line.V1 = fieldValues[1-fieldIndex] + line.V1 = &fieldValues[1-fieldIndex] } if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) { - line.V2 = fieldValues[2-fieldIndex] + line.V2 = &fieldValues[2-fieldIndex] } if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) { - line.V3 = fieldValues[3-fieldIndex] + line.V3 = &fieldValues[3-fieldIndex] } if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) { - line.V4 = fieldValues[4-fieldIndex] + line.V4 = &fieldValues[4-fieldIndex] } if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) { - line.V5 = fieldValues[5-fieldIndex] + line.V5 = &fieldValues[5-fieldIndex] } newP := make([]CasbinRule, 0, len(newPolicies)) @@ -519,24 +551,32 @@ func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [ newP = append(newP, *(savePolicyLine(ptype, newRule))) } - err := a.db.RunInTransaction(context.Background(), func(tx *pg.Tx) error { - for i := range newP { - str, args := line.queryString() - _, err := tx.Model(&oldP).Table(a.tableName).Where(str, args...).Delete() - if err != nil { - tx.Rollback() - return err - } - _, err = tx.Model(&newP[i]).Table(a.tableName). - OnConflict("DO NOTHING"). - Insert() - if err != nil { - tx.Rollback() - return err - } + tx, err := a.db.Begin(context.Background()) + if err != nil { + return nil, err + } + defer tx.Rollback(context.Background()) + + for i := range newP { + str, args := line.queryString() + _, err := tx.Exec(context.Background(), fmt.Sprintf("DELETE FROM %s WHERE %s", a.tableName, str), args...) + if err != nil { + return nil, err } - return nil - }) + + _, err = tx.Exec(context.Background(), fmt.Sprintf(` + INSERT INTO %s (id, ptype, v0, v1, v2, v3, v4, v5) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT DO NOTHING`, a.tableName), + newP[i].ID, newP[i].Ptype, newP[i].V0, newP[i].V1, newP[i].V2, newP[i].V3, newP[i].V4, newP[i].V5) + if err != nil { + return nil, err + } + } + + if err = tx.Commit(context.Background()); err != nil { + return nil, err + } // return deleted rulues oldPolicies := make([][]string, 0) @@ -546,19 +586,18 @@ func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [ } return oldPolicies, err } - func (c *CasbinRule) queryString() (string, []interface{}) { queryArgs := []interface{}{c.Ptype} - queryStr := "ptype = ?" + queryStr := "ptype = $1" values := c.getValues() lastIndex := getLastNonEmptyIndex(values) - + // Include all fields up to and including the last non-empty one // This ensures empty strings in the middle are matched explicitly fields := []string{"v0", "v1", "v2", "v3", "v4", "v5"} for i := 0; i <= lastIndex; i++ { - queryStr += " and " + fields[i] + " = ?" + queryStr += fmt.Sprintf(" AND %s = $%d", fields[i], len(queryArgs)+1) queryArgs = append(queryArgs, values[i]) } @@ -570,36 +609,36 @@ func (c *CasbinRule) toStringPolicy() []string { if c.Ptype != "" { policy = append(policy, c.Ptype) } - + values := c.getValues() lastIndex := getLastNonEmptyIndex(values) - + // Include all values up to and including the last non-empty one // This preserves empty strings in the middle while trimming trailing empty strings for i := 0; i <= lastIndex; i++ { policy = append(policy, values[i]) } - + return policy } func (a *Adapter) updatePolicies(oldLines, newLines []*CasbinRule) error { - tx, err := a.db.Begin() + tx, err := a.db.Begin(context.Background()) if err != nil { return err } - defer tx.Close() + defer tx.Rollback(context.Background()) for i, line := range oldLines { - str, args := line.queryString() - _, err = tx.Model(newLines[i]).Table(a.tableName).Where(str, args...).Update() + str, _ := line.queryString() + _, err = tx.Exec(context.Background(), fmt.Sprintf("UPDATE %s SET ptype = $1, v0 = $2, v1 = $3, v2 = $4, v3 = $5, v4 = $6, v5 = $7 WHERE %s", a.tableName, str), + newLines[i].Ptype, newLines[i].V0, newLines[i].V1, newLines[i].V2, newLines[i].V3, newLines[i].V4, newLines[i].V5) if err != nil { - tx.Rollback() return err } } - if err = tx.Commit(); err != nil { + if err = tx.Commit(context.Background()); err != nil { return err } return nil diff --git a/adapter_test.go b/adapter_test.go index 7bc45e8..623b7ec 100644 --- a/adapter_test.go +++ b/adapter_test.go @@ -1,12 +1,13 @@ package pgadapter import ( + "context" "os" "testing" "github.com/casbin/casbin/v2" "github.com/casbin/casbin/v2/util" - "github.com/go-pg/pg/v10" + "github.com/jackc/pgx/v5/pgxpool" "github.com/stretchr/testify/suite" ) @@ -23,11 +24,11 @@ func (s *AdapterTestSuite) assertPolicy(expected, res [][]string) { } func (s *AdapterTestSuite) dropCasbinDB() { - opts, err := pg.ParseURL(os.Getenv("PG_CONN")) + db, err := pgxpool.New(context.Background(), os.Getenv("PG_CONN")) s.Require().NoError(err) - db := pg.Connect(opts) defer db.Close() - db.Exec("DROP DATABASE casbin") + + db.Exec(context.Background(), "DROP DATABASE casbin") } func (s *AdapterTestSuite) SetupTest() { @@ -37,9 +38,6 @@ func (s *AdapterTestSuite) SetupTest() { s.a, err = NewAdapter(os.Getenv("PG_CONN")) s.Require().NoError(err) - // This is a trick to save the current policy to the DB. - // We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter. - // The current policy means the policy in the Casbin enforcer (aka in memory). e, err := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") s.Require().NoError(err) err = s.a.SavePolicy(e.GetModel()) @@ -138,10 +136,11 @@ func (s *AdapterTestSuite) TestAutoSave() { } func (s *AdapterTestSuite) TestConstructorOptions() { - opts, err := pg.ParseURL(os.Getenv("PG_CONN")) + db, err := pgxpool.New(context.Background(), os.Getenv("PG_CONN")) s.Require().NoError(err) + defer db.Close() - a, err := NewAdapter(opts) + a, err := NewAdapter(os.Getenv("PG_CONN")) s.Require().NoError(err) defer a.Close() @@ -350,28 +349,28 @@ func (s *AdapterTestSuite) TestEmptyStringSupport() { // Test that empty strings in the middle of rules are properly stored and retrieved // Note: Casbin trims trailing empty strings, so we focus on empty strings in the middle var err error - + // Add policies with empty strings in the middle _, err = s.e.AddPolicy("alice", "", "read") s.Require().NoError(err) - + _, err = s.e.AddPolicy("bob", "", "write") s.Require().NoError(err) - + // Reload to ensure they were saved correctly err = s.e.LoadPolicy() s.Require().NoError(err) - + // Check that all policies including empty strings are present policies := s.e.GetPolicy() - + // Should have original 4 policies plus 2 new ones with empty strings s.Assert().Len(policies, 6) - + // Verify the new policies with empty strings exist hasAliceEmpty := false hasBobEmpty := false - + for _, p := range policies { if len(p) == 3 && p[0] == "alice" && p[1] == "" && p[2] == "read" { hasAliceEmpty = true @@ -380,34 +379,34 @@ func (s *AdapterTestSuite) TestEmptyStringSupport() { hasBobEmpty = true } } - + s.Assert().True(hasAliceEmpty, "Policy with alice and empty string in middle not found") s.Assert().True(hasBobEmpty, "Policy with bob and empty string in middle not found") - + // Test removing a policy with empty string _, err = s.e.RemovePolicy("alice", "", "read") s.Require().NoError(err) - + err = s.e.LoadPolicy() s.Require().NoError(err) - + policies = s.e.GetPolicy() s.Assert().Len(policies, 5) - + // Verify alice policy with empty string was removed for _, p := range policies { if len(p) == 3 && p[0] == "alice" && p[1] == "" && p[2] == "read" { s.Fail("Policy with alice and empty string should have been removed") } } - + // Test updating a policy with empty string _, err = s.e.UpdatePolicy([]string{"bob", "", "write"}, []string{"bob", "", "read"}) s.Require().NoError(err) - + err = s.e.LoadPolicy() s.Require().NoError(err) - + policies = s.e.GetPolicy() hasBobEmptyRead := false for _, p := range policies { @@ -425,24 +424,24 @@ func (s *AdapterTestSuite) TestEmptyStringSupport() { func (s *AdapterTestSuite) TestEmptyStringVsWildcard() { // Test that empty strings in rules are different from wildcards in filters var err error - + // Add a policy with an empty string _, err = s.e.AddPolicy("user1", "", "write") s.Require().NoError(err) - + // Add a policy with a non-empty value _, err = s.e.AddPolicy("user1", "resource1", "write") s.Require().NoError(err) - + // Reload err = s.e.LoadPolicy() s.Require().NoError(err) - + // Both should exist policies := s.e.GetPolicy() hasEmpty := false hasNonEmpty := false - + for _, p := range policies { if len(p) >= 3 && p[0] == "user1" && p[2] == "write" { if p[1] == "" { @@ -452,17 +451,17 @@ func (s *AdapterTestSuite) TestEmptyStringVsWildcard() { } } } - + s.Assert().True(hasEmpty, "Policy with empty string should exist") s.Assert().True(hasNonEmpty, "Policy with resource1 should exist") - + // Remove using wildcard (empty string in filter) should remove both _, err = s.e.RemoveFilteredPolicy(0, "user1", "", "write") s.Require().NoError(err) - + err = s.e.LoadPolicy() s.Require().NoError(err) - + policies = s.e.GetPolicy() for _, p := range policies { if len(p) >= 3 && p[0] == "user1" && p[2] == "write" { diff --git a/docker-compose.yml b/docker-compose.yml index c92aaa3..44cc48c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: build: context: ./postgres ports: - - 5432:5432 + - 5433:5432 environment: - POSTGRES_PASSWORD=password go: @@ -22,7 +22,7 @@ services: command: - go - test - - github.com/casbin/casbin-pg-adapter + - github.com/cicdata-io/casbin-pgx-adapter volumes: gopkg: diff --git a/go.mod b/go.mod index 57747ab..45a0649 100644 --- a/go.mod +++ b/go.mod @@ -1,18 +1,27 @@ -module github.com/casbin/casbin-pg-adapter +module github.com/cicdata-io/casbin-pgx-adapter -go 1.18 +go 1.24.0 require ( github.com/casbin/casbin/v2 v2.55.1 - github.com/go-pg/pg/v10 v10.12.0 + github.com/go-pg/pg/v10 v10.15.0 github.com/mmcloughlin/meow v0.0.0-20181112033425-871e50784daf - github.com/stretchr/testify v1.7.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + golang.org/x/sync v0.17.0 // indirect + golang.org/x/text v0.29.0 // indirect ) require ( github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-pg/zerochecker v0.2.0 // indirect + github.com/jackc/pgx/v5 v5.8.0 github.com/jinzhu/inflection v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect @@ -20,8 +29,8 @@ require ( github.com/vmihailenco/msgpack/v5 v5.3.4 // indirect github.com/vmihailenco/tagparser v0.1.2 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect - golang.org/x/crypto v0.17.0 // indirect - golang.org/x/sys v0.15.0 // indirect - gopkg.in/yaml.v3 v3.0.0 // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/sys v0.31.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect mellium.im/sasl v0.3.1 // indirect ) diff --git a/go.sum b/go.sum index 68c2724..bba5094 100644 --- a/go.sum +++ b/go.sum @@ -6,12 +6,21 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= -github.com/go-pg/pg/v10 v10.12.0 h1:rBmfDDHTN7FQW0OemYmcn5UuBy6wkYWgh/Oqt1OBEB8= -github.com/go-pg/pg/v10 v10.12.0/go.mod h1:USA08CdIasAn0F6wC1nBf5nQhMHewVQodWoH89RPXaI= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/go-pg/pg/v10 v10.15.0 h1:6DQwbaxJz/e4wvgzbxBkBLiL/Uuk87MGgHhkURtzx24= +github.com/go-pg/pg/v10 v10.15.0/go.mod h1:FIn/x04hahOf9ywQ1p68rXqaDVbTRLYlu4MQR0lhoB8= github.com/go-pg/zerochecker v0.2.0 h1:pp7f72c3DobMWOb2ErtZsnrPaSvHd2W4o9//8HtF4mU= github.com/go-pg/zerochecker v0.2.0/go.mod h1:NJZ4wKL0NmTtz0GKCoJ8kym6Xn/EQzXRl2OnAe7MmDo= github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo= +github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -21,16 +30,23 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/mmcloughlin/meow v0.0.0-20181112033425-871e50784daf h1:bD6uvpTs5gpzCesUWCGmlEUnU2OINvCQHri8geYwuv0= github.com/mmcloughlin/meow v0.0.0-20181112033425-871e50784daf/go.mod h1:uxCZJI8Z1PD2WRnSJtVJGHCyxC5qWhz5lOsx3Bx1NXo= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/onsi/ginkgo v1.14.2 h1:8mVmC9kjFFmA8H4pKMUhcblgifdkOIXPvbhN1T36q1M= +github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/gomega v1.10.3 h1:gph6h/qe9GSUw1NhH1gp+qb+h8rXD8Cy60Z32Qw3ELA= +github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo= github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs= github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94= @@ -42,26 +58,37 @@ github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgq github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= -golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA= gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= mellium.im/sasl v0.3.1 h1:wE0LW6g7U83vhvxjC1IY8DnXM+EU095yeo8XClvCdfo= mellium.im/sasl v0.3.1/go.mod h1:xm59PUYpZHhgQ9ZqoJ5QaCqzWMi8IeS49dhp6plPCzw= diff --git a/go/Dockerfile b/go/Dockerfile index 8a7c4ab..3f08356 100644 --- a/go/Dockerfile +++ b/go/Dockerfile @@ -1,9 +1,10 @@ -FROM golang:1.13-alpine +FROM golang:1.25-alpine -RUN apk add --no-cache make git curl build-base tar +RUN apk add --no-cache make git curl build-base tar bash -RUN git clone https://github.com/go-delve/delve.git /go/src/github.com/go-delve/delve && \ - cd /go/src/github.com/go-delve/delve && \ - make install +RUN git clone https://github.com/go-delve/delve.git /go/src/github.com/go-delve/delve +WORKDIR /go/src/github.com/go-delve/delve + +RUN make install RUN go get golang.org/x/tools/cmd/godoc diff --git a/pgexample/main.go b/pgexample/main.go index 1ab972c..725f5f1 100644 --- a/pgexample/main.go +++ b/pgexample/main.go @@ -1,37 +1,21 @@ package main import ( - pgadapter "github.com/casbin/casbin-pg-adapter" "github.com/casbin/casbin/v2" + pgadapter "github.com/cicdata-io/casbin-pgx-adapter" ) func main() { - // Initialize a Go-pg adapter and use it in a Casbin enforcer: + // Initialize a pgx adapter and use it in a Casbin enforcer: // The adapter will use the Postgres database named "casbin". // If it doesn't exist, the adapter will create it automatically. a, _ := pgadapter.NewAdapter("postgresql://postgres:password@postgres:5432/postgres?sslmode=disable") // Your driver and data source. - // Alternatively, you can construct an adapter instance with *pg.Options: - // a, _ := pgadapter.NewAdapter(&pg.Options{ - // Database: "...", - // User: "...", - // Password: "...", - // }) - - // Or you can use an existing DB "abc" like this: - // The adapter will use the table named "casbin_rule". - // If it doesn't exist, the adapter will create it automatically. e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) // Load the policy from DB. e.LoadPolicy() - // Alternatively load a subset of policy as demonstrated at https://casbin.org/docs/policy-subset-loading/ - // e.LoadFilteredPolicy(&pgadapter.Filter{ - // P: []string{"", "data1"}, - // G: []string{"alice"}, - // }) - // Check the permission. e.Enforce("alice", "data1", "read")