Skip to content
Open
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
19 changes: 13 additions & 6 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ import (
"go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring"
)

const defaultTimeout time.Duration = 30 * time.Second
const defaultDatabaseName string = "casbin"
const defaultCollectionName string = "casbin_rule"
const (
defaultTimeout time.Duration = 30 * time.Second
defaultDatabaseName string = "casbin"
defaultCollectionName string = "casbin_rule"
)

// CasbinRule represents a rule in Casbin.
type CasbinRule struct {
Expand Down Expand Up @@ -69,7 +71,6 @@ func NewAdapter(url string, timeout ...interface{}) (persist.BatchAdapter, error

// Parse and validate url before apply it.
connString, err := connstring.ParseAndValidate(url)

if err != nil {
return nil, err
}
Expand Down Expand Up @@ -238,8 +239,10 @@ func (a *adapter) dropTable() error {
}

func loadPolicyLine(line CasbinRule, model model.Model) error {
var p = []string{line.PType,
line.V0, line.V1, line.V2, line.V3, line.V4, line.V5}
p := []string{
line.PType,
line.V0, line.V1, line.V2, line.V3, line.V4, line.V5,
}

index := len(p) - 1
for p[index] == "" {
Expand Down Expand Up @@ -351,6 +354,10 @@ func (a *adapter) SavePolicy(model model.Model) error {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()

if len(lines) < 1 {
return nil
}
Comment on lines +357 to +359

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a regression test covering the new behavior where saving an empty model results in no InsertMany call (i.e., SavePolicy succeeds and the collection is left empty after dropTable). The current test suite exercises SavePolicy in other scenarios, but doesn’t assert this empty-policy case that previously triggered the driver error.

Copilot uses AI. Check for mistakes.

Comment on lines 354 to +360

Copilot AI Mar 10, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The empty-lines guard can be checked before creating the timeout context to avoid allocating a context/defer for a no-op insert path (dropTable has already completed). This also keeps the function’s control flow a bit clearer.

Suggested change
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()
if len(lines) < 1 {
return nil
}
if len(lines) < 1 {
return nil
}
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()

Copilot uses AI. Check for mistakes.
if _, err := a.collection.InsertMany(ctx, lines); err != nil {
return err
}
Expand Down