From 27586c086185858b537a40b6582b0ff424105666 Mon Sep 17 00:00:00 2001 From: MuZhou233 Date: Tue, 30 Jul 2024 17:11:41 +0100 Subject: [PATCH 1/5] feat: basic embed idea --- adapter_test.go | 30 +- adapter.go => ent/casbin.go | 82 ++--- ent/casbinrule.go | 56 +-- ent/casbinrule/casbinrule.go | 49 ++- ent/casbinrule/where.go | 613 ++++++-------------------------- ent/casbinrule_create.go | 155 ++++---- ent/casbinrule_delete.go | 60 ++-- ent/casbinrule_query.go | 659 ++++++++--------------------------- ent/casbinrule_update.go | 183 ++-------- ent/client.go | 152 +++++++- ent/config.go | 59 ---- ent/context.go | 33 -- ent/ent.go | 437 ++++++++++++++++++++--- ent/enttest/enttest.go | 22 +- ent/generate.go | 23 +- ent/hook/hook.go | 13 +- ent/migrate/migrate.go | 30 +- ent/migrate/schema.go | 9 +- ent/mutation.go | 82 +++-- ent/predicate/predicate.go | 2 +- ent/runtime.go | 19 +- ent/runtime/runtime.go | 6 +- ent/schema/casbinrule.go | 27 +- ent/tx.go | 50 +-- go.mod | 23 +- go.sum | 384 +++----------------- template/casbin.tmpl | 514 +++++++++++++++++++++++++++ template/extension.go | 16 + template/mixin.go | 30 ++ 29 files changed, 1799 insertions(+), 2019 deletions(-) rename adapter.go => ent/casbin.go (84%) delete mode 100644 ent/config.go delete mode 100644 ent/context.go create mode 100644 template/casbin.tmpl create mode 100644 template/extension.go create mode 100644 template/mixin.go diff --git a/adapter_test.go b/adapter_test.go index fd7754d..31dd3a7 100644 --- a/adapter_test.go +++ b/adapter_test.go @@ -77,7 +77,7 @@ func arrayEqualsWithoutOrder(a [][]string, b [][]string) bool { return true } -func initPolicy(t *testing.T, a *Adapter) { +func initPolicy(t *testing.T, a *ent.Adapter) { // Because the DB is empty at first, // so we need to load the policy from the file adapter (.CSV) first. e, err := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") @@ -105,7 +105,7 @@ func initPolicy(t *testing.T, a *Adapter) { testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) } -func testSaveLoad(t *testing.T, a *Adapter) { +func testSaveLoad(t *testing.T, a *ent.Adapter) { // Initialize some policy in DB. initPolicy(t, a) // Note: you don't need to look at the above code @@ -119,9 +119,9 @@ func testSaveLoad(t *testing.T, a *Adapter) { testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) } -func initAdapter(t *testing.T, driverName string, dataSourceName string, options ...Option) *Adapter { +func initAdapter(t *testing.T, driverName string, dataSourceName string) *ent.Adapter { // Create an adapter - a, err := NewAdapter(driverName, dataSourceName, options...) + a, err := ent.NewAdapter(driverName, dataSourceName) if err != nil { panic(err) } @@ -135,9 +135,9 @@ func initAdapter(t *testing.T, driverName string, dataSourceName string, options return a } -func initAdapterWithClientInstance(t *testing.T, client *ent.Client) *Adapter { +func initAdapterWithClientInstance(t *testing.T, client *ent.Client) *ent.Adapter { // Create an adapter - a, _ := NewAdapterWithClient(client) + a, _ := ent.NewAdapterWithClient(client) // Initialize some policy in DB. initPolicy(t, a) // Now the DB has policy, so we can provide a normal use case. @@ -147,7 +147,7 @@ func initAdapterWithClientInstance(t *testing.T, client *ent.Client) *Adapter { return a } -func testAutoSave(t *testing.T, a *Adapter) { +func testAutoSave(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) @@ -213,7 +213,7 @@ func testAutoSave(t *testing.T, a *Adapter) { // testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}}) //} -func testUpdatePolicy(t *testing.T, a *Adapter) { +func testUpdatePolicy(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) @@ -223,7 +223,7 @@ func testUpdatePolicy(t *testing.T, a *Adapter) { testGetPolicy(t, e, [][]string{{"alice", "data1", "write"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) } -func testUpdatePolicies(t *testing.T, a *Adapter) { +func testUpdatePolicies(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) @@ -233,7 +233,7 @@ func testUpdatePolicies(t *testing.T, a *Adapter) { testGetPolicyWithoutOrder(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "read"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) } -func testUpdateFilteredPolicies(t *testing.T, a *Adapter) { +func testUpdateFilteredPolicies(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) @@ -244,7 +244,7 @@ func testUpdateFilteredPolicies(t *testing.T, a *Adapter) { testGetPolicyWithoutOrder(t, e, [][]string{{"alice", "data1", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"bob", "data2", "read"}}) } -func testFilteredPolicy(t *testing.T, a *Adapter) { +func testFilteredPolicy(t *testing.T, a *ent.Adapter) { // NewEnforcer() without an adapter will not auto load the policy e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") @@ -254,19 +254,19 @@ func testFilteredPolicy(t *testing.T, a *Adapter) { assert.Nil(t, e.SavePolicy()) // Load only alice's policies - assert.Nil(t, e.LoadFilteredPolicy(Filter{V0: []string{"alice"}})) + assert.Nil(t, e.LoadFilteredPolicy(ent.Filter{V0: []string{"alice"}})) testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}}) // Load only bob's policies - assert.Nil(t, e.LoadFilteredPolicy(Filter{V0: []string{"bob"}})) + assert.Nil(t, e.LoadFilteredPolicy(ent.Filter{V0: []string{"bob"}})) testGetPolicy(t, e, [][]string{{"bob", "data2", "write"}}) // Load policies for data2_admin - assert.Nil(t, e.LoadFilteredPolicy(Filter{V0: []string{"data2_admin"}})) + assert.Nil(t, e.LoadFilteredPolicy(ent.Filter{V0: []string{"data2_admin"}})) testGetPolicy(t, e, [][]string{{"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) // Load policies for alice and bob - assert.Nil(t, e.LoadFilteredPolicy(Filter{V0: []string{"alice", "bob"}})) + assert.Nil(t, e.LoadFilteredPolicy(ent.Filter{V0: []string{"alice", "bob"}})) testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}}) } diff --git a/adapter.go b/ent/casbin.go similarity index 84% rename from adapter.go rename to ent/casbin.go index ad2fccf..6d2d265 100644 --- a/adapter.go +++ b/ent/casbin.go @@ -1,18 +1,6 @@ -// Copyright 2021 The casbin Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package entadapter +// Code generated by ent, DO NOT EDIT. + +package ent import ( "context" @@ -28,12 +16,10 @@ import ( "github.com/casbin/ent-adapter/ent/predicate" "github.com/casbin/casbin/v2/model" - "github.com/casbin/ent-adapter/ent" _ "github.com/go-sql-driver/mysql" _ "github.com/jackc/pgx/v5/stdlib" _ "github.com/lib/pq" - //_ "github.com/mattn/go-sqlite3" "github.com/pkg/errors" ) @@ -43,7 +29,7 @@ const ( ) type Adapter struct { - client *ent.Client + client *Client ctx context.Context filtered bool @@ -59,9 +45,7 @@ type Filter struct { V5 []string } -type Option func(a *Adapter) error - -func open(driverName, dataSourceName string) (*ent.Client, error) { +func open(driverName, dataSourceName string) (*Client, error) { db, err := sql.Open(driverName, dataSourceName) if err != nil { return nil, err @@ -72,11 +56,11 @@ func open(driverName, dataSourceName string) (*ent.Client, error) { } else { drv = entsql.OpenDB(driverName, db) } - return ent.NewClient(ent.Driver(drv)), nil + return NewClient(Driver(drv)), nil } // NewAdapter returns an adapter by driver name and data source string. -func NewAdapter(driverName, dataSourceName string, options ...Option) (*Adapter, error) { +func NewAdapter(driverName, dataSourceName string) (*Adapter, error) { client, err := open(driverName, dataSourceName) if err != nil { return nil, err @@ -85,11 +69,6 @@ func NewAdapter(driverName, dataSourceName string, options ...Option) (*Adapter, client: client, ctx: context.Background(), } - for _, option := range options { - if err := option(a); err != nil { - return nil, err - } - } if err := client.Schema.Create(a.ctx); err != nil { return nil, err } @@ -98,16 +77,11 @@ func NewAdapter(driverName, dataSourceName string, options ...Option) (*Adapter, // NewAdapterWithClient create an adapter with client passed in. // This method does not ensure the existence of database, user should create database manually. -func NewAdapterWithClient(client *ent.Client, options ...Option) (*Adapter, error) { +func NewAdapterWithClient(client *Client) (*Adapter, error) { a := &Adapter{ client: client, ctx: context.Background(), } - for _, option := range options { - if err := option(a); err != nil { - return nil, err - } - } if err := client.Schema.Create(a.ctx); err != nil { return nil, err } @@ -116,7 +90,7 @@ func NewAdapterWithClient(client *ent.Client, options ...Option) (*Adapter, erro // LoadPolicy loads all policy rules from the storage. func (a *Adapter) LoadPolicy(model model.Model) error { - policies, err := a.client.CasbinRule.Query().Order(ent.Asc("id")).All(a.ctx) + policies, err := a.client.CasbinRule.Query().Order(Asc("id")).All(a.ctx) if err != nil { return err } @@ -178,11 +152,11 @@ func (a *Adapter) IsFiltered() bool { // SavePolicy saves all policy rules to the storage. func (a *Adapter) SavePolicy(model model.Model) error { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { if _, err := tx.CasbinRule.Delete().Exec(a.ctx); err != nil { return err } - lines := make([]*ent.CasbinRuleCreate, 0) + lines := make([]*CasbinRuleCreate, 0) for ptype, ast := range model["p"] { for _, policy := range ast.Policy { @@ -206,7 +180,7 @@ func (a *Adapter) SavePolicy(model model.Model) error { // AddPolicy adds a policy rule to the storage. // This is part of the Auto-Save feature. func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { _, err := a.savePolicyLine(tx, ptype, rule).Save(a.ctx) return err }) @@ -215,7 +189,7 @@ func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error { // RemovePolicy removes a policy rule from the storage. // This is part of the Auto-Save feature. func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { instance := a.toInstance(ptype, rule) _, err := tx.CasbinRule.Delete().Where( casbinrule.PtypeEQ(instance.Ptype), @@ -233,7 +207,7 @@ func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { // RemoveFilteredPolicy removes policy rules that match the filter from the storage. // This is part of the Auto-Save feature. func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { cond := make([]predicate.CasbinRule, 0) cond = append(cond, casbinrule.PtypeEQ(ptype)) if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) && len(fieldValues[0-fieldIndex]) > 0 { @@ -264,7 +238,7 @@ func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, // AddPolicies adds policy rules to the storage. // This is part of the Auto-Save feature. func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { return a.createPolicies(tx, ptype, rules) }) } @@ -272,7 +246,7 @@ func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error // RemovePolicies removes policy rules from the storage. // This is part of the Auto-Save feature. func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) error { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { for _, rule := range rules { instance := a.toInstance(ptype, rule) if _, err := tx.CasbinRule.Delete().Where( @@ -291,7 +265,7 @@ func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) err }) } -func (a *Adapter) WithTx(fn func(tx *ent.Tx) error) error { +func (a *Adapter) WithTx(fn func(tx *Tx) error) error { tx, err := a.client.Tx(a.ctx) if err != nil { return err @@ -314,7 +288,7 @@ func (a *Adapter) WithTx(fn func(tx *ent.Tx) error) error { return nil } -func loadPolicyLine(line *ent.CasbinRule, model model.Model) { +func loadPolicyLine(line *CasbinRule, model model.Model) { var p = []string{line.Ptype, line.V0, line.V1, line.V2, line.V3, line.V4, line.V5} @@ -336,8 +310,8 @@ func loadPolicyLine(line *ent.CasbinRule, model model.Model) { persist.LoadPolicyLine(lineText, model) } -func (a *Adapter) toInstance(ptype string, rule []string) *ent.CasbinRule { - instance := &ent.CasbinRule{} +func (a *Adapter) toInstance(ptype string, rule []string) *CasbinRule { + instance := &CasbinRule{} instance.Ptype = ptype @@ -362,7 +336,7 @@ func (a *Adapter) toInstance(ptype string, rule []string) *ent.CasbinRule { return instance } -func (a *Adapter) savePolicyLine(tx *ent.Tx, ptype string, rule []string) *ent.CasbinRuleCreate { +func (a *Adapter) savePolicyLine(tx *Tx, ptype string, rule []string) *CasbinRuleCreate { line := tx.CasbinRule.Create() line.SetPtype(ptype) @@ -391,7 +365,7 @@ func (a *Adapter) savePolicyLine(tx *ent.Tx, ptype string, rule []string) *ent.C // UpdatePolicy updates a policy rule from storage. // This is part of the Auto-Save feature. func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { rule := a.toInstance(ptype, oldRule) line := tx.CasbinRule.Update().Where( casbinrule.PtypeEQ(rule.Ptype), @@ -416,7 +390,7 @@ 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 { - return a.WithTx(func(tx *ent.Tx) error { + return a.WithTx(func(tx *Tx) error { for _, policy := range oldRules { rule := a.toInstance(ptype, policy) if _, err := tx.CasbinRule.Delete().Where( @@ -431,7 +405,7 @@ func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [] return err } } - lines := make([]*ent.CasbinRuleCreate, 0) + lines := make([]*CasbinRuleCreate, 0) for _, policy := range newRules { lines = append(lines, a.savePolicyLine(tx, ptype, policy)) } @@ -445,7 +419,7 @@ func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [] // UpdateFilteredPolicies deletes old rules and adds new rules. func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) { oldPolicies := make([][]string, 0) - err := a.WithTx(func(tx *ent.Tx) error { + err := a.WithTx(func(tx *Tx) error { cond := make([]predicate.CasbinRule, 0) cond = append(cond, casbinrule.PtypeEQ(ptype)) if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) && len(fieldValues[0-fieldIndex]) > 0 { @@ -498,8 +472,8 @@ func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [ return oldPolicies, nil } -func (a *Adapter) createPolicies(tx *ent.Tx, ptype string, policies [][]string) error { - lines := make([]*ent.CasbinRuleCreate, 0) +func (a *Adapter) createPolicies(tx *Tx, ptype string, policies [][]string) error { + lines := make([]*CasbinRuleCreate, 0) for _, policy := range policies { lines = append(lines, a.savePolicyLine(tx, ptype, policy)) } @@ -509,7 +483,7 @@ func (a *Adapter) createPolicies(tx *ent.Tx, ptype string, policies [][]string) return nil } -func CasbinRuleToStringArray(rule *ent.CasbinRule) []string { +func CasbinRuleToStringArray(rule *CasbinRule) []string { arr := make([]string, 0) if rule.V0 != "" { arr = append(arr, rule.V0) diff --git a/ent/casbinrule.go b/ent/casbinrule.go index 1b6eae6..d029267 100644 --- a/ent/casbinrule.go +++ b/ent/casbinrule.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "entgo.io/ent" "entgo.io/ent/dialect/sql" "github.com/casbin/ent-adapter/ent/casbinrule" ) @@ -28,12 +29,13 @@ type CasbinRule struct { // V4 holds the value of the "V4" field. V4 string `json:"V4,omitempty"` // V5 holds the value of the "V5" field. - V5 string `json:"V5,omitempty"` + V5 string `json:"V5,omitempty"` + selectValues sql.SelectValues } // scanValues returns the types for scanning values from sql.Rows. -func (*CasbinRule) scanValues(columns []string) ([]interface{}, error) { - values := make([]interface{}, len(columns)) +func (*CasbinRule) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) for i := range columns { switch columns[i] { case casbinrule.FieldID: @@ -41,7 +43,7 @@ func (*CasbinRule) scanValues(columns []string) ([]interface{}, error) { case casbinrule.FieldPtype, casbinrule.FieldV0, casbinrule.FieldV1, casbinrule.FieldV2, casbinrule.FieldV3, casbinrule.FieldV4, casbinrule.FieldV5: values[i] = new(sql.NullString) default: - return nil, fmt.Errorf("unexpected column %q for type CasbinRule", columns[i]) + values[i] = new(sql.UnknownType) } } return values, nil @@ -49,7 +51,7 @@ func (*CasbinRule) scanValues(columns []string) ([]interface{}, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the CasbinRule fields. -func (cr *CasbinRule) assignValues(columns []string, values []interface{}) error { +func (cr *CasbinRule) assignValues(columns []string, values []any) error { if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } @@ -103,26 +105,34 @@ func (cr *CasbinRule) assignValues(columns []string, values []interface{}) error } else if value.Valid { cr.V5 = value.String } + default: + cr.selectValues.Set(columns[i], values[i]) } } return nil } +// Value returns the ent.Value that was dynamically selected and assigned to the CasbinRule. +// This includes values selected through modifiers, order, etc. +func (cr *CasbinRule) Value(name string) (ent.Value, error) { + return cr.selectValues.Get(name) +} + // Update returns a builder for updating this CasbinRule. // Note that you need to call CasbinRule.Unwrap() before calling this method if this CasbinRule // was returned from a transaction, and the transaction was committed or rolled back. func (cr *CasbinRule) Update() *CasbinRuleUpdateOne { - return (&CasbinRuleClient{config: cr.config}).UpdateOne(cr) + return NewCasbinRuleClient(cr.config).UpdateOne(cr) } // Unwrap unwraps the CasbinRule entity that was returned from a transaction after it was closed, // so that all future queries will be executed through the driver which created the transaction. func (cr *CasbinRule) Unwrap() *CasbinRule { - tx, ok := cr.config.driver.(*txDriver) + _tx, ok := cr.config.driver.(*txDriver) if !ok { panic("ent: CasbinRule is not a transactional entity") } - cr.config.driver = tx.drv + cr.config.driver = _tx.drv return cr } @@ -130,20 +140,26 @@ func (cr *CasbinRule) Unwrap() *CasbinRule { func (cr *CasbinRule) String() string { var builder strings.Builder builder.WriteString("CasbinRule(") - builder.WriteString(fmt.Sprintf("id=%v", cr.ID)) - builder.WriteString(", Ptype=") + builder.WriteString(fmt.Sprintf("id=%v, ", cr.ID)) + builder.WriteString("Ptype=") builder.WriteString(cr.Ptype) - builder.WriteString(", V0=") + builder.WriteString(", ") + builder.WriteString("V0=") builder.WriteString(cr.V0) - builder.WriteString(", V1=") + builder.WriteString(", ") + builder.WriteString("V1=") builder.WriteString(cr.V1) - builder.WriteString(", V2=") + builder.WriteString(", ") + builder.WriteString("V2=") builder.WriteString(cr.V2) - builder.WriteString(", V3=") + builder.WriteString(", ") + builder.WriteString("V3=") builder.WriteString(cr.V3) - builder.WriteString(", V4=") + builder.WriteString(", ") + builder.WriteString("V4=") builder.WriteString(cr.V4) - builder.WriteString(", V5=") + builder.WriteString(", ") + builder.WriteString("V5=") builder.WriteString(cr.V5) builder.WriteByte(')') return builder.String() @@ -151,9 +167,3 @@ func (cr *CasbinRule) String() string { // CasbinRules is a parsable slice of CasbinRule. type CasbinRules []*CasbinRule - -func (cr CasbinRules) config(cfg config) { - for _i := range cr { - cr[_i].config = cfg - } -} diff --git a/ent/casbinrule/casbinrule.go b/ent/casbinrule/casbinrule.go index cf0ead5..d739603 100644 --- a/ent/casbinrule/casbinrule.go +++ b/ent/casbinrule/casbinrule.go @@ -1,7 +1,11 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package casbinrule +import ( + "entgo.io/ent/dialect/sql" +) + const ( // Label holds the string label denoting the casbinrule type in the database. Label = "casbin_rule" @@ -63,3 +67,46 @@ var ( // DefaultV5 holds the default value on creation for the "V5" field. DefaultV5 string ) + +// OrderOption defines the ordering options for the CasbinRule queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByPtype orders the results by the Ptype field. +func ByPtype(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPtype, opts...).ToFunc() +} + +// ByV0 orders the results by the V0 field. +func ByV0(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldV0, opts...).ToFunc() +} + +// ByV1 orders the results by the V1 field. +func ByV1(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldV1, opts...).ToFunc() +} + +// ByV2 orders the results by the V2 field. +func ByV2(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldV2, opts...).ToFunc() +} + +// ByV3 orders the results by the V3 field. +func ByV3(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldV3, opts...).ToFunc() +} + +// ByV4 orders the results by the V4 field. +func ByV4(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldV4, opts...).ToFunc() +} + +// ByV5 orders the results by the V5 field. +func ByV5(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldV5, opts...).ToFunc() +} diff --git a/ent/casbinrule/where.go b/ent/casbinrule/where.go index 3065ff7..c779990 100644 --- a/ent/casbinrule/where.go +++ b/ent/casbinrule/where.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package casbinrule @@ -9,941 +9,550 @@ import ( // ID filters vertices based on their ID field. func ID(id int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldID, id)) } // Ptype applies equality check predicate on the "Ptype" field. It's identical to PtypeEQ. func Ptype(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldPtype, v)) } // V0 applies equality check predicate on the "V0" field. It's identical to V0EQ. func V0(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV0, v)) } // V1 applies equality check predicate on the "V1" field. It's identical to V1EQ. func V1(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV1, v)) } // V2 applies equality check predicate on the "V2" field. It's identical to V2EQ. func V2(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV2, v)) } // V3 applies equality check predicate on the "V3" field. It's identical to V3EQ. func V3(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV3, v)) } // V4 applies equality check predicate on the "V4" field. It's identical to V4EQ. func V4(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV4, v)) } // V5 applies equality check predicate on the "V5" field. It's identical to V5EQ. func V5(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV5, v)) } // PtypeEQ applies the EQ predicate on the "Ptype" field. func PtypeEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldPtype, v)) } // PtypeNEQ applies the NEQ predicate on the "Ptype" field. func PtypeNEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldPtype, v)) } // PtypeIn applies the In predicate on the "Ptype" field. func PtypeIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldPtype), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldPtype, vs...)) } // PtypeNotIn applies the NotIn predicate on the "Ptype" field. func PtypeNotIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldPtype), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldPtype, vs...)) } // PtypeGT applies the GT predicate on the "Ptype" field. func PtypeGT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldPtype, v)) } // PtypeGTE applies the GTE predicate on the "Ptype" field. func PtypeGTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldPtype, v)) } // PtypeLT applies the LT predicate on the "Ptype" field. func PtypeLT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldPtype, v)) } // PtypeLTE applies the LTE predicate on the "Ptype" field. func PtypeLTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldPtype, v)) } // PtypeContains applies the Contains predicate on the "Ptype" field. func PtypeContains(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldContains(FieldPtype, v)) } // PtypeHasPrefix applies the HasPrefix predicate on the "Ptype" field. func PtypeHasPrefix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldHasPrefix(FieldPtype, v)) } // PtypeHasSuffix applies the HasSuffix predicate on the "Ptype" field. func PtypeHasSuffix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldHasSuffix(FieldPtype, v)) } // PtypeEqualFold applies the EqualFold predicate on the "Ptype" field. func PtypeEqualFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldEqualFold(FieldPtype, v)) } // PtypeContainsFold applies the ContainsFold predicate on the "Ptype" field. func PtypeContainsFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldPtype), v)) - }) + return predicate.CasbinRule(sql.FieldContainsFold(FieldPtype, v)) } // V0EQ applies the EQ predicate on the "V0" field. func V0EQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV0, v)) } // V0NEQ applies the NEQ predicate on the "V0" field. func V0NEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldV0, v)) } // V0In applies the In predicate on the "V0" field. func V0In(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldV0), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldV0, vs...)) } // V0NotIn applies the NotIn predicate on the "V0" field. func V0NotIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldV0), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldV0, vs...)) } // V0GT applies the GT predicate on the "V0" field. func V0GT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldV0, v)) } // V0GTE applies the GTE predicate on the "V0" field. func V0GTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldV0, v)) } // V0LT applies the LT predicate on the "V0" field. func V0LT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldV0, v)) } // V0LTE applies the LTE predicate on the "V0" field. func V0LTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldV0, v)) } // V0Contains applies the Contains predicate on the "V0" field. func V0Contains(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldContains(FieldV0, v)) } // V0HasPrefix applies the HasPrefix predicate on the "V0" field. func V0HasPrefix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldHasPrefix(FieldV0, v)) } // V0HasSuffix applies the HasSuffix predicate on the "V0" field. func V0HasSuffix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldHasSuffix(FieldV0, v)) } // V0EqualFold applies the EqualFold predicate on the "V0" field. func V0EqualFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldEqualFold(FieldV0, v)) } // V0ContainsFold applies the ContainsFold predicate on the "V0" field. func V0ContainsFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldV0), v)) - }) + return predicate.CasbinRule(sql.FieldContainsFold(FieldV0, v)) } // V1EQ applies the EQ predicate on the "V1" field. func V1EQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV1, v)) } // V1NEQ applies the NEQ predicate on the "V1" field. func V1NEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldV1, v)) } // V1In applies the In predicate on the "V1" field. func V1In(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldV1), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldV1, vs...)) } // V1NotIn applies the NotIn predicate on the "V1" field. func V1NotIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldV1), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldV1, vs...)) } // V1GT applies the GT predicate on the "V1" field. func V1GT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldV1, v)) } // V1GTE applies the GTE predicate on the "V1" field. func V1GTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldV1, v)) } // V1LT applies the LT predicate on the "V1" field. func V1LT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldV1, v)) } // V1LTE applies the LTE predicate on the "V1" field. func V1LTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldV1, v)) } // V1Contains applies the Contains predicate on the "V1" field. func V1Contains(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldContains(FieldV1, v)) } // V1HasPrefix applies the HasPrefix predicate on the "V1" field. func V1HasPrefix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldHasPrefix(FieldV1, v)) } // V1HasSuffix applies the HasSuffix predicate on the "V1" field. func V1HasSuffix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldHasSuffix(FieldV1, v)) } // V1EqualFold applies the EqualFold predicate on the "V1" field. func V1EqualFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldEqualFold(FieldV1, v)) } // V1ContainsFold applies the ContainsFold predicate on the "V1" field. func V1ContainsFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldV1), v)) - }) + return predicate.CasbinRule(sql.FieldContainsFold(FieldV1, v)) } // V2EQ applies the EQ predicate on the "V2" field. func V2EQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV2, v)) } // V2NEQ applies the NEQ predicate on the "V2" field. func V2NEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldV2, v)) } // V2In applies the In predicate on the "V2" field. func V2In(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldV2), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldV2, vs...)) } // V2NotIn applies the NotIn predicate on the "V2" field. func V2NotIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldV2), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldV2, vs...)) } // V2GT applies the GT predicate on the "V2" field. func V2GT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldV2, v)) } // V2GTE applies the GTE predicate on the "V2" field. func V2GTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldV2, v)) } // V2LT applies the LT predicate on the "V2" field. func V2LT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldV2, v)) } // V2LTE applies the LTE predicate on the "V2" field. func V2LTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldV2, v)) } // V2Contains applies the Contains predicate on the "V2" field. func V2Contains(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldContains(FieldV2, v)) } // V2HasPrefix applies the HasPrefix predicate on the "V2" field. func V2HasPrefix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldHasPrefix(FieldV2, v)) } // V2HasSuffix applies the HasSuffix predicate on the "V2" field. func V2HasSuffix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldHasSuffix(FieldV2, v)) } // V2EqualFold applies the EqualFold predicate on the "V2" field. func V2EqualFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldEqualFold(FieldV2, v)) } // V2ContainsFold applies the ContainsFold predicate on the "V2" field. func V2ContainsFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldV2), v)) - }) + return predicate.CasbinRule(sql.FieldContainsFold(FieldV2, v)) } // V3EQ applies the EQ predicate on the "V3" field. func V3EQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV3, v)) } // V3NEQ applies the NEQ predicate on the "V3" field. func V3NEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldV3, v)) } // V3In applies the In predicate on the "V3" field. func V3In(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldV3), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldV3, vs...)) } // V3NotIn applies the NotIn predicate on the "V3" field. func V3NotIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldV3), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldV3, vs...)) } // V3GT applies the GT predicate on the "V3" field. func V3GT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldV3, v)) } // V3GTE applies the GTE predicate on the "V3" field. func V3GTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldV3, v)) } // V3LT applies the LT predicate on the "V3" field. func V3LT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldV3, v)) } // V3LTE applies the LTE predicate on the "V3" field. func V3LTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldV3, v)) } // V3Contains applies the Contains predicate on the "V3" field. func V3Contains(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldContains(FieldV3, v)) } // V3HasPrefix applies the HasPrefix predicate on the "V3" field. func V3HasPrefix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldHasPrefix(FieldV3, v)) } // V3HasSuffix applies the HasSuffix predicate on the "V3" field. func V3HasSuffix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldHasSuffix(FieldV3, v)) } // V3EqualFold applies the EqualFold predicate on the "V3" field. func V3EqualFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldEqualFold(FieldV3, v)) } // V3ContainsFold applies the ContainsFold predicate on the "V3" field. func V3ContainsFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldV3), v)) - }) + return predicate.CasbinRule(sql.FieldContainsFold(FieldV3, v)) } // V4EQ applies the EQ predicate on the "V4" field. func V4EQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV4, v)) } // V4NEQ applies the NEQ predicate on the "V4" field. func V4NEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldV4, v)) } // V4In applies the In predicate on the "V4" field. func V4In(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldV4), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldV4, vs...)) } // V4NotIn applies the NotIn predicate on the "V4" field. func V4NotIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldV4), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldV4, vs...)) } // V4GT applies the GT predicate on the "V4" field. func V4GT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldV4, v)) } // V4GTE applies the GTE predicate on the "V4" field. func V4GTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldV4, v)) } // V4LT applies the LT predicate on the "V4" field. func V4LT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldV4, v)) } // V4LTE applies the LTE predicate on the "V4" field. func V4LTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldV4, v)) } // V4Contains applies the Contains predicate on the "V4" field. func V4Contains(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldContains(FieldV4, v)) } // V4HasPrefix applies the HasPrefix predicate on the "V4" field. func V4HasPrefix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldHasPrefix(FieldV4, v)) } // V4HasSuffix applies the HasSuffix predicate on the "V4" field. func V4HasSuffix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldHasSuffix(FieldV4, v)) } // V4EqualFold applies the EqualFold predicate on the "V4" field. func V4EqualFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldEqualFold(FieldV4, v)) } // V4ContainsFold applies the ContainsFold predicate on the "V4" field. func V4ContainsFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldV4), v)) - }) + return predicate.CasbinRule(sql.FieldContainsFold(FieldV4, v)) } // V5EQ applies the EQ predicate on the "V5" field. func V5EQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldEQ(FieldV5, v)) } // V5NEQ applies the NEQ predicate on the "V5" field. func V5NEQ(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldNEQ(FieldV5, v)) } // V5In applies the In predicate on the "V5" field. func V5In(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldV5), v...)) - }) + return predicate.CasbinRule(sql.FieldIn(FieldV5, vs...)) } // V5NotIn applies the NotIn predicate on the "V5" field. func V5NotIn(vs ...string) predicate.CasbinRule { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.CasbinRule(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldV5), v...)) - }) + return predicate.CasbinRule(sql.FieldNotIn(FieldV5, vs...)) } // V5GT applies the GT predicate on the "V5" field. func V5GT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldGT(FieldV5, v)) } // V5GTE applies the GTE predicate on the "V5" field. func V5GTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldGTE(FieldV5, v)) } // V5LT applies the LT predicate on the "V5" field. func V5LT(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldLT(FieldV5, v)) } // V5LTE applies the LTE predicate on the "V5" field. func V5LTE(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldLTE(FieldV5, v)) } // V5Contains applies the Contains predicate on the "V5" field. func V5Contains(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldContains(FieldV5, v)) } // V5HasPrefix applies the HasPrefix predicate on the "V5" field. func V5HasPrefix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldHasPrefix(FieldV5, v)) } // V5HasSuffix applies the HasSuffix predicate on the "V5" field. func V5HasSuffix(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldHasSuffix(FieldV5, v)) } // V5EqualFold applies the EqualFold predicate on the "V5" field. func V5EqualFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldEqualFold(FieldV5, v)) } // V5ContainsFold applies the ContainsFold predicate on the "V5" field. func V5ContainsFold(v string) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldV5), v)) - }) + return predicate.CasbinRule(sql.FieldContainsFold(FieldV5, v)) } // And groups predicates with the AND operator between them. func And(predicates ...predicate.CasbinRule) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for _, p := range predicates { - p(s1) - } - s.Where(s1.P()) - }) + return predicate.CasbinRule(sql.AndPredicates(predicates...)) } // Or groups predicates with the OR operator between them. func Or(predicates ...predicate.CasbinRule) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - s1 := s.Clone().SetP(nil) - for i, p := range predicates { - if i > 0 { - s1.Or() - } - p(s1) - } - s.Where(s1.P()) - }) + return predicate.CasbinRule(sql.OrPredicates(predicates...)) } // Not applies the not operator on the given predicate. func Not(p predicate.CasbinRule) predicate.CasbinRule { - return predicate.CasbinRule(func(s *sql.Selector) { - p(s.Not()) - }) + return predicate.CasbinRule(sql.NotPredicates(p)) } diff --git a/ent/casbinrule_create.go b/ent/casbinrule_create.go index 4eb7ec0..64b8d93 100644 --- a/ent/casbinrule_create.go +++ b/ent/casbinrule_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -124,38 +124,8 @@ func (crc *CasbinRuleCreate) Mutation() *CasbinRuleMutation { // Save creates the CasbinRule in the database. func (crc *CasbinRuleCreate) Save(ctx context.Context) (*CasbinRule, error) { - var ( - err error - node *CasbinRule - ) crc.defaults() - if len(crc.hooks) == 0 { - if err = crc.check(); err != nil { - return nil, err - } - node, err = crc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CasbinRuleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = crc.check(); err != nil { - return nil, err - } - crc.mutation = mutation - node, err = crc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(crc.hooks) - 1; i >= 0; i-- { - mut = crc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, crc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, crc.sqlSave, crc.mutation, crc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -167,6 +137,19 @@ func (crc *CasbinRuleCreate) SaveX(ctx context.Context) *CasbinRule { return v } +// Exec executes the query. +func (crc *CasbinRuleCreate) Exec(ctx context.Context) error { + _, err := crc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (crc *CasbinRuleCreate) ExecX(ctx context.Context) { + if err := crc.Exec(ctx); err != nil { + panic(err) + } +} + // defaults sets the default values of the builder before save. func (crc *CasbinRuleCreate) defaults() { if _, ok := crc.mutation.Ptype(); !ok { @@ -202,107 +185,78 @@ func (crc *CasbinRuleCreate) defaults() { // check runs all checks and user-defined validators on the builder. func (crc *CasbinRuleCreate) check() error { if _, ok := crc.mutation.Ptype(); !ok { - return &ValidationError{Name: "Ptype", err: errors.New("ent: missing required field \"Ptype\"")} + return &ValidationError{Name: "Ptype", err: errors.New(`ent: missing required field "CasbinRule.Ptype"`)} } if _, ok := crc.mutation.V0(); !ok { - return &ValidationError{Name: "V0", err: errors.New("ent: missing required field \"V0\"")} + return &ValidationError{Name: "V0", err: errors.New(`ent: missing required field "CasbinRule.V0"`)} } if _, ok := crc.mutation.V1(); !ok { - return &ValidationError{Name: "V1", err: errors.New("ent: missing required field \"V1\"")} + return &ValidationError{Name: "V1", err: errors.New(`ent: missing required field "CasbinRule.V1"`)} } if _, ok := crc.mutation.V2(); !ok { - return &ValidationError{Name: "V2", err: errors.New("ent: missing required field \"V2\"")} + return &ValidationError{Name: "V2", err: errors.New(`ent: missing required field "CasbinRule.V2"`)} } if _, ok := crc.mutation.V3(); !ok { - return &ValidationError{Name: "V3", err: errors.New("ent: missing required field \"V3\"")} + return &ValidationError{Name: "V3", err: errors.New(`ent: missing required field "CasbinRule.V3"`)} } if _, ok := crc.mutation.V4(); !ok { - return &ValidationError{Name: "V4", err: errors.New("ent: missing required field \"V4\"")} + return &ValidationError{Name: "V4", err: errors.New(`ent: missing required field "CasbinRule.V4"`)} } if _, ok := crc.mutation.V5(); !ok { - return &ValidationError{Name: "V5", err: errors.New("ent: missing required field \"V5\"")} + return &ValidationError{Name: "V5", err: errors.New(`ent: missing required field "CasbinRule.V5"`)} } return nil } func (crc *CasbinRuleCreate) sqlSave(ctx context.Context) (*CasbinRule, error) { + if err := crc.check(); err != nil { + return nil, err + } _node, _spec := crc.createSpec() if err := sqlgraph.CreateNode(ctx, crc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + crc.mutation.id = &_node.ID + crc.mutation.done = true return _node, nil } func (crc *CasbinRuleCreate) createSpec() (*CasbinRule, *sqlgraph.CreateSpec) { var ( _node = &CasbinRule{config: crc.config} - _spec = &sqlgraph.CreateSpec{ - Table: casbinrule.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: casbinrule.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(casbinrule.Table, sqlgraph.NewFieldSpec(casbinrule.FieldID, field.TypeInt)) ) if value, ok := crc.mutation.Ptype(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldPtype, - }) + _spec.SetField(casbinrule.FieldPtype, field.TypeString, value) _node.Ptype = value } if value, ok := crc.mutation.V0(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV0, - }) + _spec.SetField(casbinrule.FieldV0, field.TypeString, value) _node.V0 = value } if value, ok := crc.mutation.V1(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV1, - }) + _spec.SetField(casbinrule.FieldV1, field.TypeString, value) _node.V1 = value } if value, ok := crc.mutation.V2(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV2, - }) + _spec.SetField(casbinrule.FieldV2, field.TypeString, value) _node.V2 = value } if value, ok := crc.mutation.V3(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV3, - }) + _spec.SetField(casbinrule.FieldV3, field.TypeString, value) _node.V3 = value } if value, ok := crc.mutation.V4(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV4, - }) + _spec.SetField(casbinrule.FieldV4, field.TypeString, value) _node.V4 = value } if value, ok := crc.mutation.V5(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV5, - }) + _spec.SetField(casbinrule.FieldV5, field.TypeString, value) _node.V5 = value } return _node, _spec @@ -311,11 +265,15 @@ func (crc *CasbinRuleCreate) createSpec() (*CasbinRule, *sqlgraph.CreateSpec) { // CasbinRuleCreateBulk is the builder for creating many CasbinRule entities in bulk. type CasbinRuleCreateBulk struct { config + err error builders []*CasbinRuleCreate } // Save creates the CasbinRule entities in the database. func (crcb *CasbinRuleCreateBulk) Save(ctx context.Context) ([]*CasbinRule, error) { + if crcb.err != nil { + return nil, crcb.err + } specs := make([]*sqlgraph.CreateSpec, len(crcb.builders)) nodes := make([]*CasbinRule, len(crcb.builders)) mutators := make([]Mutator, len(crcb.builders)) @@ -332,24 +290,28 @@ func (crcb *CasbinRuleCreateBulk) Save(ctx context.Context) ([]*CasbinRule, erro return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, crcb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, crcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, crcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -374,3 +336,16 @@ func (crcb *CasbinRuleCreateBulk) SaveX(ctx context.Context) []*CasbinRule { } return v } + +// Exec executes the query. +func (crcb *CasbinRuleCreateBulk) Exec(ctx context.Context) error { + _, err := crcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (crcb *CasbinRuleCreateBulk) ExecX(ctx context.Context) { + if err := crcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/casbinrule_delete.go b/ent/casbinrule_delete.go index f85dff5..b29b722 100644 --- a/ent/casbinrule_delete.go +++ b/ent/casbinrule_delete.go @@ -1,10 +1,9 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -20,39 +19,15 @@ type CasbinRuleDelete struct { mutation *CasbinRuleMutation } -// Where adds a new predicate to the CasbinRuleDelete builder. +// Where appends a list predicates to the CasbinRuleDelete builder. func (crd *CasbinRuleDelete) Where(ps ...predicate.CasbinRule) *CasbinRuleDelete { - crd.mutation.predicates = append(crd.mutation.predicates, ps...) + crd.mutation.Where(ps...) return crd } // Exec executes the deletion query and returns how many vertices were deleted. func (crd *CasbinRuleDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(crd.hooks) == 0 { - affected, err = crd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CasbinRuleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - crd.mutation = mutation - affected, err = crd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(crd.hooks) - 1; i >= 0; i-- { - mut = crd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, crd.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, crd.sqlExec, crd.mutation, crd.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -65,15 +40,7 @@ func (crd *CasbinRuleDelete) ExecX(ctx context.Context) int { } func (crd *CasbinRuleDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: casbinrule.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: casbinrule.FieldID, - }, - }, - } + _spec := sqlgraph.NewDeleteSpec(casbinrule.Table, sqlgraph.NewFieldSpec(casbinrule.FieldID, field.TypeInt)) if ps := crd.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -81,7 +48,12 @@ func (crd *CasbinRuleDelete) sqlExec(ctx context.Context) (int, error) { } } } - return sqlgraph.DeleteNodes(ctx, crd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, crd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + crd.mutation.done = true + return affected, err } // CasbinRuleDeleteOne is the builder for deleting a single CasbinRule entity. @@ -89,6 +61,12 @@ type CasbinRuleDeleteOne struct { crd *CasbinRuleDelete } +// Where appends a list predicates to the CasbinRuleDelete builder. +func (crdo *CasbinRuleDeleteOne) Where(ps ...predicate.CasbinRule) *CasbinRuleDeleteOne { + crdo.crd.mutation.Where(ps...) + return crdo +} + // Exec executes the deletion query. func (crdo *CasbinRuleDeleteOne) Exec(ctx context.Context) error { n, err := crdo.crd.Exec(ctx) @@ -104,5 +82,7 @@ func (crdo *CasbinRuleDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (crdo *CasbinRuleDeleteOne) ExecX(ctx context.Context) { - crdo.crd.ExecX(ctx) + if err := crdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/casbinrule_query.go b/ent/casbinrule_query.go index a2993ae..21eeac8 100644 --- a/ent/casbinrule_query.go +++ b/ent/casbinrule_query.go @@ -1,13 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "errors" "fmt" "math" + "entgo.io/ent" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -18,11 +18,9 @@ import ( // CasbinRuleQuery is the builder for querying CasbinRule entities. type CasbinRuleQuery struct { config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string + ctx *QueryContext + order []casbinrule.OrderOption + inters []Interceptor predicates []predicate.CasbinRule // intermediate query (i.e. traversal path). sql *sql.Selector @@ -35,27 +33,27 @@ func (crq *CasbinRuleQuery) Where(ps ...predicate.CasbinRule) *CasbinRuleQuery { return crq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (crq *CasbinRuleQuery) Limit(limit int) *CasbinRuleQuery { - crq.limit = &limit + crq.ctx.Limit = &limit return crq } -// Offset adds an offset step to the query. +// Offset to start from. func (crq *CasbinRuleQuery) Offset(offset int) *CasbinRuleQuery { - crq.offset = &offset + crq.ctx.Offset = &offset return crq } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. func (crq *CasbinRuleQuery) Unique(unique bool) *CasbinRuleQuery { - crq.unique = &unique + crq.ctx.Unique = &unique return crq } -// Order adds an order step to the query. -func (crq *CasbinRuleQuery) Order(o ...OrderFunc) *CasbinRuleQuery { +// Order specifies how the records should be ordered. +func (crq *CasbinRuleQuery) Order(o ...casbinrule.OrderOption) *CasbinRuleQuery { crq.order = append(crq.order, o...) return crq } @@ -63,7 +61,7 @@ func (crq *CasbinRuleQuery) Order(o ...OrderFunc) *CasbinRuleQuery { // First returns the first CasbinRule entity from the query. // Returns a *NotFoundError when no CasbinRule was found. func (crq *CasbinRuleQuery) First(ctx context.Context) (*CasbinRule, error) { - nodes, err := crq.Limit(1).All(ctx) + nodes, err := crq.Limit(1).All(setContextOp(ctx, crq.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -86,7 +84,7 @@ func (crq *CasbinRuleQuery) FirstX(ctx context.Context) *CasbinRule { // Returns a *NotFoundError when no CasbinRule ID was found. func (crq *CasbinRuleQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = crq.Limit(1).IDs(ctx); err != nil { + if ids, err = crq.Limit(1).IDs(setContextOp(ctx, crq.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -106,10 +104,10 @@ func (crq *CasbinRuleQuery) FirstIDX(ctx context.Context) int { } // Only returns a single CasbinRule entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when exactly one CasbinRule entity is not found. +// Returns a *NotSingularError when more than one CasbinRule entity is found. // Returns a *NotFoundError when no CasbinRule entities are found. func (crq *CasbinRuleQuery) Only(ctx context.Context) (*CasbinRule, error) { - nodes, err := crq.Limit(2).All(ctx) + nodes, err := crq.Limit(2).All(setContextOp(ctx, crq.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -133,11 +131,11 @@ func (crq *CasbinRuleQuery) OnlyX(ctx context.Context) *CasbinRule { } // OnlyID is like Only, but returns the only CasbinRule ID in the query. -// Returns a *NotSingularError when exactly one CasbinRule ID is not found. +// Returns a *NotSingularError when more than one CasbinRule ID is found. // Returns a *NotFoundError when no entities are found. func (crq *CasbinRuleQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = crq.Limit(2).IDs(ctx); err != nil { + if ids, err = crq.Limit(2).IDs(setContextOp(ctx, crq.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -162,10 +160,12 @@ func (crq *CasbinRuleQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of CasbinRules. func (crq *CasbinRuleQuery) All(ctx context.Context) ([]*CasbinRule, error) { + ctx = setContextOp(ctx, crq.ctx, ent.OpQueryAll) if err := crq.prepareQuery(ctx); err != nil { return nil, err } - return crq.sqlAll(ctx) + qr := querierAll[[]*CasbinRule, *CasbinRuleQuery]() + return withInterceptors[[]*CasbinRule](ctx, crq, qr, crq.inters) } // AllX is like All, but panics if an error occurs. @@ -178,9 +178,12 @@ func (crq *CasbinRuleQuery) AllX(ctx context.Context) []*CasbinRule { } // IDs executes the query and returns a list of CasbinRule IDs. -func (crq *CasbinRuleQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := crq.Select(casbinrule.FieldID).Scan(ctx, &ids); err != nil { +func (crq *CasbinRuleQuery) IDs(ctx context.Context) (ids []int, err error) { + if crq.ctx.Unique == nil && crq.path != nil { + crq.Unique(true) + } + ctx = setContextOp(ctx, crq.ctx, ent.OpQueryIDs) + if err = crq.Select(casbinrule.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -197,10 +200,11 @@ func (crq *CasbinRuleQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (crq *CasbinRuleQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, crq.ctx, ent.OpQueryCount) if err := crq.prepareQuery(ctx); err != nil { return 0, err } - return crq.sqlCount(ctx) + return withInterceptors[int](ctx, crq, querierCount[*CasbinRuleQuery](), crq.inters) } // CountX is like Count, but panics if an error occurs. @@ -214,10 +218,15 @@ func (crq *CasbinRuleQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (crq *CasbinRuleQuery) Exist(ctx context.Context) (bool, error) { - if err := crq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, crq.ctx, ent.OpQueryExist) + switch _, err := crq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return crq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -237,9 +246,9 @@ func (crq *CasbinRuleQuery) Clone() *CasbinRuleQuery { } return &CasbinRuleQuery{ config: crq.config, - limit: crq.limit, - offset: crq.offset, - order: append([]OrderFunc{}, crq.order...), + ctx: crq.ctx.Clone(), + order: append([]casbinrule.OrderOption{}, crq.order...), + inters: append([]Interceptor{}, crq.inters...), predicates: append([]predicate.CasbinRule{}, crq.predicates...), // clone intermediate query. sql: crq.sql.Clone(), @@ -261,17 +270,13 @@ func (crq *CasbinRuleQuery) Clone() *CasbinRuleQuery { // GroupBy(casbinrule.FieldPtype). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (crq *CasbinRuleQuery) GroupBy(field string, fields ...string) *CasbinRuleGroupBy { - group := &CasbinRuleGroupBy{config: crq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := crq.prepareQuery(ctx); err != nil { - return nil, err - } - return crq.sqlQuery(ctx), nil - } - return group + crq.ctx.Fields = append([]string{field}, fields...) + grbuild := &CasbinRuleGroupBy{build: crq} + grbuild.flds = &crq.ctx.Fields + grbuild.label = casbinrule.Label + grbuild.scan = grbuild.Scan + return grbuild } // Select allows the selection one or more fields/columns for the given query, @@ -286,14 +291,31 @@ func (crq *CasbinRuleQuery) GroupBy(field string, fields ...string) *CasbinRuleG // client.CasbinRule.Query(). // Select(casbinrule.FieldPtype). // Scan(ctx, &v) -// -func (crq *CasbinRuleQuery) Select(field string, fields ...string) *CasbinRuleSelect { - crq.fields = append([]string{field}, fields...) - return &CasbinRuleSelect{CasbinRuleQuery: crq} +func (crq *CasbinRuleQuery) Select(fields ...string) *CasbinRuleSelect { + crq.ctx.Fields = append(crq.ctx.Fields, fields...) + sbuild := &CasbinRuleSelect{CasbinRuleQuery: crq} + sbuild.label = casbinrule.Label + sbuild.flds, sbuild.scan = &crq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CasbinRuleSelect configured with the given aggregations. +func (crq *CasbinRuleQuery) Aggregate(fns ...AggregateFunc) *CasbinRuleSelect { + return crq.Select().Aggregate(fns...) } func (crq *CasbinRuleQuery) prepareQuery(ctx context.Context) error { - for _, f := range crq.fields { + for _, inter := range crq.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, crq); err != nil { + return err + } + } + } + for _, f := range crq.ctx.Fields { if !casbinrule.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} } @@ -308,23 +330,22 @@ func (crq *CasbinRuleQuery) prepareQuery(ctx context.Context) error { return nil } -func (crq *CasbinRuleQuery) sqlAll(ctx context.Context) ([]*CasbinRule, error) { +func (crq *CasbinRuleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CasbinRule, error) { var ( nodes = []*CasbinRule{} _spec = crq.querySpec() ) - _spec.ScanValues = func(columns []string) ([]interface{}, error) { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*CasbinRule).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &CasbinRule{config: crq.config} nodes = append(nodes, node) - return node.scanValues(columns) - } - _spec.Assign = func(columns []string, values []interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] return node.assignValues(columns, values) } + for i := range hooks { + hooks[i](ctx, _spec) + } if err := sqlgraph.QueryNodes(ctx, crq.driver, _spec); err != nil { return nil, err } @@ -336,34 +357,22 @@ func (crq *CasbinRuleQuery) sqlAll(ctx context.Context) ([]*CasbinRule, error) { func (crq *CasbinRuleQuery) sqlCount(ctx context.Context) (int, error) { _spec := crq.querySpec() - return sqlgraph.CountNodes(ctx, crq.driver, _spec) -} - -func (crq *CasbinRuleQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := crq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %w", err) + _spec.Node.Columns = crq.ctx.Fields + if len(crq.ctx.Fields) > 0 { + _spec.Unique = crq.ctx.Unique != nil && *crq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, crq.driver, _spec) } func (crq *CasbinRuleQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: casbinrule.Table, - Columns: casbinrule.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: casbinrule.FieldID, - }, - }, - From: crq.sql, - Unique: true, - } - if unique := crq.unique; unique != nil { + _spec := sqlgraph.NewQuerySpec(casbinrule.Table, casbinrule.Columns, sqlgraph.NewFieldSpec(casbinrule.FieldID, field.TypeInt)) + _spec.From = crq.sql + if unique := crq.ctx.Unique; unique != nil { _spec.Unique = *unique + } else if crq.path != nil { + _spec.Unique = true } - if fields := crq.fields; len(fields) > 0 { + if fields := crq.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, casbinrule.FieldID) for i := range fields { @@ -379,10 +388,10 @@ func (crq *CasbinRuleQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := crq.limit; limit != nil { + if limit := crq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := crq.offset; offset != nil { + if offset := crq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := crq.order; len(ps) > 0 { @@ -398,10 +407,17 @@ func (crq *CasbinRuleQuery) querySpec() *sqlgraph.QuerySpec { func (crq *CasbinRuleQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(crq.driver.Dialect()) t1 := builder.Table(casbinrule.Table) - selector := builder.Select(t1.Columns(casbinrule.Columns...)...).From(t1) + columns := crq.ctx.Fields + if len(columns) == 0 { + columns = casbinrule.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if crq.sql != nil { selector = crq.sql - selector.Select(selector.Columns(casbinrule.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if crq.ctx.Unique != nil && *crq.ctx.Unique { + selector.Distinct() } for _, p := range crq.predicates { p(selector) @@ -409,12 +425,12 @@ func (crq *CasbinRuleQuery) sqlQuery(ctx context.Context) *sql.Selector { for _, p := range crq.order { p(selector) } - if offset := crq.offset; offset != nil { + if offset := crq.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := crq.limit; limit != nil { + if limit := crq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -422,12 +438,8 @@ func (crq *CasbinRuleQuery) sqlQuery(ctx context.Context) *sql.Selector { // CasbinRuleGroupBy is the group-by builder for CasbinRule entities. type CasbinRuleGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *CasbinRuleQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -436,471 +448,80 @@ func (crgb *CasbinRuleGroupBy) Aggregate(fns ...AggregateFunc) *CasbinRuleGroupB return crgb } -// Scan applies the group-by query and scans the result into the given value. -func (crgb *CasbinRuleGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := crgb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (crgb *CasbinRuleGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, crgb.build.ctx, ent.OpQueryGroupBy) + if err := crgb.build.prepareQuery(ctx); err != nil { return err } - crgb.sql = query - return crgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := crgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(crgb.fields) > 1 { - return nil, errors.New("ent: CasbinRuleGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := crgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) StringsX(ctx context.Context) []string { - v, err := crgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = crgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) StringX(ctx context.Context) string { - v, err := crgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(crgb.fields) > 1 { - return nil, errors.New("ent: CasbinRuleGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := crgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) IntsX(ctx context.Context) []int { - v, err := crgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = crgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) IntX(ctx context.Context) int { - v, err := crgb.Int(ctx) - if err != nil { - panic(err) - } - return v + return scanWithInterceptors[*CasbinRuleQuery, *CasbinRuleGroupBy](ctx, crgb.build, crgb, crgb.build.inters, v) } -// Float64s returns list of float64s from group-by. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(crgb.fields) > 1 { - return nil, errors.New("ent: CasbinRuleGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := crgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := crgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = crgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) Float64X(ctx context.Context) float64 { - v, err := crgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(crgb.fields) > 1 { - return nil, errors.New("ent: CasbinRuleGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := crgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) BoolsX(ctx context.Context) []bool { - v, err := crgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a group-by query. -// It is only allowed when executing a group-by query with one field. -func (crgb *CasbinRuleGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = crgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (crgb *CasbinRuleGroupBy) BoolX(ctx context.Context) bool { - v, err := crgb.Bool(ctx) - if err != nil { - panic(err) +func (crgb *CasbinRuleGroupBy) sqlScan(ctx context.Context, root *CasbinRuleQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(crgb.fns)) + for _, fn := range crgb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (crgb *CasbinRuleGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range crgb.fields { - if !casbinrule.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*crgb.flds)+len(crgb.fns)) + for _, f := range *crgb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := crgb.sqlQuery() + selector.GroupBy(selector.Columns(*crgb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := crgb.driver.Query(ctx, query, args, rows); err != nil { + if err := crgb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (crgb *CasbinRuleGroupBy) sqlQuery() *sql.Selector { - selector := crgb.sql - columns := make([]string, 0, len(crgb.fields)+len(crgb.fns)) - columns = append(columns, crgb.fields...) - for _, fn := range crgb.fns { - columns = append(columns, fn(selector)) - } - return selector.Select(columns...).GroupBy(crgb.fields...) -} - // CasbinRuleSelect is the builder for selecting fields of CasbinRule entities. type CasbinRuleSelect struct { *CasbinRuleQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (crs *CasbinRuleSelect) Aggregate(fns ...AggregateFunc) *CasbinRuleSelect { + crs.fns = append(crs.fns, fns...) + return crs } // Scan applies the selector query and scans the result into the given value. -func (crs *CasbinRuleSelect) Scan(ctx context.Context, v interface{}) error { +func (crs *CasbinRuleSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, crs.ctx, ent.OpQuerySelect) if err := crs.prepareQuery(ctx); err != nil { return err } - crs.sql = crs.CasbinRuleQuery.sqlQuery(ctx) - return crs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (crs *CasbinRuleSelect) ScanX(ctx context.Context, v interface{}) { - if err := crs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) Strings(ctx context.Context) ([]string, error) { - if len(crs.fields) > 1 { - return nil, errors.New("ent: CasbinRuleSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := crs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*CasbinRuleQuery, *CasbinRuleSelect](ctx, crs.CasbinRuleQuery, crs, crs.inters, v) } -// StringsX is like Strings, but panics if an error occurs. -func (crs *CasbinRuleSelect) StringsX(ctx context.Context) []string { - v, err := crs.Strings(ctx) - if err != nil { - panic(err) +func (crs *CasbinRuleSelect) sqlScan(ctx context.Context, root *CasbinRuleQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(crs.fns)) + for _, fn := range crs.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = crs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (crs *CasbinRuleSelect) StringX(ctx context.Context) string { - v, err := crs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) Ints(ctx context.Context) ([]int, error) { - if len(crs.fields) > 1 { - return nil, errors.New("ent: CasbinRuleSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := crs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (crs *CasbinRuleSelect) IntsX(ctx context.Context) []int { - v, err := crs.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = crs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleSelect.Ints returned %d results when one was expected", len(v)) + switch n := len(*crs.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) } - return -} - -// IntX is like Int, but panics if an error occurs. -func (crs *CasbinRuleSelect) IntX(ctx context.Context) int { - v, err := crs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(crs.fields) > 1 { - return nil, errors.New("ent: CasbinRuleSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := crs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (crs *CasbinRuleSelect) Float64sX(ctx context.Context) []float64 { - v, err := crs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = crs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (crs *CasbinRuleSelect) Float64X(ctx context.Context) float64 { - v, err := crs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) Bools(ctx context.Context) ([]bool, error) { - if len(crs.fields) > 1 { - return nil, errors.New("ent: CasbinRuleSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := crs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (crs *CasbinRuleSelect) BoolsX(ctx context.Context) []bool { - v, err := crs.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (crs *CasbinRuleSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = crs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{casbinrule.Label} - default: - err = fmt.Errorf("ent: CasbinRuleSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (crs *CasbinRuleSelect) BoolX(ctx context.Context) bool { - v, err := crs.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (crs *CasbinRuleSelect) sqlScan(ctx context.Context, v interface{}) error { rows := &sql.Rows{} - query, args := crs.sqlQuery().Query() + query, args := selector.Query() if err := crs.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (crs *CasbinRuleSelect) sqlQuery() sql.Querier { - selector := crs.sql - selector.Select(selector.Columns(crs.fields...)...) - return selector -} diff --git a/ent/casbinrule_update.go b/ent/casbinrule_update.go index e7fb5a5..d462041 100644 --- a/ent/casbinrule_update.go +++ b/ent/casbinrule_update.go @@ -1,9 +1,10 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" "entgo.io/ent/dialect/sql" @@ -20,9 +21,9 @@ type CasbinRuleUpdate struct { mutation *CasbinRuleMutation } -// Where adds a new predicate for the CasbinRuleUpdate builder. +// Where appends a list predicates to the CasbinRuleUpdate builder. func (cru *CasbinRuleUpdate) Where(ps ...predicate.CasbinRule) *CasbinRuleUpdate { - cru.mutation.predicates = append(cru.mutation.predicates, ps...) + cru.mutation.Where(ps...) return cru } @@ -131,31 +132,7 @@ func (cru *CasbinRuleUpdate) Mutation() *CasbinRuleMutation { // Save executes the query and returns the number of nodes affected by the update operation. func (cru *CasbinRuleUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(cru.hooks) == 0 { - affected, err = cru.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CasbinRuleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - cru.mutation = mutation - affected, err = cru.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(cru.hooks) - 1; i >= 0; i-- { - mut = cru.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, cru.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, cru.sqlSave, cru.mutation, cru.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -181,16 +158,7 @@ func (cru *CasbinRuleUpdate) ExecX(ctx context.Context) { } func (cru *CasbinRuleUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: casbinrule.Table, - Columns: casbinrule.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: casbinrule.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(casbinrule.Table, casbinrule.Columns, sqlgraph.NewFieldSpec(casbinrule.FieldID, field.TypeInt)) if ps := cru.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -199,62 +167,35 @@ func (cru *CasbinRuleUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := cru.mutation.Ptype(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldPtype, - }) + _spec.SetField(casbinrule.FieldPtype, field.TypeString, value) } if value, ok := cru.mutation.V0(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV0, - }) + _spec.SetField(casbinrule.FieldV0, field.TypeString, value) } if value, ok := cru.mutation.V1(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV1, - }) + _spec.SetField(casbinrule.FieldV1, field.TypeString, value) } if value, ok := cru.mutation.V2(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV2, - }) + _spec.SetField(casbinrule.FieldV2, field.TypeString, value) } if value, ok := cru.mutation.V3(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV3, - }) + _spec.SetField(casbinrule.FieldV3, field.TypeString, value) } if value, ok := cru.mutation.V4(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV4, - }) + _spec.SetField(casbinrule.FieldV4, field.TypeString, value) } if value, ok := cru.mutation.V5(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV5, - }) + _spec.SetField(casbinrule.FieldV5, field.TypeString, value) } if n, err = sqlgraph.UpdateNodes(ctx, cru.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{casbinrule.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + cru.mutation.done = true return n, nil } @@ -369,6 +310,12 @@ func (cruo *CasbinRuleUpdateOne) Mutation() *CasbinRuleMutation { return cruo.mutation } +// Where appends a list predicates to the CasbinRuleUpdate builder. +func (cruo *CasbinRuleUpdateOne) Where(ps ...predicate.CasbinRule) *CasbinRuleUpdateOne { + cruo.mutation.Where(ps...) + return cruo +} + // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. func (cruo *CasbinRuleUpdateOne) Select(field string, fields ...string) *CasbinRuleUpdateOne { @@ -378,31 +325,7 @@ func (cruo *CasbinRuleUpdateOne) Select(field string, fields ...string) *CasbinR // Save executes the query and returns the updated CasbinRule entity. func (cruo *CasbinRuleUpdateOne) Save(ctx context.Context) (*CasbinRule, error) { - var ( - err error - node *CasbinRule - ) - if len(cruo.hooks) == 0 { - node, err = cruo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CasbinRuleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - cruo.mutation = mutation - node, err = cruo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(cruo.hooks) - 1; i >= 0; i-- { - mut = cruo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, cruo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, cruo.sqlSave, cruo.mutation, cruo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -428,19 +351,10 @@ func (cruo *CasbinRuleUpdateOne) ExecX(ctx context.Context) { } func (cruo *CasbinRuleUpdateOne) sqlSave(ctx context.Context) (_node *CasbinRule, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: casbinrule.Table, - Columns: casbinrule.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: casbinrule.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(casbinrule.Table, casbinrule.Columns, sqlgraph.NewFieldSpec(casbinrule.FieldID, field.TypeInt)) id, ok := cruo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing CasbinRule.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "CasbinRule.id" for update`)} } _spec.Node.ID.Value = id if fields := cruo.fields; len(fields) > 0 { @@ -463,53 +377,25 @@ func (cruo *CasbinRuleUpdateOne) sqlSave(ctx context.Context) (_node *CasbinRule } } if value, ok := cruo.mutation.Ptype(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldPtype, - }) + _spec.SetField(casbinrule.FieldPtype, field.TypeString, value) } if value, ok := cruo.mutation.V0(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV0, - }) + _spec.SetField(casbinrule.FieldV0, field.TypeString, value) } if value, ok := cruo.mutation.V1(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV1, - }) + _spec.SetField(casbinrule.FieldV1, field.TypeString, value) } if value, ok := cruo.mutation.V2(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV2, - }) + _spec.SetField(casbinrule.FieldV2, field.TypeString, value) } if value, ok := cruo.mutation.V3(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV3, - }) + _spec.SetField(casbinrule.FieldV3, field.TypeString, value) } if value, ok := cruo.mutation.V4(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV4, - }) + _spec.SetField(casbinrule.FieldV4, field.TypeString, value) } if value, ok := cruo.mutation.V5(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: casbinrule.FieldV5, - }) + _spec.SetField(casbinrule.FieldV5, field.TypeString, value) } _node = &CasbinRule{config: cruo.config} _spec.Assign = _node.assignValues @@ -517,10 +403,11 @@ func (cruo *CasbinRuleUpdateOne) sqlSave(ctx context.Context) (_node *CasbinRule if err = sqlgraph.UpdateNode(ctx, cruo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{casbinrule.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + cruo.mutation.done = true return _node, nil } diff --git a/ent/client.go b/ent/client.go index 49398d5..ee8d988 100644 --- a/ent/client.go +++ b/ent/client.go @@ -1,18 +1,20 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" "log" + "reflect" "github.com/casbin/ent-adapter/ent/migrate" - "github.com/casbin/ent-adapter/ent/casbinrule" - + "entgo.io/ent" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "github.com/casbin/ent-adapter/ent/casbinrule" ) // Client is the client that holds all ent builders. @@ -26,9 +28,7 @@ type Client struct { // NewClient creates a new client configured with the given options. func NewClient(opts ...Option) *Client { - cfg := config{log: log.Println, hooks: &hooks{}} - cfg.options(opts...) - client := &Client{config: cfg} + client := &Client{config: newConfig(opts...)} client.init() return client } @@ -38,6 +38,62 @@ func (c *Client) init() { c.CasbinRule = NewCasbinRuleClient(c.config) } +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + // Open opens a database/sql.DB specified by the driver name and // the data source name, and returns a new client attached to it. // Optional parameters can be added for configuring the client. @@ -54,11 +110,14 @@ func Open(driverName, dataSourceName string, options ...Option) (*Client, error) } } +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") + // Tx returns a new transactional client. The provided context // is used until the transaction is committed or rolled back. func (c *Client) Tx(ctx context.Context) (*Tx, error) { if _, ok := c.driver.(*txDriver); ok { - return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + return nil, ErrTxStarted } tx, err := newTx(ctx, c.driver) if err != nil { @@ -76,7 +135,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { // BeginTx returns a transactional client with specified options. func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { if _, ok := c.driver.(*txDriver); ok { - return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + return nil, errors.New("ent: cannot start a transaction within a transaction") } tx, err := c.driver.(interface { BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) @@ -87,6 +146,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ + ctx: ctx, config: cfg, CasbinRule: NewCasbinRuleClient(cfg), }, nil @@ -98,7 +158,6 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) // CasbinRule. // Query(). // Count(ctx) -// func (c *Client) Debug() *Client { if c.debug { return c @@ -121,6 +180,22 @@ func (c *Client) Use(hooks ...Hook) { c.CasbinRule.Use(hooks...) } +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.CasbinRule.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *CasbinRuleMutation: + return c.CasbinRule.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + // CasbinRuleClient is a client for the CasbinRule schema. type CasbinRuleClient struct { config @@ -137,7 +212,13 @@ func (c *CasbinRuleClient) Use(hooks ...Hook) { c.hooks.CasbinRule = append(c.hooks.CasbinRule, hooks...) } -// Create returns a create builder for CasbinRule. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `casbinrule.Intercept(f(g(h())))`. +func (c *CasbinRuleClient) Intercept(interceptors ...Interceptor) { + c.inters.CasbinRule = append(c.inters.CasbinRule, interceptors...) +} + +// Create returns a builder for creating a CasbinRule entity. func (c *CasbinRuleClient) Create() *CasbinRuleCreate { mutation := newCasbinRuleMutation(c.config, OpCreate) return &CasbinRuleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} @@ -148,6 +229,21 @@ func (c *CasbinRuleClient) CreateBulk(builders ...*CasbinRuleCreate) *CasbinRule return &CasbinRuleCreateBulk{config: c.config, builders: builders} } +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *CasbinRuleClient) MapCreateBulk(slice any, setFunc func(*CasbinRuleCreate, int)) *CasbinRuleCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CasbinRuleCreateBulk{err: fmt.Errorf("calling to CasbinRuleClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CasbinRuleCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CasbinRuleCreateBulk{config: c.config, builders: builders} +} + // Update returns an update builder for CasbinRule. func (c *CasbinRuleClient) Update() *CasbinRuleUpdate { mutation := newCasbinRuleMutation(c.config, OpUpdate) @@ -172,12 +268,12 @@ func (c *CasbinRuleClient) Delete() *CasbinRuleDelete { return &CasbinRuleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CasbinRuleClient) DeleteOne(cr *CasbinRule) *CasbinRuleDeleteOne { return c.DeleteOneID(cr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *CasbinRuleClient) DeleteOneID(id int) *CasbinRuleDeleteOne { builder := c.Delete().Where(casbinrule.ID(id)) builder.mutation.id = &id @@ -189,6 +285,8 @@ func (c *CasbinRuleClient) DeleteOneID(id int) *CasbinRuleDeleteOne { func (c *CasbinRuleClient) Query() *CasbinRuleQuery { return &CasbinRuleQuery{ config: c.config, + ctx: &QueryContext{Type: TypeCasbinRule}, + inters: c.Interceptors(), } } @@ -210,3 +308,33 @@ func (c *CasbinRuleClient) GetX(ctx context.Context, id int) *CasbinRule { func (c *CasbinRuleClient) Hooks() []Hook { return c.hooks.CasbinRule } + +// Interceptors returns the client interceptors. +func (c *CasbinRuleClient) Interceptors() []Interceptor { + return c.inters.CasbinRule +} + +func (c *CasbinRuleClient) mutate(ctx context.Context, m *CasbinRuleMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CasbinRuleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CasbinRuleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CasbinRuleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CasbinRuleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown CasbinRule mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + CasbinRule []ent.Hook + } + inters struct { + CasbinRule []ent.Interceptor + } +) diff --git a/ent/config.go b/ent/config.go deleted file mode 100644 index b89d2d1..0000000 --- a/ent/config.go +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package ent - -import ( - "entgo.io/ent" - "entgo.io/ent/dialect" -) - -// Option function to configure the client. -type Option func(*config) - -// Config is the configuration for the client and its builder. -type config struct { - // driver used for executing database requests. - driver dialect.Driver - // debug enable a debug logging. - debug bool - // log used for logging on debug mode. - log func(...interface{}) - // hooks to execute on mutations. - hooks *hooks -} - -// hooks per client, for fast access. -type hooks struct { - CasbinRule []ent.Hook -} - -// Options applies the options on the config object. -func (c *config) options(opts ...Option) { - for _, opt := range opts { - opt(c) - } - if c.debug { - c.driver = dialect.Debug(c.driver, c.log) - } -} - -// Debug enables debug logging on the ent.Driver. -func Debug() Option { - return func(c *config) { - c.debug = true - } -} - -// Log sets the logging function for debug mode. -func Log(fn func(...interface{})) Option { - return func(c *config) { - c.log = fn - } -} - -// Driver configures the client driver. -func Driver(driver dialect.Driver) Option { - return func(c *config) { - c.driver = driver - } -} diff --git a/ent/context.go b/ent/context.go deleted file mode 100644 index 0840726..0000000 --- a/ent/context.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package ent - -import ( - "context" -) - -type clientCtxKey struct{} - -// FromContext returns a Client stored inside a context, or nil if there isn't one. -func FromContext(ctx context.Context) *Client { - c, _ := ctx.Value(clientCtxKey{}).(*Client) - return c -} - -// NewContext returns a new context with the given Client attached. -func NewContext(parent context.Context, c *Client) context.Context { - return context.WithValue(parent, clientCtxKey{}, c) -} - -type txCtxKey struct{} - -// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. -func TxFromContext(ctx context.Context) *Tx { - tx, _ := ctx.Value(txCtxKey{}).(*Tx) - return tx -} - -// NewTxContext returns a new context with the given Tx attached. -func NewTxContext(parent context.Context, tx *Tx) context.Context { - return context.WithValue(parent, txCtxKey{}, tx) -} diff --git a/ent/ent.go b/ent/ent.go index 198497e..c648965 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -1,13 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( + "context" "errors" "fmt" + "reflect" + "sync" "entgo.io/ent" - "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/casbin/ent-adapter/ent/casbinrule" @@ -15,44 +17,73 @@ import ( // ent aliases to avoid import conflicts in user's code. type ( - Op = ent.Op - Hook = ent.Hook - Value = ent.Value - Query = ent.Query - Policy = ent.Policy - Mutator = ent.Mutator - Mutation = ent.Mutation - MutateFunc = ent.MutateFunc + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc ) +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + // OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. type OrderFunc func(*sql.Selector) -// columnChecker returns a function indicates if the column exists in the given column. -func columnChecker(table string) func(string) error { - checks := map[string]func(string) bool{ - casbinrule.Table: casbinrule.ValidColumn, - } - check, ok := checks[table] - if !ok { - return func(string) error { - return fmt.Errorf("unknown table %q", table) - } - } - return func(column string) error { - if !check(column) { - return fmt.Errorf("unknown column %q for table %q", column, table) - } - return nil - } +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + casbinrule.Table: casbinrule.ValidColumn, + }) + }) + return columnCheck(table, column) } // Asc applies the given fields in ASC order. -func Asc(fields ...string) OrderFunc { +func Asc(fields ...string) func(*sql.Selector) { return func(s *sql.Selector) { - check := columnChecker(s.TableName()) for _, f := range fields { - if err := check(f); err != nil { + if err := checkColumn(s.TableName(), f); err != nil { s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) } s.OrderBy(sql.Asc(s.C(f))) @@ -61,11 +92,10 @@ func Asc(fields ...string) OrderFunc { } // Desc applies the given fields in DESC order. -func Desc(fields ...string) OrderFunc { +func Desc(fields ...string) func(*sql.Selector) { return func(s *sql.Selector) { - check := columnChecker(s.TableName()) for _, f := range fields { - if err := check(f); err != nil { + if err := checkColumn(s.TableName(), f); err != nil { s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) } s.OrderBy(sql.Desc(s.C(f))) @@ -81,7 +111,6 @@ type AggregateFunc func(*sql.Selector) string // GroupBy(field1, field2). // Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). // Scan(ctx, &v) -// func As(fn AggregateFunc, end string) AggregateFunc { return func(s *sql.Selector) string { return sql.As(fn(s), end) @@ -98,8 +127,7 @@ func Count() AggregateFunc { // Max applies the "max" aggregation function on the given field of each group. func Max(field string) AggregateFunc { return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { + if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } @@ -110,8 +138,7 @@ func Max(field string) AggregateFunc { // Mean applies the "mean" aggregation function on the given field of each group. func Mean(field string) AggregateFunc { return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { + if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } @@ -122,8 +149,7 @@ func Mean(field string) AggregateFunc { // Min applies the "min" aggregation function on the given field of each group. func Min(field string) AggregateFunc { return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { + if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } @@ -134,8 +160,7 @@ func Min(field string) AggregateFunc { // Sum applies the "sum" aggregation function on the given field of each group. func Sum(field string) AggregateFunc { return func(s *sql.Selector) string { - check := columnChecker(s.TableName()) - if err := check(field); err != nil { + if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } @@ -143,7 +168,7 @@ func Sum(field string) AggregateFunc { } } -// ValidationError returns when validating a field fails. +// ValidationError returns when validating a field or edge fails. type ValidationError struct { Name string // Field or edge name. err error @@ -159,7 +184,7 @@ func (e *ValidationError) Unwrap() error { return e.err } -// IsValidationError returns a boolean indicating whether the error is a validaton error. +// IsValidationError returns a boolean indicating whether the error is a validation error. func IsValidationError(err error) bool { if err == nil { return false @@ -260,20 +285,324 @@ func IsConstraintError(err error) bool { return errors.As(err, &e) } -func isSQLConstraintError(err error) (*ConstraintError, bool) { - if sqlgraph.IsConstraintError(err) { - return &ConstraintError{err.Error(), err}, true +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err } - return nil, false + return v, nil } -// rollback calls tx.Rollback and wraps the given error with the rollback error if present. -func rollback(tx dialect.Tx, err error) error { - if rerr := tx.Rollback(); rerr != nil { - err = fmt.Errorf("%w: %v", err, rerr) +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) } - if err, ok := isSQLConstraintError(err); ok { + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { return err } - return err + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil } + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/ent/enttest/enttest.go b/ent/enttest/enttest.go index 1983e85..a56c14d 100644 --- a/ent/enttest/enttest.go +++ b/ent/enttest/enttest.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package enttest @@ -10,6 +10,7 @@ import ( _ "github.com/casbin/ent-adapter/ent/runtime" "entgo.io/ent/dialect/sql/schema" + "github.com/casbin/ent-adapter/ent/migrate" ) type ( @@ -17,7 +18,7 @@ type ( // testing.T and testing.B and used by enttest. TestingT interface { FailNow() - Error(...interface{}) + Error(...any) } // Option configures client creation. @@ -59,10 +60,7 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl t.Error(err) t.FailNow() } - if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { - t.Error(err) - t.FailNow() - } + migrateSchema(t, c, o) return c } @@ -70,9 +68,17 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl func NewClient(t TestingT, opts ...Option) *ent.Client { o := newOptions(opts) c := ent.NewClient(o.opts...) - if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *ent.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { t.Error(err) t.FailNow() } - return c } diff --git a/ent/generate.go b/ent/generate.go index 8d3fdfd..cb0bed9 100644 --- a/ent/generate.go +++ b/ent/generate.go @@ -1,3 +1,22 @@ -package ent +//go:build ignore +// +build ignore -//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema +package main + +import ( + "log" + + "entgo.io/ent/entc" + "entgo.io/ent/entc/gen" + "github.com/casbin/ent-adapter/template" +) + +func main() { + err := entc.Generate("./schema", + &gen.Config{}, + entc.Extensions(&template.CasbinExtension{}), + ) + if err != nil { + log.Fatal("running ent codegen:", err) + } +} diff --git a/ent/hook/hook.go b/ent/hook/hook.go index 820fc49..11a5ead 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package hook @@ -15,11 +15,10 @@ type CasbinRuleFunc func(context.Context, *ent.CasbinRuleMutation) (ent.Value, e // Mutate calls f(ctx, m). func (f CasbinRuleFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.CasbinRuleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CasbinRuleMutation", m) + if mv, ok := m.(*ent.CasbinRuleMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CasbinRuleMutation", m) } // Condition is a hook condition function. @@ -117,7 +116,6 @@ func HasFields(field string, fields ...string) Condition { // If executes the given hook under condition. // // hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) -// func If(hk ent.Hook, cond Condition) ent.Hook { return func(next ent.Mutator) ent.Mutator { return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { @@ -132,7 +130,6 @@ func If(hk ent.Hook, cond Condition) ent.Hook { // On executes the given hook only for the given operation. // // hook.On(Log, ent.Delete|ent.Create) -// func On(hk ent.Hook, op ent.Op) ent.Hook { return If(hk, HasOp(op)) } @@ -140,7 +137,6 @@ func On(hk ent.Hook, op ent.Op) ent.Hook { // Unless skips the given hook only for the given operation. // // hook.Unless(Log, ent.Update|ent.UpdateOne) -// func Unless(hk ent.Hook, op ent.Op) ent.Hook { return If(hk, Not(HasOp(op))) } @@ -161,7 +157,6 @@ func FixedError(err error) ent.Hook { // Reject(ent.Delete|ent.Update), // } // } -// func Reject(op ent.Op) ent.Hook { hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) return On(hk, op) diff --git a/ent/migrate/migrate.go b/ent/migrate/migrate.go index e4a9a22..1956a6b 100644 --- a/ent/migrate/migrate.go +++ b/ent/migrate/migrate.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package migrate @@ -28,17 +28,13 @@ var ( // and therefore, it's recommended to enable this option to get more // flexibility in the schema changes. WithDropIndex = schema.WithDropIndex - // WithFixture sets the foreign-key renaming option to the migration when upgrading - // ent from v0.1.0 (issue-#285). Defaults to false. - WithFixture = schema.WithFixture // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. WithForeignKeys = schema.WithForeignKeys ) // Schema is the API for creating, migrating and dropping a schema. type Schema struct { - drv dialect.Driver - universalID bool + drv dialect.Driver } // NewSchema creates a new schema client. @@ -46,27 +42,23 @@ func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } // Create creates all schema resources. func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { migrate, err := schema.NewMigrate(s.drv, opts...) if err != nil { return fmt.Errorf("ent/migrate: %w", err) } - return migrate.Create(ctx, Tables...) + return migrate.Create(ctx, tables...) } // WriteTo writes the schema changes to w instead of running them against the database. // -// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { // log.Fatal(err) -// } -// +// } func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { - drv := &schema.WriteDriver{ - Writer: w, - Driver: s.drv, - } - migrate, err := schema.NewMigrate(drv, opts...) - if err != nil { - return fmt.Errorf("ent/migrate: %w", err) - } - return migrate.Create(ctx, Tables...) + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) } diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index 681a4cb..4e3cd0e 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package migrate @@ -21,10 +21,9 @@ var ( } // CasbinRulesTable holds the schema information for the "casbin_rules" table. CasbinRulesTable = &schema.Table{ - Name: "casbin_rules", - Columns: CasbinRulesColumns, - PrimaryKey: []*schema.Column{CasbinRulesColumns[0]}, - ForeignKeys: []*schema.ForeignKey{}, + Name: "casbin_rules", + Columns: CasbinRulesColumns, + PrimaryKey: []*schema.Column{CasbinRulesColumns[0]}, } // Tables holds all the tables in the schema. Tables = []*schema.Table{ diff --git a/ent/mutation.go b/ent/mutation.go index 1137e36..e016001 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -1,16 +1,17 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" "sync" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/casbin/ent-adapter/ent/casbinrule" "github.com/casbin/ent-adapter/ent/predicate" - - "entgo.io/ent" ) const ( @@ -74,7 +75,7 @@ func withCasbinRuleID(id int) casbinruleOption { m.oldValue = func(ctx context.Context) (*CasbinRule, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().CasbinRule.Get(ctx, id) } @@ -107,15 +108,15 @@ func (m CasbinRuleMutation) Client() *Client { // it returns an error otherwise. func (m CasbinRuleMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the ID value in the mutation. Note that the ID -// is only available if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *CasbinRuleMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -123,6 +124,25 @@ func (m *CasbinRuleMutation) ID() (id int, exists bool) { return *m.id, true } +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *CasbinRuleMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().CasbinRule.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + // SetPtype sets the "Ptype" field. func (m *CasbinRuleMutation) SetPtype(s string) { m._Ptype = &s @@ -142,10 +162,10 @@ func (m *CasbinRuleMutation) Ptype() (r string, exists bool) { // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CasbinRuleMutation) OldPtype(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldPtype is only allowed on UpdateOne operations") + return v, errors.New("OldPtype is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldPtype requires an ID field in the mutation") + return v, errors.New("OldPtype requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -178,10 +198,10 @@ func (m *CasbinRuleMutation) V0() (r string, exists bool) { // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CasbinRuleMutation) OldV0(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldV0 is only allowed on UpdateOne operations") + return v, errors.New("OldV0 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldV0 requires an ID field in the mutation") + return v, errors.New("OldV0 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -214,10 +234,10 @@ func (m *CasbinRuleMutation) V1() (r string, exists bool) { // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CasbinRuleMutation) OldV1(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldV1 is only allowed on UpdateOne operations") + return v, errors.New("OldV1 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldV1 requires an ID field in the mutation") + return v, errors.New("OldV1 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -250,10 +270,10 @@ func (m *CasbinRuleMutation) V2() (r string, exists bool) { // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CasbinRuleMutation) OldV2(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldV2 is only allowed on UpdateOne operations") + return v, errors.New("OldV2 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldV2 requires an ID field in the mutation") + return v, errors.New("OldV2 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -286,10 +306,10 @@ func (m *CasbinRuleMutation) V3() (r string, exists bool) { // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CasbinRuleMutation) OldV3(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldV3 is only allowed on UpdateOne operations") + return v, errors.New("OldV3 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldV3 requires an ID field in the mutation") + return v, errors.New("OldV3 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -322,10 +342,10 @@ func (m *CasbinRuleMutation) V4() (r string, exists bool) { // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CasbinRuleMutation) OldV4(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldV4 is only allowed on UpdateOne operations") + return v, errors.New("OldV4 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldV4 requires an ID field in the mutation") + return v, errors.New("OldV4 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -358,10 +378,10 @@ func (m *CasbinRuleMutation) V5() (r string, exists bool) { // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CasbinRuleMutation) OldV5(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldV5 is only allowed on UpdateOne operations") + return v, errors.New("OldV5 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldV5 requires an ID field in the mutation") + return v, errors.New("OldV5 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -375,11 +395,31 @@ func (m *CasbinRuleMutation) ResetV5() { m._V5 = nil } +// Where appends a list predicates to the CasbinRuleMutation builder. +func (m *CasbinRuleMutation) Where(ps ...predicate.CasbinRule) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CasbinRuleMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CasbinRuleMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.CasbinRule, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *CasbinRuleMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *CasbinRuleMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (CasbinRule). func (m *CasbinRuleMutation) Type() string { return m.typ diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index 0ef87b7..8890880 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package predicate diff --git a/ent/runtime.go b/ent/runtime.go index 3379890..a83b349 100644 --- a/ent/runtime.go +++ b/ent/runtime.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -11,34 +11,37 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + casbinruleMixin := schema.CasbinRule{}.Mixin() + casbinruleMixinFields0 := casbinruleMixin[0].Fields() + _ = casbinruleMixinFields0 casbinruleFields := schema.CasbinRule{}.Fields() _ = casbinruleFields // casbinruleDescPtype is the schema descriptor for Ptype field. - casbinruleDescPtype := casbinruleFields[0].Descriptor() + casbinruleDescPtype := casbinruleMixinFields0[0].Descriptor() // casbinrule.DefaultPtype holds the default value on creation for the Ptype field. casbinrule.DefaultPtype = casbinruleDescPtype.Default.(string) // casbinruleDescV0 is the schema descriptor for V0 field. - casbinruleDescV0 := casbinruleFields[1].Descriptor() + casbinruleDescV0 := casbinruleMixinFields0[1].Descriptor() // casbinrule.DefaultV0 holds the default value on creation for the V0 field. casbinrule.DefaultV0 = casbinruleDescV0.Default.(string) // casbinruleDescV1 is the schema descriptor for V1 field. - casbinruleDescV1 := casbinruleFields[2].Descriptor() + casbinruleDescV1 := casbinruleMixinFields0[2].Descriptor() // casbinrule.DefaultV1 holds the default value on creation for the V1 field. casbinrule.DefaultV1 = casbinruleDescV1.Default.(string) // casbinruleDescV2 is the schema descriptor for V2 field. - casbinruleDescV2 := casbinruleFields[3].Descriptor() + casbinruleDescV2 := casbinruleMixinFields0[3].Descriptor() // casbinrule.DefaultV2 holds the default value on creation for the V2 field. casbinrule.DefaultV2 = casbinruleDescV2.Default.(string) // casbinruleDescV3 is the schema descriptor for V3 field. - casbinruleDescV3 := casbinruleFields[4].Descriptor() + casbinruleDescV3 := casbinruleMixinFields0[4].Descriptor() // casbinrule.DefaultV3 holds the default value on creation for the V3 field. casbinrule.DefaultV3 = casbinruleDescV3.Default.(string) // casbinruleDescV4 is the schema descriptor for V4 field. - casbinruleDescV4 := casbinruleFields[5].Descriptor() + casbinruleDescV4 := casbinruleMixinFields0[5].Descriptor() // casbinrule.DefaultV4 holds the default value on creation for the V4 field. casbinrule.DefaultV4 = casbinruleDescV4.Default.(string) // casbinruleDescV5 is the schema descriptor for V5 field. - casbinruleDescV5 := casbinruleFields[6].Descriptor() + casbinruleDescV5 := casbinruleMixinFields0[6].Descriptor() // casbinrule.DefaultV5 holds the default value on creation for the V5 field. casbinrule.DefaultV5 = casbinruleDescV5.Default.(string) } diff --git a/ent/runtime/runtime.go b/ent/runtime/runtime.go index fe2794b..8f12166 100644 --- a/ent/runtime/runtime.go +++ b/ent/runtime/runtime.go @@ -1,10 +1,10 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package runtime // The schema-stitching logic is generated in github.com/casbin/ent-adapter/ent/runtime.go const ( - Version = "v0.8.0" // Version of ent codegen. - Sum = "h1:xirrW//1oda7pp0bz+XssSOv4/C3nmgYQOxjIfljFt8=" // Sum of ent codegen. + Version = "v0.14.0" // Version of ent codegen. + Sum = "h1:EO3Z9aZ5bXJatJeGqu/EVdnNr6K4mRq3rWe5owt0MC4=" // Sum of ent codegen. ) diff --git a/ent/schema/casbinrule.go b/ent/schema/casbinrule.go index 4c87380..bfb047b 100644 --- a/ent/schema/casbinrule.go +++ b/ent/schema/casbinrule.go @@ -2,8 +2,7 @@ package schema import ( "entgo.io/ent" - "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" + "github.com/casbin/ent-adapter/template" ) // CasbinRule holds the schema definition for the CasbinRule entity. @@ -11,26 +10,8 @@ type CasbinRule struct { ent.Schema } -// Fields of the CasbinRule. -func (CasbinRule) Fields() []ent.Field { - return []ent.Field{ - field.String("Ptype").Default(""), - field.String("V0").Default(""), - field.String("V1").Default(""), - field.String("V2").Default(""), - field.String("V3").Default(""), - field.String("V4").Default(""), - field.String("V5").Default(""), - } -} - -// Edges of the CasbinRule. -func (CasbinRule) Edges() []ent.Edge { - return nil -} - -func (CasbinRule) Index() []ent.Index { - return []ent.Index{ - index.Fields("Ptype", "V0", "V1", "V2", "V3", "V4", "V5").Unique(), +func (CasbinRule) Mixin() []ent.Mixin { + return []ent.Mixin{ + template.CasbinRuleMixin{}, } } diff --git a/ent/tx.go b/ent/tx.go index 8357541..70f051f 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -18,19 +18,13 @@ type Tx struct { // lazily loaded. client *Client clientOnce sync.Once - - // completion callbacks. - mu sync.Mutex - onCommit []CommitHook - onRollback []RollbackHook - // ctx lives for the life of the transaction. It is // the same context used by the underlying connection. ctx context.Context } type ( - // Committer is the interface that wraps the Committer method. + // Committer is the interface that wraps the Commit method. Committer interface { Commit(context.Context, *Tx) error } @@ -44,7 +38,7 @@ type ( // and returns a Committer. For example: // // hook := func(next ent.Committer) ent.Committer { - // return ent.CommitFunc(func(context.Context, tx *ent.Tx) error { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { // // Do some stuff before. // if err := next.Commit(ctx, tx); err != nil { // return err @@ -68,9 +62,9 @@ func (tx *Tx) Commit() error { var fn Committer = CommitFunc(func(context.Context, *Tx) error { return txDriver.tx.Commit() }) - tx.mu.Lock() - hooks := append([]CommitHook(nil), tx.onCommit...) - tx.mu.Unlock() + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() for i := len(hooks) - 1; i >= 0; i-- { fn = hooks[i](fn) } @@ -79,13 +73,14 @@ func (tx *Tx) Commit() error { // OnCommit adds a hook to call on commit. func (tx *Tx) OnCommit(f CommitHook) { - tx.mu.Lock() - defer tx.mu.Unlock() - tx.onCommit = append(tx.onCommit, f) + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() } type ( - // Rollbacker is the interface that wraps the Rollbacker method. + // Rollbacker is the interface that wraps the Rollback method. Rollbacker interface { Rollback(context.Context, *Tx) error } @@ -99,7 +94,7 @@ type ( // and returns a Rollbacker. For example: // // hook := func(next ent.Rollbacker) ent.Rollbacker { - // return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { // // Do some stuff before. // if err := next.Rollback(ctx, tx); err != nil { // return err @@ -123,9 +118,9 @@ func (tx *Tx) Rollback() error { var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { return txDriver.tx.Rollback() }) - tx.mu.Lock() - hooks := append([]RollbackHook(nil), tx.onRollback...) - tx.mu.Unlock() + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() for i := len(hooks) - 1; i >= 0; i-- { fn = hooks[i](fn) } @@ -134,9 +129,10 @@ func (tx *Tx) Rollback() error { // OnRollback adds a hook to call on rollback. func (tx *Tx) OnRollback(f RollbackHook) { - tx.mu.Lock() - defer tx.mu.Unlock() - tx.onRollback = append(tx.onRollback, f) + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() } // Client returns a Client that binds to current transaction. @@ -168,6 +164,10 @@ type txDriver struct { drv dialect.Driver // tx is the underlying transaction. tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook } // newTx creates a new transactional driver. @@ -198,12 +198,12 @@ func (*txDriver) Commit() error { return nil } func (*txDriver) Rollback() error { return nil } // Exec calls tx.Exec. -func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error { +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { return tx.tx.Exec(ctx, query, args, v) } // Query calls tx.Query. -func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error { +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { return tx.tx.Query(ctx, query, args, v) } diff --git a/go.mod b/go.mod index 7373e31..d96127f 100644 --- a/go.mod +++ b/go.mod @@ -1,29 +1,40 @@ module github.com/casbin/ent-adapter -go 1.20 +go 1.21 + +toolchain go1.21.12 require ( - entgo.io/ent v0.8.0 + entgo.io/ent v0.14.0 github.com/casbin/casbin/v2 v2.29.2 github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae github.com/jackc/pgx/v5 v5.6.0 github.com/lib/pq v1.10.2 - //github.com/mattn/go-sqlite3 v1.14.6 github.com/pkg/errors v0.9.1 - github.com/stretchr/testify v1.8.1 + github.com/stretchr/testify v1.8.2 ) require ( + ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 // indirect github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect + github.com/agext/levenshtein v1.2.1 // indirect + github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/google/uuid v1.2.0 // indirect + github.com/go-openapi/inflect v0.19.0 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/hashicorp/hcl/v2 v2.13.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect + github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect + github.com/zclconf/go-cty v1.8.0 // indirect golang.org/x/crypto v0.17.0 // indirect - golang.org/x/sync v0.1.0 // indirect + golang.org/x/mod v0.15.0 // indirect + golang.org/x/sync v0.6.0 // indirect golang.org/x/text v0.14.0 // indirect + golang.org/x/tools v0.18.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 299ee85..f9a2763 100644 --- a/go.sum +++ b/go.sum @@ -1,131 +1,37 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -entgo.io/ent v0.8.0 h1:xirrW//1oda7pp0bz+XssSOv4/C3nmgYQOxjIfljFt8= -entgo.io/ent v0.8.0/go.mod h1:KNjsukat/NJi6zJh1utwRadsbGOZsBbAZNDxkW7tMCc= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 h1:GwdJbXydHCYPedeeLt4x/lrlIISQ4JTH1mRWuE5ZZ14= +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43/go.mod h1:uj3pm+hUTVN/X5yfdBexHlZv+1Xu5u5ZbZx7+CDavNU= +entgo.io/ent v0.14.0 h1:EO3Z9aZ5bXJatJeGqu/EVdnNr6K4mRq3rWe5owt0MC4= +entgo.io/ent v0.14.0/go.mod h1:qCEmo+biw3ccBn9OyL4ZK5dfpwg++l1Gxwac5B1206A= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= +github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= +github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= +github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/casbin/casbin/v2 v2.29.2 h1:a1lsr3ZFh9IQ+7L8L36ddyTebofxH/XoHmRh6iI7Rtg= github.com/casbin/casbin/v2 v2.29.2/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= -github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-bindata/go-bindata v1.0.1-0.20190711162640-ee3c2418e368/go.mod h1:7xCgX1lzlrXPHkfvn3EhumqHkmSlzt8at9q7v0ax19c= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae h1:L6V0ANsMIMdLgXly241UXhXNFWYgXbgjHupTAAURrV0= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= +github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= 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/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= -github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= -github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= -github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= -github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= +github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= 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-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= @@ -134,268 +40,68 @@ github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY= github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw= github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= -github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/lib/pq v1.10.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8= github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= -github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= +github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= -github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= -go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= +github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= +github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA= +github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 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/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ= +golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= 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-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/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= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/template/casbin.tmpl b/template/casbin.tmpl new file mode 100644 index 0000000..0bcad82 --- /dev/null +++ b/template/casbin.tmpl @@ -0,0 +1,514 @@ +{{ /* Tell Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */ }} +{{ /* gotype: entgo.io/ent/entc/gen.Graph */ }} + +{{ define "casbin" }} + +{{ /* Add the base header for the generated file */ }} +{{ $pkg := base $.Config.Package }} +{{ template "header" $ }} + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "strings" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/casbin/casbin/v2/persist" + "{{ $.Config.Package }}/casbinrule" + "{{ $.Config.Package }}/predicate" + + "github.com/casbin/casbin/v2/model" + _ "github.com/go-sql-driver/mysql" + _ "github.com/jackc/pgx/v5/stdlib" + _ "github.com/lib/pq" + + "github.com/pkg/errors" +) + +const ( + DefaultTableName = "casbin_rule" + DefaultDatabase = "casbin" +) + +type Adapter struct { + client *Client + ctx context.Context + + filtered bool +} + +type Filter struct { + Ptype []string + V0 []string + V1 []string + V2 []string + V3 []string + V4 []string + V5 []string +} + +func open(driverName, dataSourceName string) (*Client, error) { + db, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + var drv dialect.Driver + if driverName == "pgx" { + drv = entsql.OpenDB(dialect.Postgres, db) + } else { + drv = entsql.OpenDB(driverName, db) + } + return NewClient(Driver(drv)), nil +} + +// NewAdapter returns an adapter by driver name and data source string. +func NewAdapter(driverName, dataSourceName string) (*Adapter, error) { + client, err := open(driverName, dataSourceName) + if err != nil { + return nil, err + } + a := &Adapter{ + client: client, + ctx: context.Background(), + } + if err := client.Schema.Create(a.ctx); err != nil { + return nil, err + } + return a, nil +} + +// NewAdapterWithClient create an adapter with client passed in. +// This method does not ensure the existence of database, user should create database manually. +func NewAdapterWithClient(client *Client) (*Adapter, error) { + a := &Adapter{ + client: client, + ctx: context.Background(), + } + if err := client.Schema.Create(a.ctx); err != nil { + return nil, err + } + return a, nil +} + +// LoadPolicy loads all policy rules from the storage. +func (a *Adapter) LoadPolicy(model model.Model) error { + policies, err := a.client.CasbinRule.Query().Order(Asc("id")).All(a.ctx) + if err != nil { + return err + } + for _, policy := range policies { + loadPolicyLine(policy, model) + } + return nil +} + +// LoadFilteredPolicy loads only policy rules that match the filter. +// Filter parameter here is a Filter structure +func (a *Adapter) LoadFilteredPolicy(model model.Model, filter interface{}) error { + + filterValue, ok := filter.(Filter) + if !ok { + return fmt.Errorf("invalid filter type: %v", reflect.TypeOf(filter)) + } + + session := a.client.CasbinRule.Query() + if len(filterValue.Ptype) != 0 { + session.Where(casbinrule.PtypeIn(filterValue.Ptype...)) + } + if len(filterValue.V0) != 0 { + session.Where(casbinrule.V0In(filterValue.V0...)) + } + if len(filterValue.V1) != 0 { + session.Where(casbinrule.V1In(filterValue.V1...)) + } + if len(filterValue.V2) != 0 { + session.Where(casbinrule.V2In(filterValue.V2...)) + } + if len(filterValue.V3) != 0 { + session.Where(casbinrule.V3In(filterValue.V3...)) + } + if len(filterValue.V4) != 0 { + session.Where(casbinrule.V4In(filterValue.V4...)) + } + if len(filterValue.V5) != 0 { + session.Where(casbinrule.V5In(filterValue.V5...)) + } + + lines, err := session.All(a.ctx) + if err != nil { + return err + } + + for _, line := range lines { + loadPolicyLine(line, model) + } + a.filtered = true + + return nil +} + +// IsFiltered returns true if the loaded policy has been filtered. +func (a *Adapter) IsFiltered() bool { + return a.filtered +} + +// SavePolicy saves all policy rules to the storage. +func (a *Adapter) SavePolicy(model model.Model) error { + return a.WithTx(func(tx *Tx) error { + if _, err := tx.CasbinRule.Delete().Exec(a.ctx); err != nil { + return err + } + lines := make([]*CasbinRuleCreate, 0) + + for ptype, ast := range model["p"] { + for _, policy := range ast.Policy { + line := a.savePolicyLine(tx, ptype, policy) + lines = append(lines, line) + } + } + + for ptype, ast := range model["g"] { + for _, policy := range ast.Policy { + line := a.savePolicyLine(tx, ptype, policy) + lines = append(lines, line) + } + } + + _, err := tx.CasbinRule.CreateBulk(lines...).Save(a.ctx) + return err + }) +} + +// AddPolicy adds a policy rule to the storage. +// This is part of the Auto-Save feature. +func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error { + return a.WithTx(func(tx *Tx) error { + _, err := a.savePolicyLine(tx, ptype, rule).Save(a.ctx) + return err + }) +} + +// RemovePolicy removes a policy rule from the storage. +// This is part of the Auto-Save feature. +func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { + return a.WithTx(func(tx *Tx) error { + instance := a.toInstance(ptype, rule) + _, err := tx.CasbinRule.Delete().Where( + casbinrule.PtypeEQ(instance.Ptype), + casbinrule.V0EQ(instance.V0), + casbinrule.V1EQ(instance.V1), + casbinrule.V2EQ(instance.V2), + casbinrule.V3EQ(instance.V3), + casbinrule.V4EQ(instance.V4), + casbinrule.V5EQ(instance.V5), + ).Exec(a.ctx) + return err + }) +} + +// RemoveFilteredPolicy removes policy rules that match the filter from the storage. +// This is part of the Auto-Save feature. +func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { + return a.WithTx(func(tx *Tx) error { + cond := make([]predicate.CasbinRule, 0) + cond = append(cond, casbinrule.PtypeEQ(ptype)) + if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) && len(fieldValues[0-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V0EQ(fieldValues[0-fieldIndex])) + } + if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) && len(fieldValues[1-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V1EQ(fieldValues[1-fieldIndex])) + } + if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) && len(fieldValues[2-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V2EQ(fieldValues[2-fieldIndex])) + } + if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) && len(fieldValues[3-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V3EQ(fieldValues[3-fieldIndex])) + } + if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) && len(fieldValues[4-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V4EQ(fieldValues[4-fieldIndex])) + } + if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) && len(fieldValues[5-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V5EQ(fieldValues[5-fieldIndex])) + } + _, err := tx.CasbinRule.Delete().Where( + cond..., + ).Exec(a.ctx) + return err + }) +} + +// AddPolicies adds policy rules to the storage. +// This is part of the Auto-Save feature. +func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error { + return a.WithTx(func(tx *Tx) error { + return a.createPolicies(tx, ptype, rules) + }) +} + +// RemovePolicies removes policy rules from the storage. +// This is part of the Auto-Save feature. +func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) error { + return a.WithTx(func(tx *Tx) error { + for _, rule := range rules { + instance := a.toInstance(ptype, rule) + if _, err := tx.CasbinRule.Delete().Where( + casbinrule.PtypeEQ(instance.Ptype), + casbinrule.V0EQ(instance.V0), + casbinrule.V1EQ(instance.V1), + casbinrule.V2EQ(instance.V2), + casbinrule.V3EQ(instance.V3), + casbinrule.V4EQ(instance.V4), + casbinrule.V5EQ(instance.V5), + ).Exec(a.ctx); err != nil { + return err + } + } + return nil + }) +} + +func (a *Adapter) WithTx(fn func(tx *Tx) error) error { + tx, err := a.client.Tx(a.ctx) + if err != nil { + return err + } + defer func() { + if v := recover(); v != nil { + _ = tx.Rollback() + panic(v) + } + }() + if err := fn(tx); err != nil { + if rerr := tx.Rollback(); rerr != nil { + err = errors.Wrapf(err, "rolling back transaction: %v", rerr) + } + return err + } + if err := tx.Commit(); err != nil { + return errors.Wrapf(err, "committing transaction: %v", err) + } + return nil +} + +func loadPolicyLine(line *CasbinRule, model model.Model) { + var p = []string{line.Ptype, + line.V0, line.V1, line.V2, line.V3, line.V4, line.V5} + + var lineText string + if line.V5 != "" { + lineText = strings.Join(p, ", ") + } else if line.V4 != "" { + lineText = strings.Join(p[:6], ", ") + } else if line.V3 != "" { + lineText = strings.Join(p[:5], ", ") + } else if line.V2 != "" { + lineText = strings.Join(p[:4], ", ") + } else if line.V1 != "" { + lineText = strings.Join(p[:3], ", ") + } else if line.V0 != "" { + lineText = strings.Join(p[:2], ", ") + } + + persist.LoadPolicyLine(lineText, model) +} + +func (a *Adapter) toInstance(ptype string, rule []string) *CasbinRule { + instance := &CasbinRule{} + + instance.Ptype = ptype + + if len(rule) > 0 { + instance.V0 = rule[0] + } + if len(rule) > 1 { + instance.V1 = rule[1] + } + if len(rule) > 2 { + instance.V2 = rule[2] + } + if len(rule) > 3 { + instance.V3 = rule[3] + } + if len(rule) > 4 { + instance.V4 = rule[4] + } + if len(rule) > 5 { + instance.V5 = rule[5] + } + return instance +} + +func (a *Adapter) savePolicyLine(tx *Tx, ptype string, rule []string) *CasbinRuleCreate { + line := tx.CasbinRule.Create() + + line.SetPtype(ptype) + if len(rule) > 0 { + line.SetV0(rule[0]) + } + if len(rule) > 1 { + line.SetV1(rule[1]) + } + if len(rule) > 2 { + line.SetV2(rule[2]) + } + if len(rule) > 3 { + line.SetV3(rule[3]) + } + if len(rule) > 4 { + line.SetV4(rule[4]) + } + if len(rule) > 5 { + line.SetV5(rule[5]) + } + + return line +} + +// UpdatePolicy updates a policy rule from storage. +// This is part of the Auto-Save feature. +func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error { + return a.WithTx(func(tx *Tx) error { + rule := a.toInstance(ptype, oldRule) + line := tx.CasbinRule.Update().Where( + casbinrule.PtypeEQ(rule.Ptype), + casbinrule.V0EQ(rule.V0), + casbinrule.V1EQ(rule.V1), + casbinrule.V2EQ(rule.V2), + casbinrule.V3EQ(rule.V3), + casbinrule.V4EQ(rule.V4), + casbinrule.V5EQ(rule.V5), + ) + rule = a.toInstance(ptype, newPolicy) + line.SetV0(rule.V0) + line.SetV1(rule.V1) + line.SetV2(rule.V2) + line.SetV3(rule.V3) + line.SetV4(rule.V4) + line.SetV5(rule.V5) + _, err := line.Save(a.ctx) + return err + }) +} + +// UpdatePolicies updates some policy rules to storage, like db, redis. +func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error { + return a.WithTx(func(tx *Tx) error { + for _, policy := range oldRules { + rule := a.toInstance(ptype, policy) + if _, err := tx.CasbinRule.Delete().Where( + casbinrule.PtypeEQ(rule.Ptype), + casbinrule.V0EQ(rule.V0), + casbinrule.V1EQ(rule.V1), + casbinrule.V2EQ(rule.V2), + casbinrule.V3EQ(rule.V3), + casbinrule.V4EQ(rule.V4), + casbinrule.V5EQ(rule.V5), + ).Exec(a.ctx); err != nil { + return err + } + } + lines := make([]*CasbinRuleCreate, 0) + for _, policy := range newRules { + lines = append(lines, a.savePolicyLine(tx, ptype, policy)) + } + if _, err := tx.CasbinRule.CreateBulk(lines...).Save(a.ctx); err != nil { + return err + } + return nil + }) +} + +// UpdateFilteredPolicies deletes old rules and adds new rules. +func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) { + oldPolicies := make([][]string, 0) + err := a.WithTx(func(tx *Tx) error { + cond := make([]predicate.CasbinRule, 0) + cond = append(cond, casbinrule.PtypeEQ(ptype)) + if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) && len(fieldValues[0-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V0EQ(fieldValues[0-fieldIndex])) + } + if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) && len(fieldValues[1-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V1EQ(fieldValues[1-fieldIndex])) + } + if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) && len(fieldValues[2-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V2EQ(fieldValues[2-fieldIndex])) + } + if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) && len(fieldValues[3-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V3EQ(fieldValues[3-fieldIndex])) + } + if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) && len(fieldValues[4-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V4EQ(fieldValues[4-fieldIndex])) + } + if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) && len(fieldValues[5-fieldIndex]) > 0 { + cond = append(cond, casbinrule.V5EQ(fieldValues[5-fieldIndex])) + } + rules, err := tx.CasbinRule.Query(). + Where(cond...). + All(a.ctx) + if err != nil { + return err + } + ruleIDs := make([]int, 0, len(rules)) + for _, r := range rules { + ruleIDs = append(ruleIDs, r.ID) + } + + _, err = tx.CasbinRule.Delete(). + Where(casbinrule.IDIn(ruleIDs...)). + Exec(a.ctx) + if err != nil { + return err + } + + if err := a.createPolicies(tx, ptype, newPolicies); err != nil { + return err + } + for _, rule := range rules { + oldPolicies = append(oldPolicies, CasbinRuleToStringArray(rule)) + } + return nil + }) + if err != nil { + return nil, err + } + return oldPolicies, nil +} + +func (a *Adapter) createPolicies(tx *Tx, ptype string, policies [][]string) error { + lines := make([]*CasbinRuleCreate, 0) + for _, policy := range policies { + lines = append(lines, a.savePolicyLine(tx, ptype, policy)) + } + if _, err := tx.CasbinRule.CreateBulk(lines...).Save(a.ctx); err != nil { + return err + } + return nil +} + +func CasbinRuleToStringArray(rule *CasbinRule) []string { + arr := make([]string, 0) + if rule.V0 != "" { + arr = append(arr, rule.V0) + } + if rule.V1 != "" { + arr = append(arr, rule.V1) + } + if rule.V2 != "" { + arr = append(arr, rule.V2) + } + if rule.V3 != "" { + arr = append(arr, rule.V3) + } + if rule.V4 != "" { + arr = append(arr, rule.V4) + } + if rule.V5 != "" { + arr = append(arr, rule.V5) + } + return arr +} + +{{ end }} diff --git a/template/extension.go b/template/extension.go new file mode 100644 index 0000000..7aa2539 --- /dev/null +++ b/template/extension.go @@ -0,0 +1,16 @@ +package template + +import ( + "entgo.io/ent/entc" + "entgo.io/ent/entc/gen" +) + +type CasbinExtension struct { + entc.DefaultExtension +} + +func (*CasbinExtension) Templates() []*gen.Template { + return []*gen.Template{ + gen.MustParse(gen.NewTemplate("casbin").ParseFiles("../template/casbin.tmpl")), + } +} diff --git a/template/mixin.go b/template/mixin.go new file mode 100644 index 0000000..c8e43ca --- /dev/null +++ b/template/mixin.go @@ -0,0 +1,30 @@ +package template + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "entgo.io/ent/schema/mixin" +) + +type CasbinRuleMixin struct { + mixin.Schema +} + +func (CasbinRuleMixin) Fields() []ent.Field { + return []ent.Field{ + field.String("Ptype").Default(""), + field.String("V0").Default(""), + field.String("V1").Default(""), + field.String("V2").Default(""), + field.String("V3").Default(""), + field.String("V4").Default(""), + field.String("V5").Default(""), + } +} + +func (CasbinRuleMixin) Index() []ent.Index { + return []ent.Index{ + index.Fields("Ptype", "V0", "V1", "V2", "V3", "V4", "V5").Unique(), + } +} From 29c1c27ea3944ea06956a732abdc838f93e36afb Mon Sep 17 00:00:00 2001 From: MuZhou233 Date: Tue, 30 Jul 2024 17:14:04 +0100 Subject: [PATCH 2/5] feat: update go to 1.21 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9564b77..f47c72b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.20' + go-version: '1.21' - uses: actions/checkout@v2 - name: Run Unit tests From dd6b91a1f825be89356410f7419636fa0364a36b Mon Sep 17 00:00:00 2001 From: MuZhou233 Date: Mon, 19 Aug 2024 09:01:08 +0100 Subject: [PATCH 3/5] refactor: move files --- adapter_test.go | 2 +- template/casbin.tmpl => casbin.tmpl | 6 ++-- {ent => examples/ent}/casbin.go | 4 +-- {ent => examples/ent}/casbinrule.go | 2 +- .../ent}/casbinrule/casbinrule.go | 0 {ent => examples/ent}/casbinrule/where.go | 2 +- {ent => examples/ent}/casbinrule_create.go | 2 +- {ent => examples/ent}/casbinrule_delete.go | 4 +-- {ent => examples/ent}/casbinrule_query.go | 4 +-- {ent => examples/ent}/casbinrule_update.go | 4 +-- {ent => examples/ent}/client.go | 4 +-- {ent => examples/ent}/ent.go | 2 +- {ent => examples/ent}/enttest/enttest.go | 6 ++-- examples/ent/generate.go | 3 ++ {ent => examples/ent}/hook/hook.go | 2 +- ent/generate.go => examples/ent/main.go | 4 +-- {ent => examples/ent}/migrate/migrate.go | 0 {ent => examples/ent}/migrate/schema.go | 0 {ent => examples/ent}/mutation.go | 4 +-- {ent => examples/ent}/predicate/predicate.go | 0 {ent => examples/ent}/runtime.go | 4 +-- {ent => examples/ent}/runtime/runtime.go | 2 +- {ent => examples/ent}/schema/casbinrule.go | 4 +-- {ent => examples/ent}/tx.go | 0 extension.go | 29 +++++++++++++++++++ template/mixin.go => mixin.go | 2 +- template/extension.go | 16 ---------- 27 files changed, 64 insertions(+), 48 deletions(-) rename template/casbin.tmpl => casbin.tmpl (98%) rename {ent => examples/ent}/casbin.go (99%) rename {ent => examples/ent}/casbinrule.go (98%) rename {ent => examples/ent}/casbinrule/casbinrule.go (100%) rename {ent => examples/ent}/casbinrule/where.go (99%) rename {ent => examples/ent}/casbinrule_create.go (99%) rename {ent => examples/ent}/casbinrule_delete.go (95%) rename {ent => examples/ent}/casbinrule_query.go (99%) rename {ent => examples/ent}/casbinrule_update.go (99%) rename {ent => examples/ent}/client.go (98%) rename {ent => examples/ent}/ent.go (99%) rename {ent => examples/ent}/enttest/enttest.go (91%) create mode 100644 examples/ent/generate.go rename {ent => examples/ent}/hook/hook.go (99%) rename ent/generate.go => examples/ent/main.go (73%) rename {ent => examples/ent}/migrate/migrate.go (100%) rename {ent => examples/ent}/migrate/schema.go (100%) rename {ent => examples/ent}/mutation.go (99%) rename {ent => examples/ent}/predicate/predicate.go (100%) rename {ent => examples/ent}/runtime.go (95%) rename {ent => examples/ent}/runtime/runtime.go (89%) rename {ent => examples/ent}/schema/casbinrule.go (75%) rename {ent => examples/ent}/tx.go (100%) create mode 100644 extension.go rename template/mixin.go => mixin.go (97%) delete mode 100644 template/extension.go diff --git a/adapter_test.go b/adapter_test.go index 31dd3a7..febed18 100644 --- a/adapter_test.go +++ b/adapter_test.go @@ -20,7 +20,7 @@ import ( "github.com/casbin/casbin/v2" "github.com/casbin/casbin/v2/util" - "github.com/casbin/ent-adapter/ent" + "github.com/casbin/ent-adapter/examples/ent" "github.com/stretchr/testify/assert" ) diff --git a/template/casbin.tmpl b/casbin.tmpl similarity index 98% rename from template/casbin.tmpl rename to casbin.tmpl index 0bcad82..e3e148e 100644 --- a/template/casbin.tmpl +++ b/casbin.tmpl @@ -1,9 +1,9 @@ -{{ /* Tell Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */ }} -{{ /* gotype: entgo.io/ent/entc/gen.Graph */ }} +{{/* Tell Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}} +{{/* gotype: entgo.io/ent/entc/gen.Graph */}} {{ define "casbin" }} -{{ /* Add the base header for the generated file */ }} +{{/* Add the base header for the generated file */}} {{ $pkg := base $.Config.Package }} {{ template "header" $ }} diff --git a/ent/casbin.go b/examples/ent/casbin.go similarity index 99% rename from ent/casbin.go rename to examples/ent/casbin.go index 6d2d265..6ec6940 100644 --- a/ent/casbin.go +++ b/examples/ent/casbin.go @@ -12,8 +12,8 @@ import ( "entgo.io/ent/dialect" entsql "entgo.io/ent/dialect/sql" "github.com/casbin/casbin/v2/persist" - "github.com/casbin/ent-adapter/ent/casbinrule" - "github.com/casbin/ent-adapter/ent/predicate" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/predicate" "github.com/casbin/casbin/v2/model" _ "github.com/go-sql-driver/mysql" diff --git a/ent/casbinrule.go b/examples/ent/casbinrule.go similarity index 98% rename from ent/casbinrule.go rename to examples/ent/casbinrule.go index d029267..73e6de1 100644 --- a/ent/casbinrule.go +++ b/examples/ent/casbinrule.go @@ -8,7 +8,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" - "github.com/casbin/ent-adapter/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" ) // CasbinRule is the model entity for the CasbinRule schema. diff --git a/ent/casbinrule/casbinrule.go b/examples/ent/casbinrule/casbinrule.go similarity index 100% rename from ent/casbinrule/casbinrule.go rename to examples/ent/casbinrule/casbinrule.go diff --git a/ent/casbinrule/where.go b/examples/ent/casbinrule/where.go similarity index 99% rename from ent/casbinrule/where.go rename to examples/ent/casbinrule/where.go index c779990..ce46588 100644 --- a/ent/casbinrule/where.go +++ b/examples/ent/casbinrule/where.go @@ -4,7 +4,7 @@ package casbinrule import ( "entgo.io/ent/dialect/sql" - "github.com/casbin/ent-adapter/ent/predicate" + "github.com/casbin/ent-adapter/examples/ent/predicate" ) // ID filters vertices based on their ID field. diff --git a/ent/casbinrule_create.go b/examples/ent/casbinrule_create.go similarity index 99% rename from ent/casbinrule_create.go rename to examples/ent/casbinrule_create.go index 64b8d93..4916bf9 100644 --- a/ent/casbinrule_create.go +++ b/examples/ent/casbinrule_create.go @@ -9,7 +9,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/casbin/ent-adapter/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" ) // CasbinRuleCreate is the builder for creating a CasbinRule entity. diff --git a/ent/casbinrule_delete.go b/examples/ent/casbinrule_delete.go similarity index 95% rename from ent/casbinrule_delete.go rename to examples/ent/casbinrule_delete.go index b29b722..c7cd1b4 100644 --- a/ent/casbinrule_delete.go +++ b/examples/ent/casbinrule_delete.go @@ -8,8 +8,8 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/casbin/ent-adapter/ent/casbinrule" - "github.com/casbin/ent-adapter/ent/predicate" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/predicate" ) // CasbinRuleDelete is the builder for deleting a CasbinRule entity. diff --git a/ent/casbinrule_query.go b/examples/ent/casbinrule_query.go similarity index 99% rename from ent/casbinrule_query.go rename to examples/ent/casbinrule_query.go index 21eeac8..e8d537b 100644 --- a/ent/casbinrule_query.go +++ b/examples/ent/casbinrule_query.go @@ -11,8 +11,8 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/casbin/ent-adapter/ent/casbinrule" - "github.com/casbin/ent-adapter/ent/predicate" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/predicate" ) // CasbinRuleQuery is the builder for querying CasbinRule entities. diff --git a/ent/casbinrule_update.go b/examples/ent/casbinrule_update.go similarity index 99% rename from ent/casbinrule_update.go rename to examples/ent/casbinrule_update.go index d462041..5984ad4 100644 --- a/ent/casbinrule_update.go +++ b/examples/ent/casbinrule_update.go @@ -10,8 +10,8 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/casbin/ent-adapter/ent/casbinrule" - "github.com/casbin/ent-adapter/ent/predicate" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/predicate" ) // CasbinRuleUpdate is the builder for updating CasbinRule entities. diff --git a/ent/client.go b/examples/ent/client.go similarity index 98% rename from ent/client.go rename to examples/ent/client.go index ee8d988..a4562de 100644 --- a/ent/client.go +++ b/examples/ent/client.go @@ -9,12 +9,12 @@ import ( "log" "reflect" - "github.com/casbin/ent-adapter/ent/migrate" + "github.com/casbin/ent-adapter/examples/ent/migrate" "entgo.io/ent" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" - "github.com/casbin/ent-adapter/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" ) // Client is the client that holds all ent builders. diff --git a/ent/ent.go b/examples/ent/ent.go similarity index 99% rename from ent/ent.go rename to examples/ent/ent.go index c648965..bb2de88 100644 --- a/ent/ent.go +++ b/examples/ent/ent.go @@ -12,7 +12,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" - "github.com/casbin/ent-adapter/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" ) // ent aliases to avoid import conflicts in user's code. diff --git a/ent/enttest/enttest.go b/examples/ent/enttest/enttest.go similarity index 91% rename from ent/enttest/enttest.go rename to examples/ent/enttest/enttest.go index a56c14d..b19f9e8 100644 --- a/ent/enttest/enttest.go +++ b/examples/ent/enttest/enttest.go @@ -5,12 +5,12 @@ package enttest import ( "context" - "github.com/casbin/ent-adapter/ent" + "github.com/casbin/ent-adapter/examples/ent" // required by schema hooks. - _ "github.com/casbin/ent-adapter/ent/runtime" + _ "github.com/casbin/ent-adapter/examples/ent/runtime" "entgo.io/ent/dialect/sql/schema" - "github.com/casbin/ent-adapter/ent/migrate" + "github.com/casbin/ent-adapter/examples/ent/migrate" ) type ( diff --git a/examples/ent/generate.go b/examples/ent/generate.go new file mode 100644 index 0000000..b0695b9 --- /dev/null +++ b/examples/ent/generate.go @@ -0,0 +1,3 @@ +//go:generate go run main.go + +package ent diff --git a/ent/hook/hook.go b/examples/ent/hook/hook.go similarity index 99% rename from ent/hook/hook.go rename to examples/ent/hook/hook.go index 11a5ead..a83ad68 100644 --- a/ent/hook/hook.go +++ b/examples/ent/hook/hook.go @@ -6,7 +6,7 @@ import ( "context" "fmt" - "github.com/casbin/ent-adapter/ent" + "github.com/casbin/ent-adapter/examples/ent" ) // The CasbinRuleFunc type is an adapter to allow the use of ordinary diff --git a/ent/generate.go b/examples/ent/main.go similarity index 73% rename from ent/generate.go rename to examples/ent/main.go index cb0bed9..bf26a4c 100644 --- a/ent/generate.go +++ b/examples/ent/main.go @@ -8,13 +8,13 @@ import ( "entgo.io/ent/entc" "entgo.io/ent/entc/gen" - "github.com/casbin/ent-adapter/template" + "github.com/casbin/ent-adapter" ) func main() { err := entc.Generate("./schema", &gen.Config{}, - entc.Extensions(&template.CasbinExtension{}), + entc.Extensions(&entadapter.CasbinExtension{}), ) if err != nil { log.Fatal("running ent codegen:", err) diff --git a/ent/migrate/migrate.go b/examples/ent/migrate/migrate.go similarity index 100% rename from ent/migrate/migrate.go rename to examples/ent/migrate/migrate.go diff --git a/ent/migrate/schema.go b/examples/ent/migrate/schema.go similarity index 100% rename from ent/migrate/schema.go rename to examples/ent/migrate/schema.go diff --git a/ent/mutation.go b/examples/ent/mutation.go similarity index 99% rename from ent/mutation.go rename to examples/ent/mutation.go index e016001..6e05312 100644 --- a/ent/mutation.go +++ b/examples/ent/mutation.go @@ -10,8 +10,8 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" - "github.com/casbin/ent-adapter/ent/casbinrule" - "github.com/casbin/ent-adapter/ent/predicate" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/predicate" ) const ( diff --git a/ent/predicate/predicate.go b/examples/ent/predicate/predicate.go similarity index 100% rename from ent/predicate/predicate.go rename to examples/ent/predicate/predicate.go diff --git a/ent/runtime.go b/examples/ent/runtime.go similarity index 95% rename from ent/runtime.go rename to examples/ent/runtime.go index a83b349..d07a211 100644 --- a/ent/runtime.go +++ b/examples/ent/runtime.go @@ -3,8 +3,8 @@ package ent import ( - "github.com/casbin/ent-adapter/ent/casbinrule" - "github.com/casbin/ent-adapter/ent/schema" + "github.com/casbin/ent-adapter/examples/ent/casbinrule" + "github.com/casbin/ent-adapter/examples/ent/schema" ) // The init function reads all schema descriptors with runtime code diff --git a/ent/runtime/runtime.go b/examples/ent/runtime/runtime.go similarity index 89% rename from ent/runtime/runtime.go rename to examples/ent/runtime/runtime.go index 8f12166..2ba277f 100644 --- a/ent/runtime/runtime.go +++ b/examples/ent/runtime/runtime.go @@ -2,7 +2,7 @@ package runtime -// The schema-stitching logic is generated in github.com/casbin/ent-adapter/ent/runtime.go +// The schema-stitching logic is generated in github.com/casbin/ent-adapter/examples/ent/runtime.go const ( Version = "v0.14.0" // Version of ent codegen. diff --git a/ent/schema/casbinrule.go b/examples/ent/schema/casbinrule.go similarity index 75% rename from ent/schema/casbinrule.go rename to examples/ent/schema/casbinrule.go index bfb047b..0aa265e 100644 --- a/ent/schema/casbinrule.go +++ b/examples/ent/schema/casbinrule.go @@ -2,7 +2,7 @@ package schema import ( "entgo.io/ent" - "github.com/casbin/ent-adapter/template" + "github.com/casbin/ent-adapter" ) // CasbinRule holds the schema definition for the CasbinRule entity. @@ -12,6 +12,6 @@ type CasbinRule struct { func (CasbinRule) Mixin() []ent.Mixin { return []ent.Mixin{ - template.CasbinRuleMixin{}, + entadapter.CasbinRuleMixin{}, } } diff --git a/ent/tx.go b/examples/ent/tx.go similarity index 100% rename from ent/tx.go rename to examples/ent/tx.go diff --git a/extension.go b/extension.go new file mode 100644 index 0000000..df45b36 --- /dev/null +++ b/extension.go @@ -0,0 +1,29 @@ +package entadapter + +import ( + "fmt" + "path/filepath" + "runtime" + + "entgo.io/ent/entc" + "entgo.io/ent/entc/gen" +) + +type CasbinExtension struct { + entc.DefaultExtension +} + +func (*CasbinExtension) Templates() []*gen.Template { + _, filename, _, ok := runtime.Caller(0) + if !ok { + _ = fmt.Errorf("error retrieving current file path") + } + + dir := filepath.Dir(filename) + + relativePath := filepath.Join(dir, "casbin.tmpl") + + return []*gen.Template{ + gen.MustParse(gen.NewTemplate("casbin").ParseFiles(relativePath)), + } +} diff --git a/template/mixin.go b/mixin.go similarity index 97% rename from template/mixin.go rename to mixin.go index c8e43ca..0d98eaf 100644 --- a/template/mixin.go +++ b/mixin.go @@ -1,4 +1,4 @@ -package template +package entadapter import ( "entgo.io/ent" diff --git a/template/extension.go b/template/extension.go deleted file mode 100644 index 7aa2539..0000000 --- a/template/extension.go +++ /dev/null @@ -1,16 +0,0 @@ -package template - -import ( - "entgo.io/ent/entc" - "entgo.io/ent/entc/gen" -) - -type CasbinExtension struct { - entc.DefaultExtension -} - -func (*CasbinExtension) Templates() []*gen.Template { - return []*gen.Template{ - gen.MustParse(gen.NewTemplate("casbin").ParseFiles("../template/casbin.tmpl")), - } -} From d56b3196de7872844ab2e6b4d8a1d93f48364cab Mon Sep 17 00:00:00 2001 From: MuZhou233 Date: Mon, 19 Aug 2024 09:04:34 +0100 Subject: [PATCH 4/5] refactor: move adapter_test.go --- adapter_test.go => examples/adapter_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename adapter_test.go => examples/adapter_test.go (99%) diff --git a/adapter_test.go b/examples/adapter_test.go similarity index 99% rename from adapter_test.go rename to examples/adapter_test.go index febed18..5de3644 100644 --- a/adapter_test.go +++ b/examples/adapter_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package entadapter +package examples import ( "log" From ff79ba3bbee1789d4129a3929221928edafbe143 Mon Sep 17 00:00:00 2001 From: MuZhou233 Date: Mon, 19 Aug 2024 09:07:15 +0100 Subject: [PATCH 5/5] fix: update test file path --- examples/adapter_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/adapter_test.go b/examples/adapter_test.go index 5de3644..396ae96 100644 --- a/examples/adapter_test.go +++ b/examples/adapter_test.go @@ -80,7 +80,7 @@ func arrayEqualsWithoutOrder(a [][]string, b [][]string) bool { func initPolicy(t *testing.T, a *ent.Adapter) { // Because the DB is empty at first, // so we need to load the policy from the file adapter (.CSV) first. - e, err := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") + e, err := casbin.NewEnforcer("rbac_model.conf", "rbac_policy.csv") if err != nil { panic(err) } @@ -115,7 +115,7 @@ func testSaveLoad(t *testing.T, a *ent.Adapter) { // Create an adapter and an enforcer. // NewEnforcer() will load the policy automatically. - e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) + e, _ := casbin.NewEnforcer("rbac_model.conf", a) testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) } @@ -150,7 +150,7 @@ func initAdapterWithClientInstance(t *testing.T, client *ent.Client) *ent.Adapte func testAutoSave(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. - e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) + e, _ := casbin.NewEnforcer("rbac_model.conf", a) // AutoSave is enabled by default. // Now we disable it. e.EnableAutoSave(false) @@ -192,7 +192,7 @@ func testAutoSave(t *testing.T, a *ent.Adapter) { //func testFilteredPolicy(t *testing.T, a *Adapter) { // // NewEnforcer() without an adapter will not auto load the policy -// e, _ := casbin.NewEnforcer("examples/rbac_model.conf") +// e, _ := casbin.NewEnforcer("rbac_model.conf") // // Now set the adapter // e.SetAdapter(a) // @@ -215,7 +215,7 @@ func testAutoSave(t *testing.T, a *ent.Adapter) { func testUpdatePolicy(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. - e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) + e, _ := casbin.NewEnforcer("rbac_model.conf", a) e.EnableAutoSave(true) e.UpdatePolicy([]string{"alice", "data1", "read"}, []string{"alice", "data1", "write"}) @@ -225,7 +225,7 @@ func testUpdatePolicy(t *testing.T, a *ent.Adapter) { func testUpdatePolicies(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. - e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) + e, _ := casbin.NewEnforcer("rbac_model.conf", a) e.EnableAutoSave(true) e.UpdatePolicies([][]string{{"alice", "data1", "write"}, {"bob", "data2", "write"}}, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "read"}}) @@ -235,7 +235,7 @@ func testUpdatePolicies(t *testing.T, a *ent.Adapter) { func testUpdateFilteredPolicies(t *testing.T, a *ent.Adapter) { // NewEnforcer() will load the policy automatically. - e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) + e, _ := casbin.NewEnforcer("rbac_model.conf", a) e.EnableAutoSave(true) e.UpdateFilteredPolicies([][]string{{"alice", "data1", "write"}}, 0, "alice", "data1", "read") @@ -246,7 +246,7 @@ func testUpdateFilteredPolicies(t *testing.T, a *ent.Adapter) { func testFilteredPolicy(t *testing.T, a *ent.Adapter) { // NewEnforcer() without an adapter will not auto load the policy - e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") + e, _ := casbin.NewEnforcer("rbac_model.conf", "rbac_policy.csv") // Now set the adapter e.SetAdapter(a)