Skip to content

Commit b821ccd

Browse files
committed
feat: add PostgreSQL example to README (#279)
1 parent 133aea7 commit b821ccd

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,46 @@ func main() {
6969
e.SavePolicy()
7070
}
7171
```
72+
73+
## Simple PostgreSQL Example
74+
75+
```go
76+
package main
77+
78+
import (
79+
"github.com/casbin/casbin/v2"
80+
gormadapter "github.com/casbin/gorm-adapter/v3"
81+
_ "github.com/lib/pq"
82+
)
83+
84+
func main() {
85+
// Initialize a Gorm adapter and use it in a Casbin enforcer:
86+
// The adapter will use the PostgreSQL database named "casbin".
87+
// If it doesn't exist, the adapter will create it automatically.
88+
// You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance)
89+
a, _ := gormadapter.NewAdapter("postgres", "host=127.0.0.1 port=5432 user=postgres password=postgres sslmode=disable") // Your driver and data source.
90+
e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
91+
92+
// Or you can use an existing DB "abc" like this:
93+
// The adapter will use the table named "casbin_rule".
94+
// If it doesn't exist, the adapter will create it automatically.
95+
// a := gormadapter.NewAdapter("postgres", "host=127.0.0.1 port=5432 user=postgres password=postgres dbname=abc sslmode=disable", true)
96+
97+
// Load the policy from DB.
98+
e.LoadPolicy()
99+
100+
// Check the permission.
101+
e.Enforce("alice", "data1", "read")
102+
103+
// Modify the policy.
104+
// e.AddPolicy(...)
105+
// e.RemovePolicy(...)
106+
107+
// Save the policy back to DB.
108+
e.SavePolicy()
109+
}
110+
```
111+
72112
## Turn off AutoMigrate
73113
New an adapter will use ``AutoMigrate`` by default for create table, if you want to turn it off, please use API ``TurnOffAutoMigrate(db *gorm.DB) *gorm.DB``. See example:
74114
```go

0 commit comments

Comments
 (0)